answer
stringlengths
17
10.2M
package com.skelril.aurora; import com.sk89q.commandbook.CommandBook; import com.sk89q.commandbook.session.PersistentSession; import com.sk89q.commandbook.session.SessionComponent; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldedit.blocks.ItemID; import com.skelril.Pitfall.bukkit.event.PitfallTriggerEvent; import com.skelril.aurora.city.engine.PvPComponent; import com.skelril.aurora.events.anticheat.ThrowPlayerEvent; import com.skelril.aurora.util.ChanceUtil; import com.skelril.aurora.util.ChatUtil; import com.skelril.aurora.util.EntityDistanceComparator; import com.skelril.aurora.util.EnvironmentUtil; import com.skelril.aurora.util.item.ItemUtil; import com.zachsthings.libcomponents.ComponentInformation; import com.zachsthings.libcomponents.Depend; import com.zachsthings.libcomponents.InjectComponent; import com.zachsthings.libcomponents.bukkit.BukkitComponent; import com.zachsthings.libcomponents.config.Setting; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.entity.*; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.HorseJumpEvent; import org.bukkit.event.entity.ProjectileHitEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import static com.skelril.aurora.util.item.ItemUtil.CustomItems; @ComponentInformation(friendlyName = "Ninja", desc = "Disappear into the night!") @Depend(plugins = "Pitfall", components = {SessionComponent.class, RogueComponent.class, PvPComponent.class}) public class NinjaComponent extends BukkitComponent implements Listener, Runnable { private final CommandBook inst = CommandBook.inst(); private final Logger log = inst.getLogger(); private final Server server = CommandBook.server(); @InjectComponent private SessionComponent sessions; @InjectComponent private RogueComponent rogueComponent; private final int WATCH_DISTANCE = 14; private final int WATCH_DISTANCE_SQ = WATCH_DISTANCE * WATCH_DISTANCE; private final int SNEAK_WATCH_DISTANCE = 6; private final int SNEAK_WATCH_DISTANCE_SQ = SNEAK_WATCH_DISTANCE * SNEAK_WATCH_DISTANCE; @Override public void enable() { //noinspection AccessStaticViaInstance inst.registerEvents(this); registerCommands(Commands.class); server.getScheduler().scheduleSyncRepeatingTask(inst, this, 20 * 2, 5); } // Player Management public void ninjaPlayer(Player player) { sessions.getSession(NinjaState.class, player).setIsNinja(true); } public boolean isNinja(Player player) { return sessions.getSession(NinjaState.class, player).isNinja(); } public void showToGuild(Player player, boolean showToGuild) { sessions.getSession(NinjaState.class, player).showToGuild(showToGuild); } public boolean guildCanSee(Player player) { return sessions.getSession(NinjaState.class, player).guildCanSee(); } public void useVanish(Player player, boolean vanish) { sessions.getSession(NinjaState.class, player).useVanish(vanish); } public boolean canVanish(Player player) { return sessions.getSession(NinjaState.class, player).canVanish(); } public void usePoisonArrows(Player player, boolean poisonArrows) { sessions.getSession(NinjaState.class, player).usePoisonArrows(poisonArrows); } public boolean hasPoisonArrows(Player player) { return sessions.getSession(NinjaState.class, player).hasPoisonArrows(); } public boolean canSmokeBomb(Player player) { return sessions.getSession(NinjaState.class, player).canSmokeBomb(); } public void smokeBomb(final Player player) { sessions.getSession(NinjaState.class, player).smokeBomb(); Location[] locations = new Location[]{ player.getLocation(), player.getEyeLocation() }; EnvironmentUtil.generateRadialEffect(locations, org.bukkit.Effect.SMOKE); List<Entity> entities = player.getNearbyEntities(4, 4, 4); if (entities.isEmpty()) return; Collections.sort(entities, new EntityDistanceComparator(player.getLocation())); Location oldLoc = null; Location k = null; for (Entity entity : entities) { if (entity.equals(player) || !(entity instanceof LivingEntity)) continue; if (entity instanceof Player) { if (!PvPComponent.allowsPvP(player, (Player) entity)) return; ChatUtil.sendWarning((Player) entity, "You hear a strange ticking sound..."); } oldLoc = entity.getLocation(); k = player.getLocation(); k.setPitch((float) (ChanceUtil.getRandom(361.0) - 1)); k.setYaw((float) (ChanceUtil.getRandom(181.0) - 91)); entity.teleport(k, PlayerTeleportEvent.TeleportCause.UNKNOWN); } if (oldLoc == null || k == null) return; // Offset by 1 so that the bomb is not messed up by blocks if (k.getBlock().getType() != Material.AIR) { k.add(0, 1, 0); } final Location finalK = k; server.getScheduler().runTaskLater(inst, new Runnable() { @Override public void run() { finalK.getWorld().createExplosion(finalK, 3, false); } }, 30); oldLoc.setDirection(player.getLocation().getDirection()); player.teleport(oldLoc, PlayerTeleportEvent.TeleportCause.UNKNOWN); } public boolean canGrapple(Player player) { return sessions.getSession(NinjaState.class, player).canGrapple(); } public void grapple(Player player, Block block, double maxClimb) { server.getPluginManager().callEvent(new ThrowPlayerEvent(player)); Vector vel = player.getLocation().getDirection(); vel.multiply(.5); vel.setY(.6); // Increment the velocity while (block.getY() > player.getLocation().getY()) { block = block.getRelative(BlockFace.DOWN); } int i; Vector increment = new Vector(0, .1, 0); for (i = 0; i < maxClimb && (i < 1 || block.getType().isSolid()); i++) { double ctl = BlockType.centralTopLimit(block.getTypeId(), block.getData()); vel.add(ctl != 1 ? increment.clone().multiply(ctl) : increment); block = block.getRelative(BlockFace.UP); } player.setVelocity(vel); player.setFallDistance(0F); sessions.getSession(NinjaState.class, player).grapple(i * 200); } public void teleport(Player player) { Location[] locations = new Location[]{ player.getLocation(), player.getEyeLocation() }; EnvironmentUtil.generateRadialEffect(locations, org.bukkit.Effect.SMOKE); ItemUtil.removeItemOfName(player, ItemUtil.Guild.Ninja.makeStar(1), 1, false); player.teleport(new Location(Bukkit.getWorld("City"), 150.0001, 45, -443.0001, -180, 0)); } public void unninjaPlayer(Player player) { NinjaState session = sessions.getSession(NinjaState.class, player); session.setIsNinja(false); player.removePotionEffect(PotionEffectType.WATER_BREATHING); player.removePotionEffect(PotionEffectType.FIRE_RESISTANCE); for (Player otherPlayer : server.getOnlinePlayers()) { // Show Yourself! if (otherPlayer != player) otherPlayer.showPlayer(player); } } @EventHandler public void onProjectileLaunch(EntityShootBowEvent event) { Entity e = event.getProjectile(); Projectile p = e instanceof Projectile ? (Projectile) e : null; if (p == null || p.getShooter() == null || !(p.getShooter() instanceof Player)) return; Player player = (Player) p.getShooter(); if (isNinja(player) && hasPoisonArrows(player) && inst.hasPermission(player, "aurora.ninja.guild")) { if (p instanceof Arrow) { p.setMetadata("ninja-arrow", new FixedMetadataValue(inst, true)); } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); if (!isNinja(player)) return; switch (event.getCause()) { case FALL: event.setDamage(event.getDamage() * .5); break; case PROJECTILE: case ENTITY_ATTACK: event.setDamage(event.getDamage() * .8); break; case DROWNING: player.setRemainingAir(player.getMaximumAir()); case LAVA: case FIRE: event.setCancelled(true); break; case FIRE_TICK: player.setFireTicks(0); event.setCancelled(true); break; } } @EventHandler public void onProjectileLand(ProjectileHitEvent event) { Projectile p = event.getEntity(); if (p.getShooter() == null || !(p.getShooter() instanceof Player)) return; if (p instanceof Arrow && p.hasMetadata("ninja-arrow") && p.hasMetadata("launch-force")) { Object test = p.getMetadata("launch-force").get(0).value(); if (!(test instanceof Float)) return; poisonArrow((Arrow) p, (Float) test); } } private void poisonArrow(Arrow arrow, float force) { int duration = (int) (20 * ((7 * force) + 3)); for (Entity entity : arrow.getNearbyEntities(4, 2, 4)) { if (!ChanceUtil.getChance(3) || entity.equals(arrow.getShooter())) continue; if (entity instanceof LivingEntity) { if (entity instanceof Player) { if (!PvPComponent.allowsPvP((Player) arrow.getShooter(), (Player) entity)) continue; ((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, duration, 4), true); } ((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.POISON, duration, 1), true); } } } @EventHandler public void onClick(PlayerInteractEvent event) { final Player player = event.getPlayer(); ItemStack stack = player.getItemInHand(); if (isNinja(player)) { Block clicked = event.getClickedBlock(); if (clicked == null) return; BlockFace face = event.getBlockFace(); boolean usingBow = stack != null && stack.getTypeId() == ItemID.BOW; switch (event.getAction()) { case LEFT_CLICK_BLOCK: if (!canSmokeBomb(player)) break; if (usingBow) { smokeBomb(player); } break; case RIGHT_CLICK_BLOCK: // Check cool player specific components if (!canGrapple(player) || usingBow || player.isSneaking()) break; if (EnvironmentUtil.isInteractiveBlock(clicked) || EnvironmentUtil.isShrubBlock(clicked)) break; if (!face.equals(BlockFace.UP) && !face.equals(BlockFace.DOWN) && stack != null) { // Check types Material type = stack.getType(); if ((type != Material.AIR && type.isBlock()) || type.isEdible() && player.getFoodLevel() < 20) break; // Check for possible misclick if (EnvironmentUtil.isInteractiveBlock(clicked.getRelative(face))) break; if (clicked.getLocation().distanceSquared(player.getLocation()) <= 4) { grapple(player, clicked, 9); } } break; } } switch (event.getAction()) { case RIGHT_CLICK_BLOCK: if (stack != null && ItemUtil.isItem(stack, CustomItems.NINJA_STAR)) { teleport(player); event.setUseInteractedBlock(Event.Result.DENY); break; } } } @EventHandler(ignoreCancelled = true) public void onHorseJump(HorseJumpEvent event) { Entity passenger = event.getEntity().getPassenger(); if (passenger != null && passenger instanceof Player && isNinja((Player) passenger)) { event.setPower(event.getPower() * 1.37F); } } @EventHandler public void onPlayerDeath(PlayerRespawnEvent event) { Player player = event.getPlayer(); for (final Player otherPlayer : server.getOnlinePlayers()) { if (otherPlayer != player) otherPlayer.showPlayer(player); } } @EventHandler(ignoreCancelled = true) public void onPitfallEvent(PitfallTriggerEvent event) { Entity entity = event.getEntity(); if (entity instanceof Player) { Player player = (Player) entity; if (isNinja(player) && player.isSneaking() && inst.hasPermission(player, "aurora.ninja.guild")) { event.setCancelled(true); } } } @Override public void run() { for (NinjaState ninjaState : sessions.getSessions(NinjaState.class).values()) { if (!ninjaState.isNinja()) { continue; } Player player = ninjaState.getPlayer(); // Stop this from breaking if the player isn't here if (player == null || !player.isOnline() || player.isDead()) continue; Set<Player> invisibleNewCount = new HashSet<>(); Set<Player> visibleNewCount = new HashSet<>(); Location pLoc = player.getLocation(); Location k = player.getLocation(); for (Player otherPlayer : server.getOnlinePlayers()) { if (otherPlayer.equals(player)) continue; if (otherPlayer.getWorld().equals(player.getWorld()) && canVanish(player)) { // Sets k to the otherPlayer's current location otherPlayer.getLocation(k); double dist = pLoc.distanceSquared(k); if ((player.isSneaking() && dist >= SNEAK_WATCH_DISTANCE_SQ) || dist >= WATCH_DISTANCE_SQ) { if (otherPlayer.canSee(player) && !(guildCanSee(player) && inst.hasPermission(otherPlayer, "aurora.ninja.guild")) && !inst.hasPermission(otherPlayer, "aurora.ninja.guild.master")) { otherPlayer.hidePlayer(player); invisibleNewCount.add(otherPlayer); } } else { if (!otherPlayer.canSee(player)) { otherPlayer.showPlayer(player); visibleNewCount.add(otherPlayer); } } } else { if (!otherPlayer.canSee(player)) { otherPlayer.showPlayer(player); visibleNewCount.add(otherPlayer); } } } if (invisibleNewCount.size() > 0) { if (invisibleNewCount.size() > 3) { ChatUtil.sendNotice(player, "You are now invisible to multiple players."); } else { for (Player aPlayer : invisibleNewCount) { ChatUtil.sendNotice(player, "You are now invisible to " + aPlayer.getDisplayName() + "."); } } } if (visibleNewCount.size() > 0) { if (visibleNewCount.size() > 3) { ChatUtil.sendNotice(player, "You are now visible to multiple players."); } else { for (Player aPlayer : visibleNewCount) { ChatUtil.sendNotice(player, "You are now visible to " + aPlayer.getDisplayName() + "."); } } } } } public class Commands { @Command(aliases = {"ninja"}, desc = "Give a player the Ninja power", flags = "gtpi", min = 0, max = 0) @CommandPermissions({"aurora.ninja"}) public void ninja(CommandContext args, CommandSender sender) throws CommandException { if (!(sender instanceof Player)) throw new CommandException("You must be a player to use this command."); if (inst.hasPermission(sender, "aurora.rogue.guild") || rogueComponent.isRogue((Player) sender)) { throw new CommandException("You are a rogue not a ninja!"); } final boolean isNinja = isNinja((Player) sender); // Enter Ninja Mode ninjaPlayer((Player) sender); // Set flags showToGuild((Player) sender, args.hasFlag('g')); useVanish((Player) sender, !args.hasFlag('i')); usePoisonArrows((Player) sender, !args.hasFlag('t')); if (!isNinja) { ChatUtil.sendNotice(sender, "You are inspired and become a ninja!"); } else { ChatUtil.sendNotice(sender, "Ninja flags updated!"); } } @Command(aliases = {"unninja"}, desc = "Revoke a player's Ninja power", flags = "", min = 0, max = 0) public void unninja(CommandContext args, CommandSender sender) throws CommandException { if (!(sender instanceof Player)) throw new CommandException("You must be a player to use this command."); if (!isNinja((Player) sender)) { throw new CommandException("You are not a ninja!"); } unninjaPlayer((Player) sender); ChatUtil.sendNotice(sender, "You return to your previous boring existence."); } } // Ninja Session private static class NinjaState extends PersistentSession { public static final long MAX_AGE = TimeUnit.DAYS.toMillis(1); @Setting("ninja-enabled") private boolean isNinja = false; @Setting("ninja-vanish") private boolean useVanish = true; @Setting("ninja-show-to-guild") private boolean showToGuild = false; @Setting("ninja-toxic-arrows") private boolean toxicArrows = true; private long nextGrapple = 0; private long nextSmokeBomb = 0; protected NinjaState() { super(MAX_AGE); } public boolean isNinja() { return isNinja; } public void setIsNinja(boolean isNinja) { this.isNinja = isNinja; } public boolean guildCanSee() { return showToGuild; } public void showToGuild(boolean showToGuild) { this.showToGuild = showToGuild; } public boolean canVanish() { return useVanish; } public void useVanish(boolean useVanish) { this.useVanish = useVanish; } public boolean hasPoisonArrows() { return toxicArrows; } public void usePoisonArrows(boolean explosiveArrows) { this.toxicArrows = explosiveArrows; } public boolean canGrapple() { return nextGrapple == 0 || System.currentTimeMillis() >= nextGrapple; } public void grapple(long time) { nextGrapple = System.currentTimeMillis() + 300 + time; } public boolean canSmokeBomb() { return nextSmokeBomb == 0 || System.currentTimeMillis() >= nextSmokeBomb; } public void smokeBomb() { nextSmokeBomb = System.currentTimeMillis() + 2750; } public Player getPlayer() { CommandSender sender = super.getOwner(); return sender instanceof Player ? (Player) sender : null; } } }
package com.sudicode.fb2gh.github; import com.sudicode.fb2gh.FB2GHException; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.json.Json; import javax.json.JsonReader; import java.io.StringReader; /** * Utility methods for the GitHub API. */ final class GHUtils { private static final Logger logger = LoggerFactory.getLogger(GHUtils.class); /** * This is a utility class which is not designed for instantiation. */ private GHUtils() { throw new AssertionError("Cannot instantiate."); } /** * When the GitHub API encounters an error, it returns a JSON object which describes it. The GitHub <em>library</em> * will in turn throw an {@link AssertionError} with a rather verbose message that contains the JSON object. * <p> * Passing the {@link AssertionError} to this method does the following: * <ul> * <li>Logs the JSON object.</li> * <li>Throws an {@link FB2GHException} with the error message from GitHub API.</li> * </ul> * </p> * This method will <strong>never</strong> complete normally, but the compiler doesn't know this. Therefore, * its return type has been made a {@link RuntimeException} so that it can be invoked using * <code>throw GHUtils.rethrow(e)</code>. * * @param e An {@link AssertionError} <em>from the GitHub library</em> * @return Never returns. * @throws FB2GHException normally */ static RuntimeException rethrow(final AssertionError e) throws FB2GHException { try { // Parse e.getMessage() for GitHub's JSON response. String error = e.getMessage(); String response = StringUtils.removeEnd(error.substring(error.lastIndexOf('\n')).trim(), ">"); // Log it. logger.error("GitHub error: {}", response); // Parse the JSON and throw FB2GHException. try (JsonReader reader = Json.createReader(new StringReader(response))) { throw new FB2GHException(reader.readObject().getString("message")); } } catch (RuntimeException ex) { logger.debug("Could not parse JSON response.", ex); throw new FB2GHException("GitHub error."); } } }
package com.yubico.client.v2; import org.apache.commons.codec.binary.Base64; import com.yubico.client.v2.impl.YubicoClientImpl; public abstract class YubicoClient { protected Integer clientId; protected byte[] key; protected String sync; protected String wsapi_urls[] = { "https://api.yubico.com/wsapi/2.0/verify", "https://api2.yubico.com/wsapi/2.0/verify", "https://api3.yubico.com/wsapi/2.0/verify", "https://api4.yubico.com/wsapi/2.0/verify", "https://api5.yubico.com/wsapi/2.0/verify" }; /** * Validate an OTP using a webservice call to one or more ykval validation servers. * * @param otp YubiKey OTP in modhex format * @return result of the webservice validation operation */ public abstract YubicoResponse verify( String otp ); /* @see setClientId() */ public Integer getClientId() { return clientId; } public void setClientId(Integer clientId) { this.clientId = clientId; } public void setKey(String key) { this.key = Base64.decodeBase64(key.getBytes()); } public String getKey() { return new String(Base64.encodeBase64(this.key)); } public void setSync(String sync) { this.sync = sync; } public String getSync() { return sync; } /** * Get the list of URLs that will be used for validating OTPs. * @return list of base URLs */ public String[] getWsapiUrls() { return wsapi_urls; } public void setWsapiUrls(String[] wsapi) { this.wsapi_urls = wsapi; } /** * Instantiate a YubicoClient object. * @return client that can be used to validate YubiKey OTPs */ public static YubicoClient getClient(Integer clientId) { return new YubicoClientImpl(clientId); } /** * Extract the public ID of a Yubikey from an OTP it generated. * * @param otp The OTP to extract ID from, in modhex format. * * @return string Public ID of Yubikey that generated otp. Between 0 and 12 characters. */ public static String getPublicId(String otp) { Integer len = otp.length(); /* The OTP part is always the last 32 bytes of otp. Whatever is before that * (if anything) is the public ID of the Yubikey. The ID can be set to '' * through personalization. */ return otp.substring(0, len - 32); } private static final Integer OTP_MIN_LEN = 32; private static final Integer OTP_MAX_LEN = 48; public static boolean isValidOTPFormat(String otp) { int len = otp.length(); boolean isPrintable = true; for (int i = 0; i < len; i++) { char c = otp.charAt(i); if (c < 0x20 || c > 0x7E) { isPrintable = false; break; } } return isPrintable && (OTP_MIN_LEN <= len && len <= OTP_MAX_LEN); } }
package org.eclipse.persistence.testing.tests.wdf.jpa1.entitymanager; import java.sql.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.persistence.TransactionRequiredException; import org.junit.Test; import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Cubicle; import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Department; import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Employee; import org.eclipse.persistence.testing.models.wdf.jpa1.node.Node; import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Project; import org.eclipse.persistence.testing.models.wdf.jpa1.employee.Review; import org.eclipse.persistence.testing.framework.wdf.JPAEnvironment; import org.eclipse.persistence.testing.framework.wdf.ToBeInvestigated; import org.eclipse.persistence.testing.tests.wdf.jpa1.JPA1Base; public class TestFlush extends JPA1Base { @Test public void testRelationshipToNew() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { // case 1: direct relationship Employee -> Cubicle (new) - 1:1 Department dep = new Department(1, "dep"); Employee emp1 = new Employee(2, "first", "last", dep); Cubicle cub1 = new Cubicle(new Integer(3), new Integer(3), "color", emp1); emp1.setCubicle(cub1); env.beginTransaction(em); em.persist(dep); em.persist(emp1); boolean flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); // case 2: direct relationship Employee -> Project (new) - n:m dep = new Department(4, "dep"); emp1 = new Employee(5, "first", "last", dep); Project proj = new Project("project"); Set<Project> emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); Set<Employee> projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(dep); em.persist(emp1); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); // case 3: indirect relationship Employee -> Project -> Employee (new) dep = new Department(7, "dep"); emp1 = new Employee(8, "first1", "last1", dep); Employee emp2 = new Employee(9, "first2", "last2", dep); proj = new Project("project"); emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); Set<Project> emp2Projects = new HashSet<Project>(); emp2Projects.add(proj); emp2.setProjects(emp2Projects); projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); projEmployees.add(emp2); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(dep); em.persist(emp1); em.persist(proj); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); } finally { closeEntityManager(em); } } @SuppressWarnings("unchecked") @Test @ToBeInvestigated public void testRelationshipToRemoved() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { // case 1: direct relationship Employee -> Cubicle (FOR_DELETE) - 1:1 Department dep = new Department(101, "dep"); Employee emp1 = new Employee(102, "first", "last", dep); Cubicle cub1 = new Cubicle(new Integer(103), new Integer(103), "color", emp1); emp1.setCubicle(cub1); env.beginTransaction(em); em.persist(dep); em.persist(emp1); em.persist(cub1); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); cub1 = em.find(Cubicle.class, cub1.getId()); em.remove(cub1); boolean flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); // case 2: direct relationship Employee -> Project (FOR_DELETE) - n:m dep = new Department(104, "dep"); emp1 = new Employee(105, "first", "last", dep); Project proj = new Project("project"); Set<Project> emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); Set<Employee> projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(proj); em.persist(dep); em.persist(emp1); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); proj = em.find(Project.class, proj.getId()); emp1.getProjects().size(); em.remove(proj); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); // case 3: indirect relationship Employee -> Project -> Employee (FOR_DELETE) dep = new Department(107, "dep"); emp1 = new Employee(108, "first1", "last1", dep); Employee emp2 = new Employee(109, "first2", "last2", dep); proj = new Project("project"); emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); Set<Project> emp2Projects = new HashSet<Project>(); emp2Projects.add(proj); emp2.setProjects(emp2Projects); projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); projEmployees.add(emp2); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(proj); em.persist(dep); em.persist(emp1); em.persist(emp2); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); emp2 = em.find(Employee.class, new Integer(emp2.getId())); proj = em.find(Project.class, proj.getId()); emp1.getProjects().size(); proj.getEmployees().size(); em.remove(emp2); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); // case 1b: direct relationship Employee -> Cubicle (DELETE_EXECUTED) - 1:1 dep = new Department(111, "dep"); emp1 = new Employee(112, "first", "last", dep); cub1 = new Cubicle(new Integer(113), new Integer(112), "color", emp1); env.beginTransaction(em); em.persist(dep); em.persist(emp1); em.persist(cub1); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); cub1 = em.find(Cubicle.class, cub1.getId()); em.remove(cub1); em.flush(); emp1.setCubicle(cub1); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); // case 2b: direct relationship Employee -> Project (DELETE_EXECUTED) - n:m dep = new Department(114, "dep"); emp1 = new Employee(115, "first", "last", dep); proj = new Project("project"); env.beginTransaction(em); em.persist(dep); em.persist(emp1); em.persist(proj); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); proj = em.find(Project.class, proj.getId()); em.remove(proj); em.flush(); emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); // case 3b: indirect relationship Employee -> Project -> Employee (DELETE_EXECUTED) dep = new Department(117, "dep"); emp1 = new Employee(118, "first1", "last1", dep); emp2 = new Employee(119, "first2", "last2", dep); proj = new Project("project"); emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(proj); em.persist(dep); em.persist(emp1); em.persist(emp2); env.commitTransactionAndClear(em); env.beginTransaction(em); emp1 = em.find(Employee.class, new Integer(emp1.getId())); emp2 = em.find(Employee.class, new Integer(emp2.getId())); proj = em.find(Project.class, proj.getId()); emp1.getProjects().size(); projEmployees = proj.getEmployees(); projEmployees.size(); em.remove(emp2); em.flush(); emp2Projects = new HashSet<Project>(); emp2Projects.add(proj); emp2.setProjects(emp2Projects); projEmployees.add(emp2); flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to an unmanaged entity"); em.clear(); } finally { closeEntityManager(em); } } @Test @ToBeInvestigated public void testRelationshipToRemovedLazy() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { // case 1: explicit flush Department dep = new Department(201, "dep"); Employee emp1 = new Employee(202, "first", "last", dep); Project proj = new Project("project"); Set<Project> emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); Set<Employee> projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(proj); em.persist(dep); em.persist(emp1); env.commitTransactionAndClear(em); env.beginTransaction(em); dep = em.find(Department.class, new Integer(dep.getId())); proj = em.find(Project.class, proj.getId()); em.remove(proj); emp1 = em.find(Employee.class, new Integer(emp1.getId())); // copy all projects from emp1 to emp2 with out actually touching them Employee emp2 = new Employee(203, "aaa", "bbb", dep); emp2.setProjects(emp1.getProjects()); em.persist(emp2); boolean flushFailed = false; try { em.flush(); } catch (IllegalStateException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); env.rollbackTransactionAndClear(em); } try { if (env.isTransactionActive(em)) { env.commitTransactionAndClear(em); } } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to a removed entity"); em.clear(); // case 2: implicit flush during commit dep = new Department(204, "dep"); emp1 = new Employee(205, "first", "last", dep); proj = new Project("project"); emp1Projects = new HashSet<Project>(); emp1Projects.add(proj); emp1.setProjects(emp1Projects); projEmployees = new HashSet<Employee>(); projEmployees.add(emp1); proj.setEmployees(projEmployees); env.beginTransaction(em); em.persist(proj); em.persist(dep); em.persist(emp1); env.commitTransactionAndClear(em); env.beginTransaction(em); dep = em.find(Department.class, new Integer(dep.getId())); proj = em.find(Project.class, proj.getId()); em.remove(proj); emp1 = em.find(Employee.class, new Integer(emp1.getId())); // copy all projects from emp1 to emp2 with out actually touching them emp2 = new Employee(206, "aaa", "bbb", dep); emp2.setProjects(emp1.getProjects()); em.persist(emp2); flushFailed = false; try { env.commitTransactionAndClear(em); } catch (RuntimeException e) { if (!checkForIllegalStateException(e)) { throw e; } flushFailed = true; } verify(!env.isTransactionActive(em), "Transaction still active"); verify(flushFailed, "flush succeeded although there is a relation to a removed entity"); em.clear(); } finally { closeEntityManager(em); } } /** * Force an exception during flush and check whether the current transaction is rolled back. */ @Test public void testWithException() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { Node node = new Node(301, true); // PostPersist method will throw a Node.MyRuntimeException env.beginTransaction(em); em.persist(node); boolean flushFailed = false; try { em.flush(); } catch (Node.MyRuntimeException e) { // $JL-EXC$ this is expected behavior flushFailed = true; verify(env.isTransactionMarkedForRollback(em), "IllegalStateException during flush did not mark transaction for rollback"); } verify(flushFailed, "callback method did not throw exception as expected"); } finally { closeEntityManager(em); } } @Test public void testRestoreFieldAfterFlush() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { final String initial = "initial"; final int id = 301; Department department = new Department(id, initial); env.beginTransaction(em); em.persist(department); department.setName("changed"); em.flush(); // undo the change between flush and commit (on a new entity) department.setName(initial); env.commitTransactionAndClear(em); env.beginTransaction(em); department = em.find(Department.class, Integer.valueOf(id)); verify(initial.equals(department.getName()), "wrong name: " + department.getName()); department.setName("changed"); em.flush(); // lets try the same with a managed field department.setName(initial); env.commitTransactionAndClear(em); department = em.find(Department.class, Integer.valueOf(id)); verify(initial.equals(department.getName()), "wrong name: " + department.getName()); } finally { closeEntityManager(em); } } @Test public void testRestoreRelationAfterFlush() { JPAEnvironment env = getEnvironment(); EntityManager em = env.getEntityManager(); try { final int id = 302; Employee frank = new Employee(id, "Frank", "Schuster", null); env.beginTransaction(em); Review r1 = new Review(101, Date.valueOf("2006-10-19"), "Performance"); frank.addReview(r1); Review r2 = new Review(102, Date.valueOf("2006-10-19"), "Passion"); frank.addReview(r2); Review r3 = new Review(103, Date.valueOf("2006-10-19"), "Six-Sigma"); frank.addReview(r3); em.persist(frank); em.persist(r1); em.persist(r2); em.persist(r3); env.commitTransactionAndClear(em); env.beginTransaction(em); frank = em.find(Employee.class, Integer.valueOf(id)); Set<Review> reviewsFound = frank.getReviews(); int foundSize = reviewsFound.size(); // lets remove a department the same with a managed field Set<Review> set = new HashSet<Review>(); set.add(r1); set.add(r2); frank.setReviews(set); em.flush(); // undo the change frank.setReviews(reviewsFound); env.commitTransactionAndClear(em); env.beginTransaction(em); frank = em.find(Employee.class, Integer.valueOf(id)); verify(frank.getReviews().size() == foundSize, "wrong number of reviews: " + frank.getReviews().size()); env.rollbackTransactionAndClear(em); } finally { closeEntityManager(em); } } @Test public void testNoTransaction() { final JPAEnvironment env = getEnvironment(); final EntityManager em = env.getEntityManager(); try { em.flush(); flop("exception not thrown as expected"); } catch (TransactionRequiredException e) { // $JL-EXC$ expected behavior } finally { closeEntityManager(em); } } @SuppressWarnings("unchecked") @Test @ToBeInvestigated public void testTransactionMarkedForRollback() { final JPAEnvironment env = getEnvironment(); final EntityManager em = env.getEntityManager(); Department dep = new Department(401, "dep401"); try { env.beginTransaction(em); em.persist(dep); env.markTransactionForRollback(em); em.flush(); // verify that entity is inserted Query query = em.createQuery("select d from Department d where d.id = ?1"); query.setParameter(1, Integer.valueOf(dep.getId())); List<Department> result = query.getResultList(); verify(result.size() == 1, "query returned " + result.size() + " entities"); env.rollbackTransaction(em); } finally { closeEntityManager(em); } } @Test @ToBeInvestigated public void testChangedEntityIgnoredByFlush() { final JPAEnvironment env = getEnvironment(); final EntityManager em = env.getEntityManager(); Employee emp = new Employee(911, "Robi", "Tobi", null); try { env.beginTransaction(em); em.persist(emp); env.commitTransactionAndClear(em); env.beginTransaction(em); Employee found = em.find(Employee.class, 911); found.clearPostUpdate(); found.setLastName("lesbar"); em.createQuery("select i from Island i").getResultList(); verify(!found.postUpdateWasCalled(), "post update was called"); env.rollbackTransactionAndClear(em); } finally { closeEntityManager(em); } } }
package com.silverpeas.notification.delayed.repository; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.persistence.EntityManagerFactory; import javax.persistence.TemporalType; import javax.persistence.TypedQuery; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.time.DateUtils; import com.silverpeas.notification.delayed.constant.DelayedNotificationFrequency; import com.silverpeas.notification.delayed.model.DelayedNotificationData; import com.silverpeas.util.persistence.TypedParameter; import com.silverpeas.util.persistence.TypedParameterUtil; import com.stratelia.silverpeas.notificationManager.constant.NotifChannel; /** * @author Yohann Chastagnier */ public class DelayedNotificationRepositoryImpl implements DelayedNotificationRepositoryCustom { @Inject private EntityManagerFactory emf; /* * (non-Javadoc) * @see com.silverpeas.notification.delayed.repository.DelayedNotificationRepositoryCustom# * findUsersToBeNotified(java.util.Set, java.util.Set, boolean) */ @Override public List<Integer> findUsersToBeNotified(final Set<NotifChannel> aimedChannels, final Set<DelayedNotificationFrequency> aimedFrequencies, final boolean isThatUsersWithNoSettingHaveToBeNotified) { // Query final StringBuffer query = new StringBuffer(); query.append("select distinct d.userId from DelayedNotificationData d "); query.append(" left outer join d.delayedNotificationUserSetting p "); query.append("where d.channel in (:channels) "); query.append("and ( "); query.append(" (p.id is not null and p.frequency in (:frequencies)) "); if (isThatUsersWithNoSettingHaveToBeNotified) { query.append(" or p.id is null "); } query.append(") "); // Typed query final TypedQuery<Integer> tq = emf.createEntityManager().createQuery(query.toString(), Integer.class); // Query parameters tq.setParameter("channels", NotifChannel.toIds(aimedChannels)); tq.setParameter("frequencies", DelayedNotificationFrequency.toCodes(aimedFrequencies)); // Result return tq.getResultList(); } /* * (non-Javadoc) * @see * com.silverpeas.notification.delayed.repository.DelayedNotificationRepositoryCustom#findResource(com.silverpeas. * notification.model.NotificationResourceData) */ @Override public List<DelayedNotificationData> findDelayedNotification(final DelayedNotificationData delayedNotification) { // Parameters final List<TypedParameter<?>> parameters = new ArrayList<TypedParameter<?>>(); // Query final StringBuffer query = new StringBuffer("from DelayedNotificationData where"); query.append(" userId = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "userId", delayedNotification.getUserId())); query.append(" and fromUserId = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "fromUserId", delayedNotification.getFromUserId())); query.append(" and channel = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "channel", delayedNotification.getChannel().getId())); query.append(" and action = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "action", delayedNotification.getAction().getId())); query.append(" and language = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "language", delayedNotification.getLanguage())); query.append(" and creationDate between :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "creationDateMin", DateUtils.setSeconds(DateUtils.setMilliseconds(delayedNotification.getCreationDate(), 0), 0), TemporalType.TIMESTAMP)); query.append(" and :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "creationDateMax", DateUtils.setSeconds(DateUtils.setMilliseconds(delayedNotification.getCreationDate(), 999), 59), TemporalType.TIMESTAMP)); query.append(" and notificationResourceId = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "resourceId", delayedNotification.getResource())); // resourceDescription parameter if (StringUtils.isNotBlank(delayedNotification.getMessage())) { query.append(" and message = :"); query.append(TypedParameterUtil.addNamedParameter(parameters, "message", delayedNotification.getMessage())); } else { query.append(" and message is null"); } // Typed query final TypedQuery<DelayedNotificationData> typedQuery = emf.createEntityManager().createQuery(query.toString(), DelayedNotificationData.class); // Parameters TypedParameterUtil.computeNamedParameters(typedQuery, parameters); // Result return typedQuery.getResultList(); } }
package de.blackcraze.grb.util; import de.blackcraze.grb.i18n.Resource; import de.blackcraze.grb.model.PrintableTable; import de.blackcraze.grb.model.entity.Mate; import de.blackcraze.grb.model.entity.Stock; import de.blackcraze.grb.model.entity.StockType; import de.blackcraze.grb.util.wagu.Block; import de.blackcraze.grb.util.wagu.Board; import de.blackcraze.grb.util.wagu.Table; import org.joda.time.Duration; import org.joda.time.PeriodType; import org.joda.time.format.PeriodFormatter; import org.joda.time.format.PeriodFormatterBuilder; import java.util.*; import java.util.stream.Collectors; import static de.blackcraze.grb.util.InjectorUtils.getStockDao; public final class PrintUtils { private PrintUtils() { } public static String prettyPrint(PrintableTable... stocks) { StringBuilder returnHandle = new StringBuilder(); for (PrintableTable stock : stocks) { if (stock != null) { int boardWidth = stock.getWidth(); int headerWidth = boardWidth - 2; StringBuilder b = new StringBuilder(); b.append("```dsconfig\n"); Board board = new Board(boardWidth); // board.showBlockIndex(true); // DEBUG Block header = new Block(board, headerWidth, 1, stock.getHeader()); header.setDataAlign(Block.DATA_MIDDLE_LEFT); board.setInitialBlock(header); Table table = new Table(board, boardWidth, stock.getTitles(), stock.getRows(), stock.getWidths(), stock.getAligns()); board.appendTableTo(0, Board.APPEND_BELOW, table); for (int i = 0; i < stock.getFooter().size(); i++) { Block footer = new Block(board, stock.getWidths().get(i), 1, stock.getFooter().get(i)); footer.setDataAlign(stock.getAligns().get(i)); if (i == 0) { header.getMostBelowBlock().setBelowBlock(footer); } else { header.getMostBelowBlock().getMostRightBlock().setRightBlock(footer); } } board.build(); b.append(board.getPreview()); b.append("```\n"); if (returnHandle.length() + b.length() > 2000) { // discord limits output to 2000 chars return returnHandle.toString(); } else { returnHandle.append(b.toString()); } } } return returnHandle.toString(); } private static String getDiffFormatted(Date from, Date to) { Duration duration = new Duration(to.getTime() - from.getTime()); // in milliseconds PeriodFormatter formatter = new PeriodFormatterBuilder().printZeroNever() .appendWeeks().appendSuffix("w").appendSeparator(" ") .appendDays().appendSuffix("d").appendSeparator(" ") .appendHours().appendSuffix("h").appendSeparator(" ") .appendMinutes().appendSuffix("m").appendSeparator(" ") .appendSeconds().appendSuffix("s") .toFormatter(); String fullTimeAgo = formatter.print(duration.toPeriod(PeriodType.yearMonthDayTime())); return Arrays.stream(fullTimeAgo.split(" ")) .limit(2) .collect(Collectors.joining(" ")); } public static String prettyPrintStocks(List<StockType> stockTypes, Locale responseLocale) { if (stockTypes.isEmpty()) { return Resource.getString("RESOURCE_UNKNOWN", responseLocale); } List<String> headers = Arrays.asList( Resource.getString("USER", responseLocale), Resource.getString("AMOUNT", responseLocale), Resource.getString("UPDATED", responseLocale)); List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT, Block.DATA_MIDDLE_RIGHT); PrintableTable[] tables = new PrintableTable[stockTypes.size()]; for (int i = 0; i < stockTypes.size(); i++) { StockType type = stockTypes.get(i); List<Stock> stocks = getStockDao().findStocksByType(type); List<List<String>> rows = new ArrayList<>(stocks.size()); long sumAmount = 0; if (stocks.isEmpty()) { rows.add(Arrays.asList("-", "-", "-")); } for (Stock stock : stocks) { String mateName = stock.getMate().getName(); String amount = String.format("%,d", stock.getAmount()); String updated = PrintUtils.getDiffFormatted(stock.getUpdated(), new Date()); rows.add(Arrays.asList(mateName, amount, updated)); sumAmount += stock.getAmount(); } String resourceKey = type.getName(); String resourceName = Resource.getItem(resourceKey, responseLocale); List<String> summary = Arrays.asList(resourceName, String.format("%,d", sumAmount), ""); tables[i] = new PrintableTable(resourceName, summary, headers, rows, aligns); } return PrintUtils.prettyPrint(tables); } public static String prettyPrintStockTypes(List<StockType> stockTypes, Locale responseLocale) { StringBuilder b = new StringBuilder(); b.append("```\n"); if (stockTypes.isEmpty()) { b.append(Resource.getString("NO_DATA", responseLocale)); } for (StockType type : stockTypes) { String resourceKey = type.getName(); String resourceName = Resource.getItem(resourceKey, responseLocale); b.append(resourceName); b.append("\n"); } b.append("\n```\n"); return b.toString(); } public static String prettyPrintMate(List<Mate> mates, Locale responseLocale) { if (mates.isEmpty()) { return Resource.getString("USER_UNKNOWN", responseLocale); } List<String> headers = Arrays.asList( Resource.getString("RAW_MATERIAL", responseLocale), Resource.getString("AMOUNT", responseLocale), Resource.getString("UPDATED", responseLocale)); List<Integer> aligns = Arrays.asList(Block.DATA_MIDDLE_LEFT, Block.DATA_MIDDLE_RIGHT, Block.DATA_MIDDLE_RIGHT); PrintableTable[] tables = new PrintableTable[mates.size()]; for (int i = 0; i < mates.size(); i++) { Mate mate = mates.get(i); List<Stock> stocks = getStockDao().findStocksByMate(mate); List<List<String>> rows = new ArrayList<>(stocks.size()); for (Stock stock : stocks) { String resourceKey = stock.getType().getName(); String resourceName = Resource.getItem(resourceKey, responseLocale); String amount = String.format("%,d", stock.getAmount()); String updated = PrintUtils.getDiffFormatted(stock.getUpdated(), new Date()); rows.add(Arrays.asList(resourceName, amount, updated)); } if (stocks.isEmpty()) { rows.add(Arrays.asList("-", "-", "-")); } tables[i] = new PrintableTable(mate.getName(), Collections.emptyList(), headers, rows, aligns); } return PrintUtils.prettyPrint(tables); } }
package com.linkedin.metadata.search.elasticsearch.query.request; import com.linkedin.common.UrnArray; import com.linkedin.common.urn.Urn; import com.linkedin.data.template.LongMap; import com.linkedin.metadata.dao.utils.ESUtils; import com.linkedin.metadata.models.EntitySpec; import com.linkedin.metadata.models.SearchableFieldSpec; import com.linkedin.metadata.models.annotation.SearchableAnnotation; import com.linkedin.metadata.query.AggregationMetadata; import com.linkedin.metadata.query.AggregationMetadataArray; import com.linkedin.metadata.query.Criterion; import com.linkedin.metadata.query.Filter; import com.linkedin.metadata.query.MatchMetadata; import com.linkedin.metadata.query.MatchMetadataArray; import com.linkedin.metadata.query.MatchedField; import com.linkedin.metadata.query.MatchedFieldArray; import com.linkedin.metadata.query.SearchResult; import com.linkedin.metadata.query.SearchResultMetadata; import com.linkedin.metadata.query.SortCriterion; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.AggregationBuilder; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter; import org.elasticsearch.search.aggregations.bucket.terms.ParsedTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import static com.linkedin.metadata.dao.utils.SearchUtils.getQueryBuilderFromCriterion; @Slf4j public class SearchRequestHandler { private static final Map<EntitySpec, SearchRequestHandler> REQUEST_HANDLER_BY_ENTITY_NAME = new ConcurrentHashMap<>(); private final EntitySpec _entitySpec; private final Set<String> _facetFields; private final Set<String> _defaultQueryFieldNames; private final int _maxTermBucketSize = 100; private SearchRequestHandler(@Nonnull EntitySpec entitySpec) { _entitySpec = entitySpec; _facetFields = getFacetFields(); _defaultQueryFieldNames = getDefaultQueryFieldNames(); } public static SearchRequestHandler getBuilder(@Nonnull EntitySpec entitySpec) { return REQUEST_HANDLER_BY_ENTITY_NAME.computeIfAbsent(entitySpec, k -> new SearchRequestHandler(entitySpec)); } public Set<String> getFacetFields() { return _entitySpec.getSearchableFieldSpecs() .stream() .map(SearchableFieldSpec::getSearchableAnnotation) .filter(SearchableAnnotation::isAddToFilters) .map(SearchableAnnotation::getFieldName) .collect(Collectors.toSet()); } public Set<String> getDefaultQueryFieldNames() { return _entitySpec.getSearchableFieldSpecs() .stream() .map(SearchableFieldSpec::getSearchableAnnotation) .filter(SearchableAnnotation::isQueryByDefault) .map(SearchableAnnotation::getFieldName) .collect(Collectors.toSet()); } /** * Constructs the search query based on the query request. * * <p>TODO: This part will be replaced by searchTemplateAPI when the elastic is upgraded to 6.4 or later * * @param input the search input text * @param filter the search filter * @param from index to start the search from * @param size the number of search hits to return * @return a valid search request */ @Nonnull public SearchRequest getSearchRequest(@Nonnull String input, @Nullable Filter filter, @Nullable SortCriterion sortCriterion, int from, int size) { SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.from(from); searchSourceBuilder.size(size); BoolQueryBuilder filterQuery = ESUtils.buildFilterQuery(filter); // Filter out entities that are marked "removed" filterQuery.mustNot(QueryBuilders.matchQuery("removed", true)); searchSourceBuilder.query(QueryBuilders.boolQuery().should(getQuery(input)).must(filterQuery)); getAggregations(filter).forEach(searchSourceBuilder::aggregation); searchSourceBuilder.highlighter(getHighlights()); ESUtils.buildSortOrder(searchSourceBuilder, sortCriterion); searchRequest.source(searchSourceBuilder); log.debug("Search request is: " + searchRequest.toString()); return searchRequest; } /** * Returns a {@link SearchRequest} given filters to be applied to search query and sort criterion to be applied to * search results. * * @param filters {@link Filter} list of conditions with fields and values * @param sortCriterion {@link SortCriterion} to be applied to the search results * @param from index to start the search from * @param size the number of search hits to return * @return {@link SearchRequest} that contains the filtered query */ @Nonnull public SearchRequest getFilterRequest(@Nullable Filter filters, @Nullable SortCriterion sortCriterion, int from, int size) { SearchRequest searchRequest = new SearchRequest(); final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); if (filters != null) { filters.getCriteria().forEach(criterion -> { if (!criterion.getValue().trim().isEmpty()) { boolQueryBuilder.filter(getQueryBuilderFromCriterion(criterion)); } }); } final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(boolQueryBuilder); searchSourceBuilder.from(from).size(size); ESUtils.buildSortOrder(searchSourceBuilder, sortCriterion); searchRequest.source(searchSourceBuilder); return searchRequest; } public QueryBuilder getQuery(@Nonnull String query) { return SearchQueryBuilder.buildQuery(_entitySpec, query); } public List<AggregationBuilder> getAggregations(@Nullable Filter filter) { List<AggregationBuilder> aggregationBuilders = new ArrayList<>(); for (String facet : _facetFields) { // All facet fields must have subField keyword AggregationBuilder aggBuilder = AggregationBuilders.terms(facet).field(facet + ".keyword").size(_maxTermBucketSize); Optional.ofNullable(filter).map(Filter::getCriteria).ifPresent(criteria -> { for (Criterion criterion : criteria) { if (!_facetFields.contains(criterion.getField()) || criterion.getField().equals(facet)) { continue; } QueryBuilder filterQueryBuilder = ESUtils.getQueryBuilderFromCriterionForSearch(criterion); aggBuilder.subAggregation(AggregationBuilders.filter(criterion.getField(), filterQueryBuilder)); } }); aggregationBuilders.add(aggBuilder); } return aggregationBuilders; } public HighlightBuilder getHighlights() { HighlightBuilder highlightBuilder = new HighlightBuilder(); // Don't set tags to get the original field value highlightBuilder.preTags(""); highlightBuilder.postTags(""); // Check for each field name and any subfields _defaultQueryFieldNames.forEach(fieldName -> highlightBuilder.field(fieldName).field(fieldName + ".*")); return highlightBuilder; } public SearchResult extractResult(@Nonnull SearchResponse searchResponse, int from, int size) { int totalCount = (int) searchResponse.getHits().getTotalHits().value; List<Urn> resultList = getResults(searchResponse); SearchResultMetadata searchResultMetadata = extractSearchResultMetadata(searchResponse); searchResultMetadata.setUrns(new UrnArray(resultList)); return new SearchResult().setEntities(new UrnArray(resultList)) .setMetadata(searchResultMetadata) .setFrom(from) .setPageSize(size) .setNumEntities(totalCount); } /** * Gets list of urns returned in the search response * * @param searchResponse the raw search response from search engine * @return List of entity urns */ @Nonnull List<Urn> getResults(@Nonnull SearchResponse searchResponse) { return Arrays.stream(searchResponse.getHits().getHits()) .map(this::getUrnFromSearchHit) .collect(Collectors.toList()); } @Nonnull private Urn getUrnFromSearchHit(@Nonnull SearchHit hit) { try { return Urn.createFromString(hit.getSourceAsMap().get("urn").toString()); } catch (URISyntaxException e) { throw new RuntimeException("Invalid urn in search document " + e); } } /** * Extracts SearchResultMetadata section. * * @param searchResponse the raw {@link SearchResponse} as obtained from the search engine * @return {@link SearchResultMetadata} with aggregation and list of urns obtained from {@link SearchResponse} */ @Nonnull SearchResultMetadata extractSearchResultMetadata(@Nonnull SearchResponse searchResponse) { final SearchResultMetadata searchResultMetadata = new SearchResultMetadata().setSearchResultMetadatas(new AggregationMetadataArray()).setUrns(new UrnArray()); final List<AggregationMetadata> aggregationMetadataList = extractAggregation(searchResponse); if (!aggregationMetadataList.isEmpty()) { searchResultMetadata.setSearchResultMetadatas(new AggregationMetadataArray(aggregationMetadataList)); } final List<MatchMetadata> highlightMetadataList = extractMatchMetadataList(searchResponse); if (!highlightMetadataList.isEmpty()) { searchResultMetadata.setMatches(new MatchMetadataArray(highlightMetadataList)); } return searchResultMetadata; } public List<AggregationMetadata> extractAggregation(@Nonnull SearchResponse searchResponse) { final List<AggregationMetadata> aggregationMetadataList = new ArrayList<>(); if (searchResponse.getAggregations() == null) { return aggregationMetadataList; } for (Map.Entry<String, Aggregation> entry : searchResponse.getAggregations().getAsMap().entrySet()) { final Map<String, Long> oneTermAggResult = extractTermAggregations((ParsedTerms) entry.getValue()); if (oneTermAggResult.isEmpty()) { continue; } final AggregationMetadata aggregationMetadata = new AggregationMetadata().setName(entry.getKey()).setAggregations(new LongMap(oneTermAggResult)); aggregationMetadataList.add(aggregationMetadata); } return aggregationMetadataList; } /** * Extracts term aggregations give a parsed term. * * @param terms an abstract parse term, input can be either ParsedStringTerms ParsedLongTerms * @return a map with aggregation key and corresponding doc counts */ @Nonnull private Map<String, Long> extractTermAggregations(@Nonnull ParsedTerms terms) { final Map<String, Long> aggResult = new HashMap<>(); List<? extends Terms.Bucket> bucketList = terms.getBuckets(); for (Terms.Bucket bucket : bucketList) { String key = bucket.getKeyAsString(); ParsedFilter parsedFilter = extractBucketAggregations(bucket); // Gets filtered sub aggregation doc count if exist Long docCount = parsedFilter != null ? parsedFilter.getDocCount() : bucket.getDocCount(); if (docCount > 0) { aggResult.put(key, docCount); } } return aggResult; } /** * Extracts sub aggregations from one term bucket. * * @param bucket a term bucket * @return a parsed filter if exist */ @Nullable private ParsedFilter extractBucketAggregations(@Nonnull Terms.Bucket bucket) { ParsedFilter parsedFilter = null; Map<String, Aggregation> bucketAggregations = bucket.getAggregations().getAsMap(); for (Map.Entry<String, Aggregation> entry : bucketAggregations.entrySet()) { parsedFilter = (ParsedFilter) entry.getValue(); // TODO: implement and test multi parsed filters } return parsedFilter; } @Nonnull private List<MatchMetadata> extractMatchMetadataList(@Nonnull SearchResponse searchResponse) { final List<MatchMetadata> highlightMetadataList = new ArrayList<>(searchResponse.getHits().getHits().length); for (SearchHit hit : searchResponse.getHits().getHits()) { highlightMetadataList.add(extractMatchMetadata(hit.getHighlightFields())); } return highlightMetadataList; } @Nonnull private MatchMetadata extractMatchMetadata(@Nonnull Map<String, HighlightField> highlightedFields) { // Keep track of unique field values that matched for a given field name Map<String, Set<String>> highlightedFieldNamesAndValues = new HashMap<>(); for (Map.Entry<String, HighlightField> entry : highlightedFields.entrySet()) { // Get the field name from source e.g. name.delimited -> name Optional<String> fieldName = getFieldName(entry.getKey()); if (!fieldName.isPresent()) { continue; } if (!highlightedFieldNamesAndValues.containsKey(fieldName.get())) { highlightedFieldNamesAndValues.put(fieldName.get(), new HashSet<>()); } for (Text fieldValue : entry.getValue().getFragments()) { highlightedFieldNamesAndValues.get(fieldName.get()).add(fieldValue.string()); } } return new MatchMetadata().setMatchedFields(new MatchedFieldArray(highlightedFieldNamesAndValues.entrySet() .stream() .flatMap( entry -> entry.getValue().stream().map(value -> new MatchedField().setName(entry.getKey()).setValue(value))) .collect(Collectors.toList()))); } @Nonnull private Optional<String> getFieldName(String matchedField) { return _defaultQueryFieldNames.stream().filter(matchedField::startsWith).findFirst(); } }
package de.prob2.ui.internal; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Formatter; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.ResourceBundle; import java.util.Set; import java.util.WeakHashMap; import javax.annotation.Nullable; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.codecentric.centerdevice.MenuToolkit; import de.prob2.ui.config.FileChooserManager; import de.prob2.ui.error.ExceptionAlert; import de.prob2.ui.layout.FontSize; import de.prob2.ui.persistence.UIPersistence; import de.prob2.ui.persistence.UIState; import javafx.beans.binding.Bindings; import javafx.beans.binding.StringExpression; import javafx.beans.property.DoubleProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.geometry.BoundingBox; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.stage.Stage; /** * This singleton provides common methods for creating and initializing views, * dialogs and stages. These methods ensure that all parts of the ProB 2 UI * use the correct visual styles and are known to internal mechanisms like * the UI persistence and Mac menu bar handling. * * @see FileChooserManager * @see UIPersistence */ @Singleton public final class StageManager { private enum PropertiesKey { PERSISTENCE_ID, USE_GLOBAL_MAC_MENU_BAR } private static final String STYLESHEET = "prob.css"; private static final Image ICON = new Image(StageManager.class.getResource("/de/prob2/ui/ProB_Icon.png").toExternalForm()); private final Injector injector; private final MenuToolkit menuToolkit; private final UIState uiState; private final ResourceBundle bundle; private final ObjectProperty<Stage> current; private final Map<Stage, Void> registered; private MenuBar globalMacMenuBar; private Stage mainStage; private final DoubleProperty stageSceneWidthDifference; private final DoubleProperty stageSceneHeightDifference; @Inject private StageManager(final Injector injector, @Nullable final MenuToolkit menuToolkit, final UIState uiState, final ResourceBundle bundle) { this.injector = injector; this.menuToolkit = menuToolkit; this.uiState = uiState; this.bundle = bundle; this.current = new SimpleObjectProperty<>(this, "current"); this.registered = new WeakHashMap<>(); this.globalMacMenuBar = null; this.stageSceneWidthDifference = new SimpleDoubleProperty(this, "stageSceneWidthDifference", 0.0); this.stageSceneHeightDifference = new SimpleDoubleProperty(this, "stageSceneHeightDifference", 0.0); } /** * Load an FXML file with {@code controller} as the root and controller. * * @param controller the object to use as the FXML file's root * and controller * @param fxmlUrl the URL of the FXML file to load */ public void loadFXML(final Object controller, final URL fxmlUrl) { final FXMLLoader loader = injector.getInstance(FXMLLoader.class); loader.setLocation(fxmlUrl); loader.setRoot(controller); loader.setController(controller); try { loader.load(); } catch (IOException e) { throw new IllegalArgumentException(e); } final FontSize fontSize = injector.getInstance(FontSize.class); final StringExpression fontSizeCssValue = Bindings.format("-fx-font-size: %dpx;", fontSize.fontSizeProperty()); if (controller instanceof Node) { Node controllerNode = (Node) controller; controllerNode.styleProperty().bind(fontSizeCssValue); } else if (controller instanceof Stage) { Stage controllerStage = (Stage) controller; controllerStage.getScene().getRoot().styleProperty().bind(fontSizeCssValue); } else if (controller instanceof Dialog<?>) { Dialog<?> controllerDialog = (Dialog<?>) controller; controllerDialog.getDialogPane().styleProperty().bind(fontSizeCssValue); } } /** * Load an FXML file with {@code controller} as the root and controller. * {@code fxmlResource} is the resource name of the FXML file to load. * If {@code fxmlResource} is a relative name (i. e. one that doesn't start * with a slash), it is resolved relative to {@code controller}'s class. * * @param controller the object to use as the FXML file's root * and controller * @param fxmlResource the resource name of the FXML file to load */ public void loadFXML(final Object controller, final String fxmlResource) { final URL fxmlUrl; if (!fxmlResource.startsWith("custom")) { fxmlUrl = controller.getClass().getResource(fxmlResource); } else { try { fxmlUrl = new URL(fxmlResource.replace("custom ", "")); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } this.loadFXML(controller, fxmlUrl); } /** * <p>Load an FXML file with the {@link Stage} {@code controller} as the * root and controller, initialize it, and register it with the * UI persistence mechanism.</p> * * <p>This is equivalent to loading the FXML file using * {@link #loadFXML(Object, String)} and then registering the stage using * {@link #register(Stage, String)}.</p> * * @param controller the {@link Stage} to use as the FXML file's root * and controller * @param fxmlResource the resource name of the FXML file to load * @param persistenceID a string identifying the stage for UI persistence, * or {@code null} if the stage should not be persisted */ public void loadFXML(final Stage controller, final String fxmlResource, final String persistenceID) { this.loadFXML((Object) controller, fxmlResource); this.register(controller, persistenceID); } /** * <p>Load an FXML file with the {@link Stage} {@code controller} as the * root and controller, and initialize it without registering it with the * UI persistence mechanism.</p> * * <p>This is equivalent to loading the FXML file using * {@link #loadFXML(Stage, String, String)} with {@code null} as the * persistence ID (which disables persistence for the stage).</p> * * @param controller the {@link Stage} to use as the FXML file's root * and controller * @param fxmlResource the resource name of the FXML file to load */ public void loadFXML(final Stage controller, final String fxmlResource) { this.loadFXML(controller, fxmlResource, null); } /** * Initialize the given stage and register it with the UI persistence * mechanism. The stage must already have its scene * {@link Stage#setScene(Scene) set}. * * @param stage the stage to register * @param persistenceID a string identifying the stage for UI persistence, * or {@code null} if the stage should not be persisted */ public void register(final Stage stage, final String persistenceID) { this.registered.put(stage, null); setPersistenceID(stage, persistenceID); stage.getProperties().putIfAbsent(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, true); stage.getScene().getStylesheets().add(STYLESHEET); stage.getIcons().add(ICON); // If possible, make the stage respect the minimum size of its content. // For some reason, this is not the default behavior in JavaFX. final ChangeListener<Parent> rootListener = (o, from, to) -> { if (to instanceof Region) { final Region region = (Region)to; stage.minWidthProperty().bind( Bindings.createDoubleBinding( () -> region.minWidth(-1), region.minWidthProperty(), region.widthProperty() ).add(this.stageSceneWidthDifference) ); stage.minHeightProperty().bind( Bindings.createDoubleBinding( () -> region.minHeight(-1), region.minHeightProperty(), region.heightProperty() ).add(this.stageSceneHeightDifference) ); } else { stage.minWidthProperty().unbind(); stage.minHeightProperty().unbind(); } }; final ChangeListener<Scene> sceneListener = (o, from, to) -> { if (from != null) { from.rootProperty().removeListener(rootListener); } if (to != null) { to.rootProperty().addListener(rootListener); rootListener.changed(to.rootProperty(), null, to.getRoot()); } }; stage.sceneProperty().addListener(sceneListener); sceneListener.changed(stage.sceneProperty(), null, stage.getScene()); stage.focusedProperty().addListener(e -> { final String stageId = getPersistenceID(stage); if (stageId != null) { injector.getInstance(UIState.class).moveStageToEnd(stageId); } }); stage.showingProperty().addListener((observable, from, to) -> { final String stageId = getPersistenceID(stage); if (stageId != null) { if (to) { final BoundingBox box = uiState.getSavedStageBoxes().get(stageId); if (box != null) { stage.setX(box.getMinX()); stage.setY(box.getMinY()); stage.setWidth(box.getWidth()); stage.setHeight(box.getHeight()); } uiState.getStages().put(stageId, new WeakReference<>(stage)); uiState.getSavedVisibleStages().add(stageId); } else { uiState.getSavedVisibleStages().remove(stageId); uiState.getSavedStageBoxes().put(stageId, new BoundingBox(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight())); } } }); // Add a second ChangeListener that does nothing. stage.showingProperty().addListener((o, from, to) -> {}); stage.focusedProperty().addListener((observable, from, to) -> { if (to) { this.current.set(stage); } else if (stage.equals(this.current.get())) { this.current.set(null); } }); if (this.menuToolkit != null && this.globalMacMenuBar != null && isUseGlobalMacMenuBar(stage)) { this.menuToolkit.setMenuBar(stage, this.globalMacMenuBar); } } /** * Initialize the given stage as the ProB 2 UI's main stage and register * it with the UI persistence mechanism. The stage must already have its * scene {@link Stage#setScene(Scene) set}. * * @param stage the stage to register as the main stage * @param persistenceID a string identifying the stage for UI persistence, * or {@code null} if the stage should not be persisted */ public void registerMainStage(Stage stage, String persistenceID) { this.mainStage = stage; stage.setOnShown(event -> { this.stageSceneWidthDifference.set(stage.getWidth() - stage.getScene().getWidth()); this.stageSceneHeightDifference.set(stage.getHeight() - stage.getScene().getHeight()); stage.setOnShown(null); }); this.register(stage, persistenceID); } /** * Create a new stage with the given {@link Scene} as its scene, * initialize it, and register it with the UI persistence mechanism. * * @param scene the new stage's scene * @param persistenceID a string identifying the stage for UI persistence, * or {@code null} if the stage should not be persisted * @return a new stage with the given scene */ public Stage makeStage(final Scene scene, final String persistenceID) { final Stage stage = new Stage(); stage.setScene(scene); this.register(stage, persistenceID); return stage; } /** * Initialize the given dialog. * * @param dialog the dialog to register */ public void register(final Dialog<?> dialog) { dialog.getDialogPane().getStylesheets().add(STYLESHEET); } /** * Create and initialize a new alert with custom buttons. * * @param alertType the alert type * @param buttons the custom buttons * @param headerBundleKey the resource bundle key for the alert header * text, or {@code ""} for the default header text provided by JavaFX * @param contentBundleKey the resource bundle key for the alert content * text, whose localized value may contain {@link Formatter}-style * placeholders * @param contentParams the objects to insert into the placeholders in * {@code contentBundleKey}'s localized value * @return a new alert */ public Alert makeAlert(final Alert.AlertType alertType, final List<ButtonType> buttons, final String headerBundleKey, final String contentBundleKey, final Object... contentParams) { final Alert alert = new Alert(alertType, String.format(bundle.getString(contentBundleKey), contentParams), buttons.toArray(new ButtonType[buttons.size()])); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); this.register(alert); if (!headerBundleKey.isEmpty()) { alert.setHeaderText(bundle.getString(headerBundleKey)); } return alert; } /** * Create and initialize a new alert with the default buttons provided by * JavaFX (OK and Cancel). * * @param alertType the alert type * @param headerBundleKey the resource bundle key for the alert header * text, or {@code ""} for the default header text provided by JavaFX * @param contentBundleKey the resource bundle key for the alert content * text, whose localized value may contain {@link Formatter}-style * placeholders * @param contentParams the objects to insert into the placeholders in * {@code contentBundleKey}'s localized value * @return a new alert */ public Alert makeAlert(final Alert.AlertType alertType, final String headerBundleKey, final String contentBundleKey, final Object... contentParams) { return makeAlert(alertType, new ArrayList<>(), headerBundleKey, contentBundleKey, contentParams); } /** * Create and initialize an {@link ExceptionAlert}. * * @param exc the {@link Throwable} for which to make an alert * @param contentBundleKey the resource bundle key for the alert content * text, whose localized value may contain {@link Formatter}-style * placeholders * @param contentParams the objects to insert into the placeholders in * {@code contentBundleKey}'s localized value * @return a new exception alert */ public Alert makeExceptionAlert(final Throwable exc, final String contentBundleKey, final Object... contentParams) { return new ExceptionAlert(this.injector, String.format(bundle.getString(contentBundleKey), contentParams), exc); } /** * Create and initialize an {@link ExceptionAlert}. * * @param exc the {@link Throwable} for which to make an alert * @param headerBundleKey the resource bundle key for the alert header * text, or {@code ""} for the default header text provided by JavaFX * @param contentBundleKey the resource bundle key for the alert content * text, whose localized value may contain {@link Formatter}-style * placeholders * @param contentParams the objects to insert into the placeholders in * {@code contentBundleKey}'s localized value * @return a new exception alert */ public Alert makeExceptionAlert(final Throwable exc, final String headerBundleKey, final String contentBundleKey, final Object... contentParams) { Alert alert = makeExceptionAlert(exc, contentBundleKey, contentParams); if (!headerBundleKey.isEmpty()) { alert.setHeaderText(bundle.getString(headerBundleKey)); } return alert; } /** * A read-only property containing the currently focused stage. If a non-JavaFX * window or an unregistered stage is in focus, the property's value is * {@code null}. * * @return a property containing the currently focused stage */ public ReadOnlyObjectProperty<Stage> currentProperty() { return this.current; } /** * Get the currently focused stage. If a non-JavaFX window or an unregistered * stage is in focus, this method returns {@code null}. * * @return the currently focused stage */ public Stage getCurrent() { return this.currentProperty().get(); } /** * Get the main stage, as previously set using * {@link #registerMainStage(Stage, String)}. * * @return the main stage */ public Stage getMainStage() { return this.mainStage; } /** * Get a read-only set containing all registered stages. The returned set should * not be permanently stored or copied elsewhere, as this would prevent all * registered stages from being garbage-collected. * * @return a read-only set containing all registered stages */ public Set<Stage> getRegistered() { return Collections.unmodifiableSet(this.registered.keySet()); } /** * Get the persistence ID of the given stage. * * @param stage the stage for which to get the persistence ID * @return the stage's persistence ID, or {@code null} if none */ public static String getPersistenceID(final Stage stage) { Objects.requireNonNull(stage); return (String) stage.getProperties().get(PropertiesKey.PERSISTENCE_ID); } /** * Set the given stage's persistence ID. * * @param stage the stage for which to set the persistence ID * @param persistenceID the persistence ID to set, or {@code null} to * remove it */ public static void setPersistenceID(final Stage stage, final String persistenceID) { Objects.requireNonNull(stage); if (persistenceID == null) { stage.getProperties().remove(PropertiesKey.PERSISTENCE_ID); } else { stage.getProperties().put(PropertiesKey.PERSISTENCE_ID, persistenceID); } } /** * Get whether the given stage uses the global Mac menu bar. On non-Mac systems * this setting should not be used. * * @param stage the stage for which to get this setting * @return whether the given stage uses the global Mac menu bar, or * {@code false} if not set */ public static boolean isUseGlobalMacMenuBar(final Stage stage) { return (boolean) stage.getProperties().getOrDefault(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, false); } /** * On Mac, set the given stage's menu bar. On other systems this method does * nothing. * * @param menuBar the menu bar to use, or {@code null} to use the global * menu bar */ public void setMacMenuBar(final Stage stage, final MenuBar menuBar) { Objects.requireNonNull(stage); if (this.menuToolkit == null) { return; } stage.getProperties().put(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, menuBar == null); final Scene scene = stage.getScene(); if (scene != null) { final Parent root = scene.getRoot(); if (root instanceof Pane) { final ObservableList<Menu> globalMenus = this.globalMacMenuBar.getMenus(); if (menuBar != null) { // Temporary placeholder for the application menu, is later replaced with the // global application menu menuBar.getMenus().add(0, new Menu("Invisible Application Menu")); // Add the Window and Help menus from the global menu bar menuBar.getMenus().addAll(globalMenus.subList(globalMenus.size()-2, globalMenus.size())); } this.menuToolkit.setMenuBar((Pane) root, menuBar == null ? this.globalMacMenuBar : menuBar); // Put the application menu from the global menu bar back menuToolkit.setApplicationMenu(globalMenus.get(0)); } } } /** * <p>On Mac, set the given menu bar as the menu bar for all registered * stages and any stages registered in the future. On other systems this * method does nothing.</p> * * <p>This method is similar to * {@link MenuToolkit#setGlobalMenuBar(MenuBar)}, except that it only * affects registered stages and handles stages with a {@code null} scene * correctly.</p> * * @param menuBar the menu bar to set */ public void setGlobalMacMenuBar(final MenuBar menuBar) { if (this.menuToolkit == null) { return; } this.globalMacMenuBar = menuBar; this.getRegistered().stream().filter(StageManager::isUseGlobalMacMenuBar) .forEach(stage -> this.setMacMenuBar(stage, null)); } }
package com.github.longkerdandy.mithril.mqtt.broker.handler; import com.github.longkerdandy.mithril.mqtt.api.Authenticator; import com.github.longkerdandy.mithril.mqtt.api.AuthorizeResult; import com.github.longkerdandy.mithril.mqtt.api.Communicator; import com.github.longkerdandy.mithril.mqtt.broker.session.SessionRegistry; import com.github.longkerdandy.mithril.mqtt.broker.util.Validator; import com.github.longkerdandy.mithril.mqtt.storage.redis.RedisStorage; import com.github.longkerdandy.mithril.mqtt.util.Topics; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.mqtt.*; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.longkerdandy.mithril.mqtt.storage.redis.RedisStorage.mapToMqtt; import static com.github.longkerdandy.mithril.mqtt.storage.redis.RedisStorage.mqttToMap; import static com.github.longkerdandy.mithril.mqtt.util.UUIDs.shortUuid; /** * Asynchronous MQTT Handler using Redis */ public class AsyncRedisHandler extends SimpleChannelInboundHandler<MqttMessage> { private static final Logger logger = LoggerFactory.getLogger(AsyncRedisHandler.class); protected final Authenticator authenticator; protected final Communicator communicator; protected final RedisStorage redis; protected final SessionRegistry registry; protected final PropertiesConfiguration config; protected final Validator validator; // session state protected String clientId; protected String userName; protected boolean connected; protected boolean cleanSession; protected int keepAlive; protected MqttPublishMessage willMessage; public AsyncRedisHandler(Authenticator authenticator, Communicator communicator, RedisStorage redis, SessionRegistry registry, PropertiesConfiguration config, Validator validator) { this.authenticator = authenticator; this.communicator = communicator; this.redis = redis; this.registry = registry; this.config = config; this.validator = validator; } @Override @SuppressWarnings("ThrowableResultOfMethodCallIgnored") protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception { // Disconnect if The MQTT message is invalid if (msg.decoderResult().isFailure()) { Throwable cause = msg.decoderResult().cause(); logger.trace("Invalid message: {}", ExceptionUtils.getMessage(msg.decoderResult().cause())); if (cause instanceof MqttUnacceptableProtocolVersionException) { // Send back CONNACK if the protocol version is invalid this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION, false), null), "INVALID", null, true); } else if (cause instanceof MqttIdentifierRejectedException) { // Send back CONNACK if the client id is invalid this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null), "INVALID", null, true); } ctx.close(); return; } switch (msg.fixedHeader().messageType()) { case CONNECT: onConnect(ctx, (MqttConnectMessage) msg); break; case PUBLISH: onPublish(ctx, (MqttPublishMessage) msg); break; case PUBACK: onPubAck(ctx, msg); break; case PUBREC: onPubRec(ctx, msg); break; case PUBREL: onPubRel(ctx, msg); break; case PUBCOMP: onPubComp(ctx, msg); break; case SUBSCRIBE: onSubscribe(ctx, (MqttSubscribeMessage) msg); break; case UNSUBSCRIBE: onUnsubscribe(ctx, (MqttUnsubscribeMessage) msg); break; case PINGREQ: onPingReq(ctx, msg); break; case DISCONNECT: onDisconnect(ctx, msg); break; } } /** * Handle CONNECT MQTT Message * * @param ctx ChannelHandlerContext * @param msg CONNECT MQTT Message */ protected void onConnect(ChannelHandlerContext ctx, MqttConnectMessage msg) { this.clientId = msg.payload().clientIdentifier(); this.cleanSession = msg.variableHeader().isCleanSession(); // A Server MAY allow a Client to supply a ClientId that has a length of zero bytes, however if it does so the // Server MUST treat this as a special case and assign a unique ClientId to that Client. It MUST then // process the CONNECT packet as if the Client had provided that unique ClientId // If the Client supplies a zero-byte ClientId with CleanSession set to 0, the Server MUST respond to the // CONNECT Packet with a CONNACK return code 0x02 (Identifier rejected) and then close the Network // Connection if (StringUtils.isBlank(this.clientId)) { if (!this.cleanSession) { logger.trace("Protocol violation: Empty client id with clean session 0, send CONNACK and disconnect the client"); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null), this.clientId, null, true); ctx.close(); return; } this.clientId = shortUuid(); } // Validate clientId based on configuration if (!validator.isClientIdValid(this.clientId)) { logger.trace("Protocol violation: Client id {} not valid based on configuration, send CONNACK and disconnect the client"); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED, false), null), this.clientId, null, true); ctx.close(); return; } // A Client can only send the CONNECT Packet once over a Network Connection. The Server MUST // process a second CONNECT Packet sent from a Client as a protocol violation and disconnect the Client if (this.connected) { logger.trace("Protocol violation: Second CONNECT packet sent from client {}, disconnect the client", this.clientId); ctx.close(); return; } boolean userNameFlag = msg.variableHeader().hasUserName(); boolean passwordFlag = msg.variableHeader().hasPassword(); this.userName = msg.payload().userName(); String password = msg.payload().password(); boolean malformed = false; // If the User Name Flag is set to 0, a user name MUST NOT be present in the payload // If the User Name Flag is set to 1, a user name MUST be present in the payload // If the Password Flag is set to 0, a password MUST NOT be present in the payload // If the Password Flag is set to 1, a password MUST be present in the payload // If the User Name Flag is set to 0, the Password Flag MUST be set to 0 if (userNameFlag) { if (StringUtils.isBlank(this.userName)) malformed = true; if (passwordFlag && StringUtils.isBlank(password)) malformed = true; if (!passwordFlag && StringUtils.isNotBlank(password)) malformed = true; } else { if (StringUtils.isNotBlank(this.userName)) malformed = true; if (passwordFlag || StringUtils.isNotBlank(password)) malformed = true; } if (malformed) { logger.trace("Protocol violation: Bad user name or password from client {}, send CONNACK and disconnect the client", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD, false), null), this.clientId, null, true); ctx.close(); return; } // Authorize client connect using provided Authenticator this.authenticator.authConnect(this.clientId, this.userName, password).thenAccept(result -> { // Authorize successful if (result == AuthorizeResult.OK) { logger.trace("Authorization Success: For client {}", this.clientId); // If the Server accepts a connection with CleanSession set to 1, the Server MUST set Session Present to 0 // in the CONNACK packet in addition to setting a zero return code in the CONNACK packet // If the Server accepts a connection with CleanSession set to 0, the value set in Session Present depends // on whether the Server already has stored Session state for the supplied client ID. If the Server has stored // Session state, it MUST set Session Present to 1 in the CONNACK packet. If the Server // does not have stored Session state, it MUST set Session Present to 0 in the CONNACK packet. This is in // addition to setting a zero return code in the CONNACK packet. this.redis.getSessionExist(this.clientId).thenAccept(exist -> { boolean sessionPresent = "0".equals(exist) && !this.cleanSession; // The first packet sent from the Server to the Client MUST be a CONNACK Packet logger.trace("Connection Accepted: Send CONNACK back to client {}", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_ACCEPTED, sessionPresent), null), this.clientId, null, true); // If the ClientId represents a Client already connected to the Server then the Server MUST // disconnect the existing Client if (exist != null) { this.redis.getConnectedNode(this.clientId).thenAccept(node -> { if (node != null) { if (node.equals(this.config.getString("node.id"))) { logger.trace("Disconnect Exist: Try to disconnect exist client {} from local node {}", this.clientId, this.config.getString("node.id")); ChannelHandlerContext lastSession = this.registry.getSession(this.clientId); if (lastSession != null) { lastSession.close(); this.registry.removeSession(this.clientId, lastSession); } } else { logger.trace("Disconnect Exist: Try to disconnect exist client {} from remote node {}", this.clientId, node); this.communicator.oneToOne(node, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.DISCONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0), null, null ), new HashMap<String, Object>() {{ put("clientId", clientId); }}); } } }); } // If CleanSession is set to 0, the Server MUST resume communications with the Client based on state from // the current Session (as identified by the Client identifier). If there is no Session associated with the Client // identifier the Server MUST create a new Session. The Client and Server MUST store the Session after // the Client and Server are disconnected. After the disconnection of a Session that had // CleanSession set to 0, the Server MUST store further QoS 1 and QoS 2 messages that match any // subscriptions that the client had at the time of disconnection as part of the Session state. // It MAY also store QoS 0 messages that meet the same criteria. // The Session state in the Server consists of: // The existence of a Session, even if the rest of the Session state is empty. // The Client's subscriptions. // QoS 1 and QoS 2 messages which have been sent to the Client, but have not been completely acknowledged. // QoS 1 and QoS 2 messages pending transmission to the Client. // QoS 2 messages which have been received from the Client, but have not been completely acknowledged. // Optionally, QoS 0 messages pending transmission to the Client. if (!this.cleanSession) { if ("0".equals(exist)) { this.redis.handleAllInFlightMessage(this.clientId, map -> this.registry.sendMessage(ctx, mapToMqtt(map), this.clientId, Integer.parseInt(map.getOrDefault("packetId", "0")), true)); } else if ("1".equals(exist)) { this.redis.removeAllSessionState(this.clientId); } } // If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new // one. This Session lasts as long as the Network Connection. State data associated with this Session // MUST NOT be reused in any subsequent Session. // When CleanSession is set to 1 the Client and Server need not process the deletion of state atomically. else { if (exist != null) { this.redis.removeAllSessionState(this.clientId); } } // If the Will Flag is set to 1 this indicates that, if the Connect request is accepted, a Will Message MUST be // stored on the Server and associated with the Network Connection. The Will Message MUST be published // when the Network Connection is subsequently closed unless the Will Message has been deleted by the // Server on receipt of a DISCONNECT Packet. // Situations in which the Will Message is published include, but are not limited to: // An I/O error or network failure detected by the Server. // The Client fails to communicate within the Keep Alive time. // The Client closes the Network Connection without first sending a DISCONNECT Packet. // The Server closes the Network Connection because of a protocol error. if (msg.variableHeader().isWillFlag() && StringUtils.isNotBlank(msg.payload().willTopic()) && StringUtils.isNotBlank(msg.payload().willMessage())) { MqttQoS willQos = MqttQoS.valueOf(msg.variableHeader().willQos()); boolean willRetain = msg.variableHeader().isWillRetain(); this.willMessage = (MqttPublishMessage) MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBLISH, false, willQos, willRetain, 0), new MqttPublishVariableHeader(msg.payload().willTopic(), 0), msg.payload().willMessage() // TODO: payload should be ByteBuf ); } // If the Keep Alive value is non-zero and the Server does not receive a Control Packet from the Client // within one and a half times the Keep Alive time period, it MUST disconnect the Network Connection to the // Client as if the network had failed this.keepAlive = msg.variableHeader().keepAliveTimeSeconds(); if (this.keepAlive <= 0 || this.keepAlive > this.config.getInt("mqtt.keepalive.max")) this.keepAlive = this.config.getInt("mqtt.keepalive.default"); // Save connection state, add to local registry and remote storage this.connected = true; this.registry.saveSession(this.clientId, ctx); this.redis.updateConnectedNode(this.clientId, this.config.getString("node.id")); this.redis.updateSessionExist(this.clientId, this.cleanSession); }); } // Authorize failed else { logger.trace("Authorization failed: CONNECT authorize {} for client {}, send CONNACK and disconnect the client", result, this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0), new MqttConnAckVariableHeader(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED, false), null), this.clientId, null, true); ctx.close(); } }); } /** * Handle PUBLISH MQTT Message * * @param ctx ChannelHandlerContext * @param msg CONNECT MQTT Message */ protected void onPublish(ChannelHandlerContext ctx, MqttPublishMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received PUBLISH message, disconnect the client", this.clientId); ctx.close(); return; } boolean dup = msg.fixedHeader().isDup(); MqttQoS qos = msg.fixedHeader().qosLevel(); boolean retain = msg.fixedHeader().isRetain(); String topicName = msg.variableHeader().topicName(); int packetId = msg.variableHeader().messageId(); // The Topic Name in the PUBLISH Packet MUST NOT contain wildcard characters if (!Topics.isValidTopicName(topicName, this.config)) { logger.trace("Protocol violation: Client {} sent PUBLISH message contains invalid topic name {}", this.clientId, topicName); ctx.close(); return; } List<String> topicLevels = Topics.sanitizeTopicName(topicName); // The Packet Identifier field is only present in PUBLISH Packets where the QoS level is 1 or 2. if (packetId <= 0 && (qos == MqttQoS.AT_LEAST_ONCE || qos == MqttQoS.EXACTLY_ONCE)) { logger.trace("Protocol violation: Client {} sent PUBLISH message does not contain packet id", this.clientId); ctx.close(); return; } // Authorize client publish using provided Authenticator this.authenticator.authPublish(this.clientId, this.userName, topicName, qos.value(), retain).thenAccept(result -> { // Authorize successful if (result == AuthorizeResult.OK) { logger.trace("Authorization Success: Client {} authorized to publish to topic {}", this.clientId, topicName); // If the RETAIN flag is set to 1, in a PUBLISH Packet sent by a Client to a Server, the Server MUST store // the Application Message and its QoS, so that it can be delivered to future subscribers whose // subscriptions match its topic name. When a new subscription is established, the last // retained message, if any, on each matching topic name MUST be sent to the subscriber. if (retain) { // If the Server receives a QoS 0 message with the RETAIN flag set to 1 it MUST discard any message // previously retained for that topic. It SHOULD store the new QoS 0 message as the new retained // message for that topic, but MAY choose to discard it at any time - if this happens there will be no retained // message for that topic. if (qos == MqttQoS.AT_MOST_ONCE) { this.redis.removeAllRetainMessage(topicLevels); } // A PUBLISH Packet with a RETAIN flag set to 1 and a payload containing zero bytes will be processed as // normal by the Server and sent to Clients with a subscription matching the topic name. Additionally any // existing retained message with the same topic name MUST be removed and any future subscribers for // not set in the message received by existing Clients. A zero byte retained message MUST NOT be stored // as a retained message on the Server if (msg.payload() != null && msg.payload().isReadable()) { this.redis.addRetainMessage(topicLevels, packetId, mqttToMap(msg)); } } // In the QoS 0 delivery protocol, the Receiver // Accepts ownership of the message when it receives the PUBLISH packet. if (qos == MqttQoS.AT_MOST_ONCE) { onwardRecipients(msg); } // In the QoS 1 delivery protocol, the Receiver // After it has sent a PUBACK Packet the Receiver MUST treat any incoming PUBLISH packet that // contains the same Packet Identifier as being a new publication, irrespective of the setting of its // DUP flag. else if (qos == MqttQoS.AT_LEAST_ONCE) { onwardRecipients(msg); } // In the QoS 2 delivery protocol, the Receiver // Until it has received the corresponding PUBREL packet, the Receiver MUST acknowledge any // subsequent PUBLISH packet with the same Packet Identifier by sending a PUBREC. It MUST // NOT cause duplicate messages to be delivered to any onward recipients in this case. else if (qos == MqttQoS.EXACTLY_ONCE) { // The recipient of a Control Packet that contains the DUP flag set to 1 cannot assume that it has // seen an earlier copy of this packet. this.redis.addQoS2MessageId(this.clientId, packetId).thenAccept(count -> { if (!dup || count == 1) { onwardRecipients(msg); } }); } } } ); // If a Server implementation does not authorize a PUBLISH to be performed by a Client; it has no way of // informing that Client. It MUST either make a positive acknowledgement, according to the normal QoS // rules, or close the Network Connection // In the QoS 1 delivery protocol, the Receiver // MUST respond with a PUBACK Packet containing the Packet Identifier from the incoming // PUBLISH Packet, having accepted ownership of the Application Message // The receiver is not required to complete delivery of the Application Message before sending the // PUBACK. When its original sender receives the PUBACK packet, ownership of the Application // Message is transferred to the receiver. if (qos == MqttQoS.AT_LEAST_ONCE) { logger.trace("Response: Send PUBACK back to client {}", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), null), this.clientId, packetId, true); } // In the QoS 2 delivery protocol, the Receiver // UST respond with a PUBREC containing the Packet Identifier from the incoming PUBLISH // Packet, having accepted ownership of the Application Message. // The receiver is not required to complete delivery of the Application Message before sending the // PUBREC or PUBCOMP. When its original sender receives the PUBREC packet, ownership of the // Application Message is transferred to the receiver. else if (qos == MqttQoS.EXACTLY_ONCE) { logger.trace("Response: Send PUBREC back to client {}", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBREC, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), null), this.clientId, packetId, true); } } /** * Forward PUBLISH message to its recipients * * @param msg PUBLISH MQTT Message */ protected void onwardRecipients(MqttPublishMessage msg) { MqttQoS qos = msg.fixedHeader().qosLevel(); String topicName = msg.variableHeader().topicName(); List<String> topicLevels = Topics.sanitizeTopicName(topicName); // When sending a PUBLISH Packet to a Client the Server MUST set the RETAIN flag to 1 if a message is // sent as a result of a new subscription being made by a Client. It MUST set the RETAIN // flag to 0 when a PUBLISH Packet is sent to a Client because it matches an established subscription // regardless of how the flag was set in the message it received. // The Server uses a PUBLISH Packet to send an Application Message to each Client which has a // matching subscription. // subscriptions to overlap so that a published message might match multiple filters. In this case the Server // MUST deliver the message to the Client respecting the maximum QoS of all the matching subscriptions. // In addition, the Server MAY deliver further copies of the message, one for each this.redis.handleMatchSubscriptions(topicLevels, 0, map -> map.forEach((sClientId, sQos) -> { int fQos = qos.value() > Integer.valueOf(sQos) ? Integer.valueOf(sQos) : qos.value(); // Each time a Client sends a new packet of one of these // types it MUST assign it a currently unused Packet Identifier. If a Client re-sends a // particular Control Packet, then it MUST use the same Packet Identifier in subsequent re-sends of that // packet. The Packet Identifier becomes available for reuse after the Client has processed the // corresponding acknowledgement packet. In the case of a QoS 1 PUBLISH this is the corresponding // PUBACK; in the case of QoS 2 it is PUBCOMP. For SUBSCRIBE or UNSUBSCRIBE it is the // corresponding SUBACK or UNSUBACK. The same conditions apply to a Server when it // sends a PUBLISH with QoS > 0 // A PUBLISH Packet MUST NOT contain a Packet Identifier if its QoS value is set to this.redis.getNextPacketId(sClientId).thenAccept(sPacketId -> { MqttMessage sMsg = MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBLISH, false, MqttQoS.valueOf(fQos), false, 0), new MqttPublishVariableHeader(topicName, sPacketId.intValue()), msg.payload().duplicate()); // TODO, use ByteBuf.duplicate() is correct? // In the QoS 1 delivery protocol, the Sender // PUBACK packet from the receiver. // In the QoS 2 delivery protocol, the Sender // PUBREC packet from the receiver. if (fQos == MqttQoS.AT_LEAST_ONCE.value() || fQos == MqttQoS.EXACTLY_ONCE.value()) { Map<String, String> sMap = mqttToMap(sMsg); sMap.put("dup", "1"); this.redis.addInFlightMessage(sClientId, sPacketId.intValue(), sMap); } // Forward to recipient this.redis.getConnectedNode(sClientId).thenAccept(node -> { if (node != null) { if (node.equals(this.config.getString("node.id"))) { this.registry.sendMessage(sMsg, sClientId, sPacketId.intValue(), true); } else { this.communicator.oneToOne(node, sMsg, new HashMap<String, Object>() {{ put("clientId", sClientId); }}); } } }); }); })); } protected void onPubAck(ChannelHandlerContext ctx, MqttMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received PUBACK message, disconnect the client", this.clientId); ctx.close(); return; } MqttMessageIdVariableHeader variable = (MqttMessageIdVariableHeader) msg.variableHeader(); int packetId = variable.messageId(); // In the QoS 1 delivery protocol, the Sender // PUBACK packet from the receiver. this.redis.removeInFlightMessage(this.clientId, packetId); } protected void onPubRec(ChannelHandlerContext ctx, MqttMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received PUBREC message, disconnect the client", this.clientId); ctx.close(); return; } MqttMessageIdVariableHeader variable = (MqttMessageIdVariableHeader) msg.variableHeader(); int packetId = variable.messageId(); // In the QoS 2 delivery protocol, the Sender // PUBREC packet from the receiver. // MUST send a PUBREL packet when it receives a PUBREC packet from the receiver. This // PUBREL packet MUST contain the same Packet Identifier as the original PUBLISH packet. // MUST NOT re-send the PUBLISH once it has sent the corresponding PUBREL packet. this.redis.removeInFlightMessage(this.clientId, packetId).thenAccept(r -> { MqttMessage rel = MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBREL, false, MqttQoS.AT_LEAST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), null); this.redis.addInFlightMessage(this.clientId, packetId, mqttToMap(rel)); logger.trace("Response: Send PUBREL back to client {}", this.clientId); this.registry.sendMessage(ctx, rel, this.clientId, packetId, true); }); } protected void onPubRel(ChannelHandlerContext ctx, MqttMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received PUBREL message, disconnect the client", this.clientId); ctx.close(); return; } MqttMessageIdVariableHeader variable = (MqttMessageIdVariableHeader) msg.variableHeader(); int packetId = variable.messageId(); // In the QoS 2 delivery protocol, the Receiver // MUST respond to a PUBREL packet by sending a PUBCOMP packet containing the same // Packet Identifier as the PUBREL. // After it has sent a PUBCOMP, the receiver MUST treat any subsequent PUBLISH packet that // contains that Packet Identifier as being a new publication. this.redis.removeQoS2MessageId(this.clientId, packetId); MqttMessage comp = MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.PUBCOMP, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), null); logger.trace("Response: Send PUBCOMP back to client {}", this.clientId); this.registry.sendMessage(ctx, comp, this.clientId, packetId, true); } protected void onPubComp(ChannelHandlerContext ctx, MqttMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received PUBCOMP message, disconnect the client", this.clientId); ctx.close(); return; } MqttMessageIdVariableHeader variable = (MqttMessageIdVariableHeader) msg.variableHeader(); int packetId = variable.messageId(); // In the QoS 2 delivery protocol, the Sender // PUBCOMP packet from the receiver. this.redis.removeInFlightMessage(this.clientId, packetId); } protected void onSubscribe(ChannelHandlerContext ctx, MqttSubscribeMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received SUBSCRIBE message, disconnect the client", this.clientId); ctx.close(); return; } int packetId = msg.variableHeader().messageId(); List<MqttTopicSubscription> subscriptions = msg.payload().topicSubscriptions(); List<String> topics = new ArrayList<>(); List<Integer> requestQos = new ArrayList<>(); subscriptions.forEach(subscription -> { topics.add(subscription.topicName()); requestQos.add(subscription.qualityOfService().value()); }); // Authorize client subscribe using provided Authenticator this.authenticator.authSubscribe(this.clientId, this.userName, topics, requestQos).thenAccept(grantedQos -> { for (int i = 0; i < topics.size(); i++) { int maxQos = grantedQos.get(i); // Authorize successful if (maxQos >= 0 && maxQos <= 2) { List<String> topicLevels = Topics.sanitize(topics.get(i)); // If a Server receives a SUBSCRIBE Packet containing a Topic Filter that is identical to an existing // Subscription. The Topic Filter in the new Subscription will be identical to that in the previous Subscription, // although its maximum QoS value could be different. Any existing retained messages matching the Topic // Filter MUST be re-sent, but the flow of publications MUST NOT be interrupted. // and all matching retained messages are sent. this.redis.updateSubscription(this.clientId, topicLevels, String.valueOf(grantedQos.get(i))); // The Server is permitted to start sending PUBLISH packets matching the Subscription before the Server // sends the SUBACK Packet. this.redis.handleAllRetainMessage(topicLevels, map -> { int qos = Integer.parseInt(map.getOrDefault("qos", "0")); if (qos > maxQos) map.put("qos", String.valueOf(maxQos)); this.registry.sendMessage(ctx, mapToMqtt(map), this.clientId, Integer.parseInt(map.getOrDefault("packetId", "0")), true); }); } } // If a Server receives a SUBSCRIBE packet that contains multiple Topic Filters it MUST handle that packet // as if it had received a sequence of multiple SUBSCRIBE packets, except that it combines their responses // into a single SUBACK response. // When the Server receives a SUBSCRIBE Packet from a Client, the Server MUST respond with a // SUBACK Packet. The SUBACK Packet MUST have the same Packet Identifier as the // SUBSCRIBE Packet that it is acknowledging. logger.trace("Response: Send SUBACK back to client {}", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.SUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), new MqttSubAckPayload(grantedQos)), this.clientId, packetId, true); }); } protected void onUnsubscribe(ChannelHandlerContext ctx, MqttUnsubscribeMessage msg) { if (!this.connected) { logger.trace("Protocol violation: Client {} must first sent a CONNECT message, now received UNSUBSCRIBE message, disconnect the client", this.clientId); ctx.close(); return; } int packetId = msg.variableHeader().messageId(); // The Topic Filters (whether they contain wildcards or not) supplied in an UNSUBSCRIBE packet MUST be // compared character-by-character with the current set of Topic Filters held by the Server for the Client. If // any filter matches exactly then its owning Subscription is deleted, otherwise no additional processing // occurs // If a Server deletes a Subscription: // It MUST stop adding any new messages for delivery to the Client. //1 It MUST complete the delivery of any QoS 1 or QoS 2 messages which it has started to send to // the Client. // It MAY continue to deliver any existing messages buffered for delivery to the Client. msg.payload().topics().forEach(topic -> this.redis.removeSubscription(this.clientId, Topics.sanitize(topic))); // The Server MUST respond to an UNSUBSUBCRIBE request by sending an UNSUBACK packet. The // UNSUBACK Packet MUST have the same Packet Identifier as the UNSUBSCRIBE Packet. // Even where no Topic Subscriptions are deleted, the Server MUST respond with an // UNSUBACK. // If a Server receives an UNSUBSCRIBE packet that contains multiple Topic Filters it MUST handle that // packet as if it had received a sequence of multiple UNSUBSCRIBE packets, except that it sends just one // UNSUBACK response. logger.trace("Response: Send UNSUBACK back to client {}", this.clientId); this.registry.sendMessage( ctx, MqttMessageFactory.newMessage( new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(packetId), null), this.clientId, packetId, true); } protected void onPingReq(ChannelHandlerContext ctx, MqttMessage msg) { } protected void onDisconnect(ChannelHandlerContext ctx, MqttMessage msg) { } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.close(); } }
package de.svenkubiak.jpushover; import java.io.IOException; import java.util.List; import java.util.Objects; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.Consts; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.fluent.Form; import org.apache.http.client.fluent.Request; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import de.svenkubiak.jpushover.enums.Constants; import de.svenkubiak.jpushover.enums.Priority; import de.svenkubiak.jpushover.enums.Sound; /** * * @author svenkubiak * */ public class JPushover { private static final Logger LOG = LogManager.getLogger(JPushover.class); private static final int HTTP_OK = 200; private String pushoverToken; private String pushoverUser; private String pushoverMessage; private String pushoverDevice; private String pushoverTitle; private String pushoverUrl; private String pushoverUrlTitle; private String pushoverTimestamp; private String pushoverRetry; private String pushoverExpire; private String pushoverCallback; private Priority pushoverPriority; private Sound pushoverSound; private HttpHost proxy; private boolean pushoverHtml; public JPushover() { this.withSound(Sound.PUSHOVER); this.withPriority(Priority.NORMAL); } /** * Creates a new JPushover instance * @return JPushover instance */ public static JPushover build() { return new JPushover(); } /** * Your application's API token * (required) * * @param token The pushover API token * @return JPushover instance */ public final JPushover withToken(final String token) { this.pushoverToken = token; return this; } public final JPushover withUser(final String user) { this.pushoverUser = user; return this; } /** * Specifies how often (in seconds) the Pushover servers will send the same notification to the user. * Only required if priority is set to emergency. * * @param retry Number of seconds * @return JPushover instance */ public final JPushover withRetry(final String retry) { this.pushoverRetry = retry; return this; } /** * Specifies how many seconds your notification will continue to be retried for (every retry seconds). * Only required if priority is set to emergency. * * @param expire Number of seconds * @return JPushover instance */ public final JPushover withExpire(final String expire) { this.pushoverExpire = expire; return this; } /** * Your message * (required) * * @param message The message to sent * @return JPushover instance */ public final JPushover withMessage(final String message) { this.pushoverMessage = message; return this; } /** * Your user's device name to send the message directly to that device, * rather than all of the user's devices * (optional) * * @param device The device name * @return JPushover instance */ public final JPushover withDevice(final String device) { this.pushoverDevice = device; return this; } /** * Your message's title, otherwise your app's name is used * (optional) * * @param title The title * @return JPushover instance */ public final JPushover withTitle(final String title) { this.pushoverTitle = title; return this; } /** * A supplementary URL to show with your message * (optional) * * @param url The url * @return JPushover instance */ public final JPushover withUrl(final String url) { this.pushoverUrl = url; return this; } /** * Enables HTML in the pushover message * (optional) * * @return JPushover instance */ public final JPushover enableHtml() { this.pushoverHtml = true; return this; } /** * A title for your supplementary URL, otherwise just the URL is shown * * @param urlTitle The url title * @return JPushover instance */ public final JPushover withUrlTitle(final String urlTitle) { this.pushoverUrlTitle = urlTitle; return this; } /** * A Unix timestamp of your message's date and time to display to the user, * rather than the time your message is received by our API * * @param timestamp The Unix timestamp * @return JPushover instance */ public final JPushover withTimestamp(final String timestamp) { this.pushoverTimestamp = timestamp; return this; } public final JPushover withPriority(final Priority priority) { this.pushoverPriority = priority; return this; } /** * The name of one of the sounds supported by device clients to override * the user's default sound choice * (optional) * * @param sound THe sound enum * @return JPushover instance */ public final JPushover withSound(final Sound sound) { this.pushoverSound = sound; return this; } /** * Callback parameter may be supplied with a publicly-accessible URL that the * pushover servers will send a request to when the user has acknowledged your * notification. * Only required if priority is set to emergency. * * @param callback The callback URL * @return JPushover instance */ public final JPushover withCallback(final String callback) { this.pushoverCallback = callback; return this; } /** * Uses the given proxy for HTTP requests * * @param proxy The host that should be used as Proxy * @return JPushover instance */ public final JPushover withProxy(final HttpHost proxy) { this.proxy = proxy; return this; } /** * Sends a validation request to pushover ensuring that the token and user * is correct, that there is at least one active device on the account. * * Requires token parameter * Requires user parameter * Optional device parameter to check specific device * * @return true if token and user are valid and at least on device is on the account, false otherwise */ public boolean validate() { Objects.requireNonNull(this.pushoverToken, "Token is required for validation"); Objects.requireNonNull(this.pushoverUser, "User is required for validation"); final List<NameValuePair> params = Form.form() .add(Constants.TOKEN.toString(), this.pushoverToken) .add(Constants.USER.toString(), this.pushoverUser) .add(Constants.DEVICE.toString(), this.pushoverDevice) .build(); boolean valid = false; try { final Request request = Request.Post(Constants.VALIDATION_URL.toString()); if (proxy != null) { request.viaProxy(proxy); } final HttpResponse httpResponse = request .bodyForm(params, Consts.UTF_8) .execute() .returnResponse(); if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HTTP_OK) { final String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8); if (StringUtils.isNotBlank(response) && response.contains("\"status\":1")) { valid = true; } } } catch (final IOException e) { LOG.error("Failed to send validation requeste to pushover", e); } return valid; } /** * Sends a message to pushover * * @return JPushoverResponse instance */ public final JPushoverResponse push() { Objects.requireNonNull(this.pushoverToken, "Token is required for a message"); Objects.requireNonNull(this.pushoverUser, "User is required for a message"); Objects.requireNonNull(this.pushoverMessage, "Message is required for a message"); if (Priority.EMERGENCY.equals(this.pushoverPriority)) { Objects.requireNonNull(this.pushoverRetry, "Retry is required on priority emergency"); Objects.requireNonNull(this.pushoverExpire, "Expire is required on priority emergency"); } final List<NameValuePair> params = Form.form() .add(Constants.TOKEN.toString(), this.pushoverToken) .add(Constants.USER.toString(), this.pushoverUser) .add(Constants.MESSAGE.toString(), this.pushoverMessage) .add(Constants.DEVICE.toString(), this.pushoverDevice) .add(Constants.TITLE.toString(), this.pushoverTitle) .add(Constants.URL.toString(), this.pushoverUrl) .add(Constants.RETRY.toString(), this.pushoverRetry) .add(Constants.EXPIRE.toString(), this.pushoverExpire) .add(Constants.CALLBACK.toString(), this.pushoverCallback) .add(Constants.URLTITLE.toString(), this.pushoverUrlTitle) .add(Constants.PRIORITY.toString(), this.pushoverPriority.toString()) .add(Constants.TIMESTAMP.toString(), this.pushoverTimestamp) .add(Constants.SOUND.toString(), this.pushoverSound.toString()) .add(Constants.HTML.toString(), this.pushoverHtml ? "1" : "0") .build(); final JPushoverResponse jPushoverResponse = new JPushoverResponse().isSuccessful(false); try { final HttpResponse httpResponse = Request.Post(Constants.MESSAGES_URL.toString()) .bodyForm(params, Consts.UTF_8) .execute() .returnResponse(); if (httpResponse != null) { final int status = httpResponse.getStatusLine().getStatusCode(); jPushoverResponse .httpStatus(status) .response(IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8)) .isSuccessful((status == HTTP_OK) ? true : false); } } catch (final IOException e) { LOG.error("Failed to send message to pushover", e); } return jPushoverResponse; } public String getToken() { return pushoverToken; } public String getUser() { return pushoverUser; } public String getMessage() { return pushoverMessage; } public String getDevice() { return pushoverDevice; } public String getTitle() { return pushoverTitle; } public String getUrl() { return pushoverUrl; } public String getUrlTitle() { return pushoverUrlTitle; } public String getTimestamp() { return pushoverTimestamp; } public String getRetry() { return pushoverRetry; } public String getExpire() { return pushoverExpire; } public String getCallback() { return pushoverCallback; } public Priority getPriority() { return pushoverPriority; } public Sound getSound() { return pushoverSound; } public boolean isHtml() { return pushoverHtml; } public HttpHost getProxy() { return proxy; } }
package org.eclipse.birt.report.model.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.birt.report.model.api.AbstractThemeHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.command.ContentException; import org.eclipse.birt.report.model.api.core.IModuleModel; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.metadata.IElementDefn; import org.eclipse.birt.report.model.api.metadata.IPredefinedStyle; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.birt.report.model.api.validators.ThemeStyleNameValidator; import org.eclipse.birt.report.model.elements.DataSet; import org.eclipse.birt.report.model.elements.Library; import org.eclipse.birt.report.model.elements.ListingElement; import org.eclipse.birt.report.model.elements.MasterPage; import org.eclipse.birt.report.model.elements.MultiViews; import org.eclipse.birt.report.model.elements.ReportItem; import org.eclipse.birt.report.model.elements.ReportItemTheme; import org.eclipse.birt.report.model.elements.TableItem; import org.eclipse.birt.report.model.elements.TemplateElement; import org.eclipse.birt.report.model.elements.interfaces.ICubeModel; import org.eclipse.birt.report.model.elements.interfaces.IDimensionModel; import org.eclipse.birt.report.model.elements.interfaces.IListingElementModel; import org.eclipse.birt.report.model.elements.interfaces.ITableItemModel; import org.eclipse.birt.report.model.elements.interfaces.ITabularDimensionModel; import org.eclipse.birt.report.model.elements.olap.Cube; import org.eclipse.birt.report.model.elements.olap.Dimension; import org.eclipse.birt.report.model.metadata.MetaDataDictionary; import org.eclipse.birt.report.model.util.ContentExceptionFactory; import org.eclipse.birt.report.model.util.ContentIterator; class ContainerContextProviderImpl { /** * The container element. */ protected ContainerContext focus = null; /** * @param containerInfo */ public ContainerContextProviderImpl( ContainerContext containerInfo ) { if ( containerInfo == null ) throw new IllegalArgumentException( "The containerInfo of this context should not be null" ); //$NON-NLS-1$ this.focus = containerInfo; } // refactor codes /** * Determines if the slot can contain an element with the type of * <code>type</code>. * * @param module * * @param propName * the slot id * @param type * the name of the element type, like "Table", "List", etc. * @return <code>true</code> if the slot can contain the an element with * <code>type</code> type, otherwise <code>false</code>. * * @see #canContain(int, DesignElementHandle) */ public final boolean canContain( Module module, String type ) { if ( type == null ) return false; return canContain( module, MetaDataDictionary.getInstance( ) .getElement( type ) ); } /** * Determines if the slot can contain a given element. * * @param module * the module * @param element * the element to insert * @return a list containing exceptions. */ public final boolean canContain( Module module, DesignElement element ) { if ( module != null && module.isReadOnly( ) ) return false; List<SemanticException> errors = checkContainmentContext( module, element ); if ( !errors.isEmpty( ) ) return false; return true; } /** * Determines if the current element can contain an element with the * definition of <code>elementType</code> on context containment. * * @param module * the module * @param defn * the definition of the element * @return <code>true</code> if the slot can contain the an element, * otherwise <code>false</code>. */ public boolean canContain( Module module, IElementDefn defn ) { if ( defn == null || ( module != null && module.isReadOnly( ) ) ) return false; boolean retValue = canContainInRom( defn ); if ( !retValue ) return false; // if the root of element is included by report/library. Do not // allow // drop. if ( focus.getElement( ).isRootIncludedByModule( ) ) return false; if ( !canContainTemplateElement( module, defn ) ) return false; // Can not change structure of child element or a virtual element( // inside the child ). if ( focus.getElement( ).isVirtualElement( ) || focus.getElement( ).getExtendsName( ) != null ) return false; // A summany table cannot contains any detail rows if ( focus.getElement( ) instanceof TableItem && focus.getElement( ).getBooleanProperty( module, ITableItemModel.IS_SUMMARY_TABLE_PROP ) && focus.containerSlotID == IListingElementModel.DETAIL_SLOT ) return false; // special cases check table header containment. ContainerContext containerInfo = this.focus; while ( containerInfo != null ) { DesignElement container = containerInfo.getElement( ); if ( container instanceof ListingElement || container instanceof MasterPage ) { List<SemanticException> errors = container.checkContent( module, this.focus, defn ); return errors.isEmpty( ); } containerInfo = container.getContainerInfo( ); } return retValue; } /** * Determines if the slot can contain a given element. * * @param module * the module * @param element * the element to insert * @return a list containing exceptions. */ public List<SemanticException> checkContainmentContext( Module module, DesignElement element ) { if ( element == null ) return Collections.emptyList( ); boolean retValue = canContainInRom( element.getDefn( ) ); ContentException e = ContentExceptionFactory.createContentException( focus, element, ContentException.DESIGN_EXCEPTION_INVALID_CONTEXT_CONTAINMENT ); List<SemanticException> errors = new ArrayList<SemanticException>( ); if ( !retValue ) { errors.add( e ); return errors; } // if this element can not be contained in the module, return false; // such as, template elements can not be contained in the libraries, // so either a template table or a real table with a template image // in one cell of it can never be contained in a libraries if ( !canContainTemplateElement( module, element ) ) { errors.add( e ); return errors; } // if the root of element is included by report/library. Do not // allow // drop. if ( focus.getElement( ).isRootIncludedByModule( ) ) { errors.add( e ); return errors; } // Can not change the structure of child element or a virtual // element( // inside the child ). if ( focus.getElement( ).isVirtualElement( ) || focus.getElement( ).getExtendsName( ) != null ) { errors.add( e ); return errors; } // A summany table cannot contains any detail rows if ( focus.getElement( ) instanceof TableItem && focus.getElement( ).getBooleanProperty( module, ITableItemModel.IS_SUMMARY_TABLE_PROP ) && focus.containerSlotID == IListingElementModel.DETAIL_SLOT ) { errors.add( e ); return errors; } if ( focus.getElement( ) instanceof ReportItemTheme ) { ReportItemTheme theme = (ReportItemTheme) focus.getElement( ); String type = theme.getType( theme.getRoot( ) ); String styleName = element.getName( ); IPredefinedStyle style = MetaDataDictionary.getInstance( ) .getPredefinedStyle( styleName ); // first, check the style is the supported predefined styles in this // type of report item theme if ( StringUtil.isBlank( type ) || style == null || !type.equals( style.getType( ) ) ) { errors.add( e ); return errors; } // second, check the style is unique and no another same name style // exists List<SemanticException> exceptions = ThemeStyleNameValidator .getInstance( ).validateForAddingStyle( (AbstractThemeHandle) theme.getHandle( theme .getRoot( ) ), styleName ); if ( exceptions != null && !exceptions.isEmpty( ) ) { errors.addAll( exceptions ); return errors; } } // CAN NOT insert a cube into report design or library, if it contains // any dimension that shares another dimension if ( element instanceof Cube && module instanceof LayoutModule ) { List dimensions = element.getListProperty( module, ICubeModel.DIMENSIONS_PROP ); if ( dimensions != null ) { for ( int i = 0; i < dimensions.size( ); i++ ) { Dimension dimension = (Dimension) dimensions.get( i ); String dimensionName = dimension .getStringProperty( module, ITabularDimensionModel.INTERNAL_DIMENSION_RFF_TYPE_PROP ); if ( dimensionName != null ) { List hierarchies = dimension.getListProperty( module, IDimensionModel.HIERARCHIES_PROP ); if ( hierarchies == null || hierarchies.isEmpty( ) ) { // special exception for this case ContentException exception = new ContentException( focus.getElement( ), focus.getSlotID( ), element, ContentException.DESIGN_EXCEPTION_SHARE_DIMENSION_NOT_EXIST, new String[]{dimensionName} ); errors.add( exception ); return errors; } } } } } // special cases check table header containment. ContainerContext containerInfor = focus; // DesignElement tmpContainer = this.focus; while ( containerInfor != null ) { DesignElement container = containerInfor.getElement( ); if ( container == element ) { errors.add( e ); return errors; } if ( container instanceof ListingElement || container instanceof MasterPage ) { errors = container.checkContent( module, this.focus, element ); if ( errors != null && !errors.isEmpty( ) ) return errors; } containerInfor = container.getContainerInfo( ); } // when add multiviews for this element: check the case that is not // allowed: this element defines its data object(data set or cube) and // any of its children defines another different data object if ( focus.getElement( ) instanceof MultiViews || element instanceof MultiViews ) { if ( !checkMutliViews( module, element ) ) { errors.add( e ); return errors; } } if ( element instanceof ReportItem ) { ReportItem item = (ReportItem) element; DataSet dataSet = (DataSet) item.getDataSetElement( module ); Cube cube = (Cube) item.getCubeElement( module ); if ( !ContainerContext.isValidContainerment( module, focus .getElement( ), item, dataSet, cube ) ) { errors.add( e ); return errors; } } return Collections.emptyList( ); } private boolean checkMutliViews( Module module, DesignElement element ) { DesignElement targetReportItem = null; if ( element instanceof MultiViews ) { targetReportItem = focus.getElement( ); } else { targetReportItem = focus.getElement( ).getContainer( ); } if ( targetReportItem instanceof ReportItem ) { ReportItem item = (ReportItem) targetReportItem; DataSet dataSet = (DataSet) item.getDataSetElement( module ); Cube cube = (Cube) item.getCubeElement( module ); // if the container defines its data object, then check whether // any of its children defines different data object if ( dataSet != null || cube != null ) { ContentIterator iter = new ContentIterator( module, item ); while ( iter.hasNext( ) ) { DesignElement child = iter.next( ); if ( child instanceof ReportItem ) { ReportItem childItem = (ReportItem) child; DataSet childDataSet = (DataSet) childItem .getDataSetElement( module ); Cube childCube = (Cube) childItem .getCubeElement( module ); if ( childDataSet == null && childCube == null ) continue; // if any of its children defines different data // object, then invalid container context if ( ( childDataSet != dataSet && childDataSet != null ) || ( childCube != cube && childCube != null ) ) { return false; } } } } } return true; } /** * Checks whether a type of elements can reside in the given slot of the * current element. Besides the type check, it also checks the cardinality * of this slot. * * @param slotId * the slot id of the current element * @param defn * the element definition * * @return <code>true</code> if elements with the definition * <code>definition</code> can reside in the given slot. Otherwise * <code>false</code>. */ private boolean canContainInRom( IElementDefn defn ) { if ( !focus.canContainInRom( defn ) ) return false; // if the canContain is check for create template, then jump the // slot // count check for the operation won't change the content count, it // is a // replace operation. String name = defn.getName( ); if ( ReportDesignConstants.TEMPLATE_DATA_SET.equals( name ) || ReportDesignConstants.TEMPLATE_REPORT_ITEM.equals( name ) || ReportDesignConstants.TEMPLATE_ELEMENT.equals( name ) ) return true; if ( focus.getContentCount( focus.getElement( ).getRoot( ) ) > 0 && !focus.isContainerMultipleCardinality( ) ) return false; return true; } /** * Checks whether the element to insert can reside in the given module. * * @param module * the root module of the element to add * @param slotID * the slot ID to insert * @param element * the element to insert * @return false if the module is a library and the element to insert is a * template element or its content is a template element; or the * container is report design and slot is component slot and the * element to insert is a template element or its content is a * template element; otherwise true */ private boolean canContainTemplateElement( Module module, DesignElement element ) { // if this element is a kind of template element or any its content // is a // kind of template element, return false IElementDefn defn = MetaDataDictionary.getInstance( ).getElement( ReportDesignConstants.TEMPLATE_ELEMENT ); if ( element instanceof TemplateElement ) return canContainTemplateElement( module, defn ); ContentIterator contents = new ContentIterator( module, element ); while ( contents.hasNext( ) ) { DesignElement content = contents.next( ); if ( content instanceof TemplateElement ) return canContainTemplateElement( module, defn ); } return true; } /** * Checks whether the element to insert can reside in the given module. * * @param module * the root module of the element to add * @param slotID * the slot ID to insert * @param defn * the definition of element to insert * @return false if the module is a library and the element to insert is a * template element or its content is a template element; or the * container is report design and slot is component slot and the * element to insert is a template element or its content is a * template element; otherwise true */ private boolean canContainTemplateElement( Module module, IElementDefn defn ) { // if this element is a kind of template element or any its content // is a // kind of template element, return false if ( defn != null && defn.isKindOf( MetaDataDictionary.getInstance( ).getElement( ReportDesignConstants.TEMPLATE_ELEMENT ) ) ) { // components in the design/library cannot contain template // elements. ContainerContext containerInfo = focus; while ( containerInfo != null ) { DesignElement container = containerInfo.getElement( ); if ( ( container instanceof Module && containerInfo.getSlotID( ) == IModuleModel.COMPONENT_SLOT ) || container instanceof Library ) return false; containerInfo = container.getContainerInfo( ); } if ( module instanceof Library ) return false; } return true; } }
package de.tototec.utils.functional; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public abstract class FList { // TODO: concat public static <T, A extends T, B extends T> List<T> concat(final A[] first, final B[] second) { return concat(Arrays.asList(first), Arrays.asList(second)); } public static <T, A extends T, B extends T> List<T> concat(final Iterable<A> first, final Iterable<B> second) { final LinkedList<T> result = new LinkedList<T>(); for (final A a : first) { result.add(a); } for (final B b : second) { result.add(b); } return result; } public static <T, A extends T, B extends T, C extends T> List<T> concat(final A[] first, final B[] second, final C[] third) { return concat(Arrays.asList(first), Arrays.asList(second), Arrays.asList(third)); } public static <T, A extends T, B extends T, C extends T> List<T> concat(final Iterable<A> first, final Iterable<B> second, final Iterable<C> third) { final LinkedList<T> result = new LinkedList<T>(); for (final A a : first) { result.add(a); } for (final B b : second) { result.add(b); } for (final C c : third) { result.add(c); } return result; } public static <T> boolean contains(final Iterable<T> source, final T element) { for (final T t : source) { if (t == null) { if (element == null) { return true; } } else if (t.equals(element)) { return true; } } return false; } public static <T> boolean contains(final T[] source, final T element) { return contains(Arrays.asList(source), element); } public static <T> boolean containsAll(final Iterable<T> source, final Iterable<T> elements) { for (final T e : elements) { if (!contains(source, e)) { return false; } } return true; } public static <T> boolean containsAll(final Iterable<T> source, final T[] elements) { return containsAll(source, Arrays.asList(elements)); } public static <T> boolean containsAll(final T[] source, final Iterable<T> elements) { return containsAll(Arrays.asList(source), elements); } public static <T> boolean containsAll(final T[] source, final T[] elements) { return containsAll(Arrays.asList(source), Arrays.asList(elements)); } // TODO: diff public static <T> List<T> distinct(final Iterable<T> source) { final List<T> result = new LinkedList<T>(); for (final T t : source) { if (!result.contains(t)) { result.add(t); } } return result; } public static <T> List<T> distinct(final T[] source) { return distinct(Arrays.asList(source)); } public static <T> List<T> dropWhile(final Iterable<T> source, final F1<? super T, Boolean> accept) { final List<T> result = new LinkedList<T>(); boolean drop = true; for (final T t : source) { if (drop && !accept.apply(t)) { drop = false; } if (!drop) { result.add(t); } } return result; } public static <T> List<T> dropWhile(final T[] source, final F1<? super T, Boolean> accept) { return dropWhile(Arrays.asList(source), accept); } public static <T> boolean exists(final Iterable<T> source, final F1<? super T, Boolean> exists) { for (final T t : source) { if (exists.apply(t)) { return true; } } return false; } public static <T> boolean exists(final T[] source, final F1<? super T, Boolean> exists) { return exists(Arrays.asList(source), exists); } // TODO: fill public static <T> List<T> filter(final Iterable<T> source, final F1<? super T, Boolean> accept) { final List<T> result = new LinkedList<T>(); for (final T t : source) { if (accept.apply(t)) { result.add(t); } } return result; } public static <T> List<T> filter(final T[] source, final F1<? super T, Boolean> accept) { return filter(Arrays.asList(source), accept); } public static <T> List<T> filterNotNull(final Iterable<?> source) { final List<T> result = new LinkedList<T>(); for (final Object object : source) { if (object != null) { @SuppressWarnings("unchecked") final T t = (T) object; result.add(t); } } return result; } public static <T> List<T> filterNotNull(final Object[] source) { return filterNotNull(Arrays.asList(source)); } public static <T> List<T> filterType(final Iterable<?> source, final Class<T> type) { final List<T> result = new LinkedList<T>(); for (final Object object : source) { if (object != null && type.isAssignableFrom(object.getClass())) { @SuppressWarnings("unchecked") final T t = (T) object; result.add(t); } } return result; } public static <T> List<T> filterType(final Object[] source, final Class<T> type) { return filterType(Arrays.asList(source), type); } public static <T> Optional<T> find(final Iterable<T> source, final F1<? super T, Boolean> accept) { for (final T t : source) { if (accept.apply(t)) { return Optional.some(t); } } return Optional.none(); } public static <T> Optional<T> find(final T[] source, final F1<? super T, Boolean> accept) { return find(Arrays.asList(source), accept); } public static <T, R> List<R> flatMap(final Iterable<T> source, final F1<? super T, ? extends Iterable<R>> convert) { final List<R> result = (source instanceof Collection<?>) ? new ArrayList<R>(((Collection<?>) source).size()) : new LinkedList<R>(); for (final T t : source) { final Iterable<R> subList = convert.apply(t); if (subList instanceof Collection<?>) { result.addAll((Collection<? extends R>) subList); } else { for (final R r : subList) { result.add(r); } } } return result; } public static <T, R> List<R> flatMap(final T[] source, final F1<? super T, ? extends Iterable<R>> convert) { return flatMap(Arrays.asList(source), convert); } public static <T, R extends Iterable<T>> List<T> flatten(final Iterable<R> source) { final LinkedList<T> result = new LinkedList<T>(); for (final Iterable<T> list : source) { if (list instanceof Collection<?>) { result.addAll((Collection<? extends T>) list); } else { for (final T t : list) { result.add(t); } } } return result; } public static <T, R extends Iterable<T>> List<T> flatten(final R[] source) { return flatten(Arrays.asList(source)); } public static <T> List<T> flatten(final T[][] source) { final LinkedList<T> result = new LinkedList<T>(); for (final T[] list : source) { for (final T t : list) { result.add(t); } } return result; } public static <T, R> R foldLeft(final Iterable<T> source, final R left, final F2<R, ? super T, R> fold) { R theLeft = left; for (final T t : source) { theLeft = fold.apply(theLeft, t); } return theLeft; } public static <T, R> R foldLeft(final T[] source, final R left, final F2<R, ? super T, R> fold) { return foldLeft(Arrays.asList(source), left, fold); } public static <T, R> R foldRight(final Iterable<T> source, final F2<? super T, R, R> fold, final R right) { final List<T> list = source instanceof List<?> ? (List<T>) source : map(source, new F1.Identity<T>()); R theRight = right; for (int i = list.size() - 1; i >= 0; --i) { theRight = fold.apply(list.get(i), theRight); } return theRight; } public static <T, R> R foldRight(final T[] source, final F2<? super T, R, R> fold, final R right) { R theRight = right; for (int i = source.length - 1; i >= 0; --i) { theRight = fold.apply(source[i], theRight); } return theRight; } public static <T> boolean forall(final Iterable<T> source, final F1<? super T, Boolean> forall) { for (final T t : source) { if (!forall.apply(t)) { return false; } } return true; } public static <T> boolean forall(final T[] source, final F1<? super T, Boolean> forall) { return forall(Arrays.asList(source), forall); } public static <T> void foreach(final Iterable<T> source, final Procedure1<? super T> foreach) { for (final T t : source) { foreach.apply(t); } } public static <T> void foreach(final T[] source, final Procedure1<? super T> foreach) { foreach(Arrays.asList(source), foreach); } public static <T, K> Map<K, List<T>> groupBy(final T[] source, final F1<? super T, ? extends K> groupBy) { return groupBy(Arrays.asList(source), groupBy); } public static <T, K> Map<K, List<T>> groupBy(final Iterable<T> source, final F1<? super T, ? extends K> groupBy) { final Map<K, List<T>> result = new LinkedHashMap<K, List<T>>(); for (final T t : source) { final K key = groupBy.apply(t); final List<T> list; if (result.containsKey(key)) { list = result.get(key); } else { list = new LinkedList<T>(); result.put(key, list); } list.add(t); } return result; } public static <T> Optional<T> headOption(final Iterable<T> source) { final Iterator<T> it = source.iterator(); if (it.hasNext()) { return Optional.some(it.next()); } else { return Optional.<T> none(); } } public static <T> Optional<T> headOption(final T[] source) { if (source.length == 0) { return Optional.<T> none(); } else { return Optional.some(source[0]); } } public static <T, R> List<R> map(final Iterable<T> source, final F1<? super T, ? extends R> convert) { final List<R> result = (source instanceof Collection<?>) ? new ArrayList<R>(((Collection<?>) source).size()) : new LinkedList<R>(); for (final T t : source) { result.add(convert.apply(t)); } return result; } // TODO: intersect public static <T, R> List<R> map(final T[] source, final F1<? super T, ? extends R> convert) { return map(Arrays.asList(source), convert); } public static String mkString(final Iterable<?> source, final String separator) { return mkString(source, null, separator, null); } public static String mkString(final Object[] source, final String separator) { return mkString(Arrays.asList(source), separator); } public static String mkString(final Iterable<?> source, final String prefix, final String separator, final String suffix) { return mkString(source, prefix, separator, suffix, null); } public static <T> String mkString(final T[] source, final String prefix, final String separator, final String suffix) { return mkString(Arrays.asList(source), prefix, separator, suffix); } public static <T> String mkString(final Iterable<T> source, final String prefix, final String separator, final String suffix, final F1<? super T, String> convert) { final StringBuilder result = new StringBuilder(); if (prefix != null) { result.append(prefix); } boolean sep = false; for (final T t : source) { if (sep && separator != null) { result.append(separator); } sep = true; if (convert != null) { result.append(convert.apply(t)); } else { result.append(t == null ? null : t.toString()); } } if (suffix != null) { result.append(suffix); } return result.toString(); } public static <T> String mkString(final T[] source, final String prefix, final String separator, final String suffix, final F1<? super T, String> convert) { return mkString(Arrays.asList(source), prefix, separator, suffix, convert); } public static <T> Tuple2<List<T>, List<T>> partition(final Iterable<T> source, final F1<? super T, Boolean> predicate) { final List<T> left = new LinkedList<T>(); final List<T> right = new LinkedList<T>(); for (final T t : source) { if (predicate.apply(t)) { left.add(t); } else { right.add(t); } } return Tuple2.of(left, right); } public static <T> Tuple2<List<T>, List<T>> partition(final T[] source, final F1<? super T, Boolean> predicate) { return partition(Arrays.asList(source), predicate); } public static <T> List<T> reverse(final Iterable<T> source) { if (source instanceof Collection<?>) { final ArrayList<T> result = new ArrayList<T>((Collection<T>) source); Collections.reverse(result); return result; } else { final LinkedList<T> result = new LinkedList<T>(); for (final T t : source) { result.add(0, t); } return result; } } public static <T> List<T> reverse(final T[] source) { return reverse(Arrays.asList(source)); } public static <T> List<T> sort(final Iterable<T> source, final Comparator<? super T> comparator) { final List<T> result; if (source instanceof Collection<?>) { result = new ArrayList<T>((Collection<T>) source); } else { result = new ArrayList<T>(); for (final T t : source) { result.add(t); } } Collections.sort(result, comparator); return result; } public static <T> List<T> sort(final T[] source, final Comparator<? super T> comparator) { return sort(Arrays.asList(source), comparator); } public static <T, C extends Comparable<C>> List<T> sortWith(final Iterable<T> source, final F1<? super T, C> convert) { return sort(source, new Comparator<T>() { @Override public int compare(final T o1, final T o2) { return convert.apply(o1).compareTo(convert.apply(o2)); }; }); } public static <T, C extends Comparable<C>> List<T> sortWith(final T[] source, final F1<? super T, C> convert) { return sortWith(Arrays.asList(source), convert); } public static <T> List<T> tail(final Iterable<T> source) { final Iterator<T> it = source.iterator(); if (it.hasNext()) { // drop first element it.next(); } final List<T> result = new LinkedList<T>(); while (it.hasNext()) { result.add(it.next()); } return result; } public static <T> List<T> tail(final T[] source) { return tail(Arrays.asList(source)); } public static <T> List<T> takeWhile(final Iterable<T> source, final F1<? super T, Boolean> accept) { final List<T> result = new LinkedList<T>(); for (final T t : source) { if (accept.apply(t)) { result.add(t); } else { break; } } return result; } public static <T> List<T> takeWhile(final T[] source, final F1<? super T, Boolean> accept) { return takeWhile(Arrays.asList(source), accept); } public static <K, V> LinkedHashMap<K, V> toHashMap(final Iterable<Tuple2<K, V>> source) { final LinkedHashMap<K, V> result = new LinkedHashMap<K, V>(); for (final Tuple2<K, V> tuple2 : source) { result.put(tuple2.a(), tuple2.b()); } return result; } public static <K, V> LinkedHashMap<K, V> toHashMap(final Tuple2<K, V>[] source) { return toHashMap(Arrays.asList(source)); } // TODO: union public static <A, B> List<Tuple2<A, B>> zip(final A[] as, final B[] bs) { return zip(Arrays.asList(as), Arrays.asList(bs)); } public static <A, B> List<Tuple2<A, B>> zip(final Iterable<A> as, final Iterable<B> bs) { final List<Tuple2<A, B>> result = new LinkedList<Tuple2<A, B>>(); final Iterator<A> aIt = as.iterator(); final Iterator<B> bIt = bs.iterator(); while (aIt.hasNext() && bIt.hasNext()) { result.add(Tuple2.of(aIt.next(), bIt.next())); } return result; } private FList() { // no inheritance useful } }
package edu.ucsd.sbrg.bigg; import static edu.ucsd.sbrg.bigg.ModelPolisher.mpMessageBundle; import static java.text.MessageFormat.format; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.*; import java.util.Map.Entry; import java.util.logging.Logger; import javax.swing.tree.TreeNode; import javax.xml.stream.XMLStreamException; import org.sbml.jsbml.*; import org.sbml.jsbml.CVTerm.Qualifier; import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCModelPlugin; import org.sbml.jsbml.ext.fbc.FBCSpeciesPlugin; import org.sbml.jsbml.ext.fbc.GeneProduct; import org.sbml.jsbml.ext.groups.Group; import org.sbml.jsbml.ext.groups.GroupsConstants; import org.sbml.jsbml.ext.groups.GroupsModelPlugin; import org.sbml.jsbml.util.Pair; import de.zbit.util.ResourceManager; import de.zbit.util.Utils; import edu.ucsd.sbrg.miriam.Registry; import edu.ucsd.sbrg.util.SBMLUtils; /** * @author Thomas Zajac * This code runs only, if ANNOTATE_WITH_BIGG is true */ public class BiGGAnnotation { /** * BiGGBD instance, contains methods to run specific queries against the BiGG db */ private BiGGDB bigg; /** * AnnotateDB instance, contains methods to run specific queries against the AnnotateDB */ private AnnotateDB adb; /** * SBMLPolisher instance, containing methods and booleans used by BiGGAnnotation */ private SBMLPolisher polisher; /** * A {@link Logger} for this class. */ static final transient Logger logger = Logger.getLogger(BiGGAnnotation.class.getName()); /** * Localization support. */ private static final transient ResourceBundle baseBundle = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); /** * Default model notes. */ private String modelNotes = "ModelNotes.html"; /** * Mapping for generic placeholder entries in notes files to actual values */ protected Map<String, String> replacements; /** * Default document notes */ private String documentNotesFile = "SBMLDocumentNotes.html"; /** * @param bigg * @param adb * @param polisher */ public BiGGAnnotation(BiGGDB bigg, AnnotateDB adb, SBMLPolisher polisher) { this.bigg = bigg; this.adb = adb; this.polisher = polisher; } /** * @param doc * @return */ SBMLDocument annotate(SBMLDocument doc) { if (!doc.isSetModel()) { logger.info(baseBundle.getString("NO_MODEL_FOUND")); return doc; } Model model = doc.getModel(); replacements = new HashMap<>(); annotate(model); try { appendNotes(doc); } catch (IOException | XMLStreamException exc) { logger.warning(baseBundle.getString("FAILED_WRITE_NOTES")); } // Recursively sort and group all annotations in the SBMLDocument. mergeMIRIAMannotations(doc); return doc; } /** * @param model */ private void annotate(Model model) { String organism = bigg.getOrganism(model.getId()); Integer taxonId = bigg.getTaxonId(model.getId()); if (taxonId != null) { model.addCVTerm(new CVTerm(CVTerm.Qualifier.BQB_HAS_TAXON, polisher.createURI("taxonomy", taxonId))); } // Note: date is probably not accurate. // Date date = bigg.getModelCreationDate(model.getId()); // if (date != null) { // History history = model.createHistory(); // history.setCreatedDate(date); String name = polisher.getDocumentTitlePattern(); name = name.replace("[biggId]", model.getId()); name = name.replace("[organism]", organism); replacements.put("${title}", name); replacements.put("${organism}", organism); replacements.put("${bigg_id}", model.getId()); replacements.put("${year}", Integer.toString(Calendar.getInstance().get(Calendar.YEAR))); replacements.put("${bigg.timestamp}", format("{0,date}", bigg.getBiGGVersion())); replacements.put("${species_table}", ""); // XHTMLBuilder.table(header, data, "Species", attributes)); if (!model.isSetName()) { model.setName(organism); } if (bigg.isModel(model.getId())) { model.addCVTerm(new CVTerm(CVTerm.Qualifier.BQM_IS, polisher.createURI("bigg.model", model.getId()))); } if (!model.isSetMetaId() && (model.getCVTermCount() > 0)) { model.setMetaId(model.getId()); } annotatePublications(model); annotateListOfCompartments(model); annotateListOfSpecies(model); annotateListOfReactions(model); annotateListOfGeneProducts(model); } /** * Replaces generic placeholders in notes files and appends both note types * * @param doc * @throws IOException * @throws XMLStreamException */ private void appendNotes(SBMLDocument doc) throws IOException, XMLStreamException { if (replacements.containsKey("${title}") && (documentNotesFile != null)) { doc.appendNotes(parseNotes(documentNotesFile, replacements)); } if (modelNotes != null) { doc.getModel().appendNotes(parseNotes(modelNotes, replacements)); } } /** * Recursively goes through all annotations in the given {@link SBase} and * alphabetically sort annotations after grouping them by {@link org.sbml.jsbml.CVTerm.Qualifier}. * * @param sbase */ private void mergeMIRIAMannotations(SBase sbase) { if (sbase.isSetAnnotation()) { SortedMap<Qualifier, SortedSet<String>> miriam = new TreeMap<>(); boolean doMerge = hashMIRIAMuris(sbase, miriam); if (doMerge) { sbase.getAnnotation().unsetCVTerms(); for (Entry<Qualifier, SortedSet<String>> entry : miriam.entrySet()) { logger.info(format(baseBundle.getString("MERGING_MIRIAM_RESOURCES"), entry.getKey(), sbase.getClass().getSimpleName(), sbase.getId())); sbase.addCVTerm(new CVTerm(entry.getKey(), entry.getValue().toArray(new String[0]))); } } } for (int i = 0; i < sbase.getChildCount(); i++) { TreeNode node = sbase.getChildAt(i); if (node instanceof SBase) { mergeMIRIAMannotations((SBase) node); } } } /** * @param sbase * @param miriam * @return */ private boolean hashMIRIAMuris(SBase sbase, SortedMap<Qualifier, SortedSet<String>> miriam) { boolean doMerge = false; for (int i = 0; i < sbase.getCVTermCount(); i++) { CVTerm term = sbase.getCVTerm(i); Qualifier qualifier = term.getQualifier(); if (miriam.containsKey(qualifier)) { doMerge = true; } else { if (sbase instanceof Model) { if (!qualifier.isModelQualifier()) { logger.info(format(baseBundle.getString("CORRECTING_INVALID_QUALIFIERS"), qualifier.getElementNameEquivalent(), sbase.getId())); qualifier = Qualifier.getModelQualifierFor(qualifier.getElementNameEquivalent()); } } else if (!qualifier.isBiologicalQualifier()) { logger.info(format(baseBundle.getString("CORRECTING_INVALID_MODEL_QUALIFIER"), qualifier.getElementNameEquivalent(), sbase.getClass().getSimpleName(), sbase.getId())); qualifier = Qualifier.getBiologicalQualifierFor(qualifier.getElementNameEquivalent()); } miriam.put(qualifier, new TreeSet<>()); } miriam.get(qualifier).addAll(term.getResources()); } return doMerge; } /** * @param model */ private void annotatePublications(Model model) { List<Pair<String, String>> publications = null; try { publications = bigg.getPublications(model.getId()); } catch (SQLException exc) { logger.severe(format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } int numPublications; if (publications != null && (numPublications = publications.size()) > 0) { String resources[] = new String[numPublications]; int i = 0; for (Pair<String, String> publication : publications) { resources[i++] = polisher.createURI(publication.getKey(), publication.getValue()); } model.addCVTerm(new CVTerm(CVTerm.Qualifier.BQM_IS_DESCRIBED_BY, resources)); } } /** * @param model */ private void annotateListOfCompartments(Model model) { for (int i = 0; i < model.getCompartmentCount(); i++) { annotateCompartment(model.getCompartment(i)); } } /** * @param compartment */ private void annotateCompartment(Compartment compartment) { BiGGId biggId = new BiGGId(compartment.getId()); if (bigg.isCompartment(biggId.getAbbreviation())) { compartment.addCVTerm(new CVTerm(CVTerm.Qualifier.BQB_IS, polisher.createURI("bigg.compartment", biggId))); compartment.setSBOTerm(SBO.getCompartment()); // physical compartment if (!compartment.isSetName() || compartment.getName().equals("default")) { String name = bigg.getCompartmentName(biggId); if ((name != null) && !name.isEmpty()) { compartment.setName(name); } } } } /** * @param model */ private void annotateListOfSpecies(Model model) { for (int i = 0; i < model.getSpeciesCount(); i++) { annotateSpecies(model.getSpecies(i)); } } /** * @param species */ private void annotateSpecies(Species species) { String id = species.getId(); //extracting BiGGId if not present for species boolean isBiGGid = id.matches("^([RMG])_([a-zA-Z][a-zA-Z0-9_]+)(?:_([a-z][a-z0-9]?))?(?:_([A-Z][A-Z0-9]?))?$"); if(!isBiGGid){ Annotation annotation = species.getAnnotation(); ArrayList<String> list_Uri = new ArrayList<>(); for(CVTerm cvTerm : annotation.getListOfCVTerms()){ list_Uri.addAll(cvTerm.getResources()); } if(!list_Uri.isEmpty()) { String temp; temp = getSpeciesBiGGIdFromUriList(list_Uri); if(temp!=null) { //update the id in species id = temp; } } } //This biggId corresponds to BiGGId calculated from getSpeciesBiGGIdFromUriList method, if not present as species.id BiGGId biggId = polisher.extractBiGGId(id); if (biggId == null) { return; } setSpeciesName(species, biggId); setSBOTermFromComponentType(species, biggId); setCVTermResources(species, biggId); FBCSetFormulaCharge(species, biggId); } /** * @param list_Uri */ private String getSpeciesBiGGIdFromUriList(List<String> list_Uri){ String biggId = null; for(String uri : list_Uri){ String dataSource, synonym_id, currentBiGGId; //currentBiGGId is id calculated in current iteration synonym_id = uri.substring(uri.lastIndexOf('/')+1); //crop uri to remove synonym identifier from end uri = uri.substring(0,uri.lastIndexOf('/')); dataSource = uri.substring(uri.lastIndexOf('/')+1); //updating the dataSource and synonym_id to match bigg database switch (dataSource){ //bigg.metabolite data_source identifier will directly give biggId case "bigg.metabolite": return "M_"+synonym_id; case "metanetx.chemical" : dataSource = "mnx.chemical"; break; case "chebi" : break; case "kegg.compound" : break; case "hmdb" : break; case "lipidmaps" : break; case "kegg.drug" : break; case "seed.compound" : break; case "biocyc" : break; case "sgd" : return null; //it maps to a gene not a component case "uniprot" : return null; //it maps to a gene not a component default: return null; //the dataSource must belong one of above } currentBiGGId = bigg.getBiggIdFromSynonym(dataSource,synonym_id,BiGGDB.TYPE_SPECIES); if(currentBiGGId!=null){ if(biggId==null){ biggId = currentBiGGId; }else { //we must get same biggId from each synonym if(!currentBiGGId.equals(biggId)) return null; } } } return biggId == null ? null : "M_"+biggId; } /** * @param species * @param biggId */ private void setSpeciesName(Species species, BiGGId biggId) { if (!species.isSetName() || species.getName().equals(format("{0}_{1}", biggId.getAbbreviation(), biggId.getCompartmentCode()))) { try { species.setName(polisher.polishName(bigg.getComponentName(biggId))); } catch (SQLException exc) { logger.severe(format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } } } /** * @param species * @param biggId */ private void setSBOTermFromComponentType(Species species, BiGGId biggId) { String type = bigg.getComponentType(biggId); if (type == null) { return; } switch (type) { case "metabolite": species.setSBOTerm(SBO.getSimpleMolecule()); break; case "protein": species.setSBOTerm(SBO.getProtein()); break; default: if (polisher.omitGenericTerms) { species.setSBOTerm(SBO.getMaterialEntity()); } break; } } /** * @param species * @param biggId */ private void setCVTermResources(Species species, BiGGId biggId) { //Set of annotations calculated from BiGGDB and AnnotateDB Set<String> annotations_set = new HashSet<>(); CVTerm cvTerm = new CVTerm(Qualifier.BQB_IS); //using BiGG Database if (bigg.isMetabolite(biggId.getAbbreviation())) { annotations_set.add(polisher.createURI("bigg.metabolite", biggId)); } try { TreeSet<String> linkOut = bigg.getResources(biggId, polisher.includeAnyURI, false); // convert to set to remove possible duplicates; TreeSet respects order annotations_set.addAll(linkOut); } catch (SQLException exc) { logger.severe(format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } //using AnnotateDB if(adb!=null) { TreeSet<String> adb_annotations = adb.getAnnotations(AnnotateDB.BIGG_METABOLITE, biggId.getIdString()); annotations_set.addAll(adb_annotations); } //adding annotations to cvTerm for(String annotation : annotations_set){ cvTerm.addResource(annotation); } if (cvTerm.getResourceCount() > 0) { species.addCVTerm(cvTerm); } if ((species.getCVTermCount() > 0) && !species.isSetMetaId()) { species.setMetaId(species.getId()); } } /** * @param species * @param biggId */ @SuppressWarnings("deprecation") private void FBCSetFormulaCharge(Species species, BiGGId biggId) { String modelId = species.getModel().getId(); String compartmentCode = biggId.getCompartmentCode(); FBCSpeciesPlugin fbcSpecPlug = (FBCSpeciesPlugin) species.getPlugin(FBCConstants.shortLabel); if (!fbcSpecPlug.isSetChemicalFormula()) { String chemicalFormula = null; if (bigg.isModel(modelId)) { chemicalFormula = bigg.getChemicalFormula(biggId.getAbbreviation(), species.getModel().getId()); } else if (compartmentCode != null && !compartmentCode.equals("")) { chemicalFormula = bigg.getChemicalFormulaByCompartment(biggId.getAbbreviation(), compartmentCode); } try { fbcSpecPlug.setChemicalFormula(chemicalFormula); } catch (IllegalArgumentException exc) { logger.severe(format(mpMessageBundle.getString("CHEM_FORMULA_INVALID"), Utils.getMessage(exc))); } } Integer charge = null; if (bigg.isModel(modelId)) { charge = bigg.getCharge(biggId.getAbbreviation(), species.getModel().getId()); } else if (compartmentCode != null && !compartmentCode.equals("")) { charge = bigg.getChargeByCompartment(biggId.getAbbreviation(), biggId.getCompartmentCode()); } if (species.isSetCharge()) { if ((charge != null) && (charge != species.getCharge())) { logger.warning( format(mpMessageBundle.getString("CHARGE_CONTRADICTION"), charge, species.getCharge(), species.getId())); } species.unsetCharge(); } if ((charge != null) && (charge != 0)) { // If charge is set and charge = 0 -> this can mean it is only a default! fbcSpecPlug.setCharge(charge); } } /** * @param model */ private void annotateListOfReactions(Model model) { for (int i = 0; i < model.getReactionCount(); i++) { annotateReaction(model.getReaction(i)); } } /** * @param reaction */ private void annotateReaction(Reaction reaction) { String id = reaction.getId(); //extract biggId if not present for reaction boolean isBiGGid = id.matches("^([RMG])_([a-zA-Z][a-zA-Z0-9_]+)(?:_([a-z][a-z0-9]?))?(?:_([A-Z][A-Z0-9]?))?$"); if(!isBiGGid){ Annotation annotation = reaction.getAnnotation(); ArrayList<String> list_Uri = new ArrayList<>(); for(CVTerm cvTerm : annotation.getListOfCVTerms()){ list_Uri.addAll(cvTerm.getResources()); } if(!list_Uri.isEmpty()) { String temp; temp = getReactionBiGGIdFromUriList(list_Uri); if(temp!=null) { id = temp; } } } if (!reaction.isSetSBOTerm()) { if (bigg.isPseudoreaction(id)) { reaction.setSBOTerm(631); } else if (!polisher.omitGenericTerms) { reaction.setSBOTerm(375); // generic process } } if ((reaction.getCVTermCount() > 0) && !reaction.isSetMetaId()) { reaction.setMetaId(id); } //This biggId corresponds to BiGGId calculated from getSpeciesBiGGIdFromUriList method, if not present as reaction.id BiGGId biggId = polisher.extractBiGGId(id); if (id.startsWith("R_")) { id = id.substring(2); } String name = bigg.getReactionName(id); if ((name != null) && !name.equals(reaction.getName())) { reaction.setName(polisher.polishName(name)); } List<String> geneReactionRules = bigg.getGeneReactionRule(id, reaction.getModel().getId()); for (String geneRactionRule : geneReactionRules) { SBMLUtils.parseGPR(reaction, geneRactionRule, polisher.omitGenericTerms); } parseSubsystems(reaction, biggId); setCVTermResources(reaction, biggId); } /** * @param list_Uri */ private String getReactionBiGGIdFromUriList(List<String> list_Uri){ String biggId = null; for(String uri : list_Uri){ String dataSource, synonym_id, currentBiGGId; //currentBiGGId is id calculated in current iteration synonym_id = uri.substring(uri.lastIndexOf('/')+1); uri = uri.substring(0,uri.lastIndexOf('/')); dataSource = uri.substring(uri.lastIndexOf('/')+1); //updating the dataSource and synonym_id to match bigg database switch (dataSource){ //bigg.metabolite data_source identifier will directly give biggId case "bigg.reaction": return "R_"+synonym_id; case "metanetx.reaction": dataSource = "mnx.equation"; break; case "kegg.reaction" : break; case "ec-code" : dataSource = "ec"; break; case "rhea" : break; default: return null; //the dataSource must belong one of above } currentBiGGId = bigg.getBiggIdFromSynonym(dataSource,synonym_id,BiGGDB.TYPE_REACTION); if(biggId==null){ biggId = currentBiGGId; }else { //we must get same biggId from each synonym if(!currentBiGGId.equals(biggId)) return null; } } return biggId == null ? null : "R_"+biggId; } /** * @param reaction * @param biggId */ private void parseSubsystems(Reaction reaction, BiGGId biggId) { Model model = reaction.getModel(); List<String> subsystems = bigg.getSubsystems(model.getId(), biggId.getAbbreviation()); if (subsystems.size() < 1) { return; } String groupKey = "GROUP_FOR_NAME"; if (model.getUserObject(groupKey) == null) { model.putUserObject(groupKey, new HashMap<String, Group>()); } @SuppressWarnings("unchecked") Map<String, Group> groupForName = (Map<String, Group>) model.getUserObject(groupKey); for (String subsystem : subsystems) { Group group; if (groupForName.containsKey(subsystem)) { group = groupForName.get(subsystem); } else { GroupsModelPlugin groupsModelPlugin = (GroupsModelPlugin) model.getPlugin(GroupsConstants.shortLabel); group = groupsModelPlugin.createGroup("g" + (groupsModelPlugin.getGroupCount() + 1)); group.setName(subsystem); group.setKind(Group.Kind.partonomy); group.setSBOTerm(633); // subsystem groupForName.put(subsystem, group); } SBMLUtils.createSubsystemLink(reaction, group.createMember()); } } /** * @param reaction * @param biggId */ private void setCVTermResources(Reaction reaction, BiGGId biggId) { //Set of annotations calculated from BiGGDB and AnnotateDB Set<String> annotations_set = new HashSet<>(); CVTerm cvTerm = new CVTerm(Qualifier.BQB_IS); //using BiGG Database if (bigg.isReaction(reaction.getId())) { annotations_set.add(polisher.createURI("bigg.reaction", biggId)); } try { TreeSet<String> linkOut = bigg.getResources(biggId, polisher.includeAnyURI, true); annotations_set.addAll(linkOut); } catch (SQLException exc) { logger.severe(format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } //using AnnotateDB if(adb!=null) { TreeSet<String> adb_annotations = adb.getAnnotations(AnnotateDB.BIGG_REACTION, biggId.getIdString()); annotations_set.addAll(adb_annotations); } //adding annotations to cvTerm for(String annotation : annotations_set){ cvTerm.addResource(annotation); } if (cvTerm.getResourceCount() > 0) { reaction.addCVTerm(cvTerm); } if ((reaction.getCVTermCount() > 0) && !reaction.isSetMetaId()) { reaction.setMetaId(reaction.getId()); } } /** * @param model */ private void annotateListOfGeneProducts(Model model) { if (model.isSetPlugin(FBCConstants.shortLabel)) { FBCModelPlugin fbcModelPlugin = (FBCModelPlugin) model.getPlugin(FBCConstants.shortLabel); for (GeneProduct geneProduct : fbcModelPlugin.getListOfGeneProducts()) { annotateGeneProduct(geneProduct, fbcModelPlugin); } } } /** * @param geneProduct */ private void annotateGeneProduct(GeneProduct geneProduct, FBCModelPlugin fbcModelPlugin) { String label = null; String id = geneProduct.getId(); String calculatedBiGGId = id; boolean isBiGGid = id.matches("^([RMG])_([a-zA-Z][a-zA-Z0-9_]+)(?:_([a-z][a-z0-9]?))?(?:_([A-Z][A-Z0-9]?))?$"); if(!isBiGGid || !bigg.isGenePresentInBigg(geneProduct)){ Annotation annotation = geneProduct.getAnnotation(); ArrayList<String> list_Uri = new ArrayList<>(); for(CVTerm cvTerm : annotation.getListOfCVTerms()){ list_Uri.addAll(cvTerm.getResources()); } if(!list_Uri.isEmpty()) { String temp; temp = getGeneProductBiGGIdFromUriList(list_Uri); if(temp!=null) { //update the id in geneProduct calculatedBiGGId = temp; } } } if (geneProduct.isSetLabel() && !geneProduct.getLabel().equalsIgnoreCase("None")) { label = geneProduct.getLabel(); } else if (geneProduct.isSetId()) { label = id; } if (label == null) { return; } // fix not updated geneProductReference in Association SBMLUtils.updateGeneProductReference(geneProduct); setCVTermResources(geneProduct, calculatedBiGGId); if (geneProduct.getCVTermCount() > 0) { geneProduct.setMetaId(id); } setGPLabelName(geneProduct, label); } private String getGeneProductBiGGIdFromUriList(List<String> list_Uri) { String biggId = null; for(String uri : list_Uri){ String dataSource, synonym_id, currentBiGGId; //currentBiGGId is id calculated in current iteration synonym_id = uri.substring(uri.lastIndexOf('/')+1); uri = uri.substring(0,uri.lastIndexOf('/')); dataSource = uri.substring(uri.lastIndexOf('/')+1); //updating the dataSource and synonym_id to match bigg database switch (dataSource){ case "ncbigi": synonym_id = synonym_id.substring(3); break; case "ncbigene" : break; case "goa" : break; case "interpro" : break; case "asap" : break; case "ecogene" : break; case "uniprot" : break; default: return null; //the dataSource must belong one of above } currentBiGGId = bigg.getBiggIdFromSynonym(dataSource,synonym_id,BiGGDB.TYPE_GENE_PRODUCT); if(biggId==null){ biggId = currentBiGGId; }else { //we must get same biggId from each synonym if(!currentBiGGId.equals(biggId)) return null; } } return biggId == null ? null : "G_"+biggId; } /** * @param geneProduct * @param id */ private void setCVTermResources(GeneProduct geneProduct, String id) { CVTerm termIs = new CVTerm(Qualifier.BQB_IS); CVTerm termEncodedBy = new CVTerm(Qualifier.BQB_IS_ENCODED_BY); // label is stored without "G_" prefix in BiGG if (id.startsWith("G_")) { id = id.substring(2); } for (String resource : bigg.getGeneIds(id)) { // get Collection part from uri without url prefix - all uris should String collection = Registry.getDataCollectionPartFromURI(resource); if (collection == null) { continue; } else if (!resource.contains("identifiers.org")) { logger.severe(format(mpMessageBundle.getString("PATTERN_MISMATCH_DROP"), collection)); continue; } switch (collection) { case "interpro": case "pdb": case "uniprot": termIs.addResource(resource); break; default: termEncodedBy.addResource(resource); } } if (termIs.getResourceCount() > 0) { geneProduct.addCVTerm(termIs); } if (termEncodedBy.getResourceCount() > 0) { geneProduct.addCVTerm(termEncodedBy); } } /** * @param geneProduct * @param label */ private void setGPLabelName(GeneProduct geneProduct, String label) { // we successfully found information by using the id, so this needs to be the label if (geneProduct.getLabel().equalsIgnoreCase("None")) { geneProduct.setLabel(label); } String geneName = bigg.getGeneName(label); if (geneName != null) { if (geneName.isEmpty()) { logger.fine(format(mpMessageBundle.getString("NO_GENE_FOR_LABEL"), geneProduct.getName())); } else if (geneProduct.isSetName() && !geneProduct.getName().equals(geneName)) { logger.warning(format(mpMessageBundle.getString("UPDATE_GP_NAME"), geneProduct.getName(), geneName)); } geneProduct.setName(geneName); } } /** * Checks resource URIs and logs those not matching the specified pattern * Used to check URIs obtained from BiGGDB * A resource URI that does not match the pattern will be logged and not added * to the model * For a collection not in the registry correctness is assumed * * @param resource: * resource URI to be added as annotation * @return corrected resource URI */ static String checkResourceUrl(String resource) { String collection = Registry.getDataCollectionPartFromURI(resource); String identifier = Registry.getIdentifierFromURI(resource); if (collection.isEmpty()) { // not a valid resource URI, drop return null; } else if (!isCheckable(resource, collection)) { return resource; } else if (!resource.contains("identifiers.org")) { collection = Registry.getCollectionFor(resource); if (!collection.isEmpty()) { resource = Registry.getURI(collection, identifier); } } String regexp = Registry.getPattern(collection); if (regexp.equals("")) { logger.severe(format(mpMessageBundle.getString("UNCAUGHT_URI"), resource)); return resource; } Boolean correct = Registry.checkPattern(identifier, collection); String report_resource = resource; if (!correct) { logger.info(format(mpMessageBundle.getString("PATTERN_MISMATCH_INFO"), identifier, regexp, collection)); resource = fixResource(resource, identifier); } if (resource == null) { logger.warning(format(mpMessageBundle.getString("CORRECTION_FAILED_DROP"), report_resource, collection)); } logger.fine(format("Added resource {0}", resource)); return resource; } /** * @param resource * @param collection */ private static boolean isCheckable(String resource, String collection) { // not present in miriam boolean checkable = true; if (collection.contains("molecular-networks.com")) { logger.fine(format(mpMessageBundle.getString("NO_URI_CHECK_WARN"), resource)); checkable = false; } return checkable; } /** * @param resource * @param identifier * @return */ private static String fixResource(String resource, String identifier) { if (resource.contains("kegg")) { // We can correct the kegg collection resource = fixKEGGCollection(resource, identifier); } else if (resource.contains("ncbigi")) { // add possibly missing "gi:" prefix to identifier resource = fixGI(resource, identifier); } else if (resource.contains("go") && !resource.contains("goa")) { resource = fixGO(resource, identifier); } else if (resource.contains("ec-code")) { resource = fixECCode(resource, identifier); } else if (resource.contains("rhea") && resource.contains(" // remove last part, it's invalid either way, even though it gets resolved due to misinterpretation as non // existing anchor resource = resource.split(" logger.info(format(mpMessageBundle.getString("CHANGED_RHEA"), resource)); } else if (resource.contains("reactome")) { String resource_old = resource; resource = fixReactome(resource, identifier); logger.info(format(mpMessageBundle.getString("CHANGED_REACTOME"), resource_old, resource)); } else { resource = null; } return resource; } /** * @param resource * @param identifier * @return */ private static String fixKEGGCollection(String resource, String identifier) { if (identifier.startsWith("D")) { logger.info(mpMessageBundle.getString("CHANGE_KEGG_DRUG")); resource = Registry.replace(resource, "kegg.compound", "kegg.drug"); } else if (identifier.startsWith("G")) { logger.info(mpMessageBundle.getString("CHANGE_KEGG_GLYCAN")); resource = Registry.replace(resource, "kegg.compound", "kegg.glycan"); } return resource; } /** * @param resource * @param identifier * @return */ private static String fixGI(String resource, String identifier) { if (!identifier.toLowerCase().startsWith("gi:")) { logger.info(mpMessageBundle.getString("ADD_PREFIX_GI")); return Registry.replace(resource, identifier, "GI:" + identifier); } return resource; } /** * @param resource * @param identifier * @return */ private static String fixGO(String resource, String identifier) { if (!identifier.toLowerCase().startsWith("go:")) { logger.info(mpMessageBundle.getString("ADD_PREFIX_GO")); return Registry.replace(resource, identifier, "GO:" + identifier); } return resource; } /** * @param resource * @param identifier * @return */ private static String fixECCode(String resource, String identifier) { int missingDots = identifier.length() - identifier.replace(".", "").length(); if (missingDots < 1) { logger.warning(format(mpMessageBundle.getString("EC_CHANGE_FAILED"), identifier)); return null; } String replacement = identifier; for (int count = missingDots; count < 3; count++) { replacement += ".-"; } return Registry.replace(resource, identifier, replacement); } /** * @param resource * @param identifier * @return */ private static String fixReactome(String resource, String identifier) { if (!identifier.startsWith("R-ALL-REACT_")) { return null; } identifier = identifier.split("_")[1]; resource = Registry.replace(resource, "R-ALL-REACT_", ""); String collection = Registry.getDataCollectionPartFromURI(resource); if (Registry.checkPattern(identifier, collection)) { return Registry.getURI(collection, identifier); } else { return null; } } /** * @param location * relative path to the resource from this class. * @param replacements * @return Constants.URL_PREFIX + " like '%%identifiers.org%%'" * @throws IOException */ private String parseNotes(String location, Map<String, String> replacements) throws IOException { StringBuilder sb = new StringBuilder(); try (InputStream is = getClass().getResourceAsStream(location); InputStreamReader isReader = new InputStreamReader((is != null) ? is : new FileInputStream(new File(location))); BufferedReader br = new BufferedReader(isReader)) { String line; boolean start = false; while (br.ready() && ((line = br.readLine()) != null)) { if (line.matches("\\s*<body.*")) { start = true; } if (!start) { continue; } if (line.matches(".*\\$\\{.*\\}.*")) { for (String key : replacements.keySet()) { line = line.replace(key, replacements.get(key)); } } sb.append(line); sb.append('\n'); if (line.matches("\\s*</body.*")) { break; } } } return sb.toString(); } /** * @return the modelNotes */ File getModelNotesFile() { return new File(modelNotes); } /** * @param modelNotes * the modelNotes to set */ void setModelNotesFile(File modelNotes) { this.modelNotes = modelNotes != null ? modelNotes.getAbsolutePath() : null; } /** * @param documentNotesFile */ void setDocumentNotesFile(File documentNotesFile) { this.documentNotesFile = documentNotesFile != null ? documentNotesFile.getAbsolutePath() : null; } }
// $RCSfile: PlainCreate.java,v $ // @version $Revision: 1.6 $ // $Log: PlainCreate.java,v $ // Revision 1.6 2006/06/12 09:18:47 Ian.Mayo // Better layer extended messaging // Revision 1.5 2006/05/16 14:14:16 Ian.Mayo // When we're adding a raster painter (like ETOPO) only add it once // Revision 1.4 2005/09/30 09:48:24 Ian.Mayo // Allow creation of layers, not just plottables // Revision 1.3 2005/07/08 14:18:50 Ian.Mayo // Make utility methods more accessible // Revision 1.2 2004/05/25 15:44:28 Ian.Mayo // Commit updates from home // Revision 1.1.1.1 2004/03/04 20:31:26 ian // no message // Revision 1.1.1.1 2003/07/17 10:07:46 Ian.Mayo // Initial import // Revision 1.3 2002-07-02 09:13:46+01 ian_mayo // Check we are provided with a layer // Revision 1.2 2002-05-28 09:26:01+01 ian_mayo // after switch to new system // Revision 1.1 2002-05-28 09:14:04+01 ian_mayo // Initial revision // Revision 1.1 2002-04-11 13:03:36+01 ian_mayo // Initial revision // Revision 1.3 2002-01-24 14:22:30+00 administrator // Reflect fact that Layers events for reformat and modified take a Layer parameter (which is possibly null). These changes are a step towards implementing per-layer graphics updates // Revision 1.2 2001-10-29 12:58:07+00 administrator // Check that shape creation was successful // Revision 1.1 2001-08-23 13:27:56+01 administrator // Reflect new signature for PlainCreate class, to allow it to fireExtended() // Revision 1.0 2001-07-17 08:42:52+01 administrator // Initial revision // Revision 1.2 2001-07-16 15:38:07+01 novatech // add comments // Revision 1.1 2001-01-03 13:41:41+00 novatech // Initial revision // Revision 1.1.1.1 2000/12/12 21:51:58 ianmayo // initial version // Revision 1.3 1999-11-26 15:51:40+00 ian_mayo // tidying up // Revision 1.2 1999-11-11 18:23:03+00 ian_mayo // new classes, to allow creation of shapes from palette package MWC.GUI.Tools.Palette; import MWC.GUI.BaseLayer; import MWC.GUI.Layer; import MWC.GUI.Layers; import MWC.GUI.Plottable; import MWC.GUI.ToolParent; import MWC.GUI.Chart.Painters.GridPainter; import MWC.GUI.Chart.Painters.ScalePainter; import MWC.GUI.Properties.PropertiesPanel; import MWC.GUI.Tools.Action; import MWC.GUI.Tools.PlainTool; abstract public class PlainCreate extends PlainTool { /** * the panel used to edit this item */ private final PropertiesPanel _thePanel; /** * the Layers object, which we need in order to fire data extended event */ private final Layers _theData; private final BoundsProvider _boundsProvider; // constructor /** * constructor for label * * @param theParent * parent where we can change cursor * @param thePanel * panel * @param theData * the layer we are adding the item to */ public PlainCreate(final ToolParent theParent, final PropertiesPanel thePanel, final Layers theData, final BoundsProvider boundsProvider, final String theName, final String theImage) { super(theParent, theName, theImage); _thePanel = thePanel; _theData = theData; _boundsProvider = boundsProvider; } // member functions /** * Get the chart features layer,creating if necessary * * @return Chart Features layer */ private Layer getDestinationLayer() { Layer layer = _theData.findLayer(Layers.CHART_FEATURES); return layer; } /** * accessor to retrieve the layered data */ public Layers getLayers() { return _theData; } protected BoundsProvider getBounds() { return _boundsProvider; } protected abstract Plottable createItem(); public Action getData() { final Action res; // ask the child class to create itself final Plottable pl = createItem(); // did it work? if (pl != null) { final Layer theLayer = getDestinationLayer(); // wrap it up in an action res = new CreateLabelAction(_thePanel, theLayer, _theData, pl); } else { res = null; } return res; } // store action information public static class CreateLabelAction implements Action { /** * the panel we are going to show the initial editor in */ final protected PropertiesPanel _thePanel; final protected Layer _theLayer; protected Layer _addedLayer; protected Plottable _theShape; final protected Layers _myData; public CreateLabelAction(final PropertiesPanel thePanel, final Layer theLayer, final Layers theData, final Plottable theShape) { _thePanel = thePanel; _theLayer = theLayer; _theShape = theShape; _myData = theData; } public Layers getLayers() { return _myData; } public Layer getLayer() { return _theLayer; } public Plottable getNewFeature() { return _theShape; } /** * specify is this is an operation which can be undone */ public boolean isUndoable() { return true; } /** * specify is this is an operation which can be redone */ public boolean isRedoable() { return true; } /** * return string describing this operation * * @return String describing this operation */ public String toString() { return "New grid:" + _theShape.getName(); } /** * take the shape away from the layer */ public void undo() { if (_theLayer != null) { _theLayer.removeElement(_theShape); } else { if (_theShape instanceof Layer) { _myData.removeThisLayer((Layer) _theShape); } else if(_addedLayer!=null) { _myData.removeThisLayer(_addedLayer); } else MWC.Utilities.Errors.Trace.trace( "Missing layer data in undo operation"); } _myData.fireExtended(); } /** * make it so! */ public void execute() { // check that the creation worked if (_theShape != null) { if (_theLayer != null) { // add the Shape to the layer, and put it // in the property editor _theLayer.add(_theShape); if (_thePanel != null) _thePanel.addEditor(_theShape.getInfo(), _theLayer); _myData.fireExtended(_theShape, _theLayer); } else { if(_theShape instanceof ScalePainter || _theShape instanceof GridPainter) { //for scale and grid, add the shape after adding chart_features layer, if it doesnt already exist _addedLayer = new BaseLayer(); _addedLayer.setName(Layers.CHART_FEATURES); getLayers().addThisLayer(_addedLayer); _addedLayer.add(_theShape); if (_thePanel != null) _thePanel.addEditor(_theShape.getInfo(), _addedLayer); _myData.fireExtended(_theShape, _addedLayer); } // no layer provided, stick into the top level else if (_theShape instanceof Layer) { // ahh, just check we don't have one already final Layer newLayer = (Layer) _theShape; final Layer sameLayer = _myData.findLayer(newLayer.getName()); if (sameLayer == null) { // no, we don't already store it. add it. _myData.addThisLayer((Layer) _theShape); if (_thePanel != null) _thePanel.addEditor(_theShape.getInfo(), newLayer); // no need to fire-extended, "add this layer" will have done it for us // _myData.fireExtended(_theShape, newLayer); } else { // ok - just display the same layer if (_thePanel != null) _thePanel.addEditor(_theShape.getInfo(), sameLayer); // and store the existing layer as the new item _theShape = sameLayer; } } else MWC.Utilities.Errors.Trace.trace("Failed to add new layer"); } } } } // store action information public static class CreateLayerAction implements Action { /** * the panel we are going to show the initial editor in */ final protected PropertiesPanel _thePanel; final protected Layer _theLayer; final protected Layers _myData; public CreateLayerAction(final PropertiesPanel thePanel, final Layer theLayer, final Layers theData) { _thePanel = thePanel; _theLayer = theLayer; _myData = theData; } /** * specify is this is an operation which can be undone */ public boolean isUndoable() { return true; } /** * specify is this is an operation which can be redone */ public boolean isRedoable() { return true; } /** * return string describing this operation * * @return String describing this operation */ public String toString() { return "New layer:" + _theLayer.getName(); } /** * take the shape away from the layer */ public void undo() { if (_theLayer != null) { _myData.removeThisLayer(_theLayer); } _myData.fireExtended(); } /** * make it so! */ public void execute() { // add our new layer, and put it // in the property editor _myData.addThisLayer(_theLayer); if (_thePanel != null) _thePanel.addEditor(_theLayer.getInfo(), _theLayer); _myData.fireExtended(); } } }
package org.motechproject.scheduletracking.api.it; import org.joda.time.DateTime; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.motechproject.model.Time; import org.motechproject.scheduletracking.api.domain.Enrollment; import org.motechproject.scheduletracking.api.domain.EnrollmentStatus; import org.motechproject.scheduletracking.api.domain.WindowName; import org.motechproject.scheduletracking.api.repository.AllEnrollments; import org.motechproject.scheduletracking.api.repository.AllTrackedSchedules; import org.motechproject.scheduletracking.api.service.EnrollmentRecord; import org.motechproject.scheduletracking.api.service.EnrollmentsQuery; import org.motechproject.scheduletracking.api.service.ScheduleTrackingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.HashMap; import java.util.List; import java.util.Map; import static ch.lambdaj.Lambda.extract; import static ch.lambdaj.Lambda.on; import static java.util.Arrays.asList; import static junit.framework.Assert.assertEquals; import static org.hamcrest.Matchers.hasItems; import static org.junit.Assert.assertThat; import static org.motechproject.scheduletracking.api.utility.DateTimeUtil.*; import static org.motechproject.util.DateUtil.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationSchedulerTrackingAPI.xml") public class EnrollmentsSearchIT { @Autowired private ScheduleTrackingService scheduleTrackingService; @Autowired private AllEnrollments allEnrollments; @Autowired private AllTrackedSchedules allTrackedSchedules; @After public void tearDown() { for (Enrollment enrollment : allEnrollments.getAll()) allEnrollments.remove(enrollment); } @Test public void shouldReturnExternalIdsOfActiveEnrollmentsThatAreEitherInLateOrMaxWindowForAGivenSchedule() { DateTime now = now(); createEnrollment("entity_1", "IPTI Schedule", "IPTI 1", weeksAgo(1), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_2", "IPTI Schedule", "IPTI 1", weeksAgo(14), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_3", "IPTI Schedule", "IPTI 1", yearsAgo(1), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_4", "IPTI Schedule", "IPTI 2", daysAgo(20), daysAgo(20), new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_5", "IPTI Schedule", "IPTI 1", yearsAgo(1), now, new Time(6, 30), EnrollmentStatus.DEFAULTED, null); createEnrollment("entity_6", "Delivery", "Default", yearsAgo(1), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); EnrollmentsQuery query = new EnrollmentsQuery().havingSchedule("IPTI Schedule").currentlyInWindow(WindowName.late, WindowName.max).havingState(EnrollmentStatus.ACTIVE); List<EnrollmentRecord> result = scheduleTrackingService.search(query); assertEquals(asList(new String[]{ "entity_3", "entity_4" }), extract(result, on(EnrollmentRecord.class).getExternalId())); } @Test public void shouldReturnExternalIdsOfActiveEnrollmentsThatHaveEnteredDueWindowDuringTheLastWeek() { DateTime now = now(); createEnrollment("entity_1", "IPTI Schedule", "IPTI 1", weeksAgo(10), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_2", "IPTI Schedule", "IPTI 1", weeksAgo(13).minusDays(1), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_3", "IPTI Schedule", "IPTI 1", weeksAgo(14).plusHours(1), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_4", "IPTI Schedule", "IPTI 2", weeksAgo(15), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_5", "IPTI Schedule", "IPTI 1", weeksAgo(13), now, new Time(6, 30), EnrollmentStatus.DEFAULTED, null); createEnrollment("entity_6", "Delivery", "Default", weeksAgo(14), now, new Time(6, 30), EnrollmentStatus.ACTIVE, null); EnrollmentsQuery query = new EnrollmentsQuery().havingSchedule("IPTI Schedule").havingState(EnrollmentStatus.ACTIVE).havingWindowStartingDuring(WindowName.due, weeksAgo(1), now); List<EnrollmentRecord> result = scheduleTrackingService.search(query); assertEquals(asList(new String[]{ "entity_2", "entity_3" }), extract(result, on(EnrollmentRecord.class).getExternalId())); } @Test public void shouldReturnExternalIdsOfActiveEnrollmentsThatAreCompletedDuringTheLastWeek() { DateTime referenceDate = newDateTime(2012, 10, 1, 0, 0, 0); createEnrollment("entity_1", "IPTI Schedule", "IPTI 2", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); scheduleTrackingService.fulfillCurrentMilestone("entity_1", "IPTI Schedule", newDate(2012, 10, 10)); createEnrollment("entity_2", "IPTI Schedule", "IPTI 2", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); scheduleTrackingService.fulfillCurrentMilestone("entity_2", "IPTI Schedule", newDate(2012, 10, 20)); createEnrollment("entity_3", "IPTI Schedule", "IPTI 1", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); scheduleTrackingService.fulfillCurrentMilestone("entity_3", "IPTI Schedule", newDate(2012, 10, 8)); scheduleTrackingService.fulfillCurrentMilestone("entity_3", "IPTI Schedule", newDate(2012, 10, 9)); createEnrollment("entity_4", "IPTI Schedule", "IPTI 2", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_5", "IPTI Schedule", "IPTI 1", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.DEFAULTED, null); createEnrollment("entity_6", "Delivery", "Default", referenceDate, referenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); EnrollmentsQuery query = new EnrollmentsQuery().havingSchedule("IPTI Schedule").completedDuring(newDateTime(2012, 10, 9, 0, 0, 0), newDateTime(2012, 10, 15, 23, 59, 59)); List<EnrollmentRecord> result = scheduleTrackingService.search(query); assertThat(extract(result, on(EnrollmentRecord.class).getExternalId()), hasItems("entity_1", "entity_3")); } @Test public void forAGivenEntityShouldReturnAllSchedulesWithDatesWhoseDueDateFallsInTheLastWeek() { DateTime iptiReferenceDate = newDateTime(2012, 1, 1, 0, 0 ,0); DateTime deliveryReferenceDateTime = newDateTime(2011, 7, 9, 0, 0 ,0); createEnrollment("entity_1", "IPTI Schedule", "IPTI 1", iptiReferenceDate, iptiReferenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_1", "Delivery", "Default", deliveryReferenceDateTime, deliveryReferenceDateTime, new Time(6, 30), EnrollmentStatus.ACTIVE, null); createEnrollment("entity_1", "IPTI Schedule", "IPTI 1", iptiReferenceDate, iptiReferenceDate, new Time(6, 30), EnrollmentStatus.DEFAULTED, null); createEnrollment("entity_2", "IPTI Schedule", "IPTI 1", iptiReferenceDate, iptiReferenceDate, new Time(6, 30), EnrollmentStatus.ACTIVE, null); EnrollmentsQuery query = new EnrollmentsQuery() .havingExternalId("entity_1") .havingState(EnrollmentStatus.ACTIVE) .havingWindowStartingDuring(WindowName.due, newDateTime(2012, 4, 1, 0, 0, 0), newDateTime(2012, 4, 7, 23, 59, 59)); List<EnrollmentRecord> result = scheduleTrackingService.searchWithWindowDates(query); assertEquals(asList(new String[]{ "IPTI Schedule", "Delivery" }), extract(result, on(EnrollmentRecord.class).getScheduleName())); assertEquals(asList(new DateTime[]{ newDateTime(2012, 4, 1, 0, 0, 0), newDateTime(2012, 4, 7, 0, 0, 0)}), extract(result, on(EnrollmentRecord.class).getStartOfDueWindow())); } @Test public void shouldFindEnrollmentsByMetadataProperties() { HashMap<String,String> metadata; metadata = new HashMap<String, String>(); metadata.put("foo", "bar"); metadata.put("fuu", "baz"); createEnrollment("entity1", "Delivery", "milestone1", newDateTime(2010, 1, 1, 0, 0, 0), newDateTime(2010, 1, 1, 0, 0, 0), new Time(0, 0), EnrollmentStatus.ACTIVE, metadata); metadata = new HashMap<String, String>(); metadata.put("foo", "cad"); metadata.put("fuu", "cab"); createEnrollment("entity2", "Delivery", "milestone1", newDateTime(2010, 1, 1, 0, 0, 0), newDateTime(2010, 1, 1, 0, 0, 0), new Time(0, 0), EnrollmentStatus.ACTIVE, metadata); metadata = new HashMap<String, String>(); metadata.put("foo", "bar"); metadata.put("fuu", "baz"); createEnrollment("entity3", "Delivery", "milestone1", newDateTime(2010, 1, 1, 0, 0, 0), newDateTime(2010, 1, 1, 0, 0, 0), new Time(0, 0), EnrollmentStatus.ACTIVE, metadata); metadata = new HashMap<String, String>(); metadata.put("foo", "biz"); metadata.put("fuu", "boz"); createEnrollment("entity4", "Delivery", "milestone1", newDateTime(2010, 1, 1, 0, 0, 0), newDateTime(2010, 1, 1, 0, 0, 0), new Time(0, 0), EnrollmentStatus.ACTIVE, metadata); metadata = new HashMap<String, String>(); metadata.put("foo", "quz"); metadata.put("fuu", "qux"); createEnrollment("entity5", "Delivery", "milestone1", newDateTime(2010, 1, 1, 0, 0, 0), newDateTime(2010, 1, 1, 0, 0, 0), new Time(0, 0), EnrollmentStatus.ACTIVE, metadata); assertEquals(asList(new String[]{ "entity1", "entity3" }), extract(allEnrollments.findByMetadataProperty("foo", "bar"), on(Enrollment.class).getExternalId())); assertEquals(asList(new String[] { "entity4" }), extract(allEnrollments.findByMetadataProperty("fuu", "boz"), on(Enrollment.class).getExternalId())); } private Enrollment createEnrollment(String externalId, String scheduleName, String currentMilestoneName, DateTime referenceDateTime, DateTime enrollmentDateTime, Time preferredAlertTime, EnrollmentStatus enrollmentStatus, Map<String,String> metadata) { Enrollment enrollment = new Enrollment(externalId, allTrackedSchedules.getByName(scheduleName), currentMilestoneName, referenceDateTime, enrollmentDateTime, preferredAlertTime, enrollmentStatus, metadata); allEnrollments.add(enrollment); return enrollment; } }
package dyvil.tools.gensrc; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.nio.file.Files; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.Properties; public class Specialization { public static final String FILE_NAME_PROPERTY = "@fileName"; public static final String ENABLED_PROPERTY = "@enabled"; public static final String GEN_NOTICE_PROPERTY = "GEN_NOTICE"; public static final String TIME_STAMP_PROPERTY = "TIME_STAMP"; public static final String GEN_NOTICE = "GENERATED SOURCE - DO NOT EDIT"; private Properties substitutions = new Properties(); private Specialization parent; private final File sourceFile; private final String templateName; private final String name; private Template template; public Specialization(File sourceFile, String templateName, String specName) { this.sourceFile = sourceFile; this.templateName = templateName; this.name = specName; } public File getSourceFile() { return this.sourceFile; } public String getTemplateName() { return this.templateName; } public Template getTemplate() { return this.template; } public void setTemplate(Template template) { this.template = template; } public String getName() { return this.name; } public String getFileName() { return this.getSubstitution(FILE_NAME_PROPERTY); } public boolean isEnabled() { final String enabled = this.getSubstitution(ENABLED_PROPERTY); return enabled == null || "true".equals(enabled); } public String getSubstitution(String key) { final String sub = this.substitutions.getProperty(key); if (sub != null || this.parent == null) { return sub; } return this.parent.getSubstitution(key); } public void read(File sourceRoot, Map<File, Specialization> specs) { initDefaults(this.substitutions); try (BufferedReader reader = Files.newBufferedReader(this.sourceFile.toPath())) { this.substitutions.load(reader); } catch (IOException e) { // TODO better error handling e.printStackTrace(); } final String inherited = this.getSubstitution("inheritFrom"); if (inherited == null) { return; } // If the referenced file starts with '.', it is relative to the parent directory of this spec file // Otherwise, it is relative to the source root final File specFile = inherited.startsWith(".") ? new File(this.getSourceFile().getParent(), inherited) : new File(sourceRoot, inherited); final Specialization spec = specs.get(specFile); if (spec == null) { System.out.printf("Unable to resolve and inherit specialization '%s'\n", specFile); return; } this.parent = spec; } private static void initDefaults(Properties substitutions) { substitutions.put(GEN_NOTICE_PROPERTY, GEN_NOTICE); substitutions.put(TIME_STAMP_PROPERTY, DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now())); } public void processLines(List<String> lines, PrintStream writer) { for (String line : lines) { writer.println(this.processLine(line)); } } private String processLine(String line) { final int length = line.length(); if (length == 0) { return line; } final StringBuilder builder = new StringBuilder(length); int prev = 0; for (int i = 0; i < length; ) { final char c = line.charAt(i); if (c == '#' && i + 1 < length && line.charAt(i + 1) == '#') { // two consecutive ## are stripped // append contents before this identifier builder.append(line, prev, i); i = prev = i + 2; // advance by two characters continue; } if (!Character.isJavaIdentifierStart(c)) { // advance to the first identifier start character i++; continue; } // append contents before this identifier builder.append(line, prev, i); // index of the first character that is not part of this identifier final int nextIndex = findNextIndex(line, i + 1, length); final String key = line.substring(i, nextIndex); final String replacement = this.getSubstitution(key); if (replacement != null) { builder.append(replacement); // append the replacement instead of the identifier } else { builder.append(line, i, nextIndex); // append the original identifier } i = prev = nextIndex; } // append remaining characters on line builder.append(line, prev, length); return builder.toString(); } private static int findNextIndex(String line, int startIndex, int length) { for (; startIndex < length; startIndex++) { if (!Character.isJavaIdentifierPart(line.charAt(startIndex))) { return startIndex; } } return length; } }
package gov.nih.nci.camod.webapp.form; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.util.NameValue; import gov.nih.nci.camod.util.NameValueList; import gov.nih.nci.camod.util.SafeHTMLUtil; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.Globals; import org.apache.struts.action.*; import org.apache.struts.util.MessageResources; public class SearchForm extends ActionForm implements Serializable, SearchData { private static final long serialVersionUID = 3257045453799404851L; protected String keyword; protected String piName; protected String pmid; protected String modelDescriptor; protected String organ; protected String species; protected String externalSource; protected String chemicalDrug; protected String comment; protected String hormone; protected String growthFactor; protected String radiation; protected String viral; protected String surgery; protected String phenotype; protected String disease; protected String tumorClassification; protected String cellLine; protected String organTissueCode; protected String organTissueName; protected String diagnosisCode; protected String diagnosisName; protected String inducedMutationAgent; protected String transgeneName; protected String geneName; protected String genomicSegDesignator; protected String therapeuticApproach; protected String carcinogenicIntervention; protected String agentName; protected boolean searchTherapeuticApproaches = false; protected boolean searchEngineeredTransgene = false; protected boolean searchTargetedModification = false; protected boolean searchHistoMetastasis = false; protected boolean searchMicroArrayData = false; protected boolean searchImageData = false; protected boolean searchTransplant = false; protected boolean searchTransientInterference = false; protected boolean searchToolStrain = false; public SearchForm() { } public void setHormone(String hormone) { this.hormone = hormone; } public void setGrowthFactor(String growthFactor) { this.growthFactor = growthFactor; } public String getChemicalDrug() { return chemicalDrug; } public void setPmid(String pmid) { this.pmid = pmid; // Clean the parameter if (this.pmid != null && !this.pmid.equals("")) { this.pmid = SafeHTMLUtil.clean(this.pmid); } } public String getPmid() { return pmid; } public void setChemicalDrug(String chemicalDrug) { this.chemicalDrug = chemicalDrug; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; // Clean the parameter if (this.keyword != null && !this.keyword.equals("")) { this.keyword = SafeHTMLUtil.cleanKeyword(this.keyword); } } public String getModelDescriptor() { return modelDescriptor; } public void setModelDescriptor(String modelDescriptor) { this.modelDescriptor = modelDescriptor; // Clean the parameter if (this.modelDescriptor != null && !this.modelDescriptor.equals("")) { this.modelDescriptor = SafeHTMLUtil.cleanModelDescriptor(this.modelDescriptor); } } public String getOrgan() { return organ; } public void setOrgan(String organ) { this.organ = organ; // Clean the parameter if (this.organ != null && !this.organ.equals("")) { this.organ = SafeHTMLUtil.clean(this.organ); } } public String getPiName() { return piName; } public void setPiName(String piName) { this.piName = piName; // Clean the parameter if (this.piName != null && !this.piName.equals("")) { this.piName = SafeHTMLUtil.clean(this.piName); } } public String getSpecies() { return species; } public void setSpecies(String species) { this.species = species; } public String getExternalSource() { return externalSource; } public void setExternalSource(String externalSource) { this.externalSource = externalSource; } public String getGrowthFactor() { return growthFactor; } public String getHormone() { return hormone; } public String getRadiation() { return radiation; } public void setRadiation(String radiation) { this.radiation = radiation; } public String getSurgery() { return surgery; } public void setSurgery(String surgery) { this.surgery = surgery; } public String getViral() { return viral; } public void setViral(String viral) { this.viral = viral; } public String getPhenotype() { return phenotype; } public void setPhenotype(String phenotype) { this.phenotype = phenotype; // Clean the parameter if (this.phenotype != null && !this.phenotype.equals("")) { this.phenotype = SafeHTMLUtil.cleanPhenotype(this.phenotype); } } public String getDisease() { return disease; } public void setDisease(String disease) { this.disease = disease; // Clean the parameter if (this.disease != null && !this.disease.equals("")) { this.disease = SafeHTMLUtil.clean(this.disease); } } public String getCellLine() { return cellLine; } public void setCellLine(String cellLine) { this.cellLine = cellLine; } public String getOrganTissueCode() { return organTissueCode; } public void setOrganTissueCode(String organTissueCode) { this.organTissueCode = organTissueCode; // Clean the parameter if (this.organTissueCode != null && !this.organTissueCode.equals("")) { this.organTissueCode = SafeHTMLUtil.clean(this.organTissueCode); } } public String getOrganTissueName() { return organTissueName; } public void setOrganTissueName(String organTissueName) { this.organTissueName = organTissueName; // Clean the parameter if (this.organTissueName != null && !this.organTissueName.equals("")) { this.organTissueName = SafeHTMLUtil.clean(this.organTissueName); } } public String getDiagnosisCode() { return diagnosisCode; } public void setDiagnosisCode(String diagnosisCode) { this.diagnosisCode = diagnosisCode; // Clean the parameter if (this.diagnosisCode != null && !this.diagnosisCode.equals("")) { this.diagnosisCode = SafeHTMLUtil.clean(this.diagnosisCode); } } public String getDiagnosisName() { return diagnosisName; } public void setDiagnosisName(String diagnosisName) { this.diagnosisName = diagnosisName; // Clean the parameter if (this.diagnosisName != null && !this.diagnosisName.equals("")) { this.diagnosisName = SafeHTMLUtil.clean(this.diagnosisName); } } public String getInducedMutationAgent() { return inducedMutationAgent; } public void setInducedMutationAgent(String inducedMutationAgent) { this.inducedMutationAgent = inducedMutationAgent; } public String getGeneName() { return geneName; } public void setGeneName(String geneName) { this.geneName = geneName; // Clean the parameter if (this.geneName != null && !this.geneName.equals("")) { this.geneName = SafeHTMLUtil.cleanGeneName(this.geneName); } } public String getGenomicSegDesignator() { return genomicSegDesignator; } public void setGenomicSegDesignator(String genomicSegDesignator) { this.genomicSegDesignator = genomicSegDesignator; } public boolean isSearchTherapeuticApproaches() { return searchTherapeuticApproaches; } public void setSearchTherapeuticApproaches(boolean searchTherapeuticApproaches) { this.searchTherapeuticApproaches = searchTherapeuticApproaches; } public String getTherapeuticApproach() { return therapeuticApproach; } public void setTherapeuticApproach(String therapeuticApproach) { this.therapeuticApproach = therapeuticApproach; } public boolean isSearchHistoMetastasis() { return searchHistoMetastasis; } public void setSearchHistoMetastasis(boolean searchHistoMetastasis) { this.searchHistoMetastasis = searchHistoMetastasis; } public boolean isSearchMicroArrayData() { return searchMicroArrayData; } public void setSearchMicroArrayData(boolean searchMicroArrayData) { this.searchMicroArrayData = searchMicroArrayData; } public boolean isSearchImageData() { return searchImageData; } public void setSearchImageData(boolean searchImageData) { this.searchImageData = searchImageData; } public boolean isSearchTransplant() { return searchTransplant; } public void setSearchTransplant(boolean searchTransplant) { this.searchTransplant = searchTransplant; } /** * @return Returns the searchTransientInterference. */ public boolean isSearchTransientInterference() { return searchTransientInterference; } /** * @param searchTransientInterference The searchTransientInterference to set. */ public void setSearchTransientInterference(boolean searchTransientInterference) { this.searchTransientInterference = searchTransientInterference; } /** * @return Returns the searchToolStrain. */ public boolean isSearchToolStrain() { return searchToolStrain; } /** * @param searchToolStrain The searchToolStrain to set. */ public void setSearchToolStrain(boolean searchToolStrain) { this.searchToolStrain = searchToolStrain; } public String getTumorClassification() { return tumorClassification; } public void setTumorClassification(String tumorClassification) { this.tumorClassification = tumorClassification; // Clean the parameter if (this.tumorClassification != null && !this.tumorClassification.equals("")) { this.tumorClassification = SafeHTMLUtil.clean(this.tumorClassification); } } /** * Reset all fields that are not used in the simple search. Since the form * is used for both the simple and advanced search and is stored in the * session to allow users to quickly use the back arrow to refine their * search we need to make sure that when the user clicks on the simple * search page the options from the advanced search page are reset. * */ public void simpleSearchReset() { chemicalDrug = null; hormone = null; growthFactor = null; radiation = null; viral = null; surgery = null; phenotype = null; disease = null; cellLine = null; diagnosisCode = null; diagnosisName = null; tumorClassification = null; organ = null; organTissueCode = null; organTissueName = null; inducedMutationAgent = null; geneName = null; transgeneName = null; genomicSegDesignator = null; therapeuticApproach = null; carcinogenicIntervention = null; agentName = null; searchTherapeuticApproaches = false; searchTransientInterference = false; searchEngineeredTransgene = false; searchTargetedModification = false; searchHistoMetastasis = false; searchMicroArrayData = false; searchTransplant = false; searchToolStrain = false; externalSource = null; searchImageData = false; } /** * Reset all fields. */ public void allFieldsReset() { keyword = null; piName = null; modelDescriptor = null; species = null; simpleSearchReset(); } public String getAgentName() { return agentName; } public void setAgentName(String agentName) { this.agentName = agentName; } public String getCarcinogenicIntervention() { return carcinogenicIntervention; } public void setCarcinogenicIntervention(String carcinogenicIntervention) { this.carcinogenicIntervention = carcinogenicIntervention; } /** * validate the search form * @param mapping * @param request * @return */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); // Identify the request parameter containing the method name String parameter = mapping.getParameter(); // validate keyword against malicious characters to prevent blind SQL injection attacks if (keyword != null && keyword.length() > 0 ) { setKeyword(keyword); } // validate modelDescriptor against malicious characters to prevent blind SQL injection attacks if (modelDescriptor != null && modelDescriptor.length() > 0) { setModelDescriptor(modelDescriptor); } // validate for PI if (piName != null && piName.length() > 0 ) { List piNameList = new ArrayList(); piNameList = (List)request.getSession().getAttribute(Constants.Dropdowns.PRINCIPALINVESTIGATORQUERYDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHPIDROP, piNameList); if (!SafeHTMLUtil.isValidStringValue(piName,Constants.Dropdowns.SEARCHPIDROP,request)) { // populate the validation message errors.add("piName", new ActionMessage("error.piName.validValue")); } } // validate for species if (species != null && species.length() > 0 ) { NameValueList.generateApprovedSpeciesList(); request.getSession().setAttribute(Constants.Dropdowns.SEARCHSPECIESDROP, NameValueList.getApprovedSpeciesList()); if (!SafeHTMLUtil.isValidValue(species,Constants.Dropdowns.SEARCHSPECIESDROP,request)) { // populate the validation message errors.add("species", new ActionMessage("error.species.validValue")); } } // validate tumorClassification against malicious characters to prevent blind SQL injection attacks if (tumorClassification != null && tumorClassification.length() > 0) { setTumorClassification(tumorClassification); } // validate genomicSegDesignator against malicious characters to prevent blind SQL injection attacks if (genomicSegDesignator != null && genomicSegDesignator.length() > 0 ) { List genomicSegDesigList = new ArrayList(); genomicSegDesigList = (List)request.getSession().getAttribute(Constants.Dropdowns.CLONEDESIGNATORQUERYDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHGENOMICSEGMENT, genomicSegDesigList); if (!SafeHTMLUtil.isValidStringValue(genomicSegDesignator,Constants.Dropdowns.SEARCHGENOMICSEGMENT,request)) { // populate the validation message errors.add("genomicSegDesignator", new ActionMessage("error.genomicSegDesignator.validValue")); return errors; } } // validate for inducedMutationAgent if (inducedMutationAgent != null && inducedMutationAgent.length() > 0 ) { List inducedMutationAgentList = new ArrayList(); inducedMutationAgentList = (List)request.getSession().getAttribute(Constants.Dropdowns.INDUCEDMUTATIONAGENTQUERYDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHINDUCEDMUTATIONDROP, inducedMutationAgentList); if (!SafeHTMLUtil.isValidValue(inducedMutationAgent,Constants.Dropdowns.SEARCHINDUCEDMUTATIONDROP,request)) { // populate the validation message errors.add("inducedMutationAgent", new ActionMessage("error.inducedMutationAgent.validValue")); } } // validate for carcinogenicIntervention if (carcinogenicIntervention != null && carcinogenicIntervention.length() > 0 ) { NameValueList.generateCarcinogenicInterventionList(); request.getSession().setAttribute(Constants.Dropdowns.SEARCHCARCINOGENEXPOSUREDROP, NameValueList.getCarcinogenicInterventionList()); if (!SafeHTMLUtil.isValidValue(carcinogenicIntervention,Constants.Dropdowns.SEARCHCARCINOGENEXPOSUREDROP,request) | !SafeHTMLUtil.isLetterOrDigitWithExceptions(carcinogenicIntervention)) { // populate the validation message errors.add("carcinogenicIntervention", new ActionMessage("error.carcinogenicIntervention.validValue")); } // validate for agentName if (agentName != null && agentName.length() > 0 ) { List agentNameList = new ArrayList(); agentNameList = (List)request.getSession().getAttribute(Constants.Dropdowns.ENVIRONMENTALFACTORNAMESDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHENVIRONFACTORDROP, agentNameList); if (!SafeHTMLUtil.isValidStringValue(agentName,Constants.Dropdowns.SEARCHENVIRONFACTORDROP,request)) { // populate the validation message errors.add("agentName", new ActionMessage("error.agentName.validValue")); return errors; } } } // validate for cellLine if (cellLine != null && cellLine.length() > 0 ) { List cellLineList = new ArrayList(); cellLineList = (List)request.getSession().getAttribute(Constants.Dropdowns.CELLLINENAMEQUERYDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHCELLLINE, cellLineList); if (!SafeHTMLUtil.isValidStringValue(cellLine,Constants.Dropdowns.SEARCHCELLLINE,request)) { // populate the validation message errors.add("cellLine", new ActionMessage("error.cellLine.validValue")); return errors; } } // validate therpy compound/drug against malicious characters to prevent blind SQL injection attacks if (therapeuticApproach != null ) { List drugNameList = new ArrayList(); drugNameList = (List)request.getSession().getAttribute(Constants.Dropdowns.THERAPEUTICAPPROACHDRUGQUERYDROP); request.getSession().setAttribute(Constants.Dropdowns.SEARCHTHERAPEUTICDRUGNAME, drugNameList); if (!SafeHTMLUtil.isValidStringValue(therapeuticApproach,Constants.Dropdowns.SEARCHTHERAPEUTICDRUGNAME,request)) { // populate the validation message errors.add("therapeuticApproach", new ActionMessage("error.therapeuticApproach.validValue")); return errors; } } // validate for externalSource if (externalSource != null && externalSource.length() > 0 ) { NameValueList.generateExternalSourceList(); request.getSession().setAttribute(Constants.Dropdowns.SEARCHEXTERNALSOURCEDROP, NameValueList.getExternalSourceList()); if (!SafeHTMLUtil.isValidValue(externalSource,Constants.Dropdowns.SEARCHEXTERNALSOURCEDROP,request)) { // populate the validation message errors.add("externalSource", new ActionMessage("error.externalSource.validValue")); } } // validate for searchTherapeuticApproaches if (searchTherapeuticApproaches == true | searchTherapeuticApproaches == false ) { } else { // populate the validation message errors.add("searchTherapeuticApproaches", new ActionMessage("error.invalidParameter.validValue")); } // validate for engineeredTransgene if (searchEngineeredTransgene == true | searchEngineeredTransgene == false ) { } else { // populate the validation message errors.add("engineeredTransgene", new ActionMessage("error.invalidParameter.validValue")); } // validate for targetedModification if (searchTargetedModification == true | searchTargetedModification == false ) { } else { // populate the validation message errors.add("targetedModification", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchHistoMetastasis if (searchHistoMetastasis == true | searchHistoMetastasis == false ) { } else { // populate the validation message errors.add("searchHistoMetastasis", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchMicroArrayData if (searchMicroArrayData == true | searchMicroArrayData == false ) { } else { // populate the validation message errors.add("searchMicroArrayData", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchImageData if (searchImageData == true | searchImageData == false ) { } else { // populate the validation message errors.add("searchImageData", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchTransplant if (searchTransplant == true | searchTransplant == false ) { } else { // populate the validation message errors.add("searchTransplant", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchTransientInterference if (searchTransplant == true | searchTransplant == false ) { } else { // populate the validation message errors.add("searchTransientInterference", new ActionMessage("error.invalidParameter.validValue")); } // validate for searchToolStrain if (searchToolStrain == true | searchToolStrain == false ) { } else { // populate the validation message errors.add("searchToolStrain", new ActionMessage("error.invalidParameter.validValue")); } if (parameter != null) { // Identify the method name to be dispatched to. String method = request.getParameter(parameter); MessageResources resources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY); // Identify the localized message for the clear button String clear = resources.getMessage("button.clear"); // if message resource matches the clear button then no // need to validate if ((method != null) && (method.equalsIgnoreCase(clear))) { return null; } } return errors; } /** * @return the searchEngineeredTransgene */ public boolean isSearchEngineeredTransgene() { return searchEngineeredTransgene; } /** * @param searchEngineeredTransgene the searchEngineeredTransgene to set */ public void setSearchEngineeredTransgene(boolean searchEngineeredTransgene) { this.searchEngineeredTransgene = searchEngineeredTransgene; } /** * @return the searchTargetedModification */ public boolean isSearchTargetedModification() { return searchTargetedModification; } /** * @param searchTargetedModification the searchTargetedModification to set */ public void setSearchTargetedModification(boolean searchTargetedModification) { this.searchTargetedModification = searchTargetedModification; } /** * @return the transgeneName */ public String getTransgeneName() { return transgeneName; } /** * @param transgeneName the transgeneName to set */ public void setTransgeneName(String transgeneName) { this.transgeneName = transgeneName; } }
package gov.nih.nci.ncicb.cadsr.loader; import gov.nih.nci.ncicb.cadsr.loader.parser.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import gov.nih.nci.ncicb.cadsr.loader.event.*; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.ChangeTracker; import java.util.*; import java.net.URLEncoder; public class GMEAction { private Parser parser; private ElementWriter writer; private UMLDefaults defaults = UMLDefaults.getInstance(); protected ElementsLists elements = ElementsLists.getInstance(); private ProgressListener progressListener = null; public void generateDefaults(String input, String output, String projectName, Float projectVesion, Context context) { ChangeTracker changeTracker = ChangeTracker.getInstance(); String namespace = defaultNamespace(projectName, projectVesion, context); ProgressEvent pEvt = new ProgressEvent(); pEvt.setGoal(0); pEvt.setMessage("Parsing ..."); pEvt.setStatus(0); progressListener.newProgressEvent(pEvt); try { parser.parse(input); } catch (ParserException e) { throw new RuntimeException(e); } List<ObjectClass> ocs = elements.getElements(DomainObjectFactory.newObjectClass()); for(ObjectClass oc : ocs) { String className = LookupUtil.lookupFullName(oc); String pkgName = className; if(pkgName.indexOf(".") > 0) { pkgName = pkgName.substring(0, pkgName.lastIndexOf(".")); if(!hasAltName(oc.getAlternateNames(), AlternateName.TYPE_GME_NAMESPACE)) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_NAMESPACE); altName.setName(namespace + "/" + pkgName); oc.addAlternateName(altName); changeTracker.put(className, true); } if(!hasAltName(oc.getAlternateNames(), AlternateName.TYPE_GME_XML_ELEMENT)) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_XML_ELEMENT); altName.setName(className.substring(className.lastIndexOf(".") + 1)); oc.addAlternateName(altName); changeTracker.put(className, true); } } } List<DataElement> des = elements.getElements(DomainObjectFactory.newDataElement()); for(DataElement de : des) { String attName = LookupUtil.lookupFullName(de); if(attName.indexOf(".") > 0) { if(!hasAltName(de.getAlternateNames(), AlternateName.TYPE_GME_XML_LOC_REF)) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_XML_LOC_REF); altName.setName("@" + attName.substring(attName.lastIndexOf(".") + 1)); de.addAlternateName(altName); changeTracker.put(attName, true); } } } // // do the project // ClassificationScheme cs = UMLDefaults.getInstance().getProjectCs(); // AlternateName altName = DomainObjectFactory.newAlternateName(); // altName.setType(AlternateName.TYPE_GME_NAMESPACE); // altName.setName(namespace); // cs.addAlternateName(altName); UserSelections.getInstance().setProperty("GME_NAMESPACE", namespace); List<ClassificationSchemeItem> csis = elements.getElements(DomainObjectFactory.newClassificationSchemeItem()); for(ClassificationSchemeItem csi : csis) { if(!hasAltName(csi.getAlternateNames(), AlternateName.TYPE_GME_NAMESPACE)) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_NAMESPACE); altName.setName(namespace + "/" + csi.getLongName()); csi.addAlternateName(altName); changeTracker.put(csi.getLongName(), true); } } List<ObjectClassRelationship> ocrs = elements.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClassRelationship ocr : ocrs) { if(!hasAltName(ocr.getAlternateNames(), AlternateName.TYPE_GME_SRC_XML_LOC_REF) || !hasAltName(ocr.getAlternateNames(), AlternateName.TYPE_GME_TARGET_XML_LOC_REF)) { if(!StringUtil.isEmpty(ocr.getTargetRole())) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_TARGET_XML_LOC_REF); altName.setName(ocr.getTargetRole() + "/" + LookupUtil.lookupXMLElementName(ocr.getTarget())); ocr.addAlternateName(altName); } if(!StringUtil.isEmpty(ocr.getSourceRole())) { AlternateName altName = DomainObjectFactory.newAlternateName(); altName.setType(AlternateName.TYPE_GME_SRC_XML_LOC_REF); altName.setName(ocr.getSourceRole() + "/" + LookupUtil.lookupXMLElementName(ocr.getSource())); ocr.addAlternateName(altName); } OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); changeTracker.put(fullName, true); } } pEvt.setGoal(50); pEvt.setMessage("Writing ..."); pEvt.setStatus(100); progressListener.newProgressEvent(pEvt); try { writer.setOutput(output); writer.write(elements); } catch (ParserException e) { throw new RuntimeException(e); } pEvt.setGoal(100); pEvt.setMessage("Done"); pEvt.setStatus(100); pEvt.setCompleted(true); progressListener.newProgressEvent(pEvt); } // does this list contain alt name of type "type" private boolean hasAltName(List<AlternateName> altNames, String type) { for(AlternateName an : altNames) { if(an.getType().equals(type)) return true; } return false; } public void cleanup(String input, String output) { ChangeTracker changeTracker = ChangeTracker.getInstance(); ProgressEvent pEvt = new ProgressEvent(); pEvt.setGoal(0); pEvt.setMessage("Parsing ..."); pEvt.setStatus(0); progressListener.newProgressEvent(pEvt); try { parser.parse(input); } catch (ParserException e) { throw new RuntimeException(e); } List<ObjectClass> ocs = elements.getElements(DomainObjectFactory.newObjectClass()); for(ObjectClass oc : ocs) { String className = LookupUtil.lookupFullName(oc); oc.removeAlternateNames(); changeTracker.put(className, true); } List<DataElement> des = elements.getElements(DomainObjectFactory.newDataElement()); for(DataElement de : des) { String attName = LookupUtil.lookupFullName(de); de.removeAlternateNames(); changeTracker.put(attName, true); } List<ClassificationSchemeItem> csis = elements.getElements(DomainObjectFactory.newClassificationSchemeItem()); for(ClassificationSchemeItem csi : csis) { csi.removeAlternateNames(); changeTracker.put(csi.getLongName(), true); } List<ObjectClassRelationship> ocrs = elements.getElements(DomainObjectFactory.newObjectClassRelationship()); for(ObjectClassRelationship ocr : ocrs) { OCRRoleNameBuilder nameBuilder = new OCRRoleNameBuilder(); String fullName = nameBuilder.buildRoleName(ocr); ocr.removeAlternateNames(); changeTracker.put(fullName, true); } try { writer.setOutput(output); writer.write(elements); } catch (ParserException e) { throw new RuntimeException(e); } pEvt.setGoal(100); pEvt.setMessage("Done"); pEvt.setStatus(100); pEvt.setCompleted(true); progressListener.newProgressEvent(pEvt); } private String defaultNamespace(String projectName, Float projectVersion, Context context) { try { String namespace = "gme://" + URLEncoder.encode(projectName, "UTF-8") + "." + URLEncoder.encode(context.getName(), "UTF-8") + "/" + projectVersion; return namespace; } catch (java.io.UnsupportedEncodingException e) { // not gonna happen (UTF-8) } return null; } public void setParser(Parser parser) { this.parser = parser; } public void setWriter(ElementWriter writer) { this.writer = writer; } public void addProgressListener(ProgressListener l) { progressListener = l; } }
package net.sf.packtag.util; /** * Logs Events to the available Logger, Log4j, elswise System.err. * * @author Daniel Galn y Martins * @version $Revision: 1.2 $ */ public class SafeLogger { private static Boolean log4jAvailable = null; private static Boolean commonsLoggingAvailable = null; /** Returns true if the classes from the Apache Log4j library is available */ protected static boolean isLog4jAvailable() { if (log4jAvailable == null) { synchronized (SafeLogger.class) { if (log4jAvailable == null) { try { log4jAvailable = new Boolean(Class.forName("org.apache.log4j.Logger") != null); } catch (ClassNotFoundException e) { log4jAvailable = Boolean.FALSE; } } } } return log4jAvailable.booleanValue(); } /** Returns true if the classes from the Apache Commons Logging library is available */ protected static boolean isCommonsLoggingAvailable() { if (commonsLoggingAvailable == null) { synchronized (SafeLogger.class) { if (commonsLoggingAvailable == null) { try { commonsLoggingAvailable = new Boolean(Class.forName("org.apache.commons.logging") != null); } catch (ClassNotFoundException e) { commonsLoggingAvailable = Boolean.FALSE; } } } } return commonsLoggingAvailable.booleanValue(); } public static void error(final Class sender, final String message) { error(sender, message, null); } public static void error(final Class sender, final String message, final Exception exception) { if (isLog4jAvailable()) { org.apache.log4j.Logger.getLogger(sender).error(message, exception); } else if (isCommonsLoggingAvailable()) { org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(sender); log.error(message, exception); } else { System.err.println(sender.getName() + ": " + message); if (exception != null) { exception.printStackTrace(); } } } }
package org.eclipse.titan.designer.AST.TTCN3.types; import java.text.MessageFormat; import java.util.List; import java.util.Set; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.ArraySubReference; import org.eclipse.titan.designer.AST.FieldSubReference; import org.eclipse.titan.designer.AST.IReferenceChain; import org.eclipse.titan.designer.AST.IReferenceableElement; import org.eclipse.titan.designer.AST.ISubReference; import org.eclipse.titan.designer.AST.IType; import org.eclipse.titan.designer.AST.ITypeWithComponents; import org.eclipse.titan.designer.AST.Identifier; import org.eclipse.titan.designer.AST.Location; import org.eclipse.titan.designer.AST.ParameterisedSubReference; import org.eclipse.titan.designer.AST.Reference; import org.eclipse.titan.designer.AST.ReferenceFinder; import org.eclipse.titan.designer.AST.Scope; import org.eclipse.titan.designer.AST.Type; import org.eclipse.titan.designer.AST.ISubReference.Subreference_type; import org.eclipse.titan.designer.AST.ReferenceFinder.Hit; import org.eclipse.titan.designer.AST.TTCN3.Expected_Value_type; import org.eclipse.titan.designer.AST.TTCN3.attributes.MultipleWithAttributes; import org.eclipse.titan.designer.AST.TTCN3.attributes.Qualifier; import org.eclipse.titan.designer.AST.TTCN3.attributes.Qualifiers; import org.eclipse.titan.designer.AST.TTCN3.attributes.SingleWithAttribute; import org.eclipse.titan.designer.AST.TTCN3.attributes.WithAttributesPath; import org.eclipse.titan.designer.AST.TTCN3.attributes.SingleWithAttribute.Attribute_Type; import org.eclipse.titan.designer.declarationsearch.Declaration; import org.eclipse.titan.designer.editors.ProposalCollector; import org.eclipse.titan.designer.editors.actions.DeclarationCollector; import org.eclipse.titan.designer.graphics.ImageCache; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.ttcn3parser.ReParseException; import org.eclipse.titan.designer.parsers.ttcn3parser.TTCN3ReparseUpdater; /** * @author Kristof Szabados * */ public abstract class TTCN3_Set_Seq_Choice_BaseType extends Type implements ITypeWithComponents, IReferenceableElement { protected CompFieldMap compFieldMap; private boolean componentInternal; public TTCN3_Set_Seq_Choice_BaseType(final CompFieldMap compFieldMap) { this.compFieldMap = compFieldMap; componentInternal = false; compFieldMap.setMyType(this); compFieldMap.setFullNameParent(this); } @Override public final void setMyScope(final Scope scope) { super.setMyScope(scope); compFieldMap.setMyScope(scope); } /** @return the number of components */ public final int getNofComponents() { if (compFieldMap == null) { return 0; } return compFieldMap.fields.size(); } /** * Returns the element at the specified position. * * @param index index of the element to return * @return the element at the specified position in this list */ public final CompField getComponentByIndex(final int index) { return compFieldMap.fields.get(index); } /** * Returns whether a component with the name exists or not.. * * @param name the name of the element to check * @return true if there is an element with that name, false otherwise. */ public final boolean hasComponentWithName(final String name) { if (compFieldMap.componentFieldMap == null) { return false; } return compFieldMap.componentFieldMap.containsKey(name); } /** * Returns the element with the specified name. * * @param name the name of the element to return * @return the element with the specified name in this list, or null if none was found */ public final CompField getComponentByName(final String name) { if (compFieldMap.componentFieldMap == null) { return null; } return compFieldMap.componentFieldMap.get(name); } /** * Returns the identifier of the element at the specified position. * * @param index index of the element to return * @return the identifier of the element at the specified position in this * list */ public final Identifier getComponentIdentifierByIndex(final int index) { return compFieldMap.fields.get(index).getIdentifier(); } @Override public final IType getFieldType(final CompilationTimeStamp timestamp, final Reference reference, final int actualSubReference, final Expected_Value_type expectedIndex, final IReferenceChain refChain, final boolean interruptIfOptional) { List<ISubReference> subreferences = reference.getSubreferences(); if (subreferences.size() <= actualSubReference) { return this; } ISubReference subreference = subreferences.get(actualSubReference); switch (subreference.getReferenceType()) { case arraySubReference: subreference.getLocation().reportSemanticError(MessageFormat.format(ArraySubReference.INVALIDSUBREFERENCE, getTypename())); return null; case fieldSubReference: Identifier id = subreference.getId(); CompField compField = compFieldMap.getCompWithName(id); if (compField == null) { subreference.getLocation().reportSemanticError( MessageFormat.format(FieldSubReference.NONEXISTENTSUBREFERENCE, ((FieldSubReference) subreference).getId().getDisplayName(), getTypename())); return null; } IType fieldType = compField.getType(); if (fieldType == null) { return null; } if (interruptIfOptional && compField.isOptional()) { return null; } Expected_Value_type internalExpectation = expectedIndex == Expected_Value_type.EXPECTED_TEMPLATE ? Expected_Value_type.EXPECTED_DYNAMIC_VALUE : expectedIndex; return fieldType.getFieldType(timestamp, reference, actualSubReference + 1, internalExpectation, refChain, interruptIfOptional); case parameterisedSubReference: subreference.getLocation().reportSemanticError( MessageFormat.format(FieldSubReference.INVALIDSUBREFERENCE, ((ParameterisedSubReference) subreference).getId().getDisplayName(), getTypename())); return null; default: subreference.getLocation().reportSemanticError(ISubReference.INVALIDSUBREFERENCE); return null; } } @Override public boolean getSubrefsAsArray(final CompilationTimeStamp timestamp, final Reference reference, final int actualSubReference, final List<Integer> subrefsArray, final List<IType> typeArray) { List<ISubReference> subreferences = reference.getSubreferences(); if (subreferences.size() <= actualSubReference) { return true; } ISubReference subreference = subreferences.get(actualSubReference); switch (subreference.getReferenceType()) { case arraySubReference: subreference.getLocation().reportSemanticError(MessageFormat.format(ArraySubReference.INVALIDSUBREFERENCE, getTypename())); return false; case fieldSubReference: Identifier id = subreference.getId(); CompField compField = compFieldMap.getCompWithName(id); if (compField == null) { subreference.getLocation().reportSemanticError( MessageFormat.format(FieldSubReference.NONEXISTENTSUBREFERENCE, ((FieldSubReference) subreference).getId().getDisplayName(), getTypename())); return false; } int fieldIndex = compFieldMap.fields.indexOf(compField); IType fieldType = compField.getType(); if (fieldType == null) { return false; } subrefsArray.add(fieldIndex); typeArray.add(this); return fieldType.getSubrefsAsArray(timestamp, reference, actualSubReference + 1, subrefsArray, typeArray); case parameterisedSubReference: subreference.getLocation().reportSemanticError( MessageFormat.format(FieldSubReference.INVALIDSUBREFERENCE, ((ParameterisedSubReference) subreference).getId().getDisplayName(), getTypename())); return false; default: subreference.getLocation().reportSemanticError(ISubReference.INVALIDSUBREFERENCE); return false; } } @Override public boolean getFieldTypesAsArray(final Reference reference, final int actualSubReference, final List<IType> typeArray) { List<ISubReference> subreferences = reference.getSubreferences(); if (subreferences.size() <= actualSubReference) { return true; } ISubReference subreference = subreferences.get(actualSubReference); switch (subreference.getReferenceType()) { case arraySubReference: return false; case fieldSubReference: Identifier id = subreference.getId(); if (compFieldMap == null) { return false; } CompField compField = compFieldMap.getCompWithName(id); if (compField == null) { return false; } IType fieldType = compField.getType(); if (fieldType == null) { return false; } typeArray.add(this); return fieldType.getFieldTypesAsArray(reference, actualSubReference + 1, typeArray); case parameterisedSubReference: return false; default: return false; } } @Override public final boolean isComponentInternal(final CompilationTimeStamp timestamp) { check(timestamp); return componentInternal; } @Override public void parseAttributes(final CompilationTimeStamp timestamp) { checkDoneAttribute(timestamp); if (!hasVariantAttributes(timestamp)) { return; } /* This will be useful when processing of the variant attributes assigned to the whole type is implemented ArrayList<SingleWithAttribute> realAttributes = withAttributesPath.getRealAttributes(timestamp); for (int i = 0; i < realAttributes.size(); i++) { SingleWithAttribute tempSingle = realAttributes.get(i); if (Attribute_Type.Variant_Attribute.equals(tempSingle.getAttributeType()) && (tempSingle.getQualifiers() == null || tempSingle.getQualifiers().getNofQualifiers() == 0)) { } }*/ MultipleWithAttributes selfAttributes = withAttributesPath.getAttributes(); if (selfAttributes == null) { return; } MultipleWithAttributes newSelfAttributes = new MultipleWithAttributes(); for (int i = 0; i < selfAttributes.getNofElements(); i++) { SingleWithAttribute temp = selfAttributes.getAttribute(i); if (Attribute_Type.Encode_Attribute.equals(temp.getAttributeType())) { SingleWithAttribute newAttribute = new SingleWithAttribute( temp.getAttributeType(), temp.hasOverride(), null, temp.getAttributeSpecification()); newSelfAttributes.addAttribute(newAttribute); } } WithAttributesPath encodeAttributePath = null; if (newSelfAttributes.getNofElements() > 0) { //at least on "encode" was copied; create a context for them. encodeAttributePath = new WithAttributesPath(); encodeAttributePath.setWithAttributes(newSelfAttributes); encodeAttributePath.setAttributeParent(withAttributesPath.getAttributeParent()); } for (int i = 0, size = getNofComponents(); i < size; i++) { CompField componentField = getComponentByIndex(i); IType componentType = componentField.getType(); componentType.clearWithAttributes(); if (encodeAttributePath == null) { componentType.setAttributeParentPath(withAttributesPath.getAttributeParent()); } else { componentType.setAttributeParentPath(encodeAttributePath); } } // Distribute the attributes with qualifiers to the components for (int j = 0; j < selfAttributes.getNofElements(); j++) { SingleWithAttribute tempSingle = selfAttributes.getAttribute(j); Qualifiers tempQualifiers = tempSingle.getQualifiers(); if (tempQualifiers == null || tempQualifiers.getNofQualifiers() == 0) { continue; } for (int k = 0, kmax = tempQualifiers.getNofQualifiers(); k < kmax; k++) { Qualifier tempQualifier = tempQualifiers.getQualifierByIndex(k); if (tempQualifier.getNofSubReferences() == 0) { continue; } ISubReference tempSubReference = tempQualifier.getSubReferenceByIndex(0); boolean componentFound = false; for (int i = 0, size = getNofComponents(); i < size; i++) { CompField componentField = getComponentByIndex(i); Identifier componentId = componentField.getIdentifier(); if (tempSubReference.getReferenceType() == Subreference_type.fieldSubReference && tempSubReference.getId().equals(componentId)) { // Found a qualifier whose first identifier matches the component name Qualifiers calculatedQualifiers = new Qualifiers(); calculatedQualifiers.addQualifier(tempQualifier.getQualifierWithoutFirstSubRef()); SingleWithAttribute tempSingle2 = new SingleWithAttribute( tempSingle.getAttributeType(), tempSingle.hasOverride(), calculatedQualifiers, tempSingle.getAttributeSpecification()); tempSingle2.setLocation(new Location(tempSingle.getLocation())); IType componentType = componentField.getType(); MultipleWithAttributes componentAttributes = componentType.getAttributePath().getAttributes(); if (componentAttributes == null) { componentAttributes = new MultipleWithAttributes(); componentAttributes.addAttribute(tempSingle2); componentType.setWithAttributes(componentAttributes); } else { componentAttributes.addAttribute(tempSingle2); } componentFound = true; } } if (!componentFound) { if (tempSubReference.getReferenceType() == Subreference_type.arraySubReference) { tempQualifier.getLocation().reportSemanticError(Qualifier.INVALID_INDEX_QUALIFIER); } else { tempQualifier.getLocation().reportSemanticError(MessageFormat.format( Qualifier.INVALID_FIELD_QUALIFIER, tempSubReference.getId().getDisplayName())); } } } } } @Override public final void check(final CompilationTimeStamp timestamp) { if (lastTimeChecked != null && !lastTimeChecked.isLess(timestamp)) { return; } lastTimeChecked = timestamp; componentInternal = false; isErroneous = false; parseAttributes(timestamp); compFieldMap.check(timestamp); for (int i = 0, size = getNofComponents(); i < size; i++) { IType type = getComponentByIndex(i).getType(); if (type != null && type.isComponentInternal(timestamp)) { componentInternal = true; break; } } if (constraints != null) { constraints.check(timestamp); } checkSubtypeRestrictions(timestamp); } @Override public final void checkComponentInternal(final CompilationTimeStamp timestamp, final Set<IType> typeSet, final String operation) { if (typeSet.contains(this)) { return; } typeSet.add(this); for (int i = 0, size = getNofComponents(); i < size; i++) { IType type = getComponentByIndex(i).getType(); if (type != null && type.isComponentInternal(timestamp)) { type.checkComponentInternal(timestamp, typeSet, operation); } } typeSet.remove(this); } @Override public final Object[] getOutlineChildren() { return compFieldMap.getOutlineChildren(); } /** * Searches and adds a completion proposal to the provided collector if a * valid one is found. * <p> * In case of structural types, the member fields are checked if they could * complete the proposal. * * @param propCollector the proposal collector to add the proposal to, and * used to get more information * @param i index, used to identify which element of the reference (used by * the proposal collector) should be checked for completions. * */ @Override public final void addProposal(final ProposalCollector propCollector, final int i) { List<ISubReference> subreferences = propCollector.getReference().getSubreferences(); if (subreferences.size() <= i) { return; } ISubReference subreference = subreferences.get(i); if (Subreference_type.fieldSubReference.equals(subreference.getReferenceType())) { if (subreferences.size() > i + 1) { // the reference might go on CompField compField = compFieldMap.getCompWithName(subreference.getId()); if (compField == null) { return; } IType type = compField.getType(); if (type != null) { type.addProposal(propCollector, i + 1); } } else { // final part of the reference List<CompField> compFields = compFieldMap.getComponentsWithPrefix(subreference.getId().getName()); for (CompField compField : compFields) { String proposalKind = compField.getType().getProposalDescription(new StringBuilder()).toString(); propCollector.addProposal(compField.getIdentifier(), " - " + proposalKind, ImageCache.getImage(getOutlineIcon()), proposalKind); IType type = compField.getType(); if (type != null && compField.getIdentifier().equals(subreference.getId())) { type = type.getTypeRefdLast(CompilationTimeStamp.getBaseTimestamp()); type.addProposal(propCollector, i + 1); } } } } } /** * Searches and adds a declaration proposal to the provided collector if a * valid one is found. * <p> * In case of structural types, the member fields are checked if they could * be the declaration searched for. * * @param declarationCollector the declaration collector to add the * declaration to, and used to get more information. * @param i index, used to identify which element of the reference (used by * the declaration collector) should be checked. * */ @Override public final void addDeclaration(final DeclarationCollector declarationCollector, final int i) { List<ISubReference> subreferences = declarationCollector.getReference().getSubreferences(); if (subreferences.size() <= i) { return; } ISubReference subreference = subreferences.get(i); if (Subreference_type.fieldSubReference.equals(subreference.getReferenceType())) { if (subreferences.size() > i + 1) { // the reference might go on CompField compField = compFieldMap.getCompWithName(subreference.getId()); if (compField == null) { return; } IType type = compField.getType(); if (type != null) { type.addDeclaration(declarationCollector, i + 1); } } else { // final part of the reference List<CompField> compFields = compFieldMap.getComponentsWithPrefix(subreference.getId().getName()); for (CompField compField : compFields) { declarationCollector.addDeclaration(compField.getIdentifier().getDisplayName(), compField.getIdentifier().getLocation(), this); } } } } @Override public final void updateSyntax(final TTCN3ReparseUpdater reparser, final boolean isDamaged) throws ReParseException { if (isDamaged) { lastTimeChecked = null; boolean handled = false; if (compFieldMap != null && reparser.envelopsDamage(compFieldMap.getLocation())) { try { compFieldMap.updateSyntax(reparser, true); } catch (ReParseException e) { e.decreaseDepth(); throw e; } reparser.updateLocation(compFieldMap.getLocation()); handled = true; } if (subType != null) { subType.updateSyntax(reparser, false); handled = true; } if (handled) { return; } throw new ReParseException(); } reparser.updateLocation(compFieldMap.getLocation()); compFieldMap.updateSyntax(reparser, false); if (subType != null) { subType.updateSyntax(reparser, false); } if (withAttributesPath != null) { withAttributesPath.updateSyntax(reparser, false); reparser.updateLocation(withAttributesPath.getLocation()); } } @Override public void getEnclosingField(final int offset, final ReferenceFinder rf) { compFieldMap.getEnclosingField(offset, rf); } @Override public void findReferences(final ReferenceFinder referenceFinder, final List<Hit> foundIdentifiers) { super.findReferences(referenceFinder, foundIdentifiers); if (compFieldMap != null) { compFieldMap.findReferences(referenceFinder, foundIdentifiers); } } @Override protected boolean memberAccept(final ASTVisitor v) { if (!super.memberAccept(v)) { return false; } if (compFieldMap!=null && !compFieldMap.accept(v)) { return false; } return true; } @Override public Identifier getComponentIdentifierByName(final Identifier identifier) { if(identifier == null){ return null; } final CompField cf = getComponentByName(identifier.getName()); return cf == null ? null : cf.getIdentifier(); } @Override public Declaration resolveReference(final Reference reference, final int subRefIdx, final ISubReference lastSubreference) { final List<ISubReference> subreferences = reference.getSubreferences(); int localIndex = subRefIdx; while (localIndex < subreferences.size() && subreferences.get(localIndex) instanceof ArraySubReference) { ++localIndex; } if (localIndex == subreferences.size()) { return null; } final CompField compField = getComponentByName(subreferences.get(localIndex).getId().getName()); if (compField == null) { return null; } if (subreferences.get(localIndex) == lastSubreference) { return Declaration.createInstance(getDefiningAssignment(), compField.getIdentifier()); } final IType compFieldType = compField.getType().getTypeRefdLast(CompilationTimeStamp.getBaseTimestamp()); if (compFieldType instanceof IReferenceableElement) { final Declaration decl = ((IReferenceableElement) compFieldType).resolveReference(reference, localIndex + 1, lastSubreference); return decl != null ? decl : Declaration.createInstance(getDefiningAssignment(), compField.getIdentifier()); } return null; } }
package hochberger.utilities.gui.font; import hochberger.utilities.files.Closer; import java.awt.Font; import java.awt.FontFormatException; import java.io.IOException; import java.io.InputStream; public class FontLoader { private FontLoader() { super(); } public static Font loadFrom(final String filePath) { final InputStream inputStream = ClassLoader .getSystemResourceAsStream(filePath); Font result = null; try { result = Font.createFont(Font.TRUETYPE_FONT, inputStream); } catch (final FontFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { Closer.close(inputStream); } return result; } public static Font loadFromWithFallback(final String filePath, final Font fallback) { Font result = loadFrom(filePath); if (null == result) { result = fallback; } return result; } }
package org.jcryptool.visual.crtverification.views; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.window.Window; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.ResourceManager; import org.eclipse.wb.swt.SWTResourceManager; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.visual.crtverification.Activator; public class CrtVerViewComposite extends Composite implements PaintListener { // Object Controller CrtVerViewController controller = new CrtVerViewController(); // Variables static Text TextRootCaFromDay; static Text TextCaFromDay; static Text TextCertFromDay; static Text TextRootCaThruDay; static Text TextCaThruDay; static Text TextCertThruDay; static Text TextSignatureDateDay; static Text TextVerificationDateDay; static Label thruRootCa; static Label fromRootCa; static Label thruCa; static Label fromCa; static Label thruCert; static Label fromCert; static Label signatureDate; static Label verificationDate; static Scale ScaleCertBegin; static Scale ScaleCertEnd; static Scale ScaleCaBegin; static Scale ScaleCaEnd; static Scale ScaleRootCaBegin; static Scale ScaleRootCaEnd; static Scale ScaleVerificationDate; static Scale ScaleSignatureDate; private Text txtDiesIstDer; static Button btnLoadRootCa; static Button btnLoadCa; static Button btnLoadUserCert; static Button btnValidate; static Canvas canvas1; static Canvas canvas2; static int arrowSigDiff=0; static int arrowVerDiff=0; static ControlDecoration validitySymbol; private Text txtTheCertificatechainAlias; /** * Create the composite. * * @param parent * @param style */ public CrtVerViewComposite(Composite parent, int style, CrtVerView view) { super(parent, style); setLayout(new FillLayout(SWT.HORIZONTAL)); TabFolder tabFolder = new TabFolder(this, SWT.NONE); TabItem tbtmSchalenmodell = new TabItem(tabFolder, SWT.NONE); tbtmSchalenmodell.setText("Certificate Verification"); Composite composite = new Composite(tabFolder, SWT.NONE); tbtmSchalenmodell.setControl(composite); composite.setLayout(new GridLayout(15, false)); txtDiesIstDer = new Text(composite, SWT.BORDER); txtDiesIstDer.setEnabled(false); txtDiesIstDer.setEditable(false); txtDiesIstDer .setText("DE: Mit diesem Plugin können Sie sehen, wie es zu einer Bewertung der Gültigkeit einer Signatur kommt, wenn man unterschiedliche Zertifikatsbäume und unterschiedliche Gültigkeitsmodelle benutzt.\n\nEN: This plugin helps to demonstrate the validation checks of the shell- and chain model. "); GridData gd_txtDiesIstDer = new GridData(SWT.FILL, SWT.CENTER, true, false, 15, 1); gd_txtDiesIstDer.heightHint = 70; txtDiesIstDer.setLayoutData(gd_txtDiesIstDer); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); Label lblNotValidBefore = new Label(composite, SWT.NONE); lblNotValidBefore.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 12, 1)); lblNotValidBefore.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblNotValidBefore.setAlignment(SWT.CENTER); lblNotValidBefore.setText("Not Valid Before"); Label lblNotValidAfter = new Label(composite, SWT.NONE); lblNotValidAfter.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblNotValidAfter.setText("Not Valid After"); lblNotValidAfter.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblNotValidAfter.setAlignment(SWT.CENTER); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); Composite composite_4 = new Composite(composite, SWT.NONE); composite_4.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 12, 1)); Label label = new Label(composite_4, SWT.NONE); label.setText(controller.scaleUpdate(0, 180, controller.getDateformat3())); label.setBounds(0, 0, 59, 14); Label label_1 = new Label(composite_4, SWT.NONE); label_1.setText(controller.scaleUpdate(360, 180, controller.getDateformat3())); label_1.setAlignment(SWT.RIGHT); label_1.setBounds(301, 0, 59, 14); Composite composite_3 = new Composite(composite, SWT.NONE); GridData gd_composite_3 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_composite_3.widthHint = 360; composite_3.setLayoutData(gd_composite_3); Label label_2 = new Label(composite_3, SWT.NONE); label_2.setBounds(0, 0, 59, 14); label_2.setText(controller.scaleUpdate(0, 180, controller.getDateformat3())); Label label_3 = new Label(composite_3, SWT.NONE); label_3.setAlignment(SWT.RIGHT); label_3.setBounds(301, 0, 59, 14); label_3.setText(controller.scaleUpdate(360, 180, controller.getDateformat3())); new Label(composite, SWT.NONE); Label lblRootCa = new Label(composite, SWT.NONE); GridData gd_lblRootCa = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblRootCa.heightHint = 30; gd_lblRootCa.verticalIndent = 10; lblRootCa.setLayoutData(gd_lblRootCa); lblRootCa.setText("Root CA"); lblRootCa.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblRootCa.setAlignment(SWT.CENTER); final Scale ScaleRootCaBegin = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleRootCaBegin = ScaleRootCaBegin; ScaleRootCaBegin.setToolTipText(""); ScaleRootCaBegin.setMaximum(360); GridData gd_ScaleRootCaBegin = new GridData(SWT.LEFT, SWT.CENTER, false, false, 12, 1); gd_ScaleRootCaBegin.widthHint = 360; ScaleRootCaBegin.setLayoutData(gd_ScaleRootCaBegin); ScaleRootCaBegin.setSelection(180); final Scale ScaleRootCaEnd = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleRootCaEnd = ScaleRootCaEnd; GridData gd_ScaleRootCaEnd = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_ScaleRootCaEnd.widthHint = 360; ScaleRootCaEnd.setLayoutData(gd_ScaleRootCaEnd); ScaleRootCaEnd.setMaximum(360); ScaleRootCaEnd.setSelection(180); btnLoadRootCa = new Button(composite, SWT.NONE); GridData gd_btnLoadRootCa = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_btnLoadRootCa.heightHint = 30; gd_btnLoadRootCa.widthHint = 100; btnLoadRootCa.setLayoutData(gd_btnLoadRootCa); btnLoadRootCa.setText("Load Root CA"); btnLoadRootCa.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { ChooseCert wiz = new ChooseCert(3); WizardDialog dialog = new WizardDialog(new Shell(Display .getCurrent()), wiz) { @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); // set size of the wizard-window (x,y) newShell.setSize(550, 500); } }; if (dialog.open() == Window.OK) { // Hier kann man Aktionen durfuehren die passieren // sollen wenn die WizardPage aufgerufen wird // zB aktivieren/deaktivieren von Buttons der // Hauptansicht } } catch (Exception ex) { LogUtil.logError(Activator.PLUGIN_ID, ex); } } }); Label lblCa = new Label(composite, SWT.NONE); GridData gd_lblCa = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblCa.verticalIndent = 10; gd_lblCa.heightHint = 30; lblCa.setLayoutData(gd_lblCa); lblCa.setText("CA"); lblCa.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblCa.setAlignment(SWT.CENTER); final Scale ScaleCaBegin = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleCaBegin = ScaleCaBegin; ScaleCaBegin.setMaximum(360); GridData gd_ScaleCaBegin = new GridData(SWT.LEFT, SWT.CENTER, false, false, 12, 1); gd_ScaleCaBegin.widthHint = 360; ScaleCaBegin.setLayoutData(gd_ScaleCaBegin); ScaleCaBegin.setSelection(180); final Scale ScaleCaEnd = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleCaEnd = ScaleCaEnd; ScaleCaEnd.setMaximum(360); GridData gd_ScaleCaEnd = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_ScaleCaEnd.widthHint = 360; ScaleCaEnd.setLayoutData(gd_ScaleCaEnd); ScaleCaEnd.setSelection(180); btnLoadCa = new Button(composite, SWT.NONE); GridData gd_btnLoadCa = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_btnLoadCa.heightHint = 30; gd_btnLoadCa.widthHint = 100; btnLoadCa.setLayoutData(gd_btnLoadCa); btnLoadCa.setText("Load CA"); btnLoadCa.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { ChooseCert wiz = new ChooseCert(2); WizardDialog dialog = new WizardDialog(new Shell(Display .getCurrent()), wiz) { @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); // set size of the wizard-window (x,y) newShell.setSize(550, 500); } }; if (dialog.open() == Window.OK) { // Hier kann man Aktionen durfuehren die passieren // sollen wenn die WizardPage aufgerufen wird // zB aktivieren/deaktivieren von Buttons der // Hauptansicht } } catch (Exception ex) { LogUtil.logError(Activator.PLUGIN_ID, ex); } } }); Label lblUserCertificate = new Label(composite, SWT.NONE); GridData gd_lblUserCertificate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblUserCertificate.verticalIndent = 10; gd_lblUserCertificate.heightHint = 30; lblUserCertificate.setLayoutData(gd_lblUserCertificate); lblUserCertificate.setText("User Certificate"); lblUserCertificate.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblUserCertificate.setAlignment(SWT.CENTER); final Scale ScaleCertBegin = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleCertBegin = ScaleCertBegin; ScaleCertBegin.setMaximum(360); GridData gd_ScaleCertBegin = new GridData(SWT.LEFT, SWT.CENTER, false, false, 12, 1); gd_ScaleCertBegin.widthHint = 360; ScaleCertBegin.setLayoutData(gd_ScaleCertBegin); ScaleCertBegin.setSelection(180); final Scale ScaleCertEnd = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleCertEnd = ScaleCertEnd; ScaleCertEnd.setMaximum(360); GridData gd_ScaleCertEnd = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_ScaleCertEnd.widthHint = 360; ScaleCertEnd.setLayoutData(gd_ScaleCertEnd); ScaleCertEnd.setSelection(180); btnLoadUserCert = new Button(composite, SWT.NONE); // Selection Listeners | Scales btnLoadUserCert.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { ChooseCert wiz = new ChooseCert(1); WizardDialog dialog = new WizardDialog(new Shell(Display .getCurrent()), wiz) { @Override protected void configureShell(Shell newShell) { super.configureShell(newShell); // set size of the wizard-window (x,y) newShell.setSize(550, 500); } }; if (dialog.open() == Window.OK) { // Hier kann man Aktionen durfuehren die passieren // sollen wenn die WizardPage aufgerufen wird // zB aktivieren/deaktivieren von Buttons der // Hauptansicht } } catch (Exception ex) { LogUtil.logError(Activator.PLUGIN_ID, ex); } } }); GridData gd_btnLoadUserCert = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_btnLoadUserCert.heightHint = 30; gd_btnLoadUserCert.widthHint = 100; btnLoadUserCert.setLayoutData(gd_btnLoadUserCert); btnLoadUserCert.setText("Load User Cert"); Label lblArrowSig = new Label(composite, SWT.NONE); lblArrowSig.setFont(SWTResourceManager.getFont("Lucida Grande", 9, SWT.NORMAL)); GridData gd_lblArrowSig = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); gd_lblArrowSig.heightHint = 13; lblArrowSig.setLayoutData(gd_lblArrowSig); lblArrowSig.setForeground(SWTResourceManager.getColor(30, 144, 255)); lblArrowSig.setText("Signature Date"); canvas1 = new Canvas(composite, SWT.NONE | SWT.TRANSPARENT); canvas1.setLayout(new GridLayout(1, false)); GridData gd_canvas1 = new GridData(SWT.FILL, SWT.FILL, false, false, 12, 2); gd_canvas1.heightHint = 25; gd_canvas1.widthHint = 359; canvas1.setLayoutData(gd_canvas1); canvas1.addPaintListener(this); canvas2 = new Canvas(composite, SWT.NONE | SWT.TRANSPARENT); GridData gd_canvas2 = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 2); gd_canvas2.widthHint = 364; canvas2.setLayoutData(gd_canvas2); canvas2.setLayout(new GridLayout(1, false)); canvas2.addPaintListener(this); new Label(composite, SWT.NONE); Label lblArrowVer = new Label(composite, SWT.NONE); lblArrowVer.setFont(SWTResourceManager.getFont("Lucida Grande", 9, SWT.NORMAL)); lblArrowVer.setForeground(SWTResourceManager.getColor(72, 61, 139)); lblArrowVer.setText("Verification Date"); txtTheCertificatechainAlias = new Text(composite, SWT.BORDER); txtTheCertificatechainAlias.setEditable(false); txtTheCertificatechainAlias.setText("Unsuccessfully validated!\n\nUsed model:\n\tShell-model\n\nCertificate-chain:\n\tCert-Alias 1\n\tCert-Alias 2\n\tCert-Alias 3\n"); txtTheCertificatechainAlias.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 6)); Label SeperatorHorizontal = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd_SeperatorHorizontal = new GridData(SWT.LEFT, SWT.CENTER, false, false, 14, 1); gd_SeperatorHorizontal.widthHint = 835; SeperatorHorizontal.setLayoutData(gd_SeperatorHorizontal); new Label(composite, SWT.NONE); Composite composite_5 = new Composite(composite, SWT.NONE); GridData gd_composite_5 = new GridData(SWT.FILL, SWT.CENTER, false, false, 13, 1); gd_composite_5.widthHint = 720; composite_5.setLayoutData(gd_composite_5); Label label_4 = new Label(composite_5, SWT.NONE); label_4.setText(controller.scaleUpdate(0, 360, controller.getDateformat3())); label_4.setBounds(0, 0, 59, 14); Label label_5 = new Label(composite_5, SWT.NONE); label_5.setText(controller.scaleUpdate(720, 360, controller.getDateformat3())); label_5.setAlignment(SWT.RIGHT); label_5.setBounds(666, 0, 59, 14); Label lblSignatureDate = new Label(composite, SWT.NONE); GridData gd_lblSignatureDate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblSignatureDate.verticalIndent = 10; gd_lblSignatureDate.heightHint = 30; lblSignatureDate.setLayoutData(gd_lblSignatureDate); lblSignatureDate.setText("Signature Date"); lblSignatureDate.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblSignatureDate.setAlignment(SWT.CENTER); final Scale ScaleSignatureDate = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleSignatureDate = ScaleSignatureDate; ScaleSignatureDate.setMaximum(720); GridData gd_ScaleSignatureDate = new GridData(SWT.FILL, SWT.FILL, false, false, 13, 1); gd_ScaleSignatureDate.widthHint = 480; ScaleSignatureDate.setLayoutData(gd_ScaleSignatureDate); ScaleSignatureDate.setSelection(360); Label lblVerificationDate = new Label(composite, SWT.NONE); GridData gd_lblVerificationDate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_lblVerificationDate.verticalIndent = 10; gd_lblVerificationDate.heightHint = 30; lblVerificationDate.setLayoutData(gd_lblVerificationDate); lblVerificationDate.setText("Verification Date"); lblVerificationDate.setFont(SWTResourceManager.getFont("Lucida Grande", 12, SWT.NORMAL)); lblVerificationDate.setAlignment(SWT.CENTER); final Scale ScaleVerificationDate = new Scale(composite, SWT.NONE); CrtVerViewComposite.ScaleVerificationDate = ScaleVerificationDate; GridData gd_ScaleVerificationDate = new GridData(SWT.FILL, SWT.FILL, false, false, 13, 1); gd_ScaleVerificationDate.widthHint = 480; ScaleVerificationDate.setLayoutData(gd_ScaleVerificationDate); ScaleVerificationDate.setMaximum(720); ScaleVerificationDate.setSelection(360); new Label(composite, SWT.NONE); Group grpDetails = new Group(composite, SWT.NONE); GridData gd_grpDetails = new GridData(SWT.LEFT, SWT.CENTER, false, false, 13, 1); gd_grpDetails.widthHint = 717; grpDetails.setLayoutData(gd_grpDetails); grpDetails.setText("Details"); grpDetails.setLayout(new GridLayout(10, false)); new Label(grpDetails, SWT.NONE); new Label(grpDetails, SWT.NONE); Label LabelHeaderRootCa = new Label(grpDetails, SWT.NONE); LabelHeaderRootCa.setAlignment(SWT.CENTER); GridData gd_LabelHeaderRootCa = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelHeaderRootCa.widthHint = 100; LabelHeaderRootCa.setLayoutData(gd_LabelHeaderRootCa); LabelHeaderRootCa.setText("Root CA"); Label LabelHeaderCa = new Label(grpDetails, SWT.NONE); LabelHeaderCa.setAlignment(SWT.CENTER); GridData gd_LabelHeaderCa = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelHeaderCa.widthHint = 100; LabelHeaderCa.setLayoutData(gd_LabelHeaderCa); LabelHeaderCa.setText("CA"); Label LabelHeaderCert = new Label(grpDetails, SWT.NONE); LabelHeaderCert.setAlignment(SWT.CENTER); GridData gd_LabelHeaderCert = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelHeaderCert.widthHint = 100; LabelHeaderCert.setLayoutData(gd_LabelHeaderCert); LabelHeaderCert.setText("User Certificate"); new Label(grpDetails, SWT.NONE); Label SeperatorDetailsVertical = new Label(grpDetails, SWT.SEPARATOR | SWT.VERTICAL); SeperatorDetailsVertical.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 3)); new Label(grpDetails, SWT.NONE); Label LabelHeaderSignatureDate = new Label(grpDetails, SWT.NONE); LabelHeaderSignatureDate.setText("Signature Date"); Label LabelHeaderVerificationDate = new Label(grpDetails, SWT.NONE); LabelHeaderVerificationDate.setText("Verification Date"); Label lblValidFrom = new Label(grpDetails, SWT.NONE); lblValidFrom.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblValidFrom.setText("valid from:"); new Label(grpDetails, SWT.NONE); Composite composite_from_rootca = new Composite(grpDetails, SWT.NONE); composite_from_rootca.setLayout(new GridLayout(2, false)); TextRootCaFromDay = new Text(composite_from_rootca, SWT.BORDER); TextRootCaFromDay.setText("1"); TextRootCaFromDay.setTextLimit(2); GridData gd_TextRootCaFromDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextRootCaFromDay.widthHint = 17; TextRootCaFromDay.setLayoutData(gd_TextRootCaFromDay); TextRootCaFromDay.setSize(24, 19); Label LabelRootCaFrom = new Label(composite_from_rootca, SWT.NONE); GridData gd_LabelRootCaFrom = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelRootCaFrom.widthHint = 60; LabelRootCaFrom.setLayoutData(gd_LabelRootCaFrom); fromRootCa = LabelRootCaFrom; // Initialize Label "From Root CA" with actual date LabelRootCaFrom.setText(""); Composite composite_from_ca = new Composite(grpDetails, SWT.NONE); composite_from_ca.setLayout(new GridLayout(2, false)); TextCaFromDay = new Text(composite_from_ca, SWT.BORDER); TextCaFromDay.setText("1"); TextCaFromDay.setTextLimit(2); GridData gd_TextCaFromDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextCaFromDay.widthHint = 17; TextCaFromDay.setLayoutData(gd_TextCaFromDay); Label LabelCaFrom = new Label(composite_from_ca, SWT.NONE); GridData gd_LabelCaFrom = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelCaFrom.widthHint = 60; LabelCaFrom.setLayoutData(gd_LabelCaFrom); fromCa = LabelCaFrom; // Initialize Label "From CA" with actual date LabelCaFrom.setText(""); Composite composite_from_user_cert = new Composite(grpDetails, SWT.NONE); composite_from_user_cert.setLayout(new GridLayout(2, false)); TextCertFromDay = new Text(composite_from_user_cert, SWT.BORDER); TextCertFromDay.setText("1"); TextCertFromDay.setTextLimit(2); GridData gd_TextCertFromDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextCertFromDay.widthHint = 17; TextCertFromDay.setLayoutData(gd_TextCertFromDay); Label LabelCertFrom = new Label(composite_from_user_cert, SWT.NONE); GridData gd_LabelCertFrom = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelCertFrom.widthHint = 60; LabelCertFrom.setLayoutData(gd_LabelCertFrom); fromCert = LabelCertFrom; // Initialize Label "From User Cert" with actual date LabelCertFrom.setText(""); new Label(grpDetails, SWT.NONE); new Label(grpDetails, SWT.NONE); Composite composite_1 = new Composite(grpDetails, SWT.NONE); composite_1.setLayout(new GridLayout(2, false)); TextSignatureDateDay = new Text(composite_1, SWT.BORDER); TextSignatureDateDay.setText("1"); TextSignatureDateDay.setTextLimit(2); GridData gd_TextSignatureDateDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextSignatureDateDay.widthHint = 17; TextSignatureDateDay.setLayoutData(gd_TextSignatureDateDay); Label LabelSignatureDate = new Label(composite_1, SWT.NONE); GridData gd_LabelSignatureDate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelSignatureDate.widthHint = 60; LabelSignatureDate.setLayoutData(gd_LabelSignatureDate); signatureDate = LabelSignatureDate; // Initialize Label "Signature Date" with actual date LabelSignatureDate.setText(""); Composite composite_2 = new Composite(grpDetails, SWT.NONE); composite_2.setLayout(new GridLayout(2, false)); TextVerificationDateDay = new Text(composite_2, SWT.BORDER); TextVerificationDateDay.setText("1"); TextVerificationDateDay.setTextLimit(2); GridData gd_TextVerificationDateDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextVerificationDateDay.widthHint = 17; TextVerificationDateDay.setLayoutData(gd_TextVerificationDateDay); final Label LabelVerificationDate = new Label(composite_2, SWT.NONE); GridData gd_LabelVerificationDate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelVerificationDate.widthHint = 60; LabelVerificationDate.setLayoutData(gd_LabelVerificationDate); verificationDate = LabelVerificationDate; LabelVerificationDate.setText(""); Label lblValidThru = new Label(grpDetails, SWT.NONE); lblValidThru.setText("valid thru:"); new Label(grpDetails, SWT.NONE); Composite composite_thru_rootca = new Composite(grpDetails, SWT.NONE); composite_thru_rootca.setLayout(new GridLayout(2, false)); TextRootCaThruDay = new Text(composite_thru_rootca, SWT.BORDER); TextRootCaThruDay.setText("1"); TextRootCaThruDay.setTextLimit(2); GridData gd_TextRootCaThruDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextRootCaThruDay.widthHint = 17; TextRootCaThruDay.setLayoutData(gd_TextRootCaThruDay); Label LabelRootCaThru = new Label(composite_thru_rootca, SWT.NONE); GridData gd_LabelRootCaThru = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelRootCaThru.widthHint = 60; LabelRootCaThru.setLayoutData(gd_LabelRootCaThru); thruRootCa = LabelRootCaThru; // Initialize Label "Thru Root CA" with actual date LabelRootCaThru.setText(""); Composite composite_thru_ca = new Composite(grpDetails, SWT.NONE); composite_thru_ca.setLayout(new GridLayout(2, false)); TextCaThruDay = new Text(composite_thru_ca, SWT.BORDER); TextCaThruDay.setText("1"); TextCaThruDay.setTextLimit(2); GridData gd_TextCaThruDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextCaThruDay.widthHint = 17; TextCaThruDay.setLayoutData(gd_TextCaThruDay); Label LabelCaThru = new Label(composite_thru_ca, SWT.NONE); GridData gd_LabelCaThru = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelCaThru.widthHint = 60; LabelCaThru.setLayoutData(gd_LabelCaThru); thruCa = LabelCaThru; // Initialize Label "Thru CA" with actual date LabelCaThru.setText(""); Composite composite_thru_user_cert = new Composite(grpDetails, SWT.NONE); composite_thru_user_cert.setLayout(new GridLayout(2, false)); TextCertThruDay = new Text(composite_thru_user_cert, SWT.BORDER); TextCertThruDay.setText("1"); TextCertThruDay.setTextLimit(2); GridData gd_TextCertThruDay = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_TextCertThruDay.widthHint = 17; TextCertThruDay.setLayoutData(gd_TextCertThruDay); Label LabelCertThru = new Label(composite_thru_user_cert, SWT.NONE); GridData gd_LabelCertThru = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_LabelCertThru.widthHint = 60; LabelCertThru.setLayoutData(gd_LabelCertThru); thruCert = LabelCertThru; // Initialize Label "Thru User Cert" with actual date LabelCertThru.setText(""); new Label(grpDetails, SWT.NONE); new Label(grpDetails, SWT.NONE); new Label(grpDetails, SWT.NONE); new Label(grpDetails, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); new Label(composite, SWT.NONE); Composite composite_6 = new Composite(composite, SWT.NONE); composite_6.setLayout(new GridLayout(1, false)); composite_6.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); final Button btnShellModel = new Button(composite_6, SWT.RADIO); btnShellModel.setSelection(true); btnShellModel.setText("Shell Model"); final Button btnModifiedShellModel = new Button(composite_6, SWT.RADIO); btnModifiedShellModel.setText("Modified Shell Model"); final Button btnChainModel = new Button(composite_6, SWT.RADIO); btnChainModel.setText("Chain Model"); new Label(composite, SWT.NONE); Button btnReset = new Button(composite, SWT.NONE); GridData gd_btnReset = new GridData(SWT.LEFT, SWT.CENTER, false, false, 10, 1); gd_btnReset.widthHint = 100; gd_btnReset.heightHint = 30; btnReset.setLayoutData(gd_btnReset); btnReset.setText("Reset"); new Label(composite, SWT.NONE); Button btnBack = new Button(composite, SWT.NONE); GridData gd_btnBack = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1); gd_btnBack.widthHint = 100; gd_btnBack.heightHint = 30; btnBack.setLayoutData(gd_btnBack); btnBack.setText("Back"); Button btnForward = new Button(composite, SWT.NONE); GridData gd_btnForward = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); gd_btnForward.widthHint = 100; gd_btnForward.heightHint = 30; btnForward.setLayoutData(gd_btnForward); btnForward.setText("Forward"); Button btnCalculate = new Button(composite, SWT.NONE); btnValidate = btnCalculate; GridData gd_btnCalculate = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_btnCalculate.widthHint = 100; gd_btnCalculate.heightHint = 30; btnCalculate.setLayoutData(gd_btnCalculate); btnCalculate.setText("Validate"); validitySymbol = new ControlDecoration(btnCalculate, SWT.LEFT | SWT.TOP); validitySymbol.hide(); btnReset.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { controller.reset(); } }); btnCalculate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnShellModel.getSelection()){ controller.validate(0); } else if(btnModifiedShellModel.getSelection()){ controller.validate(1); } else if(btnChainModel.getSelection()){ controller.validate(2); } } }); // Selection Listeners | Scales ScaleRootCaBegin.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(fromRootCa, ScaleRootCaBegin, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleRootCaEnd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(thruRootCa, ScaleRootCaEnd, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleCaBegin.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(fromCa, ScaleCaBegin, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleCaEnd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(thruCa, ScaleCaEnd, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleCertBegin.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(fromCert, ScaleCertBegin, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleCertEnd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(thruCert, ScaleCertEnd, 180); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleSignatureDate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(signatureDate, ScaleSignatureDate, 360); if(((ScaleSignatureDate.getSelection() - 360) % 2) == 0){ arrowSigDiff = (ScaleSignatureDate.getSelection()-360)/2; } else{ arrowSigDiff = ((ScaleSignatureDate.getSelection()+1)-360)/2; } //arrowSigDiff = ScaleSignatureDate.getSelection()-360; canvas1.redraw(); canvas2.redraw(); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); ScaleVerificationDate.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Add or Remain Time dependent on selection controller.updateElements(LabelVerificationDate, ScaleVerificationDate, 360); if(((ScaleVerificationDate.getSelection() - 360) % 2) == 0){ arrowVerDiff = (ScaleVerificationDate.getSelection()-360)/2; } else{ arrowVerDiff = ((ScaleVerificationDate.getSelection()+1)-360)/2; } //arrowVerDiff = ScaleVerificationDate.getSelection()-360; canvas1.redraw(); canvas2.redraw(); // Hide Validity Symbols (red/green) validitySymbol.hide(); setLoadBtnsOrange(); } }); controller.reset(); } /** * Sets the symbols for a successful or unsuccessful validation. * The symbols are a red cross or a green checkmark. * * @param type int: * [1] valid * [2] invalid */ public static void setValidtiySymbol(int type){ if (type == 1){ validitySymbol.setImage(ResourceManager.getPluginImage("org.jcryptool.visual.crtVerification", "icons/gruenerHakenKlein.png")); validitySymbol.setDescriptionText("Sucessfully validated"); validitySymbol.show(); }else{ validitySymbol.setImage(ResourceManager.getPluginImage("org.jcryptool.visual.crtVerification", "icons/rotesKreuzKlein.png")); validitySymbol.setDescriptionText("Unsucessfully validated"); validitySymbol.show(); } } /** * This method paints the arrows used to indicate the validate date. * * @param e */ public void paintControl(PaintEvent e) { // Set the used color Color lightblue = new Color(Display.getCurrent(), 30, 144, 255); Color darkblue = new Color(Display.getCurrent(), 72, 61,139); Rectangle clientArea; int width; int height; // Coordinates of the document icon GC gc; gc = e.gc; // Max position right are left are +/-180 if (arrowSigDiff< -180){ arrowSigDiff=-180; }else if (arrowSigDiff>180){ arrowSigDiff=180; } if (arrowVerDiff< -180){ arrowVerDiff=-180; }else if (arrowVerDiff>180){ arrowVerDiff=178; } // Get the size of the canvas area clientArea = canvas1.getClientArea(); width = clientArea.width; height = clientArea.height; // Draw Arrow Signature Date gc.setBackground(lightblue); gc.fillRectangle(width/2+arrowSigDiff-4, 9, 8, height); gc.fillPolygon(new int[] {(width/2-8+arrowSigDiff), 9, (width/2+arrowSigDiff), 0, (width/2+8+arrowSigDiff), 9}); // Draw Arrow Verification Date gc.setBackground(darkblue); gc.fillRectangle(width/2+arrowVerDiff-4, 9, 8, height-4); gc.fillPolygon(new int[] {(width/2-8+arrowVerDiff), 11, (width/2+arrowVerDiff), 2, (width/2+8+arrowVerDiff), 11}); gc.dispose(); } /** * Sets the font-color of the buttons btnLoadRootCa, btnLoadCa and btnLoadUserCert to orange. * This happens when the scales are modified. */ public void setLoadBtnsOrange(){ CrtVerViewComposite.btnLoadRootCa.setForeground(SWTResourceManager.getColor(255, 140, 0)); CrtVerViewComposite.btnLoadCa.setForeground(SWTResourceManager.getColor(255, 140, 0)); CrtVerViewComposite.btnLoadUserCert.setForeground(SWTResourceManager.getColor(255, 140, 0)); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } }
package info.iconmaster.shuv.gui; import info.iconmaster.shuv.Shuv; import info.iconmaster.shuv.ShuvConsts; import info.iconmaster.shuv.ShuvDecoder; import info.iconmaster.shuv.ShuvDecoder.ShuvData; import info.iconmaster.shuv.ShuvEncoder; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TextField; import javafx.scene.control.TextInputDialog; import javafx.scene.input.Clipboard; import javafx.scene.input.ClipboardContent; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; /** * * @author iconmaster */ public class ShuvApplication extends Application { @Override public void start(Stage stage) throws Exception { if (ShuvConsts.API_KEY == null) { TextInputDialog tid = new TextInputDialog(); tid.setContentText("No key detected!\nPlease input a key:"); Optional<String> r = tid.showAndWait(); if (r.isPresent()) { ShuvConsts.setKey(r.get()); try { Files.createDirectory((new File("data")).toPath()); } catch (IOException ex) { Logger.getLogger(Shuv.class.getName()).log(Level.SEVERE, null, ex); } try { Files.write((new File("data/api_key")).toPath(), r.get().getBytes()); } catch (IOException ex) { Logger.getLogger(Shuv.class.getName()).log(Level.SEVERE, null, ex); } } else { Alert alert = new Alert(Alert.AlertType.ERROR, "Fatal error: No key."); alert.showAndWait(); return; } } Label encodeLabel = new Label("File:"); encodeLabel.setPadding(new Insets(5)); TextField encodeText = new TextField(); encodeText.setPadding(new Insets(5)); Button encodeBrowse = new Button("Browse..."); encodeBrowse.setPadding(new Insets(5)); encodeBrowse.setOnAction((ev)->{ FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(".")); fileChooser.setTitle("Open File"); File file = fileChooser.showOpenDialog(stage); if (file != null) { encodeText.setText(file.getPath()); } }); Button encodeSubmit = new Button("Upload!"); encodeSubmit.setPadding(new Insets(5)); encodeSubmit.setOnAction((ev)->{ String code = ShuvEncoder.encode(new File(encodeText.getText())); if (code == null) { Alert alert = new Alert(Alert.AlertType.ERROR, "An error occured in uploading."); alert.show(); } else { Clipboard clip = Clipboard.getSystemClipboard(); ClipboardContent cc = new ClipboardContent(); cc.putString(code); clip.setContent(cc); TextInputDialog tid = new TextInputDialog(code); tid.setContentText("Upload successful! The code has been copied to your clipboard."); //uNyRmd tid.show(); } }); HBox encodeHbox = new HBox(encodeLabel, encodeText, encodeBrowse); encodeHbox.setPadding(new Insets(10)); VBox encodeVbox = new VBox(encodeHbox, encodeSubmit); encodeVbox.setPadding(new Insets(10)); Tab encodeTab = new Tab("Upload File", encodeVbox); Label decodeLabel = new Label("Code:"); decodeLabel.setPadding(new Insets(5)); TextField decodeCode = new TextField(); decodeCode.setPadding(new Insets(5)); Button decodeSubmit = new Button("Download!"); decodeSubmit.setPadding(new Insets(5)); decodeSubmit.setOnAction((ev)->{ ShuvData data = ShuvDecoder.decode(decodeCode.getText()); if (data == null) { Alert alert = new Alert(Alert.AlertType.ERROR, "An error occured in downloading."); alert.show(); } else { FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File(".")); fileChooser.setInitialFileName(data.name); fileChooser.setTitle("Save File"); File file = fileChooser.showSaveDialog(stage); if (file != null) { try { Files.write(file.toPath(), data.data); Alert alert = new Alert(Alert.AlertType.INFORMATION, "File downloaded successfully."); alert.show(); } catch (IOException ex) { Logger.getLogger(ShuvApplication.class.getName()).log(Level.SEVERE, null, ex); Alert alert = new Alert(Alert.AlertType.ERROR, "An error occured in downloading."); alert.show(); } } } }); HBox decodeHbox = new HBox(decodeLabel, decodeCode); decodeHbox.setPadding(new Insets(10)); VBox decodeVbox = new VBox(decodeHbox, decodeSubmit); decodeVbox.setPadding(new Insets(10)); Tab decodeTab = new Tab("Download File", decodeVbox); TabPane root = new TabPane(encodeTab, decodeTab); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } }
package ua.com.fielden.platform.domaintree.impl; import static ua.com.fielden.platform.reflection.PropertyTypeDeterminator.stripIfNeeded; import static ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader.getOriginalType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ua.com.fielden.platform.domaintree.Function; import ua.com.fielden.platform.domaintree.FunctionUtils; import ua.com.fielden.platform.domaintree.ICalculatedProperty.CalculatedPropertyCategory; import ua.com.fielden.platform.domaintree.IDomainTreeRepresentation; import ua.com.fielden.platform.domaintree.exceptions.DomainTreeException; import ua.com.fielden.platform.domaintree.impl.AbstractDomainTreeManager.ITickRepresentationWithMutability; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractUnionEntity; import ua.com.fielden.platform.entity.annotation.Calculated; import ua.com.fielden.platform.entity.annotation.Ignore; import ua.com.fielden.platform.entity.annotation.Invisible; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.annotation.KeyTitle; import ua.com.fielden.platform.entity.annotation.KeyType; import ua.com.fielden.platform.reflection.AnnotationReflector; import ua.com.fielden.platform.reflection.Finder; import ua.com.fielden.platform.reflection.PropertyTypeDeterminator; import ua.com.fielden.platform.reflection.asm.impl.DynamicEntityClassLoader; import ua.com.fielden.platform.reflection.development.EntityDescriptor; import ua.com.fielden.platform.serialisation.api.ISerialiser; import ua.com.fielden.platform.types.Money; import ua.com.fielden.platform.utils.EntityUtils; import ua.com.fielden.platform.utils.Pair; /** * A base domain tree representation for all TG trees. Includes strict TG domain rules that should be used by all specific tree implementations. <br> * <br> * * @author TG Team * */ public abstract class AbstractDomainTreeRepresentation extends AbstractDomainTree implements IDomainTreeRepresentationWithMutability { private final Logger logger = Logger.getLogger(this.getClass()); /** * 0 -- to load only first level properties, Integer.MAX_VALUE -- to load all properties (obviously without cross-references ones); */ private static final Integer LOADING_LEVEL = 0; private final EnhancementLinkedRootsSet rootTypes; private final EnhancementSet manuallyExcludedProperties; private final AbstractTickRepresentation firstTick; private final AbstractTickRepresentation secondTick; /** Please do not use this field directly, use {@link #includedPropertiesMutable(Class)} lazy getter instead. */ private final transient EnhancementRootsMap<ListenedArrayList> includedProperties; /** * A <i>representation</i> constructor. Initialises also children references on itself. */ protected AbstractDomainTreeRepresentation(final ISerialiser serialiser, final Set<Class<?>> rootTypes, final Set<Pair<Class<?>, String>> excludedProperties, final AbstractTickRepresentation firstTick, final AbstractTickRepresentation secondTick) { super(serialiser); this.rootTypes = new EnhancementLinkedRootsSet(); this.rootTypes.addAll(rootTypes); this.manuallyExcludedProperties = createSet(); this.manuallyExcludedProperties.addAll(excludedProperties); this.firstTick = firstTick; this.secondTick = secondTick; // initialise the references on this instance in its children try { final Field dtrField = Finder.findFieldByName(AbstractTickRepresentation.class, "dtr"); final boolean isAccessible = dtrField.isAccessible(); dtrField.setAccessible(true); dtrField.set(firstTick, this); dtrField.set(secondTick, this); dtrField.setAccessible(isAccessible); } catch (final Exception e) { logger.fatal(e); throw new DomainTreeException("Could not instantiate doman tree representation.", e); } this.includedProperties = createRootsMap(); // managedType is not known at this stage. Included properties tree should be loaded after "enhancer" exists with all managedTypes. } private int level(final String path) { return !PropertyTypeDeterminator.isDotNotation(path) ? 0 : 1 + level(PropertyTypeDeterminator.penultAndLast(path).getKey()); } /** * Constructs recursively the list of properties using given list of fields. * * @param rootType * @param path * @param fieldsAndKeys * @return */ private List<String> constructProperties(final Class<?> managedType, final String path, final List<Field> fieldsAndKeys) { final List<String> newIncludedProps = new ArrayList<>(); for (final Field field : fieldsAndKeys) { final String property = StringUtils.isEmpty(path) ? field.getName() : path + "." + field.getName(); final String reflectionProperty = reflectionProperty(property); if (!isExcludedImmutably(managedType, reflectionProperty)) { newIncludedProps.add(property); // determine the type of property, which can be a) "union entity" property b) property under "union entity" c) collection property d) entity property e) simple property final Pair<Class<?>, String> penultAndLast = PropertyTypeDeterminator.transform(managedType, reflectionProperty); final Class<?> parentType = penultAndLast.getKey(); final Class<?> propertyType = PropertyTypeDeterminator.determineClass(parentType, penultAndLast.getValue(), true, true); // add the children for "property" based on its nature if (EntityUtils.isEntityType(propertyType)) { final boolean propertyTypeWasInHierarchyBefore = typesInHierarchy(managedType, reflectionProperty, true).contains(DynamicEntityClassLoader.getOriginalType(propertyType)); // final boolean isKeyPart = Finder.getKeyMembers(parentType).contains(field); // indicates if field is the part of the key. // final boolean isEntityItself = "".equals(property); // empty property means "entity itself" // final Pair<Class<?>, String> transformed = PropertyTypeDeterminator.transform(managedType, property); // final String penultPropertyName = PropertyTypeDeterminator.isDotNotation(property) ? PropertyTypeDeterminator.penultAndLast(property).getKey() : null; // final String lastPropertyName = transformed.getValue(); // final boolean isLinkProperty = !isEntityItself && PropertyTypeDeterminator.isDotNotation(property) // && Finder.isOne2Many_or_One2One_association(managedType, penultPropertyName) // && lastPropertyName.equals(Finder.findLinkProperty((Class<? extends AbstractEntity<?>>) managedType, penultPropertyName)); // exclude link properties in one2many and one2one associations if (level(property) >= LOADING_LEVEL && !EntityUtils.isUnionEntityType(propertyType) || propertyTypeWasInHierarchyBefore /*&& !isLinkProperty */ /*!isKeyPart*/) { newIncludedProps.add(createDummyMarker(property)); } // TODO Need to review the following commet during removal of the "common properties" concept for union entities. // else if (EntityUtils.isUnionEntityType(propertyType)) { // "union entity" property // final Pair<List<Field>, List<Field>> commonAndUnion = commonAndUnion((Class<? extends AbstractUnionEntity>) propertyType); // // a new tree branch should be created for "common" properties under "property" // final String commonBranch = createCommonBranch(property); // newIncludedProps.add(commonBranch); // final DefaultMutableTreeNode nodeForCommonProperties = addHotNode("common", null, false, klassNode, new Pair<String, String>("Common", TitlesDescsGetter.italic("<b>Common properties</b>"))); // newIncludedProps.addAll(constructProperties(managedType, commonBranch, commonAndUnion.getKey())); // // "union" properties should be added directly to "property" // newIncludedProps.addAll(constructProperties(managedType, property, commonAndUnion.getValue())); // } else if (EntityUtils.isUnionEntityType(parentType)) { // property under "union entity" // // the property under "union entity" should have only "non-common" properties added // final List<Field> propertiesWithoutCommon = constructKeysAndProperties(propertyType); // final List<String> parentCommonNames = AbstractUnionEntity.commonProperties((Class<? extends AbstractUnionEntity>) parentType); // propertiesWithoutCommon.removeAll(constructKeysAndProperties(propertyType, parentCommonNames)); // newIncludedProps.addAll(constructProperties(managedType, property, propertiesWithoutCommon)); else { // collectional or non-collectional entity property newIncludedProps.addAll(constructProperties(managedType, property, constructKeysAndProperties(propertyType))); } } } } return newIncludedProps; } @Override public Set<Pair<Class<?>, String>> excludedPropertiesMutable() { return manuallyExcludedProperties; } /** * Determines the lists of common and union fields for concrete union entity type. * * @param unionClass * @return */ private static Pair<List<Field>, List<Field>> commonAndUnion(final Class<? extends AbstractUnionEntity> unionClass) { final List<Field> unionProperties = AbstractUnionEntity.unionProperties(unionClass); final Class<? extends AbstractEntity> concreteUnionClass = (Class<? extends AbstractEntity>) unionProperties.get(0).getType(); final List<String> commonNames = AbstractUnionEntity.commonProperties(unionClass); final List<Field> commonProperties = constructKeysAndProperties(concreteUnionClass, commonNames); return new Pair<List<Field>, List<Field>>(commonProperties, unionProperties); } /** * Forms a list of fields for "type" in order ["key" or key members => "desc" (if exists) => other properties in order as declared in domain]. * * @param type * @return */ private static List<Field> constructKeysAndProperties(final Class<?> type) { // logger().info("Started constructKeysAndProperties for [" + type.getSimpleName() + "]."); final List<Field> properties = Finder.findProperties(type); // let's remove desc and key properties as they will be added separately a couple of lines below for (final Iterator<Field> iter = properties.iterator(); iter.hasNext();) { final Field prop = iter.next(); if (AbstractEntity.KEY.equals(prop.getName()) || AbstractEntity.DESC.equals(prop.getName())) { iter.remove(); } } final List<Field> keys = Finder.getKeyMembers(type); properties.removeAll(keys); // remove composite key members if any // now let's ensure that that key related properties and desc are first in the list of properties final List<Field> fieldsAndKeys = new ArrayList<Field>(); fieldsAndKeys.addAll(keys); fieldsAndKeys.add(Finder.getFieldByName(type, AbstractEntity.DESC)); fieldsAndKeys.addAll(properties); // logger().info("Ended constructProperties for [" + type.getSimpleName() + "]."); return fieldsAndKeys; } /** * Forms a list of fields for "type" in order ["key" or key members => "desc" (if exists) => other properties in order as declared in domain] and chooses only fields with * <code>names</code>. * * @param type * @param names * @return */ private static List<Field> constructKeysAndProperties(final Class<?> type, final List<String> names) { final List<Field> allProperties = constructKeysAndProperties(type); final List<Field> properties = new ArrayList<Field>(); for (final Field f : allProperties) { if (names.contains(f.getName())) { properties.add(f); } } return properties; } /** * Returns <code>true</code> if property is collection itself. * * @param root * @param property * @return */ protected static boolean isCollection(final Class<?> root, final String property) { final boolean isEntityItself = "".equals(property); // empty property means "entity itself" if (isEntityItself) { return false; } final Pair<Class<?>, String> penultAndLast = PropertyTypeDeterminator.transform(root, property); final Class<?> realType = PropertyTypeDeterminator.determineClass(penultAndLast.getKey(), penultAndLast.getValue(), true, false); return realType != null && Collection.class.isAssignableFrom(realType); // or collections itself } /** * Returns <code>true</code> if property is short collection itself. * * @param root * @param property * @return */ public static boolean isShortCollection(final Class<?> root, final String property) { final boolean isEntityItself = "".equals(property); // empty property means "entity itself" if (isEntityItself) { return false; } final Pair<Class<?>, String> penultAndLast = PropertyTypeDeterminator.transform(root, property); final Class<?> realType = PropertyTypeDeterminator.determineClass(penultAndLast.getKey(), penultAndLast.getValue(), true, false); final Class<?> elementType = PropertyTypeDeterminator.determineClass(penultAndLast.getKey(), penultAndLast.getValue(), true, true); // return !isEntityItself && realType != null && Collection.class.isAssignableFrom(realType); // or collections itself return Collection.class.isAssignableFrom(realType) && EntityUtils.isEntityType(elementType) && EntityUtils.isCompositeEntity((Class<AbstractEntity<?>>) elementType) && Finder.getKeyMembers(elementType).size() == 2 && Finder.getKeyMembers(elementType).stream().allMatch(field -> EntityUtils.isEntityType(field.getType())) && Finder.getKeyMembers(elementType).stream().anyMatch(field -> stripIfNeeded(getOriginalType(field.getType())).equals(stripIfNeeded(getOriginalType(penultAndLast.getKey())))); } /** * Returns parent collection for specified property. * * @param root * @param property * @return */ public static String parentCollection(final Class<?> root, final String property) { if (!isCollectionOrInCollectionHierarchy(root, property)) { throw new DomainTreeException("The property [" + property + "] is not in collection hierarchy."); } return isCollection(root, property) ? property : parentCollection(root, PropertyTypeDeterminator.penultAndLast(property).getKey()); } /** * Returns <code>true</code> if property is in collectional hierarchy. * * @param root * @param property * @return */ public static boolean isInCollectionHierarchy(final Class<?> root, final String property) { final boolean isEntityItself = "".equals(property); // empty property means "entity itself" return !isEntityItself && typesInHierarchy(root, property, false).contains(Collection.class); // properties in collectional hierarchy } /** * Returns <code>true</code> if property is in collectional hierarchy or is collection itself. * * @param root * @param property * @return */ public static boolean isCollectionOrInCollectionHierarchy(final Class<?> root, final String property) { return isCollection(root, property) || isInCollectionHierarchy(root, property); } /** * Returns <code>true</code> if property is in collectional hierarchy or is collection itself (not <i>short</i>). * <p> * <i>Short</i> collections are represented with 'one-to-many' association, where 'many' type contains strictly two composite keys: one key is of 'one' type and other is of * other entity type. * * @param root * @param property * @return */ public static boolean isNotShortCollectionOrInCollectionHierarchy(final Class<?> root, final String property) { return (isCollection(root, property) && !isShortCollection(root, property)) || isInCollectionHierarchy(root, property); } @Override public boolean isExcludedImmutably(final Class<?> root, final String property) { // logger().info("\t\tStarted isExcludedImmutably for property [" + property + "]."); final boolean isEntityItself = "".equals(property); // empty property means "entity itself" // logger().info("\t\t\ttransform."); final Pair<Class<?>, String> transformed = PropertyTypeDeterminator.transform(root, property); // logger().info("\t\t\tpenultAndLast."); final String penultPropertyName = PropertyTypeDeterminator.isDotNotation(property) ? PropertyTypeDeterminator.penultAndLast(property).getKey() : null; final Class<?> penultType = transformed.getKey(); final String lastPropertyName = transformed.getValue(); // logger().info("\t\t\tdetermineClass."); final Class<?> propertyType = isEntityItself ? root : PropertyTypeDeterminator.determineClass(penultType, lastPropertyName, true, true); // logger().info("\t\t\tgetOriginalType."); //final Class<?> notEnhancedRoot = DynamicEntityClassLoader.getOriginalType(root); // final Field field = isEntityItself ? null : Finder.getFieldByName(penultType, lastPropertyName); // logger().info("\t\t\tstarted conditions..."); final boolean excl = manuallyExcludedProperties.contains(key(root, property)) || // exclude manually excluded properties Money.class.isAssignableFrom(penultType) || // all properties within type Money should be excluded at this stage !isEntityItself && AbstractEntity.KEY.equals(lastPropertyName) && propertyType == null || // exclude "key" -- no KeyType annotation exists in direct owner of "key" !isEntityItself && AbstractEntity.KEY.equals(lastPropertyName) && !AnnotationReflector.isAnnotationPresentForClass(KeyTitle.class, penultType) || // exclude "key" -- no KeyTitle annotation exists in direct owner of "key" !isEntityItself && AbstractEntity.KEY.equals(lastPropertyName) && !EntityUtils.isEntityType(propertyType) || // exclude "key" -- "key" is not of entity type !isEntityItself && AbstractEntity.DESC.equals(lastPropertyName) && !EntityDescriptor.hasDesc(penultType) || // exclude "desc" -- no DescTitle annotation exists in direct owner of "desc" !isEntityItself && !AnnotationReflector.isAnnotationPresent(Finder.findFieldByName(root, property), IsProperty.class) || // exclude non-TG properties (not annotated by @IsProperty) isEntityItself && !rootTypes().contains(propertyType) || // exclude entities of non-"root types" EntityUtils.isEnum(propertyType) || // exclude enumeration properties / entities EntityUtils.isEntityType(propertyType) && Modifier.isAbstract(propertyType.getModifiers()) || // exclude properties / entities of entity type with 'abstract' modifier EntityUtils.isEntityType(propertyType) && !AnnotationReflector.isAnnotationPresentForClass(KeyType.class, propertyType) || // exclude properties / entities of entity type without KeyType annotation !isEntityItself && AnnotationReflector.isPropertyAnnotationPresent(Invisible.class, penultType, lastPropertyName) || // exclude invisible properties !isEntityItself && AnnotationReflector.isPropertyAnnotationPresent(Ignore.class, penultType, lastPropertyName) || // exclude invisible properties // !isEntityItself && Finder.getKeyMembers(penultType).contains(field) && typesInHierarchy(root, property, true).contains(DynamicEntityClassLoader.getOriginalType(propertyType)) || // exclude key parts which type was in hierarchy //TODO !isEntityItself && PropertyTypeDeterminator.isDotNotation(property) && Finder.isOne2Many_or_One2One_association(notEnhancedRoot, penultPropertyName) && lastPropertyName.equals(Finder.findLinkProperty((Class<? extends AbstractEntity<?>>) notEnhancedRoot, penultPropertyName)) || // exclude link properties in one2many and one2one associations !isEntityItself && isExcludedImmutably(root, PropertyTypeDeterminator.isDotNotation(property) ? penultPropertyName : ""); // exclude property if it is an ascender (any level) of already excluded property // logger().info("\t\tEnded isExcludedImmutably for property [" + property + "]."); return excl; } /** * Finds a complete set of <b>NOT ENHANCED</b> types in hierarchy of dot-notation expression, excluding the type of last property and including the type of root class.<br> * <br> * * E.g. : "WorkOrder$$1.vehicle.fuelUsages.vehicle.fuelCards.initDate" => <br> * => [WorkOrder.class, Vehicle.class, FuelUsage.class, FuelCard.class] (if addCollectionalElementType = true) or <br> * => [WorkOrder.class, Vehicle.class, Collection.class] (if addCollectionalElementType = false) * * @param root * @param property * @param addCollectionalElementType * -- true => then correct element type of collectional property will be added to set, otherwise a {@link Collection.class} will be added. * @return */ protected static Set<Class<?>> typesInHierarchy(final Class<?> root, final String property, final boolean addCollectionalElementType) { if (!PropertyTypeDeterminator.isDotNotation(property)) { return new HashSet<Class<?>>() { private static final long serialVersionUID = 6314144790005942324L; { add(DynamicEntityClassLoader.getOriginalType(root)); } }; } else { final Pair<String, String> penultAndLast = PropertyTypeDeterminator.penultAndLast(property); final String penult = penultAndLast.getKey(); final Pair<Class<?>, String> transformed = PropertyTypeDeterminator.transform(root, penult); return new HashSet<Class<?>>() { private static final long serialVersionUID = 6314144760005942324L; { if (addCollectionalElementType) { add(DynamicEntityClassLoader.getOriginalType(PropertyTypeDeterminator.determineClass(transformed.getKey(), transformed.getValue(), true, true))); } else { final Class<?> type = PropertyTypeDeterminator.determineClass(transformed.getKey(), transformed.getValue(), true, false); add(DynamicEntityClassLoader.getOriginalType(Collection.class.isAssignableFrom(type) ? Collection.class : type)); } addAll(typesInHierarchy(root, PropertyTypeDeterminator.penultAndLast(property).getKey(), addCollectionalElementType)); // recursively add other types } }; } } @Override public IDomainTreeRepresentation excludeImmutably(final Class<?> root, final String property) { if (includedPropertiesMutable(root).contains(property)) { final int index = includedPropertiesMutable(root).indexOf(property); while (index < includedPropertiesMutable(root).size() && includedPropertiesMutable(root).get(index).startsWith(property)) { includedPropertiesMutable(root).remove(includedPropertiesMutable(root).get(index)); } } manuallyExcludedProperties.add(key(root, property)); return this; } /** * An {@link ArrayList} specific implementation which listens to structure modifications (add / remove elements) and fires appropriate events. * * @author TG Team * */ public static class ListenedArrayList extends ArrayList<String> { private static final long serialVersionUID = -4295706377290507263L; private final transient Class<?> root; private final transient AbstractDomainTreeRepresentation parentDtr; public ListenedArrayList() { this(null, null); } public ListenedArrayList(final Class<?> root, final AbstractDomainTreeRepresentation parentDtr) { super(); this.root = root; this.parentDtr = parentDtr; } private String getElem(final int index) { try { return get(index); } catch (final IndexOutOfBoundsException e) { return null; } } @Override public boolean add(final String property) { if (property == null) { throw new DomainTreeException("'null' properties can not be added into properties set (implemented as natural ordered list)."); } else if (!EntityUtils.equalsEx(getElem(size() - 1), property)) { // when last property is equal to attempted (addition) property -- ignore addition final boolean added = super.add(property); return added; } return false; } @Override public void add(final int index, final String property) { if (property == null) { throw new DomainTreeException("'null' properties can not be added into properties set (implemented as natural ordered list)."); } else if (!EntityUtils.equalsEx(getElem(index - 1), property)) { // when last property is equal to attempted (addition) property -- ignore addition super.add(index, property); } } @Override public boolean addAll(final Collection<? extends String> properties) { for (final String property : properties) { final boolean added = add(property); if (!added) { return added; } } return true; } @Override public boolean addAll(final int index, final Collection<? extends String> properties) { int currIndex = index; for (final String property : properties) { add(currIndex++, property); } return true; } @Override public boolean remove(final Object obj) { final String property = (String) obj; final boolean removed = super.remove(obj); if (!removed) { throw new IllegalStateException("DANGEROUS: the property [" + property + "] can not be removed, because it does not exist in the list. " + "But the meta-state associated with this property has been removed! Please ensure that property removal is correct!"); } return removed; } } /** * Getter of mutable "included properties" cache for internal purposes. * <p> * Please note that you can only mutate this list with methods {@link List#add(Object)} and {@link List#remove(Object)} to correctly reflect the changes on depending objects. * (e.g. UI tree models, checked properties etc.) * * @param root * @return */ @Override public List<String> includedPropertiesMutable(final Class<?> managedType) { final Class<?> root = DynamicEntityClassLoader.getOriginalType(managedType); if (includedProperties.get(root) == null) { // not yet loaded final Date st = new Date(); // initialise included properties using isExcluded contract and manually excluded properties final ListenedArrayList includedProps = new ListenedArrayList(root, this); if (!isExcludedImmutably(root, "")) { // the entity itself is included -- add it to "included properties" list includedProps.add(""); if (!EntityUtils.isEntityType(root)) { throw new DomainTreeException("Can not add children properties to non-entity type [" + root.getSimpleName() + "] in path [" + root.getSimpleName() + "=>" + "" + "]."); } // logger().info("Started constructKeysAndProperties for [" + managedType.getSimpleName() + "]."); final List<Field> fields = constructKeysAndProperties(managedType); // logger().info("Ended constructKeysAndProperties for [" + managedType.getSimpleName() + "]."); // logger().info("Started constructProperties for [" + managedType.getSimpleName() + "]."); final List<String> props = constructProperties(managedType, "", fields); // logger().info("Ended constructProperties for [" + managedType.getSimpleName() + "]."); includedProps.addAll(props); } includedProperties.put(root, includedProps); logger().debug("Root [" + root.getSimpleName() + "] has been processed within " + (new Date().getTime() - st.getTime()) + "ms with " + includedProps.size() + " included properties."); // => [" + includedProps + "] } return includedProperties.get(root); } @Override public List<String> includedProperties(final Class<?> root) { return Collections.unmodifiableList(includedPropertiesMutable(root)); } /** * This method loads all missing properties on the tree path as defined in <code>fromPath</code> and <code>toPath</code> for type <code>root</code>. Please note that property * <code>fromPath</code> should be loaded itself (perhaps without its children). * * @param managedType * @param fromPath * @param toPath */ protected final boolean warmUp(final Class<?> managedType, final String fromPath, final String toPath) { // System.out.println("Warm up => from = " + fromPath + "; to = " + toPath); if (includedPropertiesMutable(managedType).contains(fromPath)) { // the property itself exists in "included properties" cache final String dummyMarker = createDummyMarker(fromPath); final boolean shouldBeLoaded = includedPropertiesMutable(managedType).contains(dummyMarker); if (shouldBeLoaded) { // the property is circular and has no children loaded -- it has to be done now final int index = includedPropertiesMutable(managedType).indexOf(dummyMarker); includedPropertiesMutable(managedType).remove(dummyMarker); // remove dummy property // logger().info("Started constructKeysAndProperties for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); final List<Field> fields = constructKeysAndProperties(PropertyTypeDeterminator.determinePropertyType(managedType, fromPath)); // logger().info("Ended constructKeysAndProperties for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); // logger().info("Started constructProperties for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); final List<String> props = constructProperties(managedType, fromPath, fields); // logger().info("Ended constructProperties for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); // logger().info("Started includedPropertiesMutable.addAll for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); // enableListening(false); includedPropertiesMutable(managedType).addAll(index, props); // enableListening(true); // logger().info("Ended includedPropertiesMutable.addAll for [" + managedType.getSimpleName() + "] from = " + fromPath + "."); } if (!EntityUtils.equalsEx(fromPath, toPath)) { // not the leaf is trying to be warmed up final String part = "".equals(fromPath) ? toPath : toPath.replaceFirst(fromPath + ".", ""); final String part2 = part.indexOf(".") > 0 ? part.substring(0, part.indexOf(".")) : part; final String part3 = "".equals(fromPath) ? part2 : fromPath + "." + part2; final boolean hasBeenWarmedUp = warmUp(managedType, part3, toPath); return shouldBeLoaded || hasBeenWarmedUp; } else { return shouldBeLoaded; } } else { throw new DomainTreeException("The property [" + fromPath + "] in root [" + managedType.getSimpleName() + "] should be already loaded into 'included properties'."); } } @Override public IDomainTreeRepresentation warmUp(final Class<?> managedType, final String property) { final Date st = new Date(); illegalExcludedProperties(this, managedType, reflectionProperty(property), "Could not 'warm up' an 'excluded' property [" + property + "] in type [" + managedType.getSimpleName() + "]. Only properties that are not excluded can be 'warmed up'."); includedPropertiesMutable(managedType); // ensure "included properties" to be loaded if (warmUp(managedType, "", property)) { logger().debug("Warmed up root's [" + managedType.getSimpleName() + "] property [" + property + "] within " + (new Date().getTime() - st.getTime()) + "ms."); } return this; } /** * Throws an {@link DomainTreeException} if the property is excluded. * * @param dtr * @param root * @param property * @param message */ protected static void illegalExcludedProperties(final IDomainTreeRepresentation dtr, final Class<?> root, final String property, final String message) { /* TODO HUGE PERFORMACE BOTTLENECK!! */ // if (dtr.isExcludedImmutably(root, property)) { // throw new DomainTreeException(message); } /** * An abstract tick representation. <br> * <br> * * Includes default implementations of "disabling/immutable checking", that contain: <br> * a) manual state management; <br> * b) resolution of conflicts with excluded properties; <br> * c) automatic disabling of "immutably checked" properties. * * @author TG Team * */ public static abstract class AbstractTickRepresentation implements ITickRepresentationWithMutability { private final EnhancementSet disabledManuallyProperties; private final transient AbstractDomainTreeRepresentation dtr; /** * Used for serialisation and for normal initialisation. IMPORTANT : To use this tick it should be passed into representation constructor and then into manager constructor, * which should initialise "dtr" and "tickManager" fields. */ protected AbstractTickRepresentation() { this.disabledManuallyProperties = createSet(); this.dtr = null; // IMPORTANT : to use this tick it should be passed into representation constructor, which should initialise "dtr" field. } @Override public final boolean isDisabledImmutably(final Class<?> root, final String property) { illegalExcludedProperties(dtr, root, property, "Could not ask a 'disabled' state for already 'excluded' property [" + property + "] in type [" + root.getSimpleName() + "]."); return isDisabledImmutablyLightweight(root, property); } @Override public boolean isDisabledImmutablyLightweight(final Class<?> root, final String property) { return disabledManuallyProperties.contains(key(root, property)) || // disable manually disabled properties isCheckedImmutablyLightweight(root, property); // the checked by default properties should be disabled (immutable checking) } @Override public ITickRepresentation disableImmutably(final Class<?> root, final String property) { illegalExcludedProperties(dtr, root, property, "Could not disable already 'excluded' property [" + property + "] in type [" + root.getSimpleName() + "]."); disabledManuallyProperties.add(key(root, property)); return this; } protected boolean isDisabledImmutablyPropertiesOfEntityType(final Class<?> propertyType, final KeyType keyTypeAnnotation) { // (EntityUtils.isEntityType(propertyType) && DynamicEntityKey.class.isAssignableFrom(keyTypeAnnotation.value())); // properties of "entity with composite key" type has been enabled return EntityUtils.isEntityType(propertyType) && EntityUtils.isEntityType(keyTypeAnnotation.value()); // disable properties of "entity with AE key" type } @Override public boolean isCheckedImmutably(final Class<?> root, final String property) { illegalExcludedProperties(dtr, root, property, "Could not ask a 'checked' state for already 'excluded' property [" + property + "] in type [" + root.getSimpleName() + "]."); return isCheckedImmutablyLightweight(root, property); } protected boolean isCheckedImmutablyLightweight(final Class<?> root, final String property) { return false; } public AbstractDomainTreeRepresentation getDtr() { return dtr; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (disabledManuallyProperties == null ? 0 : disabledManuallyProperties.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractTickRepresentation other = (AbstractTickRepresentation) obj; if (disabledManuallyProperties == null) { if (other.disabledManuallyProperties != null) { return false; } } else if (!disabledManuallyProperties.equals(other.disabledManuallyProperties)) { return false; } return true; } @Override public EnhancementSet disabledManuallyPropertiesMutable() { return disabledManuallyProperties; } } @Override public ITickRepresentation getFirstTick() { return firstTick; } @Override public ITickRepresentation getSecondTick() { return secondTick; } @Override public Set<Class<?>> rootTypes() { return rootTypes; } @Override public Set<Function> availableFunctions(final Class<?> root, final String property) { illegalExcludedProperties(this, root, property, "Could not ask for 'available functions' for already 'excluded' property [" + property + "] in type [" + root.getSimpleName() + "]."); final boolean isEntityItself = "".equals(property); // empty property means "entity itself" final Class<?> propertyType = isEntityItself ? root : PropertyTypeDeterminator.determinePropertyType(root, property); final Set<Function> availableFunctions = FunctionUtils.functionsFor(propertyType); if (!isEntityItself && isCalculatedAndOfTypes(root, property, CalculatedPropertyCategory.AGGREGATED_EXPRESSION, CalculatedPropertyCategory.ATTRIBUTED_COLLECTIONAL_EXPRESSION)) { final Set<Function> functions = new HashSet<Function>(); if (availableFunctions.contains(Function.SELF)) { functions.add(Function.SELF); } return functions; } if (isEntityItself) { availableFunctions.remove(Function.SELF); } if (!isInCollectionHierarchy(root, property)) { availableFunctions.remove(Function.ALL); availableFunctions.remove(Function.ANY); } if (!isEntityItself && Integer.class.isAssignableFrom(propertyType) && !isCalculatedAndOriginatedFromNotIntegerType(root, property)) { availableFunctions.remove(Function.COUNT_DISTINCT); } return availableFunctions; } /** * Returns <code>true</code> if the property is calculated. * * @param root * @param property * @return */ public static boolean isCalculated(final Class<?> root, final String property) { return AnnotationReflector.getPropertyAnnotation(Calculated.class, root, property) != null; } /** * Returns <code>true</code> if the property is calculated with one of the specified categories. * * @param root * @param property * @param types * @return */ public static boolean isCalculatedAndOfTypes(final Class<?> root, final String property, final CalculatedPropertyCategory... types) { final Calculated ca = AnnotationReflector.getPropertyAnnotation(Calculated.class, root, property); if (ca != null) { for (final CalculatedPropertyCategory type : types) { if (type.equals(ca.category())) { return true; } } } return false; } protected static boolean isCalculatedAndOriginatedFromDateType(final Class<?> root, final String property) { final Calculated calculatedAnnotation = AnnotationReflector.getPropertyAnnotation(Calculated.class, root, property); return calculatedAnnotation != null && EntityUtils.isDate(PropertyTypeDeterminator.determinePropertyType(root, calculatedAnnotation.origination())); } private static boolean isCalculatedAndOriginatedFromNotIntegerType(final Class<?> root, final String property) { final Calculated calculatedAnnotation = AnnotationReflector.getPropertyAnnotation(Calculated.class, root, property); return calculatedAnnotation != null && !Integer.class.isAssignableFrom(PropertyTypeDeterminator.determinePropertyType(root, calculatedAnnotation.origination())); } /** * A specific Kryo serialiser for {@link AbstractDomainTreeRepresentation}. * * @author TG Team * */ protected abstract static class AbstractDomainTreeRepresentationSerialiser<T extends AbstractDomainTreeRepresentation> extends AbstractDomainTreeSerialiser<T> { public AbstractDomainTreeRepresentationSerialiser(final ISerialiser serialiser) { super(serialiser); } @Override public void write(final ByteBuffer buffer, final T representation) { writeValue(buffer, representation.getRootTypes()); writeValue(buffer, representation.getManuallyExcludedProperties()); writeValue(buffer, representation.getFirstTick()); writeValue(buffer, representation.getSecondTick()); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (manuallyExcludedProperties == null ? 0 : manuallyExcludedProperties.hashCode()); result = prime * result + (firstTick == null ? 0 : firstTick.hashCode()); result = prime * result + (rootTypes == null ? 0 : rootTypes.hashCode()); result = prime * result + (secondTick == null ? 0 : secondTick.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractDomainTreeRepresentation other = (AbstractDomainTreeRepresentation) obj; if (manuallyExcludedProperties == null) { if (other.manuallyExcludedProperties != null) { return false; } } else if (!manuallyExcludedProperties.equals(other.manuallyExcludedProperties)) { return false; } if (firstTick == null) { if (other.firstTick != null) { return false; } } else if (!firstTick.equals(other.firstTick)) { return false; } if (rootTypes == null) { if (other.rootTypes != null) { return false; } } else if (!rootTypes.equals(other.rootTypes)) { return false; } if (secondTick == null) { if (other.secondTick != null) { return false; } } else if (!secondTick.equals(other.secondTick)) { return false; } return true; } public EnhancementLinkedRootsSet getRootTypes() { return rootTypes; } public EnhancementSet getManuallyExcludedProperties() { return manuallyExcludedProperties; } }
package io.coinswap.swap; public class AtomicSwapMethod { public static String VERSION = "version", KEYS_REQUEST = "keys.request", BAILIN_HASH_REQUEST = "bail_in_hash.request", EXCHANGE_SIGNATURES = "exchange.signatures", EXCHANGE_BAIL_IN = "exchange.bail.in", CANCEL_TRANSACTION = "cancel.transaction", ARBITRATE = "arbitrate"; }
package com.sun.facelets; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.FacesException; import javax.faces.FactoryFinder; import javax.faces.application.StateManager; import javax.faces.application.ViewHandler; import javax.faces.application.ViewHandlerWrapper; import javax.faces.component.UIComponent; import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import com.sun.facelets.compiler.Compiler; import com.sun.facelets.compiler.SAXCompiler; import com.sun.facelets.compiler.TagLibraryConfig; import com.sun.facelets.spi.RefreshableFaceletFactory; import com.sun.facelets.tag.TagLibrary; /** * ViewHandler implementation for Facelets * * @author Jacob Hookom * @version $Id: FaceletViewHandler.java,v 1.4 2005-05-25 03:16:30 jhook Exp $ */ public class FaceletViewHandler extends ViewHandlerWrapper { protected final static Logger log = Logger .getLogger("facelets.viewHandler"); public final static long DEFAULT_REFRESH_PERIOD = 2; public final static String REFRESH_PERIOD_PARAM_NAME = "facelet.REFRESH_PERIOD"; public final static String LIBRARIES_PARAM_NAME = "facelet.LIBRARIES"; protected final static String STATE_KEY = "com.sun.facelets.VIEW_STATE"; private final ViewHandler parent; private boolean initialized = false; private String defaultSuffix; protected static void removeTransient(UIComponent c) { UIComponent d, e; if (c.getChildCount() > 0) { for (Iterator itr = c.getChildren().iterator(); itr.hasNext();) { d = (UIComponent) itr.next(); if (d.getFacets().size() > 0) { for (Iterator jtr = d.getFacets().values().iterator(); jtr .hasNext();) { e = (UIComponent) jtr.next(); if (e.isTransient()) { jtr.remove(); } else { removeTransient(e); } } } if (d.isTransient()) { itr.remove(); } else { removeTransient(d); } } } if (c.getFacets().size() > 0) { for (Iterator itr = c.getFacets().values().iterator(); itr .hasNext();) { d = (UIComponent) itr.next(); if (d.isTransient()) { itr.remove(); } else { removeTransient(d); } } } } public FaceletViewHandler(ViewHandler parent) { this.parent = parent; } protected void initialize() { synchronized (this) { if (!this.initialized) { log.fine("Initializing"); Compiler c = this.createCompiler(); this.initializeCompiler(c); FaceletFactory f = this.createFaceletFactory(c); FaceletFactory.setInstance(f); this.initialized = true; log.fine("Initialization Successful"); } } } protected FaceletFactory createFaceletFactory(Compiler c) { long refreshPeriod = DEFAULT_REFRESH_PERIOD; FacesContext ctx = FacesContext.getCurrentInstance(); String userPeriod = ctx.getExternalContext().getInitParameter( REFRESH_PERIOD_PARAM_NAME); if (userPeriod != null && userPeriod.length() > 0) { refreshPeriod = Long.parseLong(userPeriod); } log.fine("Using Refresh Period: " + refreshPeriod + " sec"); try { return new RefreshableFaceletFactory(c, ctx.getExternalContext() .getResource("/"), refreshPeriod); } catch (MalformedURLException e) { throw new FaceletException("Error Creating FaceletFactory", e); } } protected Compiler createCompiler() { return new SAXCompiler(); } protected void initializeCompiler(Compiler c) { FacesContext ctx = FacesContext.getCurrentInstance(); ExternalContext ext = ctx.getExternalContext(); String libParam = ext.getInitParameter(LIBRARIES_PARAM_NAME); if (libParam != null) { libParam = libParam.trim(); String[] libs = libParam.split(";"); URL src; TagLibrary libObj; for (int i = 0; i < libs.length; i++) { try { src = ext.getResource(libs[i]); if (src == null) { throw new FileNotFoundException(libs[i]); } libObj = TagLibraryConfig.create(src); c.addTagLibrary(libObj); log.fine("Successfully Loaded Library: " + libs[i]); } catch (IOException e) { log.log(Level.SEVERE, "Error Loading Library: " + libs[i], e); } } } } public UIViewRoot restoreView(FacesContext context, String viewId) { UIViewRoot root = null; try { root = super.restoreView(context, viewId); } catch (Exception e) { log.log(Level.WARNING, "Error Restoring View: " + viewId, e); } if (root != null) { log.fine("View Restored: " + root.getViewId()); } else { log.fine("Unable to restore View"); } return root; } /* * (non-Javadoc) * * @see javax.faces.application.ViewHandlerWrapper#getWrapped() */ protected ViewHandler getWrapped() { return this.parent; } public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException { if (!this.initialized) { this.initialize(); } // exit if the view is not to be rendered if (!viewToRender.isRendered()) { return; } if (log.isLoggable(Level.FINE)) { log.fine("Rendering View: " + viewToRender.getViewId()); } // setup our viewId String renderedViewId = this.getRenderedViewId(context, viewToRender .getViewId()); viewToRender.setViewId(renderedViewId); // grab our FaceletFactory and create a Facelet FaceletFactory factory = FaceletFactory.getInstance(); Facelet f = factory.getFacelet(viewToRender.getViewId()); // populate UIViewRoot f.apply(context, viewToRender); // setup writer ExternalContext extContext = context.getExternalContext(); ResponseWriter writer = context.getResponseWriter(); if (writer == null) { RenderKitFactory renderFactory = (RenderKitFactory) FactoryFinder .getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = renderFactory.getRenderKit(context, viewToRender.getRenderKitId()); ServletRequest request = (ServletRequest) extContext.getRequest(); ServletResponse response = (ServletResponse) extContext .getResponse(); response.setBufferSize(8192); writer = renderKit.createResponseWriter(response.getWriter(), "text/html", request.getCharacterEncoding()); context.setResponseWriter(writer); } // save the state StateManager stateMgr = context.getApplication().getStateManager(); Object state = stateMgr.saveView(context); extContext.getRequestMap().put(STATE_KEY, state); // write the state writer.startDocument(); viewToRender.encodeAll(context); writer.endDocument(); // finally clean up transients if viewState = true if (extContext.getRequestMap().containsKey(STATE_KEY)) { removeTransient(viewToRender); } } public String getDefaultSuffix(FacesContext context) throws FacesException { if (this.defaultSuffix == null) { ExternalContext extCtx = context.getExternalContext(); String viewSuffix = extCtx .getInitParameter(ViewHandler.DEFAULT_SUFFIX_PARAM_NAME); this.defaultSuffix = (viewSuffix != null) ? viewSuffix : ViewHandler.DEFAULT_SUFFIX; } return this.defaultSuffix; } protected String getRenderedViewId(FacesContext context, String actionId) { ExternalContext extCtx = context.getExternalContext(); String viewId = extCtx.getRequestPathInfo(); if (extCtx.getRequestPathInfo() == null) { String facesSuffix = actionId.substring(actionId.lastIndexOf('.')); String viewSuffix = this.getDefaultSuffix(context); viewId = actionId.replaceFirst(facesSuffix, viewSuffix); } if (log.isLoggable(Level.FINE)) { log.fine("ActionId -> ViewId: " + actionId + " -> " + viewId); } return viewId; } public void writeState(FacesContext context) throws IOException { StateManager stateMgr = context.getApplication().getStateManager(); if (stateMgr.isSavingStateInClient(context)) { Object state = context.getExternalContext().getRequestMap().get( STATE_KEY); if (state != null) { stateMgr.writeState(context, state); } } } }
package com.intellij.codeInsight.daemon.impl; import com.intellij.codeHighlighting.*; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.ExtensionPointListener; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import gnu.trove.THashSet; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import gnu.trove.TIntObjectHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TextEditorHighlightingPassRegistrarImpl extends TextEditorHighlightingPassRegistrarEx { public static final ExtensionPointName<TextEditorHighlightingPassFactoryRegistrar> EP_NAME = new ExtensionPointName<>("com.intellij.highlightingPassFactory"); private final TIntObjectHashMap<PassConfig> myRegisteredPassFactories = new TIntObjectHashMap<>(); private final List<DirtyScopeTrackingHighlightingPassFactory> myDirtyScopeTrackingFactories = new ArrayList<>(); private int nextAvailableId = Pass.LAST_PASS + 1; private boolean checkedForCycles; private final Project myProject; public TextEditorHighlightingPassRegistrarImpl(@NotNull Project project) { myProject = project; registerFactories(); EP_NAME.addExtensionPointListener(new ExtensionPointListener<TextEditorHighlightingPassFactoryRegistrar>() { @Override public void extensionAdded(@NotNull TextEditorHighlightingPassFactoryRegistrar factoryRegistrar, @NotNull PluginDescriptor pluginDescriptor) { factoryRegistrar.registerHighlightingPassFactory(TextEditorHighlightingPassRegistrarImpl.this, project); } @Override public void extensionRemoved(@NotNull TextEditorHighlightingPassFactoryRegistrar factoryRegistrar, @NotNull PluginDescriptor pluginDescriptor) { myRegisteredPassFactories.clear(); myDirtyScopeTrackingFactories.clear(); registerFactories(); } }, myProject); Disposer.register(myProject, () -> { myRegisteredPassFactories.clear(); myDirtyScopeTrackingFactories.clear(); }); } public void registerFactories() { for (TextEditorHighlightingPassFactoryRegistrar factoryRegistrar : EP_NAME.getExtensionList()) { factoryRegistrar.registerHighlightingPassFactory(this, myProject); } } private static class PassConfig { private final TextEditorHighlightingPassFactory passFactory; private final int[] startingPredecessorIds; private final int[] completionPredecessorIds; private PassConfig(@NotNull TextEditorHighlightingPassFactory passFactory, @NotNull int[] completionPredecessorIds, @NotNull int[] startingPredecessorIds) { this.completionPredecessorIds = completionPredecessorIds; this.startingPredecessorIds = startingPredecessorIds; this.passFactory = passFactory; } } @Override public synchronized int registerTextEditorHighlightingPass(@NotNull TextEditorHighlightingPassFactory factory, @Nullable int[] runAfterCompletionOf, @Nullable int[] runAfterOfStartingOf, boolean runIntentionsPassAfter, int forcedPassId) { assert !checkedForCycles; PassConfig info = new PassConfig(factory, runAfterCompletionOf == null || runAfterCompletionOf.length == 0 ? ArrayUtilRt.EMPTY_INT_ARRAY : runAfterCompletionOf, runAfterOfStartingOf == null || runAfterOfStartingOf.length == 0 ? ArrayUtilRt.EMPTY_INT_ARRAY : runAfterOfStartingOf); int passId = forcedPassId == -1 ? nextAvailableId++ : forcedPassId; PassConfig registered = myRegisteredPassFactories.get(passId); assert registered == null: "Pass id "+passId +" has already been registered in: "+ registered.passFactory; myRegisteredPassFactories.put(passId, info); if (factory instanceof DirtyScopeTrackingHighlightingPassFactory) { myDirtyScopeTrackingFactories.add((DirtyScopeTrackingHighlightingPassFactory) factory); } return passId; } @Override @NotNull public List<TextEditorHighlightingPass> instantiatePasses(@NotNull final PsiFile psiFile, @NotNull final Editor editor, @NotNull final int[] passesToIgnore) { synchronized (this) { if (!checkedForCycles) { checkedForCycles = true; checkForCycles(); } } PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); final Document document = editor.getDocument(); PsiFile fileFromDoc = documentManager.getPsiFile(document); if (!(fileFromDoc instanceof PsiCompiledElement)) { assert fileFromDoc == psiFile : "Files are different: " + psiFile + ";" + fileFromDoc; Document documentFromFile = documentManager.getDocument(psiFile); assert documentFromFile == document : "Documents are different. Doc: " + document + "; Doc from file: " + documentFromFile +"; File: "+psiFile +"; Virtual file: "+ PsiUtilCore.getVirtualFile(psiFile); } final TIntObjectHashMap<TextEditorHighlightingPass> id2Pass = new TIntObjectHashMap<>(); final TIntArrayList passesRefusedToCreate = new TIntArrayList(); boolean isDumb = DumbService.getInstance(myProject).isDumb(); myRegisteredPassFactories.forEachKey(passId -> { if (ArrayUtil.find(passesToIgnore, passId) != -1) { return true; } PassConfig passConfig = myRegisteredPassFactories.get(passId); TextEditorHighlightingPassFactory factory = passConfig.passFactory; final TextEditorHighlightingPass pass = isDumb && !DumbService.isDumbAware(factory) ? null : factory.createHighlightingPass(psiFile, editor); if (pass == null || isDumb && !DumbService.isDumbAware(pass)) { passesRefusedToCreate.add(passId); } else { // init with editor's colors scheme pass.setColorsScheme(editor.getColorsScheme()); TIntArrayList ids = new TIntArrayList(passConfig.completionPredecessorIds.length); for (int id : passConfig.completionPredecessorIds) { if (myRegisteredPassFactories.containsKey(id)) ids.add(id); } pass.setCompletionPredecessorIds(ids.isEmpty() ? ArrayUtilRt.EMPTY_INT_ARRAY : ids.toNativeArray()); ids = new TIntArrayList(passConfig.startingPredecessorIds.length); for (int id : passConfig.startingPredecessorIds) { if (myRegisteredPassFactories.containsKey(id)) ids.add(id); } pass.setStartingPredecessorIds(ids.isEmpty() ? ArrayUtilRt.EMPTY_INT_ARRAY : ids.toNativeArray()); pass.setId(passId); id2Pass.put(passId, pass); } return true; }); DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject); final FileStatusMap statusMap = daemonCodeAnalyzer.getFileStatusMap(); passesRefusedToCreate.forEach(passId -> { statusMap.markFileUpToDate(document, passId); return true; }); return (List)Arrays.asList(id2Pass.getValues()); } @NotNull @Override public List<TextEditorHighlightingPass> instantiateMainPasses(@NotNull final PsiFile psiFile, @NotNull final Document document, @NotNull final HighlightInfoProcessor highlightInfoProcessor) { final THashSet<TextEditorHighlightingPass> ids = new THashSet<>(); myRegisteredPassFactories.forEachKey(passId -> { PassConfig passConfig = myRegisteredPassFactories.get(passId); TextEditorHighlightingPassFactory factory = passConfig.passFactory; if (factory instanceof MainHighlightingPassFactory) { final TextEditorHighlightingPass pass = ((MainHighlightingPassFactory)factory).createMainHighlightingPass(psiFile, document, highlightInfoProcessor); if (pass != null) { ids.add(pass); pass.setId(passId); } } return true; }); return new ArrayList<>(ids); } private void checkForCycles() { final TIntObjectHashMap<TIntHashSet> transitivePredecessors = new TIntObjectHashMap<>(); myRegisteredPassFactories.forEachEntry((passId, config) -> { TIntHashSet allPredecessors = new TIntHashSet(config.completionPredecessorIds); allPredecessors.addAll(config.startingPredecessorIds); transitivePredecessors.put(passId, allPredecessors); allPredecessors.forEach(predecessorId -> { PassConfig predecessor = myRegisteredPassFactories.get(predecessorId); if (predecessor == null) return true; TIntHashSet transitives = transitivePredecessors.get(predecessorId); if (transitives == null) { transitives = new TIntHashSet(); transitivePredecessors.put(predecessorId, transitives); } transitives.addAll(predecessor.completionPredecessorIds); transitives.addAll(predecessor.startingPredecessorIds); return true; }); return true; }); transitivePredecessors.forEachKey(passId -> { if (transitivePredecessors.get(passId).contains(passId)) { throw new IllegalArgumentException("There is a cycle introduced involving pass " + myRegisteredPassFactories.get(passId).passFactory); } return true; }); } @NotNull @Override public List<DirtyScopeTrackingHighlightingPassFactory> getDirtyScopeTrackingFactories() { return myDirtyScopeTrackingFactories; } }
package monitoring.impl; import monitoring.intf.Monitor; import structure.impl.Verdict; import structure.intf.QEA; /** * All incremental monitors implement the trace method using the step method. * * TODO: Consider using "incremental" instead of "smallstep" * * @author Giles Reger * @author Helena Cuenca */ public abstract class SmallStepMonitor<Q extends QEA> extends Monitor<Q> { public SmallStepMonitor(Q q) { super(q); } @Override public Verdict trace(int[] eventNames, Object[][] args) { for (int i = 0; i < eventNames.length; i++) { switch (args[i].length) { case 0: step(eventNames[i]); break; case 1: step(eventNames[i], args[i][0]); break; case 2: step(eventNames[i], args[i][0], args[i][1]); break; case 3: step(eventNames[i], args[i][0], args[i][1], args[i][2]); break; case 4: step(eventNames[i], args[i][0], args[i][1], args[i][2], args[i][3]); break; case 5: step(eventNames[i], args[i][0], args[i][1], args[i][2], args[i][3], args[i][4]); break; default: step(eventNames[i], args[i]); break; } step(eventNames[i], args[i]); } return null; // TODO: What's the return value here? } }
// $Id: CharacterSprite.java,v 1.23 2002/03/08 22:35:55 mdb Exp $ package com.threerings.cast; import com.threerings.media.sprite.MultiFrameImage; import com.threerings.media.sprite.Path; import com.threerings.media.sprite.Sprite; /** * A character sprite is a sprite that animates itself while walking * about in a scene. */ public class CharacterSprite extends Sprite implements StandardActions { /** * Initializes this character sprite with the specified character * descriptor and character manager. It will obtain animation data * from the supplied character manager. */ public void init (CharacterDescriptor descrip, CharacterManager charmgr) { // keep track of this stuff _descrip = descrip; _charmgr = charmgr; // assign an arbitrary starting orientation _orient = NORTH; } /** * Reconfigures this sprite to use the specified character descriptor. */ public void setCharacterDescriptor (CharacterDescriptor descrip) { // keep the new descriptor _descrip = descrip; // reset our action which will reload our frames setActionSequence(_action); } /** * Specifies the action to use when the sprite is at rest. The default * is <code>STANDING</code>. */ public void setRestingAction (String action) { _restingAction = action; } /** * Specifies the action to use when the sprite is following a path. * The default is <code>WALKING</code>. */ public void setFollowingPathAction (String action) { _followingPathAction = action; } /** * Sets the action sequence used when rendering the character, from * the set of available sequences. */ public void setActionSequence (String action) { // keep track of our current action in case someone swaps out our // character description _action = action; // get a reference to the action sequence so that we can obtain // our animation frames and configure our frames per second ActionSequence actseq = _charmgr.getActionSequence(action); if (actseq == null) { String errmsg = "No such action '" + action + "'."; throw new IllegalArgumentException(errmsg); } try { // obtain our animation frames for this action sequence _frames = _charmgr.getActionFrames(_descrip, action); // update the sprite render attributes setOrigin(actseq.origin.x, actseq.origin.y); setFrameRate(actseq.framesPerSecond); setFrames(_frames[_orient]); } catch (NoSuchComponentException nsce) { Log.warning("Character sprite references non-existent " + "component [sprite=" + this + ", err=" + nsce + "]."); } } // documentation inherited public void setOrientation (int orient) { super.setOrientation(orient); // update the sprite frames to reflect the direction if (_frames != null) { setFrames(_frames[orient]); } } /** * Sets the origin coordinates representing the "base" of the * sprite, which in most cases corresponds to the center of the * bottom of the sprite image. */ public void setOrigin (int x, int y) { _xorigin = x; _yorigin = y; updateRenderOffset(); updateRenderOrigin(); } // documentation inherited protected void updateRenderOffset () { super.updateRenderOffset(); if (_frame != null) { // our location is based on the character origin coordinates _rxoff = -_xorigin; _ryoff = -_yorigin; } } // documentation inherited public void cancelMove () { super.cancelMove(); halt(); } // documentation inherited protected void pathBeginning () { super.pathBeginning(); // enable walking animation setActionSequence(_followingPathAction); setAnimationMode(TIME_BASED); } // documentation inherited protected void pathCompleted () { super.pathCompleted(); halt(); } /** * Updates the sprite animation frame to reflect the cessation of * movement and disables any further animation. */ protected void halt () { // disable animation setAnimationMode(NO_ANIMATION); // come to a halt looking settled and at peace setActionSequence(_restingAction); } /** The action to use when at rest. */ protected String _restingAction = STANDING; /** The action to use when following a path. */ protected String _followingPathAction = WALKING; /** A reference to the descriptor for the character that we're * visualizing. */ protected CharacterDescriptor _descrip; /** A reference to the character manager that created us. */ protected CharacterManager _charmgr; /** The action we are currently displaying. */ protected String _action; /** The animation frames for the active action sequence in each * orientation. */ protected MultiFrameImage[] _frames; /** The origin of the sprite. */ protected int _xorigin, _yorigin; }
package java8_in_action.chapter7; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Chapter7 { public static void main(String ... args) { ystem.out.println("chapter 7 main starting..."); final String SENTENCE = " Nel mezzo del cammin di nostra vita mi ritrovai in una selva oscura che la dritta via era smarrita " + " Nel mezzo del cammin di nostra vita mi ritrovai in una selva oscura che la dritta via era smarrita " + " Nel mezzo del cammin di nostra vita mi ritrovai in una selva oscura che la dritta via era"; System.out.println("iterative sentence words=" + countWordsIteratively(SENTENCE)); // functional word counter using streams Stream<Character> charStream = IntStream.range(0, SENTENCE.length()).mapToObj(SENTENCE::charAt); WordCounter wc = charStream.reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine); System.out.println("func sentence words=" + wc.getWordCount()); WordCounterSpliterator wcs = new WordCounterSpliterator(SENTENCE); wc = StreamSupport.stream(wcs, true).reduce(new WordCounter(0, true), WordCounter::accumulate, WordCounter::combine); System.out.println("spliterator sentence words=" + wc.getWordCount()); long [] nums = LongStream.rangeClosed(1, 100).toArray(); ForkJoinPool pool = new ForkJoinPool(); ForkJoinTask<Long> task = new ForkJoinSumCalculator(nums); Long sum = pool.invoke(task); System.out.println("sum=" + sum + ", created=" + ForkJoinSumCalculator.getNumCreated()); System.out.println("main exiting."); } protected static int countWordsIteratively(String str) { int count = 0; boolean foundWord = false; for(char c : str.toCharArray()) { if(Character.isWhitespace(c)) { if(foundWord) { foundWord = false; } } else { if(!foundWord) { foundWord = true; count++; } } } return count; } /** * Class to use for maintaining state during reduction operation to count words functionally. * @author tlanders */ protected static class WordCounter { protected final int wordCount; protected final boolean lastSpace; public WordCounter(int cnt, boolean lst) { this.wordCount = cnt; this.lastSpace = lst; } public WordCounter accumulate(Character c) { if(Character.isWhitespace(c)) { if(!lastSpace) { return new WordCounter(wordCount, true); } } else { if(lastSpace) { return new WordCounter(wordCount + 1, false); } } return this; } public WordCounter combine(WordCounter wc) { // don't care about last space status when summing the results return new WordCounter(this.wordCount + wc.getWordCount(), this.lastSpace); } public int getWordCount() { return wordCount; } } }
package com.intellij.history.core; import com.intellij.history.Clock; import com.intellij.history.FileRevisionTimestampComparator; import com.intellij.history.core.changes.*; import com.intellij.history.core.revisions.RecentChange; import com.intellij.history.core.revisions.Revision; import com.intellij.history.core.revisions.RevisionAfterChange; import com.intellij.history.core.revisions.RevisionBeforeChange; import com.intellij.history.core.storage.Content; import com.intellij.history.core.storage.Storage; import com.intellij.history.core.tree.Entry; import com.intellij.history.core.tree.RootEntry; import org.jetbrains.annotations.TestOnly; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class LocalVcs implements ILocalVcs { protected Storage myStorage; private ChangeList myChangeList; private Entry myRoot; private int myEntryCounter; private Change myLastChange; private boolean wasModifiedAfterLastSave; private int myChangeSetDepth; public LocalVcs(Storage s) { myStorage = s; load(); } private void load() { Memento m = myStorage.load(); myRoot = m.myRoot; myEntryCounter = m.myEntryCounter; myChangeList = m.myChangeList; } public void save() { if (!wasModifiedAfterLastSave) return; Memento m = new Memento(); m.myRoot = myRoot; m.myEntryCounter = myEntryCounter; m.myChangeList = myChangeList; myStorage.store(m); myStorage.save(); wasModifiedAfterLastSave = false; } public void purgeObsoleteAndSave(long period) { wasModifiedAfterLastSave = true; purgeObsolete(period); save(); } private void purgeObsolete(long period) { List<Content> contentsToPurge = myChangeList.purgeObsolete(period); myStorage.purgeContents(contentsToPurge); } public boolean hasEntry(String path) { return myRoot.hasEntry(path); } public Entry getEntry(String path) { return myRoot.getEntry(path); } public Entry findEntry(String path) { return myRoot.findEntry(path); } public List<Entry> getRoots() { return myRoot.getChildren(); } public void beginChangeSet() { myChangeList.beginChangeSet(); myChangeSetDepth++; } public void endChangeSet(String name) { myChangeList.endChangeSet(name); // we must call Storage.save to make it flush all the changes made during changeset. // otherwise the ContentStorage may become corrupted if IDEA is shutdown forcefully. myChangeSetDepth if (myChangeSetDepth == 0) { myStorage.save(); } } public void createFile(String path, ContentFactory f, long timestamp, boolean isReadOnly) { doCreateFile(getNextId(), path, f, timestamp, isReadOnly); } protected Content createContentFrom(ContentFactory f) { return f.createContent(myStorage); } public void createDirectory(String path) { doCreateDirectory(getNextId(), path); } private int getNextId() { return myEntryCounter++; } public void restoreFile(int id, String path, ContentFactory f, long timestamp, boolean isReadOnly) { doCreateFile(id, path, f, timestamp, isReadOnly); } private void doCreateFile(int id, String path, ContentFactory f, long timestamp, boolean isReadOnly) { Content c = createContentFrom(f); applyChange(new CreateFileChange(id, path, c, timestamp, isReadOnly)); } public void restoreDirectory(int id, String path) { doCreateDirectory(id, path); } private void doCreateDirectory(int id, String path) { applyChange(new CreateDirectoryChange(id, path)); } public void changeFileContent(String path, ContentFactory f, long timestamp) { if (contentWasNotChanged(path, f)) return; Content c = createContentFrom(f); applyChange(new ContentChange(path, c, timestamp)); } protected boolean contentWasNotChanged(String path, ContentFactory f) { return f.equalsTo(getEntry(path).getContent()); } public void rename(String path, String newName) { applyChange(new RenameChange(path, newName)); } public void changeROStatus(String path, boolean isReadOnly) { applyChange(new ROStatusChange(path, isReadOnly)); } public void move(String path, String newParentPath) { applyChange(new MoveChange(path, newParentPath)); } public void delete(String path) { applyChange(new DeleteChange(path)); } public void putSystemLabel(String name, int color) { applyLabel(new PutSystemLabelChange(name, color, getCurrentTimestamp())); } public void putUserLabel(String name) { applyLabel(new PutLabelChange(name, getCurrentTimestamp())); } public void putUserLabel(String path, String name) { applyLabel(new PutEntryLabelChange(path, name, getCurrentTimestamp())); } private void applyLabel(PutLabelChange c) { c.applyTo(myRoot); addChangeToChangeList(c); } private void applyChange(Change c) { c.applyTo(myRoot); // todo get rid of wrapping changeset here beginChangeSet(); addChangeToChangeList(c); endChangeSet(null); myLastChange = c; } private void addChangeToChangeList(Change c) { myChangeList.addChange(c); wasModifiedAfterLastSave = true; } @TestOnly public ChangeList getChangeList() { return myChangeList; } public Change getLastChange() { return myLastChange; } public boolean isBefore(Change before, Change after, boolean canBeEqual) { return myChangeList.isBefore(before, after, canBeEqual); } public List<Change> getChain(Change initialChange) { return myChangeList.getChain(initialChange); } public List<Revision> getRevisionsFor(String path) { return new RevisionsCollector(this, path, myRoot, myChangeList).getResult(); } public byte[] getByteContent(String path, FileRevisionTimestampComparator c) { return new ByteContentRetriever(this, path, c).getResult(); } public List<RecentChange> getRecentChanges() { List<RecentChange> result = new ArrayList<RecentChange>(); List<Change> cc = myChangeList.getChanges(); for (int i = 0; i < cc.size() && result.size() < 20; i++) { Change c = cc.get(i); if (c.isFileContentChange()) continue; if (c.isLabel()) continue; if (c.getName() == null) continue; Revision before = new RevisionBeforeChange(myRoot, myRoot, myChangeList, c); Revision after = new RevisionAfterChange(myRoot, myRoot, myChangeList, c); result.add(new RecentChange(before, after)); } return result; } public void accept(ChangeVisitor v) throws IOException { myChangeList.accept(myRoot, v); } protected long getCurrentTimestamp() { return Clock.getCurrentTimestamp(); } public static class Memento { public Entry myRoot = new RootEntry(); public int myEntryCounter = 0; public ChangeList myChangeList = new ChangeList(); } }
// Narya library - tools for developing networked games // 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.threerings.io; import java.io.InputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import com.samskivert.util.HashIntMap; import com.samskivert.util.StringUtil; import com.threerings.presents.Log; /** * Used to read {@link Streamable} objects from an {@link InputStream}. * Other common object types are supported as well (@see {@link * ObjectOutputStream}). * * @see Streamable */ public class ObjectInputStream extends DataInputStream { /** * Constructs an object input stream which will read its data from the * supplied source stream. */ public ObjectInputStream (InputStream source) { super(source); } /** * Customizes the class loader used to instnatiate objects read from * the input stream. */ public void setClassLoader (ClassLoader loader) { _loader = loader; } /** * Configures this object input stream with a mapping from an old * class name to a new one. Serialized instances of the old class name * will use the new class name when unserializing. */ public void addTranslation (String oldname, String newname) { if (_translations == null) { _translations = new HashMap(); } _translations.put(oldname, newname); } /** * Reads a {@link Streamable} instance or one of the supported object * types from the input stream. */ public Object readObject () throws IOException, ClassNotFoundException { ClassMapping cmap; // create our classmap if necessary if (_classmap == null) { _classmap = new HashIntMap(); } try { // read in the class code for this instance short code = readShort(); // a zero code indicates a null value if (code == 0) { if (STREAM_DEBUG) { Log.info(hashCode() + ": Read null."); } return null; // if the code is negative, that means that we've never // seen it before and class metadata follows } else if (code < 0) { // first swap the code into positive-land code *= -1; // read in the class metadata String cname = readUTF(); // if we have a translation (used to cope when serialized // classes are renamed) use it if (_translations != null) { String tname = (String)_translations.get(cname); if (tname != null) { cname = tname; } } // create a class mapping record, and cache it Class sclass = Class.forName(cname, true, _loader); Streamer streamer = Streamer.getStreamer(sclass); if (STREAM_DEBUG) { Log.info(hashCode() + ": New class '" + cname + "'."); } // sanity check if (streamer == null) { String errmsg = "Aiya! Unable to create streamer for " + "newly seen class [code=" + code + ", class=" + cname + "]"; throw new RuntimeException(errmsg); } cmap = new ClassMapping(code, sclass, streamer); _classmap.put(code, cmap); } else { cmap = (ClassMapping)_classmap.get(code); // sanity check if (cmap == null) { // this will help with debugging Log.warning("Internal stream error, no class metadata " + "[code=" + code + ", ois=" + this + "]."); Thread.dumpStack(); Log.warning("ObjectInputStream mappings " + StringUtil.toString(_classmap.entrySet()) + "."); String errmsg = "Read object code for which we " + "have no registered class metadata [code=" + code + "]"; throw new RuntimeException(errmsg); } } // create an instance of the appropriate object _streamer = cmap.streamer; Object target = _streamer.createObject(this); _current = target; // now read the instance data _streamer.readObject(target, this, true); // and return the newly read object return target; } catch (OutOfMemoryError oome) { throw (IOException) new IOException("Malformed object data").initCause(oome); } finally { // clear out our current object references _current = null; _streamer = null; } } /** * Reads an object from the input stream that was previously written * with {@link ObjectOutputStream#writeBareObject}. * * @param object the object to be populated from data on the stream. * It cannot be <code>null</code>. */ public void readBareObject (Object object) throws IOException, ClassNotFoundException { try { // obtain the streamer for objects of this class _streamer = Streamer.getStreamer(object.getClass()); _current = object; // now read the instance data _streamer.readObject(object, this, true); } finally { // clear out our current object references _current = null; _streamer = null; } } /** * Reads the fields of the specified {@link Streamable} instance from * the input stream using the default object streaming mechanisms (a * call is not made to <code>readObject()</code>, even if such a * method exists). */ public void defaultReadObject () throws IOException, ClassNotFoundException { // sanity check if (_current == null) { throw new RuntimeException( "defaultReadObject() called illegally."); } // read the instance data _streamer.readObject(_current, this, false); } /** * Generates a string representation of this instance. */ public String toString () { return "[hash=" + hashCode() + ", mappings=" + _classmap.size() + ", current=" + StringUtil.safeToString(_current) + ", streamer=" + _streamer + "]"; } /** * Used by a {@link Streamer} that is reading an array of {@link * Streamable} instances. */ protected void setCurrent (Streamer streamer, Object current) { _streamer = streamer; _current = current; } /** Used to map classes to numeric codes and the {@link Streamer} * instance used to write them. */ protected HashIntMap _classmap; /** The object currently being read from the stream. */ protected Object _current; /** The streamer being used currently. */ protected Streamer _streamer; /** The class loader we use to instantiate objects. */ protected ClassLoader _loader = getClass().getClassLoader(); /** An optional set of class name translations to use when * unserializing objects. */ protected HashMap _translations; /** Used to activate verbose debug logging. */ protected static final boolean STREAM_DEBUG = false; }
package org.zstack.network.service.portforwarding; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.Platform; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.MessageSafe; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.*; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.AbstractService; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.core.Completion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.identity.IdentityErrors; import org.zstack.header.identity.Quota; import org.zstack.header.identity.Quota.QuotaOperator; import org.zstack.header.identity.Quota.QuotaPair; import org.zstack.header.identity.ReportQuotaExtensionPoint; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.NeedQuotaCheckMessage; import org.zstack.header.network.l3.L3NetworkInventory; import org.zstack.header.network.l3.L3NetworkVO; import org.zstack.header.network.service.NetworkServiceProviderType; import org.zstack.header.network.service.NetworkServiceType; import org.zstack.header.query.AddExpandedQueryExtensionPoint; import org.zstack.header.query.ExpandedQueryAliasStruct; import org.zstack.header.query.ExpandedQueryStruct; import org.zstack.header.quota.QuotaConstant; import org.zstack.header.vm.*; import org.zstack.identity.AccountManager; import org.zstack.identity.QuotaUtil; import org.zstack.network.service.NetworkServiceManager; import org.zstack.network.service.vip.*; import org.zstack.tag.TagManager; import org.zstack.utils.*; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import java.util.*; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.list; public class PortForwardingManagerImpl extends AbstractService implements PortForwardingManager, VipReleaseExtensionPoint, AddExpandedQueryExtensionPoint, ReportQuotaExtensionPoint, VipGetUsedPortRangeExtensionPoint, VipGetServiceReferencePoint { private static CLogger logger = Utils.getLogger(PortForwardingManagerImpl.class); @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; @Autowired private PluginRegistry pluginRgty; @Autowired private NetworkServiceManager nwServiceMgr; @Autowired private TagManager tagMgr; @Autowired private AccountManager acntMgr; @Autowired private ErrorFacade errf; @Autowired private VipManager vipMgr; @Autowired private ThreadFacade thdf; private Map<String, PortForwardingBackend> backends = new HashMap<String, PortForwardingBackend>(); private List<AttachPortForwardingRuleExtensionPoint> attachRuleExts = new ArrayList<AttachPortForwardingRuleExtensionPoint>(); private List<RevokePortForwardingRuleExtensionPoint> revokeRuleExts = new ArrayList<RevokePortForwardingRuleExtensionPoint>(); @Override public String getId() { return bus.makeLocalServiceId(PortForwardingConstant.SERVICE_ID); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } private void handleLocalMessage(Message msg) { if (msg instanceof PortForwardingRuleDeletionMsg) { handle((PortForwardingRuleDeletionMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void removePortforwardingRule(final Iterator<String> it, final Completion completion) { if (!it.hasNext()) { completion.success(); return; } String uuid = it.next(); removePortforwardingRule(uuid, new Completion(completion) { @Override public void success() { removePortforwardingRule(it, completion); } @Override public void fail(ErrorCode errorCode) { completion.fail(errorCode); } }); } private void handle(final PortForwardingRuleDeletionMsg msg) { final PortForwardingRuleDeletionReply reply = new PortForwardingRuleDeletionReply(); removePortforwardingRule(msg.getRuleUuids().iterator(), new Completion(msg) { @Override public void success () { bus.reply(msg, reply); } @Override public void fail (ErrorCode errorCode){ reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handleApiMessage(APIMessage msg) { if (msg instanceof APICreatePortForwardingRuleMsg) { handle((APICreatePortForwardingRuleMsg) msg); } else if (msg instanceof APIDeletePortForwardingRuleMsg) { handle((APIDeletePortForwardingRuleMsg) msg); } else if (msg instanceof APIListPortForwardingRuleMsg) { handle((APIListPortForwardingRuleMsg) msg); } else if (msg instanceof APIAttachPortForwardingRuleMsg) { handle((APIAttachPortForwardingRuleMsg) msg); } else if (msg instanceof APIDetachPortForwardingRuleMsg) { handle((APIDetachPortForwardingRuleMsg) msg); } else if (msg instanceof APIChangePortForwardingRuleStateMsg) { handle((APIChangePortForwardingRuleStateMsg) msg); } else if (msg instanceof APIGetPortForwardingAttachableVmNicsMsg) { handle((APIGetPortForwardingAttachableVmNicsMsg) msg); } else if (msg instanceof APIUpdatePortForwardingRuleMsg) { handle((APIUpdatePortForwardingRuleMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(APIUpdatePortForwardingRuleMsg msg) { boolean update = false; PortForwardingRuleVO vo = dbf.findByUuid(msg.getUuid(), PortForwardingRuleVO.class); if (msg.getName() != null) { vo.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { vo.setDescription(msg.getDescription()); update = true; } if (update) { vo = dbf.updateAndRefresh(vo); } APIUpdatePortForwardingRuleEvent evt = new APIUpdatePortForwardingRuleEvent(msg.getId()); evt.setInventory(PortForwardingRuleInventory.valueOf(vo)); bus.publish(evt); } private List<VmNicInventory> getAttachableVmNics(String ruleUuid) { return new SQLBatchWithReturn<List<VmNicInventory>>(){ @Override protected List<VmNicInventory> scripts() { Tuple t = sql("select l3.zoneUuid, vip.uuid" + " from L3NetworkVO l3, VipVO vip, PortForwardingRuleVO rule" + " where vip.l3NetworkUuid = l3.uuid" + " and vip.uuid = rule.vipUuid" + " and rule.uuid = :ruleUuid",Tuple.class) .param("ruleUuid", ruleUuid).find(); String zoneUuid = t.get(0, String.class); String vipUuid = t.get(1, String.class); List<VipPeerL3NetworkRefVO> vipPeerL3Refs = Q.New(VipPeerL3NetworkRefVO.class) .eq(VipPeerL3NetworkRefVO_.vipUuid, vipUuid) .list(); List<String> vipPeerL3Uuids = new ArrayList<>(); if (vipPeerL3Refs != null && !vipPeerL3Refs.isEmpty()) { vipPeerL3Uuids = vipPeerL3Refs.stream() .map(ref -> ref.getL3NetworkUuid()) .collect(Collectors.toList()); } //0.check the l3 of vm nic has been attached to port forwarding service List<String> l3Uuids = new ArrayList<>(); if (vipPeerL3Uuids == null || vipPeerL3Uuids.isEmpty()) { l3Uuids = sql("select l3.uuid" + " from L3NetworkVO l3, VipVO vip, NetworkServiceL3NetworkRefVO ref" + " where l3.system = :system" + " and l3.uuid != vip.l3NetworkUuid" + " and l3.uuid = ref.l3NetworkUuid" + " and ref.networkServiceType = :nsType" + " and l3.zoneUuid = :zoneUuid" + " and vip.uuid = :vipUuid") .param("vipUuid", vipUuid) .param("system", false) .param("zoneUuid", zoneUuid) .param("nsType", PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE).list(); } else { VmNicVO rnic = Q.New(VmNicVO.class).in(VmNicVO_.l3NetworkUuid, vipPeerL3Uuids) .notNull(VmNicVO_.metaData).limit(1).find(); if (rnic == null) { l3Uuids.addAll(vipPeerL3Uuids); } else { List<String> vrAttachedL3Uuids = Q.New(VmNicVO.class) .select(VmNicVO_.l3NetworkUuid) .eq(VmNicVO_.vmInstanceUuid, rnic.getVmInstanceUuid()) .listValues(); Set l3UuidSet = new HashSet<>(vipPeerL3Uuids); l3UuidSet.addAll(vrAttachedL3Uuids); l3Uuids.addAll(l3UuidSet); } } if (l3Uuids.isEmpty()) { return new ArrayList<>(); } // 1.select private l3 String rulePublicL3Uuid = sql("select l3NetworkUuid from VipVO where uuid = (select vipUuid from PortForwardingRuleVO where uuid = :ruleUuid)", String.class) .param("ruleUuid", ruleUuid).find(); List<String> vrouterUuids = sql("select uuid from VirtualRouterVmVO where publicNetworkUuid = :publicNetworkUuid",String.class) .param("publicNetworkUuid", rulePublicL3Uuid).list(); if(vrouterUuids.isEmpty()){ return new ArrayList<>(); } List<String> privateL3Uuids = new ArrayList<>(); for(String vrouterUuid : vrouterUuids){ List<String> vrouterPrivateL3Uuids = sql("select l3NetworkUuid from VmNicVO " + " where vmInstanceUuid = :vrouterUuid" + " and l3NetworkUuid != :rulePublicL3Uuid " + " and l3NetworkUuid != (select managementNetworkUuid from ApplianceVmVO where uuid = :vrouterUuid)", String.class) .param("vrouterUuid", vrouterUuid) .param("rulePublicL3Uuid", rulePublicL3Uuid) .list(); privateL3Uuids.addAll(vrouterPrivateL3Uuids); } if(privateL3Uuids.isEmpty()){ return new ArrayList<>(); } l3Uuids = l3Uuids.stream() .filter(l3 -> privateL3Uuids.contains(l3)) .collect(Collectors.toList()); if (l3Uuids.isEmpty()) { return new ArrayList<>(); } //2.check the state of port forwarding and vm t = sql("select pf.privatePortStart, pf.privatePortEnd, pf.protocolType" + " from PortForwardingRuleVO pf" + " where pf.uuid = :ruleUuid",Tuple.class) .param("ruleUuid", ruleUuid).find(); int sport = t.get(0, Integer.class); int eport = t.get(1, Integer.class); PortForwardingProtocolType protocol = t.get(2, PortForwardingProtocolType.class); List<VmNicVO> nics = sql("select nic from VmNicVO nic, VmInstanceVO vm where nic.l3NetworkUuid in (:l3Uuids)" + " and nic.vmInstanceUuid = vm.uuid and vm.type = :vmType and vm.state in (:vmStates)" + " and nic.uuid not in (select pf.vmNicUuid from PortForwardingRuleVO pf" + " where pf.protocolType = :protocol and pf.vmNicUuid is not null and" + " ((pf.privatePortStart >= :sport and pf.privatePortStart <= :eport) or" + " (pf.privatePortStart <= :sport and :sport <= pf.privatePortEnd)))") .param("l3Uuids", l3Uuids) .param("vmType", VmInstanceConstant.USER_VM_TYPE) .param("vmStates", asList(VmInstanceState.Running, VmInstanceState.Stopped)) .param("sport", sport) .param("eport", eport) .param("protocol", protocol).list(); if(nics.isEmpty()){ return new ArrayList<>(); } //3.exclude the vm which has port forwarding rules that have different VIPs List<String> usedVm = sql("select nic.vmInstanceUuid" + " from PortForwardingRuleVO pf1, VmNicVO nic" + " where pf1.vipUuid != :vipUuid" + " and pf1.vmNicUuid is not null" + " and pf1.vmNicUuid = nic.uuid") .param("vipUuid",vipUuid).list(); return VmNicInventory.valueOf(nics.stream().filter(nic -> !usedVm.contains(nic.getVmInstanceUuid())).collect(Collectors.toList())); } }.execute(); } private void handle(APIGetPortForwardingAttachableVmNicsMsg msg) { APIGetPortForwardingAttachableVmNicsReply reply = new APIGetPortForwardingAttachableVmNicsReply(); reply.setInventories(getAttachableVmNics(msg.getRuleUuid())); bus.reply(msg, reply); } private void handle(APIChangePortForwardingRuleStateMsg msg) { PortForwardingRuleVO vo = dbf.findByUuid(msg.getUuid(), PortForwardingRuleVO.class); vo.setState(vo.getState().nextState(PortForwardingRuleStateEvent.valueOf(msg.getStateEvent()))); vo = dbf.updateAndRefresh(vo); APIChangePortForwardingRuleStateEvent evt = new APIChangePortForwardingRuleStateEvent(msg.getId()); evt.setInventory(PortForwardingRuleInventory.valueOf(vo)); bus.publish(evt); } private void handle(APIDetachPortForwardingRuleMsg msg) { final APIDetachPortForwardingRuleEvent evt = new APIDetachPortForwardingRuleEvent(msg.getId()); final PortForwardingRuleVO vo = dbf.findByUuid(msg.getUuid(), PortForwardingRuleVO.class); PortForwardingRuleInventory inv = PortForwardingRuleInventory.valueOf(vo); final PortForwardingStruct struct = makePortForwardingStruct(inv); struct.setReleaseVmNicInfoWhenDetaching(true); final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService(struct.getGuestL3Network().getUuid(), NetworkServiceType.PortForwarding); detachPortForwardingRule(struct, providerType.toString(), new Completion(msg) { @Override public void success() { PortForwardingRuleVO prvo = dbf.reload(vo); evt.setInventory(PortForwardingRuleInventory.valueOf(prvo)); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); } @Transactional private VmInstanceState getVmStateFromVmNicUuid(String vmNicUuid) { String sql = "select vm.state from VmInstanceVO vm, VmNicVO nic where vm.uuid = nic.vmInstanceUuid and nic.uuid = :nicuuid"; TypedQuery<VmInstanceState> q = dbf.getEntityManager().createQuery(sql, VmInstanceState.class); q.setParameter("nicuuid", vmNicUuid); return q.getSingleResult(); } private void handle(final APIAttachPortForwardingRuleMsg msg) { final APIAttachPortForwardingRuleEvent evt = new APIAttachPortForwardingRuleEvent(msg.getId()); PortForwardingRuleVO vo = dbf.findByUuid(msg.getRuleUuid(), PortForwardingRuleVO.class); VmNicVO nicvo = dbf.findByUuid(msg.getVmNicUuid(), VmNicVO.class); vo.setVmNicUuid(nicvo.getUuid()); vo.setGuestIp(nicvo.getIp()); final PortForwardingRuleVO prvo = dbf.updateAndRefresh(vo); final PortForwardingRuleInventory inv = PortForwardingRuleInventory.valueOf(prvo); VmInstanceState vmState = getVmStateFromVmNicUuid(msg.getVmNicUuid()); if (VmInstanceState.Running != vmState) { Vip vip = new Vip(vo.getVipUuid()); ModifyVipAttributesStruct struct = new ModifyVipAttributesStruct(); final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService( nicvo.getL3NetworkUuid(), NetworkServiceType.PortForwarding); struct.setServiceProvider(providerType.toString()); struct.setPeerL3NetworkUuid(nicvo.getL3NetworkUuid()); vip.setStruct(struct); vip.acquire(new Completion(msg) { @Override public void success() { evt.setInventory(inv); bus.publish(evt); return; } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); } final PortForwardingStruct struct = makePortForwardingStruct(inv); final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService(struct.getGuestL3Network().getUuid(), NetworkServiceType.PortForwarding); attachPortForwardingRule(struct, providerType.toString(), new Completion(msg) { @Override public void success() { evt.setInventory(inv); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { prvo.setVmNicUuid(null); prvo.setGuestIp(null); dbf.update(prvo); evt.setError(errorCode); bus.publish(evt); } }); } private void handle(APIListPortForwardingRuleMsg msg) { List<PortForwardingRuleVO> vos = dbf.listByApiMessage(msg, PortForwardingRuleVO.class); List<PortForwardingRuleInventory> invs = PortForwardingRuleInventory.valueOf(vos); APIListPortForwardingRuleReply reply = new APIListPortForwardingRuleReply(); reply.setInventories(invs); bus.reply(msg, reply); } private boolean isNeedRemoveVip(PortForwardingRuleInventory inv) { SimpleQuery q = dbf.createQuery(PortForwardingRuleVO.class); q.add(PortForwardingRuleVO_.vipUuid, Op.EQ, inv.getVipUuid()); q.add(PortForwardingRuleVO_.vmNicUuid, Op.NOT_NULL); return q.count() == 1; } private void removePortforwardingRule(String ruleUuid, final Completion complete) { final PortForwardingRuleVO vo = dbf.findByUuid(ruleUuid, PortForwardingRuleVO.class); final PortForwardingRuleInventory inv = PortForwardingRuleInventory.valueOf(vo); if (vo.getVmNicUuid() == null) { ModifyVipAttributesStruct struct = new ModifyVipAttributesStruct(); struct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); Vip v = new Vip(vo.getVipUuid()); v.setStruct(struct); v.release(new Completion(complete) { @Override public void success() { dbf.remove(vo); complete.success(); } @Override public void fail(ErrorCode errorCode) { complete.fail(errorCode); } }); return; } final PortForwardingStruct struct = makePortForwardingStruct(inv); final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService(struct.getGuestL3Network().getUuid(), NetworkServiceType.PortForwarding); for (RevokePortForwardingRuleExtensionPoint extp : revokeRuleExts) { try { extp.preRevokePortForwardingRule(inv, providerType); } catch (PortForwardingException e) { String err = String.format("unable to revoke port forwarding rule[uuid:%s]", inv.getUuid()); logger.warn(err, e); complete.fail(errf.throwableToOperationError(e)); return; } } CollectionUtils.safeForEach(revokeRuleExts, new ForEachFunction<RevokePortForwardingRuleExtensionPoint>() { @Override public void run(RevokePortForwardingRuleExtensionPoint extp) { extp.beforeRevokePortForwardingRule(inv, providerType); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "delete-portforwarding-rule"; @Override public void run(FlowTrigger trigger, Map data) { PortForwardingBackend bkd = getPortForwardingBackend(providerType); bkd.revokePortForwardingRule(struct, new Completion(trigger) { @Override public void success() { logger.debug(String.format("successfully detached %s", struct.toString())); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); flow(new NoRollbackFlow() { String __name__ = "release-vip-if-no-rules"; @Override public void run(FlowTrigger trigger, Map data) { ModifyVipAttributesStruct struct = new ModifyVipAttributesStruct(); struct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); Vip v = new Vip(inv.getVipUuid()); v.setStruct(struct); v.release(new Completion(trigger){ @Override public void success() { logger.debug(String.format("delete backend for VIP[uuid:%s] from port forwarding", vo.getVipUuid())); trigger.next(); } @Override public void fail(ErrorCode errorCode) { //TODO: GC this VIP logger.warn(errorCode.toString()); trigger.next(); } }); } }); done(new FlowDoneHandler(complete) { @Override public void handle(Map data) { dbf.remove(vo); CollectionUtils.safeForEach(revokeRuleExts, new ForEachFunction<RevokePortForwardingRuleExtensionPoint>() { @Override public void run(RevokePortForwardingRuleExtensionPoint extp) { extp.afterRevokePortForwardingRule(inv, providerType); } }); logger.debug(String.format("successfully revoked port forwarding rule[uuid:%s]", inv.getUuid())); complete.success(); } }); error(new FlowErrorHandler(complete) { @Override public void handle(ErrorCode errCode, Map data) { CollectionUtils.safeForEach(revokeRuleExts, new ForEachFunction<RevokePortForwardingRuleExtensionPoint>() { @Override public void run(RevokePortForwardingRuleExtensionPoint extp) { extp.failToRevokePortForwardingRule(inv, providerType); } }); logger.warn(String.format("failed to revoke port forwarding rule[uuid:%s] because %s", inv.getUuid(), errCode)); complete.fail(errCode); } }); } }).start(); } private void handle(APIDeletePortForwardingRuleMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { String vipUuid = Q.New(PortForwardingRuleVO.class).eq(PortForwardingRuleVO_.uuid, msg.getUuid()).select(PortForwardingRuleVO_.vipUuid).findValue(); return String.format("api-delete-portforwardingrule-vip-%s", vipUuid); } @Override public void run(SyncTaskChain chain) { final APIDeletePortForwardingRuleEvent evt = new APIDeletePortForwardingRuleEvent(msg.getId()); removePortforwardingRule(msg.getUuid(), new Completion(msg) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("api-delete-portforwardingrule-%s", msg.getUuid()); } }); } private void handle(APICreatePortForwardingRuleMsg msg) { final APICreatePortForwardingRuleEvent evt = new APICreatePortForwardingRuleEvent(msg.getId()); int vipPortEnd = msg.getVipPortEnd() == null ? msg.getVipPortStart() : msg.getVipPortEnd(); int privatePortEnd = msg.getPrivatePortEnd() == null ? msg.getPrivatePortStart() : msg.getPrivatePortEnd(); VipVO vip = dbf.findByUuid(msg.getVipUuid(), VipVO.class); final PortForwardingRuleVO vo = new PortForwardingRuleVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); vo.setState(PortForwardingRuleState.Enabled); vo.setAllowedCidr(msg.getAllowedCidr()); vo.setVipUuid(vip.getUuid()); vo.setVipIp(vip.getIp()); vo.setVipPortStart(msg.getVipPortStart()); vo.setVipPortEnd(vipPortEnd); vo.setPrivatePortEnd(privatePortEnd); vo.setPrivatePortStart(msg.getPrivatePortStart()); vo.setProtocolType(PortForwardingProtocolType.valueOf(msg.getProtocolType())); new SQLBatch() { @Override protected void scripts() { persist(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), PortForwardingRuleVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), PortForwardingRuleVO.class.getSimpleName()); } }.execute(); VipInventory vipInventory = VipInventory.valueOf(vip); if (msg.getVmNicUuid() == null) { ModifyVipAttributesStruct struct = new ModifyVipAttributesStruct(); struct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); Vip v = new Vip(vo.getVipUuid()); v.setStruct(struct); v.acquire(new Completion(msg) { @Override public void success() { evt.setInventory(PortForwardingRuleInventory.valueOf(vo)); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); return; } VmNicVO vmNic = dbf.findByUuid(msg.getVmNicUuid(), VmNicVO.class); SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class); q.select(VmInstanceVO_.state); q.add(VmInstanceVO_.uuid, Op.EQ, vmNic.getVmInstanceUuid()); VmInstanceState vmState = q.findValue(); if (VmInstanceState.Running != vmState) { ModifyVipAttributesStruct struct = new ModifyVipAttributesStruct(); struct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); Vip v = new Vip(vo.getVipUuid()); v.setStruct(struct); v.acquire(new Completion(msg) { @Override public void success() { evt.setInventory(PortForwardingRuleInventory.valueOf(vo)); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); return; } final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService(vmNic.getL3NetworkUuid(), NetworkServiceType.PortForwarding); vo.setVmNicUuid(vmNic.getUuid()); vo.setGuestIp(vmNic.getIp()); PortForwardingRuleVO pvo = dbf.updateAndRefresh(vo); final PortForwardingRuleInventory ruleInv = PortForwardingRuleInventory.valueOf(pvo); for (AttachPortForwardingRuleExtensionPoint extp : attachRuleExts) { try { extp.preAttachPortForwardingRule(ruleInv, providerType); } catch (PortForwardingException e) { String err = String.format("unable to create port forwarding rule, extension[%s] refused it because %s", extp.getClass().getName(), e.getMessage()); logger.warn(err, e); evt.setError(errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, err)); bus.publish(evt); return; } } CollectionUtils.safeForEach(attachRuleExts, new ForEachFunction<AttachPortForwardingRuleExtensionPoint>() { @Override public void run(AttachPortForwardingRuleExtensionPoint extp) { extp.beforeAttachPortForwardingRule(ruleInv, providerType); } }); final PortForwardingStruct struct = makePortForwardingStruct(ruleInv); attachPortForwardingRule(struct, providerType.toString(), new Completion(msg) { @Override public void success() { CollectionUtils.safeForEach(attachRuleExts, new ForEachFunction<AttachPortForwardingRuleExtensionPoint>() { @Override public void run(AttachPortForwardingRuleExtensionPoint extp) { extp.afterAttachPortForwardingRule(ruleInv, providerType); } }); evt.setInventory(ruleInv); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { CollectionUtils.safeForEach(attachRuleExts, extp -> extp.failToAttachPortForwardingRule(ruleInv, providerType)); logger.debug(String.format("failed to create port forwarding rule %s, because %s", JSONObjectUtil.toJsonString(ruleInv), errorCode)); dbf.remove(vo); evt.setError(errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, errorCode)); bus.publish(evt); } }); } private void populateExtensions() { for (PortForwardingBackend extp : pluginRgty.getExtensionList(PortForwardingBackend.class)) { PortForwardingBackend old = backends.get(extp.getProviderType().toString()); if (old != null) { throw new CloudRuntimeException(String.format("duplicate PortForwardingBackend[%s, %s] for type[%s]", extp.getClass().getName(), old.getClass().getName(), extp.getProviderType())); } backends.put(extp.getProviderType().toString(), extp); } attachRuleExts = pluginRgty.getExtensionList(AttachPortForwardingRuleExtensionPoint.class); revokeRuleExts = pluginRgty.getExtensionList(RevokePortForwardingRuleExtensionPoint.class); } @Override public boolean start() { populateExtensions(); return true; } @Override public boolean stop() { return true; } public PortForwardingBackend getPortForwardingBackend(NetworkServiceProviderType nspType) { return getPortForwardingBackend(nspType.toString()); } @Override public String getVipUse() { return PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE; } private void releaseServicesOnVip(final Iterator<PortForwardingRuleVO> it, final Completion completion) { if (!it.hasNext()) { completion.success(); return; } final PortForwardingRuleVO rule = it.next(); if (rule.getVmNicUuid() == null) { dbf.remove(rule); releaseServicesOnVip(it, completion); return; } PortForwardingStruct struct = makePortForwardingStruct(PortForwardingRuleInventory.valueOf(rule)); final NetworkServiceProviderType providerType = nwServiceMgr.getTypeOfNetworkServiceProviderForService(struct.getGuestL3Network().getUuid(), NetworkServiceType.PortForwarding); PortForwardingBackend bkd = getPortForwardingBackend(providerType); bkd.revokePortForwardingRule(struct, new Completion(completion) { @Override public void success() { dbf.remove(rule); releaseServicesOnVip(it, completion); } @Override public void fail(ErrorCode errorCode) { completion.fail(errorCode); } }); } @Override public void releaseServicesOnVip(VipInventory vip, Completion complete) { SimpleQuery<PortForwardingRuleVO> q = dbf.createQuery(PortForwardingRuleVO.class); q.add(PortForwardingRuleVO_.vipUuid, Op.EQ, vip.getUuid()); List<PortForwardingRuleVO> rules = q.list(); releaseServicesOnVip(rules.iterator(), complete); } private PortForwardingStruct makePortForwardingStruct(PortForwardingRuleInventory rule) { VipVO vipvo = dbf.findByUuid(rule.getVipUuid(), VipVO.class); L3NetworkVO vipL3vo = dbf.findByUuid(vipvo.getL3NetworkUuid(), L3NetworkVO.class); VmNicVO nic = dbf.findByUuid(rule.getVmNicUuid(), VmNicVO.class); L3NetworkVO guestL3vo = dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class); PortForwardingStruct struct = new PortForwardingStruct(); struct.setRule(rule); struct.setVip(VipInventory.valueOf(vipvo)); struct.setGuestIp(nic.getIp()); struct.setGuestMac(nic.getMac()); struct.setGuestL3Network(L3NetworkInventory.valueOf(guestL3vo)); struct.setSnatInboundTraffic(PortForwardingGlobalConfig.SNAT_INBOUND_TRAFFIC.value(Boolean.class)); struct.setVipL3Network(L3NetworkInventory.valueOf(vipL3vo)); return struct; } @Override public PortForwardingBackend getPortForwardingBackend(String providerType) { PortForwardingBackend bkd = backends.get(providerType); DebugUtils.Assert(bkd != null, String.format("cannot find PortForwardingBackend[type:%s]", providerType)); return bkd; } @Override public void attachPortForwardingRule(PortForwardingStruct struct, String providerType, final Completion completion) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("attach-portforwarding-%s-vm-nic-%s", struct.getRule().getUuid(), struct.getRule().getVmNicUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new Flow() { String __name__ = "prepare-vip"; boolean s = false; @Override public void run(FlowTrigger trigger, Map data) { ModifyVipAttributesStruct vipStruct = new ModifyVipAttributesStruct(); vipStruct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); vipStruct.setServiceProvider(providerType); vipStruct.setPeerL3NetworkUuid(struct.getGuestL3Network().getUuid()); Vip vip = new Vip(struct.getVip().getUuid()); vip.setStruct(vipStruct); vip.acquire(new Completion(trigger) { @Override public void success() { s = true; trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } @Override public void rollback(FlowRollback trigger, Map data) { ModifyVipAttributesStruct vipStruct = new ModifyVipAttributesStruct(); vipStruct.setUseFor(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE); Vip v = new Vip(struct.getVip().getUuid()); v.setStruct(vipStruct); v.release(new Completion(trigger) { @Override public void success() { trigger.rollback(); } @Override public void fail(ErrorCode errorCode) { //TODO add GC logger.warn(errorCode.toString()); trigger.rollback(); } }); } }); flow(new NoRollbackFlow() { String __name__ = "attach-portfowarding-rule"; @Override public void run(FlowTrigger trigger, Map data) { PortForwardingBackend bkd = getPortForwardingBackend(providerType); bkd.applyPortForwardingRule(struct, new Completion(trigger) { @Override public void success() { logger.debug(String.format("successfully attached %s", struct.toString())); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } @Override public void detachPortForwardingRule(final PortForwardingStruct struct, String providerType, final Completion completion) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("detach-portforwarding-%s-vm-nic-%s", struct.getRule().getUuid(), struct.getRule().getVmNicUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "detach-portforwarding-rule"; @Override public void run(FlowTrigger trigger, Map data) { PortForwardingBackend bkd = getPortForwardingBackend(providerType); bkd.revokePortForwardingRule(struct, new Completion(trigger) { @Override public void success() { logger.debug(String.format("successfully detached %s", struct.toString())); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { if (struct.isReleaseVmNicInfoWhenDetaching()) { PortForwardingRuleVO vo = dbf.findByUuid(struct.getRule().getUuid(), PortForwardingRuleVO.class); vo.setVmNicUuid(null); vo.setGuestIp(null); dbf.updateAndRefresh(vo); } completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } @Override public List<ExpandedQueryStruct> getExpandedQueryStructs() { List<ExpandedQueryStruct> structs = new ArrayList<ExpandedQueryStruct>(); ExpandedQueryStruct struct = new ExpandedQueryStruct(); struct.setInventoryClassToExpand(VmNicInventory.class); struct.setExpandedField("portForwarding"); struct.setInventoryClass(PortForwardingRuleInventory.class); struct.setForeignKey("uuid"); struct.setExpandedInventoryKey("vmNicUuid"); structs.add(struct); struct = new ExpandedQueryStruct(); struct.setInventoryClassToExpand(VipInventory.class); struct.setExpandedField("portForwarding"); struct.setInventoryClass(PortForwardingRuleInventory.class); struct.setForeignKey("uuid"); struct.setExpandedInventoryKey("vipUuid"); structs.add(struct); return structs; } @Override public List<ExpandedQueryAliasStruct> getExpandedQueryAliasesStructs() { return null; } @Override public List<Quota> reportQuota() { QuotaOperator checker = new QuotaOperator() { @Override public void checkQuota(APIMessage msg, Map<String, QuotaPair> pairs) { if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) { if (msg instanceof APICreatePortForwardingRuleMsg) { check((APICreatePortForwardingRuleMsg) msg, pairs); } } } @Override public void checkQuota(NeedQuotaCheckMessage msg, Map<String, QuotaPair> pairs) { } @Override public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) { Quota.QuotaUsage usage = new Quota.QuotaUsage(); usage.setName(PortForwardingConstant.QUOTA_PF_NUM); usage.setUsed(getUsedPf(accountUuid)); return list(usage); } @Transactional(readOnly = true) private long getUsedPf(String accountUuid) { String sql = "select count(pf) from PortForwardingRuleVO pf, AccountResourceRefVO ref where pf.uuid = ref.resourceUuid" + " and ref.accountUuid = :auuid and ref.resourceType = :rtype"; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("auuid", accountUuid); q.setParameter("rtype", PortForwardingRuleVO.class.getSimpleName()); Long pfn = q.getSingleResult(); pfn = pfn == null ? 0 : pfn; return pfn; } private void check(APICreatePortForwardingRuleMsg msg, Map<String, QuotaPair> pairs) { long pfNum = pairs.get(PortForwardingConstant.QUOTA_PF_NUM).getValue(); long pfn = getUsedPf(msg.getSession().getAccountUuid()); if (pfn + 1 > pfNum) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode(IdentityErrors.QUOTA_EXCEEDING, String.format("quota exceeding. The account[uuid: %s] exceeds a quota[name: %s, value: %s]", msg.getSession().getAccountUuid(), PortForwardingConstant.QUOTA_PF_NUM, pfNum) )); } } }; Quota quota = new Quota(); quota.setOperator(checker); quota.addMessageNeedValidation(APICreatePortForwardingRuleMsg.class); QuotaPair p = new QuotaPair(); p.setName(PortForwardingConstant.QUOTA_PF_NUM); p.setValue(QuotaConstant.QUOTA_PF_NUM); quota.addPair(p); return list(quota); } @Override public RangeSet getVipUsePortRange(String vipUuid, String protocol, VipUseForList useForList){ RangeSet portRangeList = new RangeSet(); List<RangeSet.Range> portRanges = new ArrayList<RangeSet.Range>(); if (protocol.toUpperCase().equals(PortForwardingProtocolType.UDP.toString()) || protocol.toUpperCase().equals(PortForwardingProtocolType.TCP.toString())) { List<Tuple> pfPortList = Q.New(PortForwardingRuleVO.class).select(PortForwardingRuleVO_.vipPortStart, PortForwardingRuleVO_.vipPortEnd) .eq(PortForwardingRuleVO_.vipUuid, vipUuid).eq(PortForwardingRuleVO_.protocolType, PortForwardingProtocolType.valueOf(protocol.toUpperCase())).listTuple(); Iterator<Tuple> it = pfPortList.iterator(); while (it.hasNext()){ Tuple strRange = it.next(); int start = strRange.get(0, Integer.class); int end = strRange.get(1, Integer.class); RangeSet.Range range = new RangeSet.Range(start, end); portRanges.add(range); } } portRangeList.setRanges(portRanges); return portRangeList; } @Override public ServiceReference getServiceReference(String vipUuid) { long count = Q.New(PortForwardingRuleVO.class).eq(PortForwardingRuleVO_.vipUuid, vipUuid).count(); return new VipGetServiceReferencePoint.ServiceReference(PortForwardingConstant.PORTFORWARDING_NETWORK_SERVICE_TYPE, count); } }
package mrriegel.flexibletools; import java.util.stream.Collectors; import mrriegel.flexibletools.item.ITool; import mrriegel.limelib.helper.RecipeHelper; import mrriegel.limelib.recipe.ShapelessRecipeExt; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.oredict.OreDictionary; public class ModRecipes { public static void init() { RecipeHelper.addShapelessRecipe(new ItemStack(ModItems.multi), ModItems.pick, ModItems.axe, ModItems.shovel, Blocks.SLIME_BLOCK); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.sword), "qqq", "ltl", "gog", 't', Items.DIAMOND_SWORD, 'q', Items.QUARTZ, 'l', new ItemStack(Items.DYE, 1, 4), 'g', Items.GOLD_INGOT, 'o', Blocks.OBSIDIAN); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.pick), "qqq", "ltl", "gog", 't', Items.DIAMOND_PICKAXE, 'q', Items.QUARTZ, 'l', new ItemStack(Items.DYE, 1, 4), 'g', Items.GOLD_INGOT, 'o', Blocks.OBSIDIAN); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.axe), "qqq", "ltl", "gog", 't', Items.DIAMOND_AXE, 'q', Items.QUARTZ, 'l', new ItemStack(Items.DYE, 1, 4), 'g', Items.GOLD_INGOT, 'o', Blocks.OBSIDIAN); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.shovel), "qqq", "ltl", "gog", 't', Items.DIAMOND_SHOVEL, 'q', Items.QUARTZ, 'l', new ItemStack(Items.DYE, 1, 4), 'g', Items.GOLD_INGOT, 'o', Blocks.OBSIDIAN); RecipeHelper.add(new Repair(ModItems.sword)); RecipeHelper.add(new Repair(ModItems.pick)); RecipeHelper.add(new Repair(ModItems.axe)); RecipeHelper.add(new Repair(ModItems.shovel)); RecipeHelper.add(new Repair(ModItems.multi)); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_area, 1, 0), " f ", "dbd", " i ", 'f', Items.FLINT, 'd', "gemDiamond", 'b', "ingotBrick", 'i', "ingotIron"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_area, 1, 1), " f ", "dbd", " i ", 'f', Items.FLINT, 'd', "gemDiamond", 'b', "ingotBrick", 'i', "ingotGold"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_area, 1, 2), " f ", "dbd", " i ", 'f', Items.FLINT, 'd', "gemDiamond", 'b', "ingotBrick", 'i', "gemQuartz"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_area, 1, 3), " r ", "dbl", " c ", 'r', "oreRedstone", 'd', "oreDiamond", 'b', "ingotBrick", 'l', "oreLapis", 'c', "oreCoal"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_transport, 1, 0), " f ", "dbd", " i ", 'f', "enderpearl", 'd', Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE, 'b', "ingotBrick", 'i', Blocks.HOPPER); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_transport, 1, 1), " f ", "dbd", " i ", 'f', "gemDiamond", 'd', "enderpearl", 'b', "ingotBrick", 'i', "obsidian"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_effect, 1, 0), " f ", "dbd", " i ", 'f', "dustGlowstone", 'd', Items.SPIDER_EYE, 'b', "ingotBrick", 'i', new ItemStack(Items.POTIONITEM, 1, OreDictionary.WILDCARD_VALUE)); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_effect, 1, 1), " f ", "dbl", " i ", 'f', "dustGlowstone", 'd', Items.MAGMA_CREAM, 'b', "ingotBrick", 'i', new ItemStack(Items.POTIONITEM, 1, OreDictionary.WILDCARD_VALUE), 'l', Items.LAVA_BUCKET); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_effect, 1, 2), " f ", "dbd", " i ", 'f', "dustGlowstone", 'd', Items.FERMENTED_SPIDER_EYE, 'b', "ingotBrick", 'i', new ItemStack(Items.POTIONITEM, 1, OreDictionary.WILDCARD_VALUE)); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_effect, 1, 3), " f ", "dbd", " i ", 'f', "dustGlowstone", 'd', new ItemStack(Items.SKULL, 1, 1), 'b', "ingotBrick", 'i', new ItemStack(Items.POTIONITEM, 1, OreDictionary.WILDCARD_VALUE)); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_effect, 1, 4), " f ", "dbd", " i ", 'f', "dustGlowstone", 'd', Items.SPECKLED_MELON, 'b', "ingotBrick", 'i', new ItemStack(Items.POTIONITEM, 1, OreDictionary.WILDCARD_VALUE)); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 0), " f ", "dbd", " f ", 'f', Items.FLINT, 'd', "blockQuartz", 'b', "ingotBrick"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 1), " f ", "dbd", " f ", 'f', Items.GLOWSTONE_DUST, 'd', "blockRedstone", 'b', "ingotBrick"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 2), " f ", "dbd", " f ", 'f', Items.GLOWSTONE_DUST, 'd', "blockLapis", 'b', "ingotBrick"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 3), " f ", "dbd", " e ", 'f', new ItemStack(Blocks.WOOL, 1, OreDictionary.WILDCARD_VALUE), 'd', "blockSlime", 'b', "ingotBrick", 'e', "gemEmerald"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 4), " f ", "dbd", " d ", 'f', Items.FLINT, 'd', new ItemStack(Items.SKULL, 1, OreDictionary.WILDCARD_VALUE), 'b', "ingotBrick"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 5), " f ", "dbd", " g ", 'f', "slimeball", 'd', new ItemStack(Blocks.WOOL, 1, OreDictionary.WILDCARD_VALUE), 'b', "ingotBrick", 'g', "gemDiamond"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 6), " f ", "dbd", " g ", 'f', "nuggetGold", 'd', Items.GOLDEN_CARROT, 'b', "ingotBrick", 'g', Items.GOLDEN_APPLE); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_support, 1, 7), " f ", "dbd", " f ", 'f', "ingotGold", 'd', "blockRedstone", 'b', "ingotBrick"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_skill, 1, 0), " g ", "gbg", " g ", 'b', "ingotBrick", 'g', "blockGlass"); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_skill, 1, 1), " a ", "gbg", " o ", 'b', "ingotBrick", 'g', Items.FLINT_AND_STEEL, 'a', Items.ARROW, 'o', Items.BOW); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_skill, 1, 2), " a ", "gbg", " o ", 'b', "ingotBrick", 'g', "gemQuartz", 'a', "enderpearl", 'o', Items.ENDER_EYE); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_skill, 1, 3), " a ", "gbg", " o ", 'b', "ingotBrick", 'g', "blockGlass", 'a', "chestWood", 'o', Blocks.LIGHT_WEIGHTED_PRESSURE_PLATE); RecipeHelper.addShapedRecipe(new ItemStack(ModItems.upgrade_skill, 1, 4), " a ", "gbg", " o ", 'b', "ingotBrick", 'g', "obsidian", 'a', "blockDiamond", 'o', "gemEmerald"); } private static class Repair extends ShapelessRecipeExt { public Repair(Item tool) { super(new ResourceLocation(FlexibleTools.MODID, tool.getRegistryName().getResourcePath()), new ItemStack(tool), new ItemStack(tool, 1, OreDictionary.WILDCARD_VALUE), ToolHelper.repairMap.keySet().stream().sorted((i1, i2) -> i1.getRegistryName().toString().compareTo(i2.getRegistryName().toString())).collect(Collectors.toList())); isSimple = false; } @Override public ItemStack getCraftingResult(InventoryCrafting var1) { ItemStack tool = ItemStack.EMPTY; Item repair = null; for (int i = 0; i < var1.getSizeInventory(); i++) { ItemStack slot = var1.getStackInSlot(i); if (slot.getItem() instanceof ITool) tool = slot.copy(); else if (!slot.isEmpty()) repair = slot.getItem(); } if (!tool.isEmpty() && tool.getMetadata() == 0) return ItemStack.EMPTY; if (!tool.isEmpty() && repair != null) ToolHelper.damageItem(-ToolHelper.repairMap.get(repair), null, tool, null); return tool; } } }
package org.quenlen.magic; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.provider.Settings; import android.support.annotation.NonNull; import android.util.Log; /** * Provider image process method */ public class MagicImage { private static final String LIBRARY_NAME = "MagicImage"; private static final String TAG = "MagicImage"; private static int STATE = 0; private final static int MASK_SUCCESS = 1; private final static int MASK_FAILURE = 2; static { try { System.loadLibrary(LIBRARY_NAME); STATE = MASK_SUCCESS; } catch (Exception ex) { Log.e(TAG, "Auto load library error"); STATE = MASK_FAILURE; } } /** * Manual load the library. * * In normal state. user will not need call this method, * * In the case, user develop an apk and need to pre install roms. * system can't check the so file which contains in apk, * now need push the so file to /system/lib or /system/lib64. * * Use this method, User can manual load the .so file, * no matter the .so file locate where, just need its * absolutely path. * * Use can call {@link isLibraryLoadSuccess()} to check is or * not load success. * * Notice: This class will try to load .so file if possiable. * if auto loal success, this method will do nothing. * * @param libraryPath the absolutely .so path. * */ public static void loadLibrary(String libraryPath) { if (isLibraryLoadSuccess()) { try { System.load(libraryPath); STATE = MASK_SUCCESS; } catch (Exception ex) { Log.e(TAG, "Manual load library error"); STATE = MASK_FAILURE; } } } /** * Check load the .so file is or not success. * * @return true if load success, otherwise false. */ public static boolean isLibraryLoadSuccess() { return (STATE & MASK_SUCCESS) == MASK_SUCCESS; } /** * Gaussian blur a bitmap. * * The default blur radius is 32. * */ public static void gaussianBlur(Bitmap bitmap) { gaussianBlur(bitmap, 32, false); } public static void gaussianBlur(Bitmap bitmap, boolean ignoreAlpha) { nGaussianBlur(bitmap, 32, ignoreAlpha); } public static void gaussianBlur(Bitmap bitmap, int radius) { nGaussianBlur(bitmap, radius, false); } public static void gaussianBlur(Bitmap bitmap, int radiua, boolean ignoreAlpha) { nGaussianBlur(bitmap, radiua, ignoreAlpha); } private static native void nGaussianBlur(Bitmap bitmap, int radius, boolean ignoreAlpha); /** * Compose bitmap. * @param background * @param foreground * @return */ public synchronized static Bitmap composeBitmap(@NonNull Bitmap background,@NonNull Bitmap foreground) { Rect backRect = new Rect(0, 0, background.getWidth(), background.getHeight()); Rect foreRect = new Rect(0, 0, foreground.getWidth(), foreground.getHeight()); return composeBitmap(backRect.width(), backRect.height(), background, backRect, foreground, foreRect); } private static Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); public static Bitmap composeBitmap(int dstWidth, int dstHeight, @NonNull Bitmap background, @NonNull Rect backRect, @NonNull Bitmap foreground, @NonNull Rect foreRect) { Bitmap result = background; if (background.getWidth() != dstWidth || background.getHeight() != dstHeight) { result = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888); } Rect resultRect = new Rect(0, 0, result.getWidth(), result.getHeight()); Canvas canvas = new Canvas(result); if (result != background) { canvas.drawBitmap(background, backRect, resultRect, mPaint); } canvas.drawBitmap(foreground, foreRect, resultRect, mPaint); return result; } private static native void nComposeBitmap(Bitmap result, Bitmap bitmap); }
package org.zstack.network.l2.vxlan.vxlanNetworkPool; import org.springframework.beans.factory.annotation.Autowired; import org.zstack.core.asyncbatch.While; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.Q; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.WhileDoneCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.ErrorCodeList; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.HostConstant; import org.zstack.header.host.HostVO; import org.zstack.header.host.HostVO_; import org.zstack.header.host.HypervisorType; import org.zstack.header.message.MessageReply; import org.zstack.header.network.l2.*; import org.zstack.header.network.l3.L3NetworkInventory; import org.zstack.header.vm.InstantiateResourceOnAttachingNicExtensionPoint; import org.zstack.header.vm.VmInstanceSpec; import org.zstack.header.vm.VmNicInventory; import org.zstack.kvm.*; import org.zstack.network.l2.vxlan.vtep.CreateVtepMsg; import org.zstack.network.l2.vxlan.vtep.VtepVO; import org.zstack.network.l2.vxlan.vtep.VtepVO_; import org.zstack.network.l2.vxlan.vxlanNetwork.L2VxlanNetworkInventory; import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkConstant; import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO; import org.zstack.network.l2.vxlan.vxlanNetwork.VxlanNetworkVO_; import org.zstack.network.service.MtuGetter; import org.zstack.tag.SystemTagCreator; import org.zstack.utils.Utils; import org.zstack.utils.logging.CLogger; import java.util.*; import java.util.stream.Collectors; import static org.zstack.core.Platform.operr; import static org.zstack.network.l2.vxlan.vxlanNetworkPool.VxlanNetworkPoolConstant.*; import static org.zstack.utils.CollectionDSL.e; import static org.zstack.utils.CollectionDSL.map; public class KVMRealizeL2VxlanNetworkBackend implements L2NetworkRealizationExtensionPoint, KVMCompleteNicInformationExtensionPoint, InstantiateResourceOnAttachingNicExtensionPoint { private static CLogger logger = Utils.getLogger(KVMRealizeL2VxlanNetworkBackend.class); @Autowired private DatabaseFacade dbf; @Autowired private CloudBus bus; private static String VTEP_IP = "vtepIp"; private static String NEED_POPULATE = "needPopulate"; public static String makeBridgeName(int vxlan) { return String.format("br_vx_%s",vxlan); } @Override public void realize(final L2NetworkInventory l2Network, final String hostUuid, final Completion completion) { realize(l2Network, hostUuid, false, completion); } @Override public void realize(final L2NetworkInventory l2Network, final String hostUuid, boolean noStatusCheck, final Completion completion) { final L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network; final List<String> vtepIps = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.hostUuid, hostUuid).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues(); if (vtepIps.size() > 1) { throw new OperationFailureException(operr("find multiple vtep ips[%s] for one host[uuid:%s], need to delete host and add again", vtepIps, hostUuid)); } if (vtepIps.size() == 0) { ErrorCode err = operr("failed to find vtep on host[uuid: %s], please re-attach vxlanpool[uuid: %s] to cluster.", hostUuid, l2vxlan.getPoolUuid()); completion.fail(err); return; } String vtepIp = vtepIps.get(0); List<String> peers = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues(); Set<String> p = new HashSet<String>(peers); p.remove(vtepIp); peers.clear(); peers.addAll(p); String info = String.format( "get vtep peers [%s] and vtep ip [%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", peers, vtepIp, l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid); logger.debug(info); List<Integer> dstports = Q.New(VtepVO.class).select(VtepVO_.port) .eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()) .eq(VtepVO_.hostUuid,hostUuid) .eq(VtepVO_.vtepIp,vtepIp) .listValues(); Integer dstport = dstports.get(0); final VxlanKvmAgentCommands.CreateVxlanBridgeCmd cmd = new VxlanKvmAgentCommands.CreateVxlanBridgeCmd(); cmd.setVtepIp(vtepIp); cmd.setBridgeName(makeBridgeName(l2vxlan.getVni())); cmd.setVni(l2vxlan.getVni()); cmd.setL2NetworkUuid(l2Network.getUuid()); cmd.setPeers(peers); cmd.setDstport(dstport); cmd.setMtu(new MtuGetter().getL2Mtu(l2Network)); KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg(); msg.setHostUuid(hostUuid); msg.setCommand(cmd); msg.setNoStatusCheck(noStatusCheck); msg.setPath(VXLAN_KVM_REALIZE_L2VXLAN_NETWORK_PATH); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { completion.fail(reply.getError()); return; } KVMHostAsyncHttpCallReply hreply = reply.castReply(); VxlanKvmAgentCommands.CreateVxlanBridgeResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.CreateVxlanBridgeResponse.class); if (!rsp.isSuccess()) { ErrorCode err = operr("failed to create bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s], because %s", cmd.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid, rsp.getError()); completion.fail(err); return; } String info = String.format( "successfully realize bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", cmd .getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid); logger.debug(info); SystemTagCreator creator = KVMSystemTags.L2_BRIDGE_NAME.newSystemTagCreator(l2Network.getUuid()); creator.inherent = true; creator.ignoreIfExisting = true; creator.setTagByTokens(map(e(KVMSystemTags.L2_BRIDGE_NAME_TOKEN, cmd.getBridgeName()))); creator.create(); completion.success(); } }); } @Override public void check(final L2NetworkInventory l2Network, final String hostUuid, final Completion completion) { check(l2Network, hostUuid, false, completion); } public void check(L2NetworkInventory l2Network, String hostUuid, boolean noStatusCheck, Completion completion) { final L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network; final String clusterUuid = Q.New(HostVO.class).select(HostVO_.clusterUuid).eq(HostVO_.uuid, hostUuid).findValue(); final VxlanNetworkPoolVO poolVO = Q.New(VxlanNetworkPoolVO.class).eq(VxlanNetworkPoolVO_.uuid, l2vxlan.getPoolUuid()).find(); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("check-l2-vxlan-%s-on-host-%s", l2Network.getUuid(), hostUuid)); chain.then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { VxlanKvmAgentCommands.CheckVxlanCidrCmd cmd = new VxlanKvmAgentCommands.CheckVxlanCidrCmd(); cmd.setCidr(getAttachedCidrs(l2vxlan.getPoolUuid()).get(clusterUuid)); if (!poolVO.getPhysicalInterface().isEmpty()) { cmd.setPhysicalInterfaceName(poolVO.getPhysicalInterface()); } VtepVO vtep = Q.New(VtepVO.class).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).eq(VtepVO_.hostUuid, hostUuid).find(); if (vtep != null) { cmd.setVtepip(vtep.getVtepIp()); } KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg(); msg.setHostUuid(hostUuid); msg.setCommand(cmd); msg.setPath(VXLAN_KVM_CHECK_L2VXLAN_NETWORK_PATH); msg.setNoStatusCheck(noStatusCheck); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } KVMHostAsyncHttpCallReply hreply = reply.castReply(); VxlanKvmAgentCommands.CheckVxlanCidrResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.CheckVxlanCidrResponse.class); if (!rsp.isSuccess()) { ErrorCode err = operr("failed to check cidr[%s] for l2VxlanNetwork[uuid:%s, name:%s] on kvm host[uuid:%s], %s", cmd.getCidr(), l2vxlan.getUuid(), l2vxlan.getName(), hostUuid, rsp.getError()); trigger.fail(err); return; } String info = String.format("successfully checked cidr[%s] for l2VxlanNetwork[uuid:%s, name:%s] on kvm host[uuid:%s]", cmd.getCidr(), l2vxlan.getUuid(), l2vxlan.getName(), hostUuid); logger.debug(info); data.put(VTEP_IP, rsp.getVtepIp()); trigger.next(); } }); } }).then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { List<VtepVO> vtepVOS = Q.New(VtepVO.class) .eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()) .eq(VtepVO_.hostUuid, hostUuid) .list(); if (vtepVOS == null || vtepVOS.isEmpty()) { /* vtep is not created, no action here */ } else if (vtepVOS.size() > 1) { /* more than 1 vtep, shoult not happen */ throw new CloudRuntimeException(String.format("multiple vteps[ips: %s] found on host[uuid: %s]", vtepVOS.stream().map(v -> v.getVtepIp()).collect(Collectors.toSet()), hostUuid)); } else if (vtepVOS.get(0).getVtepIp().equals(data.get(VTEP_IP))) { /* vtep is already created */ logger.debug(String.format( "vtep[ip:%s] from host[uuid:%s] for l2 vxlan network pool[uuid:%s] checks successfully", vtepVOS.get(0).getVtepIp(), hostUuid, l2Network.getUuid())); data.put(NEED_POPULATE, false); trigger.next(); return; } else { /* remove old vtep */ logger.debug(String.format( "remove deprecated vtep[ip:%s] from host[uuid:%s] for l2 vxlan network pool[uuid:%s]", vtepVOS.get(0).getVtepIp(), hostUuid, l2Network.getUuid())); dbf.remove(vtepVOS.get(0)); } data.put(NEED_POPULATE, true); CreateVtepMsg cmsg = new CreateVtepMsg(); cmsg.setPoolUuid(l2vxlan.getPoolUuid()); cmsg.setClusterUuid(clusterUuid); cmsg.setHostUuid(hostUuid); cmsg.setPort(VXLAN_PORT); cmsg.setVtepIp((String) data.get(VTEP_IP)); cmsg.setType(KVM_VXLAN_TYPE); bus.makeTargetServiceIdByResourceUuid(cmsg, L2NetworkConstant.SERVICE_ID, l2vxlan.getPoolUuid()); bus.send(cmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(reply.getError().toString()); trigger.fail(reply.getError()); return; } logger.debug(String.format("created new vtep [%s] on vxlan network pool [%s]", cmsg.getVtepIp(), ((L2VxlanNetworkInventory) l2Network).getPoolUuid())); trigger.next(); } }); } }).then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { if (data.get(NEED_POPULATE).equals(false)) { trigger.next(); return; } List<VtepVO> vteps = Q.New(VtepVO.class).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).list(); if (vteps.size() == 1) { logger.debug("no need to populate fdb since there are only one vtep"); trigger.next(); return; } new While<>(vteps).all((vtep, completion1) -> { List<String> peers = new ArrayList<>(); for (VtepVO vo : vteps) { if (peers.contains(vo.getVtepIp()) || vo.getVtepIp().equals(vtep.getVtepIp())) { continue; } else { peers.add(vo.getVtepIp()); } } logger.info(String.format("populate fdb for vtep %s in vxlan network %s", vtep.getVtepIp(), l2vxlan.getUuid())); VxlanKvmAgentCommands.PopulateVxlanFdbCmd cmd = new VxlanKvmAgentCommands.PopulateVxlanFdbCmd(); cmd.setPeers(peers); cmd.setVni(l2vxlan.getVni()); KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg(); msg.setHostUuid(vtep.getHostUuid()); msg.setCommand(cmd); msg.setPath(VXLAN_KVM_POPULATE_FDB_L2VXLAN_NETWORK_PATH); msg.setNoStatusCheck(noStatusCheck); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion1) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(reply.getError().toString()); } completion1.done(); } }); }).run(new WhileDoneCompletion(trigger) { @Override public void done(ErrorCodeList errorCodeList) { trigger.next(); } }); } }).done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Override public L2NetworkType getSupportedL2NetworkType() { return L2NetworkType.valueOf(VxlanNetworkConstant.VXLAN_NETWORK_TYPE); } @Override public HypervisorType getSupportedHypervisorType() { return HypervisorType.valueOf(KVMConstant.KVM_HYPERVISOR_TYPE); } @Override public L2NetworkType getL2NetworkTypeVmNicOn() { return getSupportedL2NetworkType(); } @Override public KVMAgentCommands.NicTO completeNicInformation(L2NetworkInventory l2Network, L3NetworkInventory l3Network, VmNicInventory nic) { final Integer vni = getVni(l2Network.getUuid()); KVMAgentCommands.NicTO to = new KVMAgentCommands.NicTO(); to.setMac(nic.getMac()); to.setUuid(nic.getUuid()); to.setBridgeName(makeBridgeName(vni)); to.setDeviceId(nic.getDeviceId()); to.setNicInternalName(nic.getInternalName()); to.setMetaData(String.valueOf(vni)); to.setMtu(new MtuGetter().getMtu(l3Network.getUuid())); return to; } @Override public String getBridgeName(L2NetworkInventory l2Network) { final Integer vni = getVni(l2Network.getUuid()); return makeBridgeName(vni); } public Map<String, String> getAttachedCidrs(String l2NetworkUuid) { List<Map<String, String>> tokenList = VxlanSystemTags.VXLAN_POOL_CLUSTER_VTEP_CIDR.getTokensOfTagsByResourceUuid(l2NetworkUuid); Map<String, String> attachedClusters = new HashMap<>(); for (Map<String, String> tokens : tokenList) { attachedClusters.put(tokens.get(VxlanSystemTags.CLUSTER_UUID_TOKEN), tokens.get(VxlanSystemTags.VTEP_CIDR_TOKEN).split("[{}]")[1]); } return attachedClusters; } private Integer getVni(String l2NetworkUuid) { return Q.New(VxlanNetworkVO.class) .eq(VxlanNetworkVO_.uuid, l2NetworkUuid) .select(VxlanNetworkVO_.vni) .findValue(); } @Override public void instantiateResourceOnAttachingNic(VmInstanceSpec spec, L3NetworkInventory l3, Completion completion) { L2NetworkVO vo = Q.New(L2NetworkVO.class).eq(L2NetworkVO_.uuid, l3.getL2NetworkUuid()).find(); if (!vo.getType().equals(VxlanNetworkConstant.VXLAN_NETWORK_TYPE)) { completion.success(); return; } else { FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); L2VxlanNetworkInventory l2 = L2VxlanNetworkInventory.valueOf((VxlanNetworkVO) Q.New(VxlanNetworkVO.class).eq(VxlanNetworkVO_.uuid, vo.getUuid()).find()); chain.setName(String.format("attach-l2-vxlan-%s-on-host-%s", l2.getUuid(), spec.getDestHost().getUuid())); chain.then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { check(l2, spec.getDestHost().getUuid(), new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { logger.debug(String.format("check l2 vxlan failed for %s", errorCode.toString())); trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(FlowTrigger trigger, Map data) { realize(l2, spec.getDestHost().getUuid(), new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { logger.debug(String.format("realize l2 vxlan failed for %s", errorCode.toString())); trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } } @Override public void releaseResourceOnAttachingNic(VmInstanceSpec spec, L3NetworkInventory l3, NoErrorCompletion completion) { completion.done(); } public void delete(L2NetworkInventory l2Network, String hostUuid, Completion completion) { L2VxlanNetworkInventory l2vxlan = (L2VxlanNetworkInventory) l2Network; final VxlanKvmAgentCommands.DeleteVxlanBridgeCmd cmd = new VxlanKvmAgentCommands.DeleteVxlanBridgeCmd(); cmd.setBridgeName(makeBridgeName(l2vxlan.getVni())); cmd.setVni(l2vxlan.getVni()); cmd.setL2NetworkUuid(l2Network.getUuid()); final List<String> vtepIps = Q.New(VtepVO.class).select(VtepVO_.vtepIp).eq(VtepVO_.hostUuid, hostUuid).eq(VtepVO_.poolUuid, l2vxlan.getPoolUuid()).listValues(); String vtepIp = vtepIps.get(0); cmd.setVtepIp(vtepIp); KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg(); msg.setHostUuid(hostUuid); msg.setCommand(cmd); msg.setPath(VXLAN_KVM_DELETE_L2VXLAN_NETWORK_PATH); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { completion.fail(reply.getError()); return; } KVMHostAsyncHttpCallReply hreply = reply.castReply(); VxlanKvmAgentCommands.DeleteVxlanBridgeResponse rsp = hreply.toResponse(VxlanKvmAgentCommands.DeleteVxlanBridgeResponse.class); if (!rsp.isSuccess()) { ErrorCode err = operr("failed to delete bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s], because %s", cmd.getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid, rsp.getError()); completion.fail(err); return; } String message = String.format( "successfully delete bridge[%s] for l2Network[uuid:%s, type:%s, vni:%s] on kvm host[uuid:%s]", cmd .getBridgeName(), l2Network.getUuid(), l2Network.getType(), l2vxlan.getVni(), hostUuid); logger.debug(message); completion.success(); } }); } }
package net.imagej.launcher; import java.awt.GraphicsEnvironment; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.util.Arrays; /** * This class is the central entry point into Java from the ImageJ launcher. * <p> * Except for ImageJ 1.x, for backwards-compatibility, the ImageJ launcher calls * all Java main classes through this class, to be able to generate appropriate * class paths using the platform-independent convenience provided by Java's * class library. * </p> * * @author Johannes Schindelin */ public class ClassLauncher { protected static boolean debug; static { try { debug = Boolean.getBoolean("ij.debug") || "debug".equalsIgnoreCase(System.getProperty("scijava.log.level")) || System.getenv("DEBUG_IJ_LAUNCHER") != null; } catch (Throwable t) { // ignore; Java 1.4 pretended that getenv() goes away } } protected static String[] originalArguments; /** * Patch ij.jar and launch the class given as first argument passing on the * remaining arguments * * @param arguments A list containing the name of the class whose main() * method is to be called with the remaining arguments. */ public static void main(final String[] arguments) { originalArguments = arguments; if (Boolean.getBoolean("imagej.splash") || System.getProperty("imagej.splash") == null) { try { SplashScreen.show(); } catch (Throwable t) { t.printStackTrace(); } } run(arguments); } public static void restart() { Thread.currentThread().setContextClassLoader( ClassLoader.class.getClassLoader()); run(originalArguments); } protected static void run(String[] arguments) { boolean retrotranslator = false, jdb = false, passClasspath = false; URLClassLoader classLoader = null; int i = 0; for (; i < arguments.length && arguments[i].charAt(0) == '-'; i++) { final String option = arguments[i]; if (option.equals("-cp") || option.equals("-classpath")) { classLoader = ClassLoaderPlus.get(classLoader, new File(arguments[++i])); } else if (option.equals("-ijcp") || option.equals("-ijclasspath")) { classLoader = ClassLoaderPlus.getInImageJDirectory(classLoader, arguments[++i]); } else if (option.equals("-jarpath")) { classLoader = ClassLoaderPlus.getRecursively(classLoader, true, new File(arguments[++i])); } else if (option.equals("-ijjarpath")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, arguments[++i]); if ("plugins".equals(arguments[i])) { final String ij1PluginDirs = System.getProperty("ij1.plugin.dirs"); if (debug) System.err.println("ij1.plugin.dirs: " + ij1PluginDirs); if (ij1PluginDirs != null) { for (final String path : ij1PluginDirs.split(File.pathSeparator)) { final File dir = new File(path); if (dir.exists()) { ClassLoaderPlus.getRecursively(classLoader, false, dir); } } } else { final File dir = new File(System.getProperty("user.home"), ".plugins"); if (debug) { System.err.println("$HOME/.plugins: " + dir + " " + (dir.exists() ? "exists" : "does not exist")); } if (dir.exists()) { ClassLoaderPlus.getRecursively(classLoader, false, dir); } } } } else if (option.equals("-jdb")) jdb = true; else if (option.equals("-retrotranslator")) { classLoader = ClassLoaderPlus.getRecursivelyInImageJDirectory(classLoader, true, "retro"); retrotranslator = true; } else if (option.equals("-pass-classpath")) passClasspath = true; else if (option.equals("-freeze-classloader")) ClassLoaderPlus.freeze(classLoader); else { System.err.println("Unknown option: " + option + "!"); System.exit(1); } } if (i >= arguments.length) { System.err.println("Missing argument: main class"); System.exit(1); } String mainClass = arguments[i]; arguments = slice(arguments, i + 1); if (!"false".equals(System.getProperty("patch.ij1")) && !mainClass.equals("net.imagej.Main") && !mainClass.equals("org.scijava.minimaven.MiniMaven")) { classLoader = ClassLoaderPlus.getInImageJDirectory(null, "jars/fiji-compat.jar"); try { patchIJ1(classLoader); } catch (final Exception e) { if (!"fiji.IJ1Patcher".equals(e.getMessage())) { e.printStackTrace(); } } } if (passClasspath && classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } if (jdb) { arguments = prepend(arguments, mainClass); if (classLoader != null) { arguments = prepend(arguments, "-classpath", ClassLoaderPlus.getClassPath(classLoader)); } mainClass = "com.sun.tools.example.debug.tty.TTY"; } if (retrotranslator) { arguments = prepend(arguments, "-advanced", mainClass); mainClass = "net.sf.retrotranslator.transformer.JITRetrotranslator"; } if (debug) System.err.println("Launching main class " + mainClass + " with parameters " + Arrays.toString(arguments)); try { launch(classLoader, mainClass, arguments); } catch (final Throwable t) { t.printStackTrace(); if ("net.imagej.Main".equals(mainClass) && !containsBatchOption(arguments) && !GraphicsEnvironment.isHeadless() && RemoteUpdater.runRemote(t)) { return; } System.exit(1); } } private static boolean containsBatchOption(String[] arguments) { for (final String argument : arguments) { if ("-batch".equals(argument) || "-batch-no-exit".equals(argument)) { return true; } } return false; } protected static void patchIJ1(final ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException { @SuppressWarnings("unchecked") final Class<Runnable> clazz = (Class<Runnable>) classLoader.loadClass("fiji.IJ1Patcher"); final Runnable ij1Patcher = clazz.newInstance(); ij1Patcher.run(); } protected static String[] slice(final String[] array, final int from) { return slice(array, from, array.length); } protected static String[] slice(final String[] array, final int from, final int to) { final String[] result = new String[to - from]; if (result.length > 0) System.arraycopy(array, from, result, 0, result.length); return result; } protected static String[] prepend(final String[] array, final String... before) { if (before.length == 0) return array; final String[] result = new String[before.length + array.length]; System.arraycopy(before, 0, result, 0, before.length); System.arraycopy(array, 0, result, before.length, array.length); return result; } protected static void launch(ClassLoader classLoader, final String className, final String[] arguments) { Class<?> main = null; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (debug) System.err.println("Class loader = " + classLoader); final String noSlashes = className.replace('/', '.'); try { main = classLoader.loadClass(noSlashes); } catch (final ClassNotFoundException e) { if (debug) e.printStackTrace(); if (noSlashes.startsWith("net.imagej.")) try { // fall back to old package name main = classLoader.loadClass(noSlashes.substring(4)); } catch (final ClassNotFoundException e2) { if (debug) e2.printStackTrace(); System.err.println("Class '" + noSlashes + "' was not found"); System.exit(1); } } final Class<?>[] argsType = new Class<?>[] { arguments.getClass() }; Method mainMethod = null; try { mainMethod = main.getMethod("main", argsType); } catch (final NoSuchMethodException e) { if (debug) e.printStackTrace(); System.err.println("Class '" + className + "' does not have a main() method."); System.exit(1); } Integer result = new Integer(1); try { result = (Integer) mainMethod.invoke(null, new Object[] { arguments }); } catch (final IllegalAccessException e) { if (debug) e.printStackTrace(); System.err.println("The main() method of class '" + className + "' is not public."); } catch (final InvocationTargetException e) { System.err.println("Error while executing the main() " + "method of class '" + className + "':"); e.getTargetException().printStackTrace(); } if (result != null) System.exit(result.intValue()); } }
package roart.config; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.HierarchicalConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.XMLConfiguration; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.io.FileLocator; import org.apache.commons.configuration2.io.FileLocator.FileLocatorBuilder; import org.apache.commons.configuration2.tree.ImmutableNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import roart.common.config.ConfigConstants; import roart.common.config.ConfigTreeMap; import roart.common.config.MyConfig; import roart.common.constants.Constants; public class MyXMLConfig { protected static Logger log = LoggerFactory.getLogger(MyConfig.class); protected static MyXMLConfig instance = null; public static MyXMLConfig instance() { if (instance == null) { instance = new MyXMLConfig(); } return instance; } protected static MyConfig configInstance = null; public static MyConfig getConfigInstance() { if (configInstance == null) { configInstance = new MyConfig(); if (instance == null) { instance(); } } return configInstance; } private static Configuration config = null; private static XMLConfiguration configxml = null; public MyXMLConfig() { try { Parameters params = new Parameters(); FileBasedConfigurationBuilder<XMLConfiguration> fileBuilder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class) .configure(params.fileBased().setFileName("../conf/" + ConfigConstants.CONFIGFILE)); InputStream stream = new FileInputStream(new File("../conf/" + ConfigConstants.CONFIGFILE)); configxml = fileBuilder.getConfiguration(); configxml.read(stream); } catch (Exception e) { log.error(Constants.EXCEPTION, e); configxml = null; } Document doc = null; configInstance.setConfigTreeMap(new ConfigTreeMap()); configInstance.setConfigValueMap(new HashMap<String, Object>()); ConfigConstantMaps.makeDefaultMap(); ConfigConstantMaps.makeTextMap(); ConfigConstantMaps.makeRangeMap(); ConfigConstantMaps.makeTypeMap(); configInstance.setDeflt(ConfigConstantMaps.deflt); configInstance.setType(ConfigConstantMaps.map); configInstance.setText(ConfigConstantMaps.text); configInstance.setRange(ConfigConstantMaps.range); if (configxml != null) { printout(); doc = configxml.getDocument(); if (doc != null) { handleDoc(doc.getDocumentElement(), configInstance.getConfigTreeMap(), ""); } Iterator<String> iter = configxml.getKeys(); while(iter.hasNext()) { String s = iter.next(); Object o = null; String text = s; Class myclass = ConfigConstantMaps.map.get(text); if (myclass == null) { log.info("Unknown {}", text); continue; } switch (myclass.getName()) { case "java.lang.String": o = configxml.getString(s); break; case "java.lang.Integer": o = configxml.getInt(s); break; case "java.lang.Double": o = configxml.getDouble(s); break; case "java.lang.Boolean": o = configxml.getBoolean(s); break; default: log.info("unknown {}", myclass.getName()); } configInstance.getConfigValueMap().put(s, o); } } Set<String> setKeys = configInstance.getConfigValueMap().keySet(); Set<String> dfltKeys = new HashSet<>(configInstance.getDeflt().keySet()); dfltKeys.removeAll(setKeys); System.out.println("keys to set " + dfltKeys); for (String key : dfltKeys) { ConfigTreeMap map = configInstance.getConfigTreeMap(); ConfigTreeMap.insert(map.getConfigTreeMap(), key, key, "", ConfigConstantMaps.deflt); Object object = ConfigConstantMaps.deflt.get(key); if (configInstance.getConfigValueMap().get(key) == null) { configInstance.getConfigValueMap().put(key, object); } } } private void printout() { String root = configxml.getRootElementName(); List<HierarchicalConfiguration<ImmutableNode>> fields = configxml.childConfigurationsAt(root); for (HierarchicalConfiguration<ImmutableNode> field : fields) { String fieldString = field.toString(); log.info("field {}", fieldString); } fields = configxml.childConfigurationsAt("machinelearning"); for (HierarchicalConfiguration<ImmutableNode> field : fields) { String fieldString = field.toString(); log.info("field {}", fieldString); Iterator<String> iter = field.getKeys(); while(iter.hasNext()) { String s = iter.next(); log.info("s1 {}", s); } } fields = (configxml).childConfigurationsAt("/misc"); for (HierarchicalConfiguration<ImmutableNode> field : fields) { String fieldString = field.toString(); log.info("field {}", fieldString); } fields = ( configxml).childConfigurationsAt("misc"); for (HierarchicalConfiguration<ImmutableNode> field : fields) { String fieldString = field.toString(); log.info("field {}", fieldString); Iterator<String> iter = field.getKeys(); while(iter.hasNext()) { String s = iter.next(); log.info("s2 {}", s); } } } private void print(ConfigTreeMap map2, int indent) { String space = " "; log.info("map2 {} {} {}", space.substring(0, indent), map2.getName(), map2.getEnabled()); Map<String, ConfigTreeMap> map3 = map2.getConfigTreeMap(); for (Entry<String, ConfigTreeMap> entry : map3.entrySet()) { print(entry.getValue(), indent + 1); } } private void handleDoc(Element documentElement, ConfigTreeMap configMap, String baseString) { String name = documentElement.getNodeName(); String basename = name; String attribute = documentElement.getAttribute("enable"); NodeList elements = documentElement.getChildNodes(); boolean leafNode = elements.getLength() == 0; Boolean enabled = null; if (attribute != null) { enabled = !attribute.equals("false"); if (/*leafNode &&*/ !attribute.isEmpty()) { name = name + "[@enable]"; } } configMap.setName(baseString + "." + name); configMap.setName(configMap.getName().replaceFirst(".config.", "")); configMap.setEnabled(enabled); configMap.setConfigTreeMap(new HashMap<String, ConfigTreeMap>()); for (int i = 0; i < elements.getLength(); i++) { Node node = elements.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { ConfigTreeMap newMap = new ConfigTreeMap(); Element element = (Element) node; String newBaseString = baseString + "." + basename; newBaseString = newBaseString.replaceFirst(".config.", ""); handleDoc(element, newMap, newBaseString); String text = element.getNodeName(); configMap.getConfigTreeMap().put(text, newMap); } } } }
package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.WKTReader; import java.io.StringReader; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; 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 javax.persistence.EntityManager; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.geojson.GeoJSON; import nl.b3p.kar.hibernate.*; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.type.Type; import org.hibernatespatial.GeometryUserType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de edit functionaliteit regelt. * * @author Meine Toonen meinetoonen@b3partners.nl */ @StrictBinding @UrlBinding("/action/editor") public class EditorActionBean implements ActionBean { private static final Log log = LogFactory.getLog(EditorActionBean.class); private static final String JSP = "/WEB-INF/jsp/viewer/editor.jsp"; private static final int RIJKSDRIEHOEKSTELSEL = 28992; private ActionBeanContext context; private boolean magWalapparaatMaken; @Validate private RoadsideEquipment rseq; @Validate private String json; private JSONArray vehicleTypesJSON; private JSONArray dataOwnersJSON; @Validate private String extent; public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker)getContext().getRequest().getAttribute(attribute); if(g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * Stripes methode waarmee de view van het edit proces wordt voorbereid. * * @return Stripes Resolution view * @throws Exception */ @DefaultHandler public Resolution view() throws Exception { EntityManager em = Stripersist.getEntityManager(); boolean isBeheerder = getGebruiker().isBeheerder(); Set s = getGebruiker().getEditableDataOwners(); if (s.size() >= 1 || isBeheerder) { magWalapparaatMaken = true; } else { magWalapparaatMaken = false; } vehicleTypesJSON = new JSONArray(); for (VehicleType vt : (List<VehicleType>) em.createQuery("from VehicleType order by nummer").getResultList()) { JSONObject jvt = new JSONObject(); jvt.put("nummer", vt.getNummer()); jvt.put("groep", vt.getGroep()); jvt.put("omschrijving", vt.getOmschrijving()); vehicleTypesJSON.put(jvt); } dataOwnersJSON = new JSONArray(); Collection<DataOwner> dataOwners; if(isBeheerder) { dataOwners = (List<DataOwner>) em.createQuery("from DataOwner order by code").getResultList(); } else { dataOwners = s; } for (DataOwner dao : dataOwners) { JSONObject jdao = new JSONObject(); jdao.put("code", dao.getCode()); jdao.put("classificatie", dao.getClassificatie()); jdao.put("companyNumber", dao.getCompanyNumber()); jdao.put("omschrijving", dao.getOmschrijving()); dataOwnersJSON.put(jdao); } return new ForwardResolution(JSP); } /** * Stripes methode waarmee de huidge roadside equipement wordt opgehaald. * * @return Stripes Resolution rseqJSON * @throws Exception */ public Resolution rseqJSON() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { RoadsideEquipment rseq2; if (rseq != null) { rseq2 = rseq; } else { throw new IllegalArgumentException("RoadSideEquipment not defined."); } if(!getGebruiker().isBeheerder() && !getGebruiker().canEditDataOwner(rseq2.getDataOwner())) { info.put("error", "Forbidden"); } else { info.put("roadsideEquipment", rseq2.getJSON()); info.put("success", Boolean.TRUE); } } catch (Exception e) { log.error("rseqJSON exception", e); info.put("error", ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } /** * Stripes methode waarmee alle roadside equipement wordt opgehaald. * * @return Stripes Resolution allRseqJSON * @throws Exception */ public Resolution allRseqJSON() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { List<RoadsideEquipment> rseq2; if(getGebruiker().isBeheerder()) { if (rseq != null) { rseq2 = (List<RoadsideEquipment>) em.createQuery("from RoadsideEquipment where id <> :id").setParameter("id", rseq.getId()).getResultList(); } else { rseq2 = (List<RoadsideEquipment>) em.createQuery("from RoadsideEquipment").getResultList(); } } else { Set<DataOwner> dos = getGebruiker().getEditableDataOwners(); if(dos.isEmpty()) { rseq2 = Collections.EMPTY_LIST; } else { if (rseq != null) { rseq2 = (List<RoadsideEquipment>) em.createQuery( "from RoadsideEquipment " + "where id <> :id " + "and dataOwner in (:dos)") .setParameter("id", rseq.getId()) .setParameter("dos", dos) .getResultList(); } else { rseq2 = (List<RoadsideEquipment>) em.createQuery( "from RoadsideEquipment " + "where dataOwner in (:dos)") .setParameter("dos", dos) .getResultList(); } } } JSONArray rseqs = new JSONArray(); for (RoadsideEquipment r : rseq2) { rseqs.put(r.getRseqGeoJSON()); } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("allRseqJSON exception", e); info.put("error", ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } public Resolution roads() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Point p = rseq.getLocation(); Polygon buffer = (Polygon) p.buffer(300, 1); buffer.setSRID(RIJKSDRIEHOEKSTELSEL); Session session = (Session) em.getDelegate(); Query q = session.createQuery("from Road where intersects(geometry, ?) = true"); q.setMaxResults(100); Type geometryType = GeometryUserType.TYPE; q.setParameter(0, buffer, geometryType); List<Road> roads = (List<Road>)q.list(); JSONArray rs = new JSONArray(); for (Road r : roads) { rs.put(r.getGeoJSON()); } info.put("roads", rs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("roads exception", e); info.put("error", ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } public Resolution surroundingPoints() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { GeometryFactory gf = new GeometryFactory(new PrecisionModel(), RIJKSDRIEHOEKSTELSEL); WKTReader reader= new WKTReader(gf); Polygon p = (Polygon)reader.read(extent); // p.setSRID(RIJKSDRIEHOEKSTELSEL); Session session = (Session) em.getDelegate(); Collection<DataOwner> editableDataOwners = getGebruiker().getEditableDataOwners(); List<ActivationPoint> points; if(getGebruiker().isBeheerder()) { points = session.createQuery( "from ActivationPoint " + "where intersects(location, :pos) = true " + "and roadsideEquipment <> :this") .setParameter("pos", p, GeometryUserType.TYPE) .setParameter("this", rseq) .list(); } else if(editableDataOwners.isEmpty()) { points = Collections.EMPTY_LIST; } else { points = session.createQuery( "from ActivationPoint " + "where roadsideEquipment.dataOwner in (:dos) " + "and intersects(location, :pos) = true and roadsideEquipment <> :this") .setParameterList("dos", getGebruiker().getEditableDataOwners()) .setParameter("pos", p, GeometryUserType.TYPE) .setParameter("this", rseq) .list(); } JSONArray rs = new JSONArray(); for (ActivationPoint r : points) { rs.put(r.getGeoJSON()); } info.put("points", rs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("surroundingPoints exception", e); info.put("error", ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } /** * Bepaalt of een JSON object nieuw gemaakt client-side. De door JavaScript * client-side gestuurde JSON om een RoadsideEquipment op te slaan kan nieuw * gemaakte objecten bevatten die nog geen persistente JPA entities zijn, * deze hebben een door ExtJS bepaald id dat begint met "ext-gen". * * @param j het JSON object * @return of het JSON object client-side nieuw gemaakt is */ private static boolean isNew(JSONObject j) { String id = j.optString("id"); return id != null && id.startsWith("ext-gen"); } /** * Ajax handler om een RSEQ te verwijderen. * */ public Resolution removeRseq () throws JSONException{ EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try{ em.remove(rseq); em.getTransaction().commit(); info.put("success", Boolean.TRUE); }catch(Exception e){ log.error("Removing of rseq failed.",e); info.put("error",ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } /** * Ajax handler om een RoadsideEquipment die in de json parameter is * meegegeven op te slaan. */ public Resolution saveOrUpdateRseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { JSONObject jrseq = new JSONObject(json); Gebruiker g = getGebruiker(); if (isNew(jrseq)) { rseq = new RoadsideEquipment(); } else { rseq = em.find(RoadsideEquipment.class, jrseq.getLong("id")); if(rseq == null) { throw new IllegalStateException("Kan verkeerssysteem niet vinden, verwijderd door andere gebruiker?"); } } rseq.setLocation(GeoJSON.toPoint(jrseq.getJSONObject("location"))); rseq.setDescription(jrseq.optString("description")); rseq.setTown(jrseq.optString("town")); rseq.setType(jrseq.getString("type")); rseq.setKarAddress(jrseq.getInt("karAddress")); rseq.setCrossingCode(jrseq.optString("crossingCode")); rseq.setDataOwner(em.find(DataOwner.class, jrseq.getString("dataOwner"))); if(rseq.getDataOwner() == null) { throw new IllegalArgumentException("Data owner is verplicht"); } if(!g.isBeheerder()) { if(!g.canEditDataOwner(rseq.getDataOwner())) { throw new IllegalStateException( String.format("Gebruiker \"%s\" heeft geen rechten op data owner code %s (\"%s\")", g.getUsername(), rseq.getDataOwner().getCode(), rseq.getDescription())); } } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); rseq.setValidFrom(jrseq.has("validFrom") ? sdf.parse(jrseq.getString("validFrom")) : null); rseq.setValidUntil(jrseq.has("validUntil") ? sdf.parse(jrseq.getString("validUntil")) : null); rseq.setMemo(jrseq.has("memo") ? jrseq.getString("memo") : null); rseq.getKarAttributes().clear(); JSONObject attributes = jrseq.getJSONObject("attributes"); for(Iterator it = attributes.keys(); it.hasNext();) { String serviceType = (String)it.next(); JSONArray perCommandType = attributes.getJSONArray(serviceType); KarAttributes ka = new KarAttributes( serviceType, ActivationPointSignal.COMMAND_INMELDPUNT, perCommandType.getJSONArray(0)); if(ka.getUsedAttributesMask() != 0) { rseq.getKarAttributes().add(ka); } ka = new KarAttributes( serviceType, ActivationPointSignal.COMMAND_UITMELDPUNT, perCommandType.getJSONArray(1)); if(ka.getUsedAttributesMask() != 0) { rseq.getKarAttributes().add(ka); } ka = new KarAttributes( serviceType, ActivationPointSignal.COMMAND_VOORINMELDPUNT, perCommandType.getJSONArray(2)); if(ka.getUsedAttributesMask() != 0) { rseq.getKarAttributes().add(ka); } } if (rseq.getId() == null) { em.persist(rseq); } JSONArray jpts = jrseq.getJSONArray("points"); Integer highestPointNumber = 0; Map<String, ActivationPoint> pointsByJSONId = new HashMap(); for (int i = 0; i < jpts.length(); i++) { JSONObject jpt = jpts.getJSONObject(i); ActivationPoint p = null; if (isNew(jpt)) { p = new ActivationPoint(); p.setRoadsideEquipment(rseq); } else { for (ActivationPoint ap2 : rseq.getPoints()) { if (ap2.getId().equals(jpt.getLong("id"))) { p = ap2; break; } } } pointsByJSONId.put(jpt.getString("id"), p); p.setNummer(jpt.has("nummer") ? jpt.getInt("nummer") : null); p.setLabel(jpt.optString("label")); p.setLocation(GeoJSON.toPoint(jpt.getJSONObject("geometry"))); if (p.getNummer() != null) { highestPointNumber = Math.max(p.getNummer(), highestPointNumber); } } for (ActivationPoint ap : pointsByJSONId.values()) { if (ap.getNummer() == null) { ap.setNummer(++highestPointNumber); } if (ap.getId() == null) { rseq.getPoints().add(ap); em.persist(ap); } } // XXX delete niet goed rseq.getPoints().retainAll(pointsByJSONId.values()); Set<Long> mIds = new HashSet(); for (Movement m : rseq.getMovements()) { m.getPoints().clear(); mIds.add(m.getId()); } em.flush(); if (!mIds.isEmpty()) { em.createNativeQuery("delete from movement_activation_point where movement in (:m)") .setParameter("m", mIds) .executeUpdate(); } rseq.getMovements().clear(); em.flush(); JSONArray jmvmts = jrseq.getJSONArray("movements"); for (int i = 0; i < jmvmts.length(); i++) { JSONObject jmvmt = jmvmts.getJSONObject(i); Movement m = new Movement(); m.setRoadsideEquipment(rseq); m.setNummer(jmvmt.has("nummer") ? jmvmt.getInt("nummer") : null); JSONArray jmaps = jmvmt.getJSONArray("maps"); for (int j = 0; j < jmaps.length(); j++) { JSONObject jmap = jmaps.getJSONObject(j); MovementActivationPoint map = new MovementActivationPoint(); map.setMovement(m); map.setBeginEndOrActivation(jmap.getString("beginEndOrActivation")); map.setPoint(pointsByJSONId.get(jmap.getString("pointId"))); if (MovementActivationPoint.ACTIVATION.equals(map.getBeginEndOrActivation())) { ActivationPointSignal signal = new ActivationPointSignal(); map.setSignal(signal); String s = jmap.optString("distanceTillStopLine", ""); signal.setDistanceTillStopLine(!"".equals(s) ? new Integer(s) : null); signal.setKarCommandType(jmap.getInt("commandType")); s = jmap.optString("signalGroupNumber"); signal.setSignalGroupNumber(!"".equals(s) ? new Integer(s) : null); s = jmap.optString("virtualLocalLoopNumber"); signal.setVirtualLocalLoopNumber(!"".equals(s) ? new Integer(s) : null); signal.setTriggerType(jmap.getString("triggerType")); JSONArray vtids = jmap.optJSONArray("vehicleTypes"); if (vtids != null) { for (int k = 0; k < vtids.length(); k++) { signal.getVehicleTypes().add(em.find(VehicleType.class, vtids.getInt(k))); } } JSONArray dir = jmap.optJSONArray("direction"); if(dir != null){ String direction = dir.join(","); signal.setDirection(direction); } } m.getPoints().add(map); } if (!m.getPoints().isEmpty()) { m.setNummer(rseq.getMovements().size() + 1); em.persist(m); rseq.getMovements().add(m); } } em.persist(rseq); em.getTransaction().commit(); info.put("roadsideEquipment", rseq.getJSON()); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("saveOrUpdateRseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } return new StreamingResolution("application/json", new StringReader(info.toString(4))); } // <editor-fold desc="Getters and Setters"> public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return magWalapparaatMaken */ public boolean isMagWalapparaatMaken() { return magWalapparaatMaken; } /** * * @param magWalapparaatMaken */ public void setMagWalapparaatMaken(boolean magWalapparaatMaken) { this.magWalapparaatMaken = magWalapparaatMaken; } /** * * @return rseq */ public RoadsideEquipment getRseq() { return rseq; } /** * * @param rseq */ public void setRseq(RoadsideEquipment rseq) { this.rseq = rseq; } /** * * @return dataOwnersJSON */ public JSONArray getDataOwnersJSON() { return dataOwnersJSON; } /** * * @param dataOwnersJSON */ public void setDataOwnersJSON(JSONArray dataOwnersJSON) { this.dataOwnersJSON = dataOwnersJSON; } /** * * @return vehicleTypesJSON */ public JSONArray getVehicleTypesJSON() { return vehicleTypesJSON; } /** * * @param vehicleTypesJSON */ public void setVehicleTypesJSON(JSONArray vehicleTypesJSON) { this.vehicleTypesJSON = vehicleTypesJSON; } /** * * @return json */ public String getJson() { return json; } /** * * @param json */ public void setJson(String json) { this.json = json; } public String getExtent() { return extent; } public void setExtent(String extent) { this.extent = extent; } // </editor-fold> }
package com.redhat.ceylon.eclipse.code.editor; import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getTokenIndexAtCharacter; import static java.lang.Math.min; import java.util.List; import org.antlr.runtime.CommonToken; import org.antlr.runtime.Token; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextSelection; import org.eclipse.ltk.core.refactoring.DocumentChange; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.text.edits.InsertEdit; import org.eclipse.text.edits.MultiTextEdit; import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer; import com.redhat.ceylon.compiler.typechecker.tree.NaturalVisitor; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CompilationUnit; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; final class TerminateStatementAction extends Action { private final CeylonEditor editor; int line; private abstract class Processor extends Visitor implements NaturalVisitor {} TerminateStatementAction(CeylonEditor editor) { super(null); this.editor = editor; } // int count(String s, char c) { // int count=0; // for (int i=0; i<s.length(); i++) { // if (s.charAt(i)==c) count++; // return count; @Override public void run() { ITextSelection ts = (ITextSelection) editor.getSelectionProvider().getSelection(); String before = editor.getSelectionText(); line = ts.getEndLine(); try { terminateWithSemicolon(); boolean changed; int count=0; do { changed = terminateWithBrace(); count++; } while (changed&&count<5); // IRegion li = editor.getCeylonSourceViewer().getDocument().getLineInformation(line); // editor.getCeylonSourceViewer().getTextWidget().setSelection(li.getOffset()+li.getLength()); if (!editor.getSelectionText().equals(before)) { //if the caret was at the end of the line, //and a semi was added, it winds up selected //so move the caret after the semi IRegion selection = editor.getSelection(); editor.getCeylonSourceViewer().setSelectedRange(selection.getOffset()+1,0); } // change = new DocumentChange("Terminate Statement", doc); // change.setEdit(new MultiTextEdit()); // editor.getParseController().parse(doc, new NullProgressMonitor(), null); // terminateWithParen(doc, change); // change.perform(new NullProgressMonitor()); editor.scheduleParsing(); } catch (Exception e) { e.printStackTrace(); } } private int getCodeEnd(IRegion li, String lineText, List<CommonToken> tokens) { int j=lineText.length()-1; for (; j>=0; j int offset = li.getOffset()+j; if (!skipToken(tokens, offset)) break; } int endOfCodeInLine = li.getOffset()+j; return endOfCodeInLine; } private int getCodeStart(IRegion li, String lineText, List<CommonToken> tokens) { int k=0; for (; k<lineText.length(); k++) { int offset = li.getOffset()+k; if (!skipToken(tokens, offset)) break; } int startOfCodeInLine = li.getOffset()+k; return startOfCodeInLine; } // private void terminateWithParen(final IDocument doc, final TextChange change) // throws Exception { // CompilationUnit rootNode = parse(); // IRegion li = getLineInfo(doc); // String lineText = doc.get(li.getOffset(), li.getLength()); // final List<CommonToken> tokens = editor.getParseController().getTokens(); // final int startOfCodeInLine = getCodeStart(li, lineText, tokens); // final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); // new Visitor() { // @Override // public void visit(Tree.Expression that) { // super.visit(that); // if (that.getStopIndex()<=endOfCodeInLine && // that.getStartIndex()>=startOfCodeInLine) { // if (that.getToken().getType()==CeylonLexer.LPAREN && // that.getEndToken().getType()!=CeylonLexer.RPAREN) { // change.addEdit(new InsertEdit(that.getStopIndex()+1, // /*try { // String text = doc.get(that.getStartIndex(), // that.getStopIndex()-that.getStartIndex()+1); // StringBuilder terminators = new StringBuilder(); // for (int i=0; i<count(text, '(')-count(text,')'); i++) { // terminators.append(')'); // } // if (terminators.length()!=0) { // change.addEdit(new InsertEdit(that.getStopIndex()+1, // terminators.toString())); // } // } // catch (Exception e) { // e.printStackTrace(); // }*/ // }.visit(rootNode); private boolean terminateWithBrace() throws Exception { IDocument doc = editor.getCeylonSourceViewer().getDocument(); final TextChange change = new DocumentChange("Terminate Statement", doc); change.setEdit(new MultiTextEdit()); CeylonParseController parser = parse(); CompilationUnit rootNode = parser.getRootNode(); IRegion li = getLineInfo(doc); final String lineText = doc.get(li.getOffset(), li.getLength()); final List<CommonToken> tokens = parser.getTokens(); final int startOfCodeInLine = getCodeStart(li, lineText, tokens); final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); new Processor() { @Override public void visit(Tree.Expression that) { super.visit(that); if (that.getStopIndex()<=endOfCodeInLine && that.getStartIndex()>=startOfCodeInLine) { Token et = that.getMainEndToken(); Token st = that.getMainToken(); if (st!=null && st.getType()==CeylonLexer.LPAREN && (et==null || et.getType()!=CeylonLexer.RPAREN)) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getStopIndex()+1, ")")); } } } } @Override public void visit(Tree.ParameterList that) { super.visit(that); terminate(that, CeylonLexer.RPAREN, ")"); } public void visit(Tree.IndexExpression that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.TypeParameterList that) { super.visit(that); terminate(that, CeylonLexer.LARGER_OP, ">"); } @Override public void visit(Tree.TypeArgumentList that) { super.visit(that); terminate(that, CeylonLexer.LARGER_OP, ">"); } @Override public void visit(Tree.PositionalArgumentList that) { super.visit(that); Token t = that.getToken(); if (t!=null && t.getType()==CeylonLexer.LPAREN) { //for infix function syntax terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.NamedArgumentList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.SequenceEnumeration that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.IterableType that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, "}"); } @Override public void visit(Tree.Tuple that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.TupleType that) { super.visit(that); terminate(that, CeylonLexer.RBRACKET, "]"); } @Override public void visit(Tree.ConditionList that) { super.visit(that); if (!that.getMainToken().getText().startsWith("<missing ")) { terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.ForIterator that) { super.visit(that); if (!that.getMainToken().getText().startsWith("<missing ")) { terminate(that, CeylonLexer.RPAREN, ")"); } } @Override public void visit(Tree.ImportMemberOrTypeList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.Import that) { if (that.getImportMemberOrTypeList()==null|| that.getImportMemberOrTypeList() .getMainToken().getText().startsWith("<missing ")) { if (!change.getEdit().hasChildren()) { if (that.getImportPath()!=null && that.getImportPath().getStopIndex()<=endOfCodeInLine) { change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1, " { ... }")); } } } super.visit(that); } @Override public void visit(Tree.ImportModule that) { super.visit(that); if (that.getImportPath()!=null) { terminate(that, CeylonLexer.SEMICOLON, ";"); } if (that.getVersion()==null) { if (!change.getEdit().hasChildren()) { if (that.getImportPath()!=null && that.getImportPath().getStopIndex()<=endOfCodeInLine) { change.addEdit(new InsertEdit(that.getImportPath().getStopIndex()+1, " \"1.0.0\"")); } } } } @Override public void visit(Tree.ImportModuleList that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.PackageDescriptor that) { super.visit(that); terminate(that, CeylonLexer.SEMICOLON, ";"); } @Override public void visit(Tree.Body that) { super.visit(that); terminate(that, CeylonLexer.RBRACE, " }"); } @Override public void visit(Tree.MetaLiteral that) { super.visit(that); terminate(that, CeylonLexer.BACKTICK, "`"); } @Override public void visit(Tree.StatementOrArgument that) { super.visit(that); if (/*that instanceof Tree.ExecutableStatement && !(that instanceof Tree.ControlStatement) || that instanceof Tree.AttributeDeclaration || that instanceof Tree.MethodDeclaration || that instanceof Tree.ClassDeclaration || that instanceof Tree.InterfaceDeclaration ||*/ that instanceof Tree.SpecifiedArgument) { terminate(that, CeylonLexer.SEMICOLON, ";"); } } private boolean inLine(Node that) { return that.getStartIndex()>=startOfCodeInLine && that.getStartIndex()<=endOfCodeInLine; } private void initiate(Node that, int tokenType, String ch) { if (inLine(that)) { Token mt = that.getMainToken(); if (mt==null || mt.getType()!=tokenType || mt.getText().startsWith("<missing ")) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getStartIndex(), ch)); } } } } private void terminate(Node that, int tokenType, String ch) { if (inLine(that)) { Token et = that.getMainEndToken(); if ((et==null || et.getType()!=tokenType) || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(min(endOfCodeInLine,that.getStopIndex())+1, ch)); } } } } @Override public void visit(Tree.AnyClass that) { super.visit(that); if (that.getParameterList()==null) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()")); } } } @Override public void visit(Tree.AnyMethod that) { super.visit(that); if (that.getParameterLists().isEmpty()) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(that.getIdentifier().getStopIndex()+1, "()")); } } } }.visit(rootNode); if (change.getEdit().hasChildren()) { change.perform(new NullProgressMonitor()); return true; } return false; } private boolean terminateWithSemicolon() throws Exception { final IDocument doc = editor.getCeylonSourceViewer().getDocument(); final TextChange change = new DocumentChange("Terminate Statement", doc); change.setEdit(new MultiTextEdit()); CeylonParseController parser = parse(); CompilationUnit rootNode = parser.getRootNode(); IRegion li = getLineInfo(doc); String lineText = doc.get(li.getOffset(), li.getLength()); final List<CommonToken> tokens = parser.getTokens(); //final int startOfCodeInLine = getCodeStart(li, lineText, tokens); final int endOfCodeInLine = getCodeEnd(li, lineText, tokens); if (!doc.get(endOfCodeInLine,1).equals(";")) { new Processor() { @Override public void visit(Tree.Annotation that) { super.visit(that); terminateWithSemicolon(that); } @Override public void visit(Tree.IfClause that) { super.visit(that); if (that.getBlock()==null && that.getConditionList()!=null) { terminateWithBaces(that); } } @Override public void visit(Tree.ElseClause that) { super.visit(that); if (that.getBlock()==null) { terminateWithBaces(that); } } @Override public void visit(Tree.ForClause that) { super.visit(that); if (that.getBlock()==null && that.getForIterator()!=null) { terminateWithBaces(that); } } @Override public void visit(Tree.WhileClause that) { super.visit(that); if (that.getBlock()==null && that.getConditionList()!=null) { terminateWithBaces(that); } } @Override public void visit(Tree.CaseClause that) { super.visit(that); if (that.getBlock()==null && that.getCaseItem()!=null) { terminateWithBaces(that); } } @Override public void visit(Tree.TryClause that) { super.visit(that); if (that.getBlock()==null) { terminateWithBaces(that); } } @Override public void visit(Tree.CatchClause that) { super.visit(that); if (that.getBlock()==null && that.getCatchVariable()!=null) { terminateWithBaces(that); } } @Override public void visit(Tree.FinallyClause that) { super.visit(that); if (that.getBlock()==null) { terminateWithBaces(that); } } @Override public void visit(Tree.StatementOrArgument that) { super.visit(that); if (that instanceof Tree.ExecutableStatement && !(that instanceof Tree.ControlStatement) || that instanceof Tree.AttributeDeclaration || that instanceof Tree.ImportModule || that instanceof Tree.TypeAliasDeclaration || that instanceof Tree.SpecifiedArgument) { terminateWithSemicolon(that); } if (that instanceof Tree.ClassDeclaration && ((Tree.ClassDeclaration) that).getClassSpecifier()==null|| that instanceof Tree.MethodDeclaration && ((Tree.MethodDeclaration) that).getSpecifierExpression()==null || that instanceof Tree.InterfaceDeclaration && ((Tree.InterfaceDeclaration) that).getTypeSpecifier()==null) { terminateWithBaces(that); } if (that instanceof Tree.ClassDeclaration && ((Tree.ClassDeclaration) that).getClassSpecifier()!=null|| that instanceof Tree.MethodDeclaration && ((Tree.MethodDeclaration) that).getSpecifierExpression()!=null || that instanceof Tree.InterfaceDeclaration && ((Tree.InterfaceDeclaration) that).getTypeSpecifier()!=null) { terminateWithSemicolon(that); } } private void terminateWithBaces(Node that) { try { if (that.getStartIndex()<=endOfCodeInLine && that.getStopIndex()>=endOfCodeInLine) { Token et = that.getEndToken(); if (et==null || et.getType()!=CeylonLexer.SEMICOLON && et.getType()!=CeylonLexer.RBRACE || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, " {}")); } } } } catch (Exception e) { e.printStackTrace(); } } private void terminateWithSemicolon(Node that) { try { if (that.getStartIndex()<=endOfCodeInLine && that.getStopIndex()>=endOfCodeInLine) { Token et = that.getEndToken(); if (et==null || et.getType()!=CeylonLexer.SEMICOLON || that.getStopIndex()>endOfCodeInLine) { if (!change.getEdit().hasChildren()) { change.addEdit(new InsertEdit(endOfCodeInLine+1, ";")); } } } } catch (Exception e) { e.printStackTrace(); } } }.visit(rootNode); if (change.getEdit().hasChildren()) { change.perform(new NullProgressMonitor()); return true; } } return false; } private IRegion getLineInfo(final IDocument doc) throws BadLocationException { return doc.getLineInformation(line); } private boolean skipToken(List<CommonToken> tokens, int offset) { int ti = getTokenIndexAtCharacter(tokens, offset); if (ti<0) ti=-ti; int type = tokens.get(ti).getType(); return type==CeylonLexer.WS || type==CeylonLexer.MULTI_COMMENT || type==CeylonLexer.LINE_COMMENT; } private CeylonParseController parse() { CeylonParseController cpc = new CeylonParseController(); cpc.initialize(editor.getParseController().getPath(), editor.getParseController().getProject(), null); cpc.parse(editor.getCeylonSourceViewer().getDocument(), new NullProgressMonitor(), null); return cpc; } }
package net.imagej.ops.math; import java.util.Random; import net.imagej.ops.AbstractNamespace; import net.imagej.ops.MathOps; import net.imagej.ops.OpMethod; import net.imglib2.IterableInterval; import net.imglib2.IterableRealInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.basictypeaccess.array.ByteArray; import net.imglib2.img.basictypeaccess.array.DoubleArray; import net.imglib2.img.planar.PlanarImg; import net.imglib2.type.numeric.NumericType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.real.DoubleType; /** * The math namespace contains arithmetic operations. * * @author Curtis Rueden */ public class MathNamespace extends AbstractNamespace { // -- Math namespace ops -- @OpMethod(op = net.imagej.ops.MathOps.Abs.class) public Object abs(final Object... args) { return ops().run(net.imagej.ops.MathOps.Abs.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAbs.class) public int abs(final int a) { final int result = (Integer) ops() .run(net.imagej.ops.math.PrimitiveMath.IntegerAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAbs.class) public long abs(final long a) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAbs.class) public float abs(final float a) { final float result = (Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAbs.class) public double abs(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAbs.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAbs.class) public <I extends RealType<I>, O extends RealType<O>> O abs(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAbs.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Add.class) public Object add(final Object... args) { return ops().run(net.imagej.ops.MathOps.Add.class, args); } @OpMethod(ops = { net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayByteImageP.class, net.imagej.ops.arithmetic.add.AddConstantToArrayByteImage.class }) public ArrayImg<ByteType, ByteArray> add( final ArrayImg<ByteType, ByteArray> image, final byte value) { @SuppressWarnings("unchecked") final ArrayImg<ByteType, ByteArray> result = (ArrayImg<ByteType, ByteArray>) ops().run(MathOps.Add.NAME, image, value); return result; } @OpMethod( ops = { net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayDoubleImageP.class, net.imagej.ops.arithmetic.add.AddConstantToArrayDoubleImage.class }) public ArrayImg<DoubleType, DoubleArray> add( final ArrayImg<DoubleType, DoubleArray> image, final double value) { @SuppressWarnings("unchecked") final ArrayImg<DoubleType, DoubleArray> result = (ArrayImg<DoubleType, DoubleArray>) ops().run(MathOps.Add.NAME, image, value); return result; } @OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.AddOp.class) public Object add(final Object result, final Object a, final Object b) { final Object result_op = ops().run(net.imagej.ops.onthefly.ArithmeticOp.AddOp.class, result, a, b); return result_op; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAdd.class) public int add(final int a, final int b) { final int result = (Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAdd.class) public long add(final long a, final long b) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAdd.class) public float add(final float a, final float b) { final float result = (Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAdd.class) public double add(final double a, final double b) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAdd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAdd.class) public <I extends RealType<I>, O extends RealType<O>> RealType<O> add( final RealType<O> out, final RealType<I> in, final double constant) { @SuppressWarnings("unchecked") final RealType<O> result = (RealType<O>) ops().run(net.imagej.ops.arithmetic.real.RealAdd.class, out, in, constant); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class) public <T extends NumericType<T>> IterableInterval<T> add( final IterableInterval<T> a, final RandomAccessibleInterval<T> b) { @SuppressWarnings("unchecked") final IterableInterval<T> result = (IterableInterval<T>) ops() .run( net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class, a, b); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class) public PlanarImg<DoubleType, DoubleArray> add( final PlanarImg<DoubleType, DoubleArray> image, final double value) { @SuppressWarnings("unchecked") final PlanarImg<DoubleType, DoubleArray> result = (PlanarImg<DoubleType, DoubleArray>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class, image, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class) public <T extends NumericType<T>> IterableRealInterval<T> add( final IterableRealInterval<T> image, final T value) { @SuppressWarnings("unchecked") final IterableRealInterval<T> result = (IterableRealInterval<T>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class, image, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class) public <T extends NumericType<T>> T add(final T in, final T value) { @SuppressWarnings("unchecked") final T result = (T) ops() .run(net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, in, value); return result; } @OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class) public <T extends NumericType<T>> T add(final T out, final T in, final T value) { @SuppressWarnings("unchecked") final T result = (T) ops().run( net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, out, in, value); return result; } @OpMethod( op = net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class) public <T extends NumericType<T>> RandomAccessibleInterval<T> add( final RandomAccessibleInterval<T> out, final IterableInterval<T> in, final T value) { @SuppressWarnings("unchecked") final RandomAccessibleInterval<T> result = (RandomAccessibleInterval<T>) ops().run( net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class, out, in, value); return result; } @OpMethod(op = net.imagej.ops.MathOps.AddNoise.class) public Object addnoise(final Object... args) { return ops().run(net.imagej.ops.MathOps.AddNoise.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAddNoise.class) public <I extends RealType<I>, O extends RealType<O>> O addnoise(final O out, final I in, final double rangeMin, final double rangeMax, final double rangeStdDev, final Random rng) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAddNoise.class, out, in, rangeMin, rangeMax, rangeStdDev, rng); return result; } @OpMethod(op = net.imagej.ops.MathOps.And.class) public Object and(final Object... args) { return ops().run(net.imagej.ops.MathOps.And.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAnd.class) public int and(final int a, final int b) { final int result = (Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAnd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAnd.class) public long and(final long a, final long b) { final long result = (Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAnd.class, a, b); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealAndConstant.class) public <I extends RealType<I>, O extends RealType<O>> O and(final O out, final I in, final long constant) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealAndConstant.class, out, in, constant); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccos.class) public Object arccos(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccos.class, args); } @OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArccos.class) public double arccos(final double a) { final double result = (Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArccos.class, a); return result; } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccos.class) public <I extends RealType<I>, O extends RealType<O>> O arccos(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccos.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccosh.class) public Object arccosh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccosh.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccosh.class) public <I extends RealType<I>, O extends RealType<O>> O arccosh(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccosh.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccot.class) public Object arccot(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccot.class, args); } @OpMethod(op = net.imagej.ops.arithmetic.real.RealArccot.class) public <I extends RealType<I>, O extends RealType<O>> O arccot(final O out, final I in) { @SuppressWarnings("unchecked") final O result = (O) ops().run(net.imagej.ops.arithmetic.real.RealArccot.class, out, in); return result; } @OpMethod(op = net.imagej.ops.MathOps.Arccoth.class) public Object arccoth(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccoth.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arccsc.class) public Object arccsc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccsc.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arccsch.class) public Object arccsch(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arccsch.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arcsec.class) public Object arcsec(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsec.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arcsech.class) public Object arcsech(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsech.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arcsin.class) public Object arcsin(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsin.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arcsinh.class) public Object arcsinh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arcsinh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arctan.class) public Object arctan(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arctan.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Arctanh.class) public Object arctanh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Arctanh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Ceil.class) public Object ceil(final Object... args) { return ops().run(net.imagej.ops.MathOps.Ceil.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Complement.class) public Object complement(final Object... args) { return ops().run(net.imagej.ops.MathOps.Complement.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Copy.class) public Object copy(final Object... args) { return ops().run(net.imagej.ops.MathOps.Copy.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Cos.class) public Object cos(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cos.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Cosh.class) public Object cosh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cosh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Cot.class) public Object cot(final Object... args) { return ops().run(net.imagej.ops.MathOps.Cot.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Coth.class) public Object coth(final Object... args) { return ops().run(net.imagej.ops.MathOps.Coth.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Csc.class) public Object csc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Csc.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Csch.class) public Object csch(final Object... args) { return ops().run(net.imagej.ops.MathOps.Csch.class, args); } @OpMethod(op = net.imagej.ops.MathOps.CubeRoot.class) public Object cuberoot(final Object... args) { return ops().run(net.imagej.ops.MathOps.CubeRoot.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Divide.class) public Object divide(final Object... args) { return ops().run(net.imagej.ops.MathOps.Divide.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Exp.class) public Object exp(final Object... args) { return ops().run(net.imagej.ops.MathOps.Exp.class, args); } @OpMethod(op = net.imagej.ops.MathOps.ExpMinusOne.class) public Object expminusone(final Object... args) { return ops().run(net.imagej.ops.MathOps.ExpMinusOne.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Floor.class) public Object floor(final Object... args) { return ops().run(net.imagej.ops.MathOps.Floor.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Gamma.class) public Object gamma(final Object... args) { return ops().run(net.imagej.ops.MathOps.Gamma.class, args); } @OpMethod(op = net.imagej.ops.MathOps.GaussianRandom.class) public Object gaussianrandom(final Object... args) { return ops().run(net.imagej.ops.MathOps.GaussianRandom.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Invert.class) public Object invert(final Object... args) { return ops().run(net.imagej.ops.MathOps.Invert.class, args); } @OpMethod(op = net.imagej.ops.MathOps.LeftShift.class) public Object leftshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.LeftShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log.class) public Object log(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log2.class) public Object log2(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log2.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Log10.class) public Object log10(final Object... args) { return ops().run(net.imagej.ops.MathOps.Log10.class, args); } @OpMethod(op = net.imagej.ops.MathOps.LogOnePlusX.class) public Object logoneplusx(final Object... args) { return ops().run(net.imagej.ops.MathOps.LogOnePlusX.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Max.class) public Object max(final Object... args) { return ops().run(net.imagej.ops.MathOps.Max.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Min.class) public Object min(final Object... args) { return ops().run(net.imagej.ops.MathOps.Min.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Multiply.class) public Object multiply(final Object... args) { return ops().run(net.imagej.ops.MathOps.Multiply.class, args); } @OpMethod(op = net.imagej.ops.MathOps.NearestInt.class) public Object nearestint(final Object... args) { return ops().run(net.imagej.ops.MathOps.NearestInt.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Negate.class) public Object negate(final Object... args) { return ops().run(net.imagej.ops.MathOps.Negate.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Or.class) public Object or(final Object... args) { return ops().run(net.imagej.ops.MathOps.Or.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Power.class) public Object power(final Object... args) { return ops().run(net.imagej.ops.MathOps.Power.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Reciprocal.class) public Object reciprocal(final Object... args) { return ops().run(net.imagej.ops.MathOps.Reciprocal.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Remainder.class) public Object remainder(final Object... args) { return ops().run(net.imagej.ops.MathOps.Remainder.class, args); } @OpMethod(op = net.imagej.ops.MathOps.RightShift.class) public Object rightshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.RightShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Round.class) public Object round(final Object... args) { return ops().run(net.imagej.ops.MathOps.Round.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sec.class) public Object sec(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sec.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sech.class) public Object sech(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sech.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Signum.class) public Object signum(final Object... args) { return ops().run(net.imagej.ops.MathOps.Signum.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sin.class) public Object sin(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sin.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sinc.class) public Object sinc(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sinc.class, args); } @OpMethod(op = net.imagej.ops.MathOps.SincPi.class) public Object sincpi(final Object... args) { return ops().run(net.imagej.ops.MathOps.SincPi.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sinh.class) public Object sinh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sinh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sqr.class) public Object sqr(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sqr.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Sqrt.class) public Object sqrt(final Object... args) { return ops().run(net.imagej.ops.MathOps.Sqrt.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Step.class) public Object step(final Object... args) { return ops().run(net.imagej.ops.MathOps.Step.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Subtract.class) public Object subtract(final Object... args) { return ops().run(net.imagej.ops.MathOps.Subtract.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Tan.class) public Object tan(final Object... args) { return ops().run(net.imagej.ops.MathOps.Tan.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Tanh.class) public Object tanh(final Object... args) { return ops().run(net.imagej.ops.MathOps.Tanh.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Ulp.class) public Object ulp(final Object... args) { return ops().run(net.imagej.ops.MathOps.Ulp.class, args); } @OpMethod(op = net.imagej.ops.MathOps.UniformRandom.class) public Object uniformrandom(final Object... args) { return ops().run(net.imagej.ops.MathOps.UniformRandom.class, args); } @OpMethod(op = net.imagej.ops.MathOps.UnsignedRightShift.class) public Object unsignedrightshift(final Object... args) { return ops().run(net.imagej.ops.MathOps.UnsignedRightShift.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Xor.class) public Object xor(final Object... args) { return ops().run(net.imagej.ops.MathOps.Xor.class, args); } @OpMethod(op = net.imagej.ops.MathOps.Zero.class) public Object zero(final Object... args) { return ops().run(net.imagej.ops.MathOps.Zero.class, args); } // -- Named methods -- @Override public String getName() { return "math"; } }
package org.apache.commons.lang; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * The empty String <code>""</code>. * @since 2.0 */ public static final String EMPTY = ""; /** * Represents a failed index search. * @since 2.?.? */ public static final int INDEX_NOT_FOUND = -1; /** * <p>The maximum size to which the padding constant(s) can expand.</p> */ private static final int PAD_LIMIT = 8192; /** * <p>An array of <code>String</code>s used for padding.</p> * * <p>Used for efficient space padding. The length of each String expands as needed.</p> */ private static final String[] PADDING = new String[Character.MAX_VALUE]; static { // space padding is most common, start with 64 chars PADDING[32] = " "; } /** * <p><code>StringUtils</code> instances should NOT be constructed in * standard programming. Instead, the class should be used as * <code>StringUtils.trim(" foo ");</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean * instance to operate.</p> */ public StringUtils() { // no init. } // Empty checks /** * <p>Checks if a String is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().</p> * * @param str the String to check, may be null * @return <code>true</code> if the String is empty or null */ public static boolean isEmpty(String str) { return (str == null || str.length() == 0); } /** * <p>Checks if a String is not empty ("") and not null.</p> * * <pre> * StringUtils.isNotEmpty(null) = false * StringUtils.isNotEmpty("") = false * StringUtils.isNotEmpty(" ") = true * StringUtils.isNotEmpty("bob") = true * StringUtils.isNotEmpty(" bob ") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is not empty and not null */ public static boolean isNotEmpty(String str) { return (str != null && str.length() > 0); } /** * <p>Checks if a String is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is null, empty or whitespace * @since 2.0 */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } /** * <p>Checks if a String is not empty (""), not null and not whitespace only.</p> * * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param str the String to check, may be null * @return <code>true</code> if the String is * not empty and not null and not whitespace * @since 2.0 */ public static boolean isNotBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return false; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return true; } } return false; } // Trim /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String, handling <code>null</code> by returning * an empty String ("").</p> * * <pre> * StringUtils.clean(null) = "" * StringUtils.clean("") = "" * StringUtils.clean("abc") = "abc" * StringUtils.clean(" abc ") = "abc" * StringUtils.clean(" ") = "" * </pre> * * @see java.lang.String#trim() * @param str the String to clean, may be null * @return the trimmed text, never <code>null</code> * @deprecated Use the clearer named {@link #trimToEmpty(String)}. * Method will be removed in Commons Lang 3.0. */ public static String clean(String str) { return (str == null ? EMPTY : str.trim()); } /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String, handling <code>null</code> by returning * <code>null</code>.</p> * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32. * To strip whitespace use {@link #strip(String)}.</p> * * <p>To trim your choice of characters, use the * {@link #strip(String, String)} methods.</p> * * <pre> * StringUtils.trim(null) = null * StringUtils.trim("") = "" * StringUtils.trim(" ") = "" * StringUtils.trim("abc") = "abc" * StringUtils.trim(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, <code>null</code> if null String input */ public static String trim(String str) { return (str == null ? null : str.trim()); } /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String returning <code>null</code> if the String is * empty ("") after the trim or if it is <code>null</code>. * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32. * To strip whitespace use {@link #stripToNull(String)}.</p> * * <pre> * StringUtils.trimToNull(null) = null * StringUtils.trimToNull("") = null * StringUtils.trimToNull(" ") = null * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, * <code>null</code> if only chars &lt;= 32, empty or null String input * @since 2.0 */ public static String trimToNull(String str) { String ts = trim(str); return (ts == null || ts.length() == 0 ? null : ts); } /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String returning an empty String ("") if the String * is empty ("") after the trim or if it is <code>null</code>. * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32. * To strip whitespace use {@link #stripToEmpty(String)}.</p> * * <pre> * StringUtils.trimToEmpty(null) = "" * StringUtils.trimToEmpty("") = "" * StringUtils.trimToEmpty(" ") = "" * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, or an empty String if <code>null</code> input * @since 2.0 */ public static String trimToEmpty(String str) { return (str == null ? EMPTY : str.trim()); } // Stripping /** * <p>Strips whitespace from the start and end of a String.</p> * * <p>This is similar to {@link #trim(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.strip(null) = null * StringUtils.strip("") = "" * StringUtils.strip(" ") = "" * StringUtils.strip("abc") = "abc" * StringUtils.strip(" abc") = "abc" * StringUtils.strip("abc ") = "abc" * StringUtils.strip(" abc ") = "abc" * StringUtils.strip(" ab c ") = "ab c" * </pre> * * @param str the String to remove whitespace from, may be null * @return the stripped String, <code>null</code> if null String input */ public static String strip(String str) { return strip(str, null); } /** * <p>Strips whitespace from the start and end of a String returning * <code>null</code> if the String is empty ("") after the strip.</p> * * <p>This is similar to {@link #trimToNull(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.strip(null) = null * StringUtils.strip("") = null * StringUtils.strip(" ") = null * StringUtils.strip("abc") = "abc" * StringUtils.strip(" abc") = "abc" * StringUtils.strip("abc ") = "abc" * StringUtils.strip(" abc ") = "abc" * StringUtils.strip(" ab c ") = "ab c" * </pre> * * @param str the String to be stripped, may be null * @return the stripped String, * <code>null</code> if whitespace, empty or null String input * @since 2.0 */ public static String stripToNull(String str) { if (str == null) { return null; } str = strip(str, null); return (str.length() == 0 ? null : str); } /** * <p>Strips whitespace from the start and end of a String returning * an empty String if <code>null</code> input.</p> * * <p>This is similar to {@link #trimToEmpty(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.strip(null) = "" * StringUtils.strip("") = "" * StringUtils.strip(" ") = "" * StringUtils.strip("abc") = "abc" * StringUtils.strip(" abc") = "abc" * StringUtils.strip("abc ") = "abc" * StringUtils.strip(" abc ") = "abc" * StringUtils.strip(" ab c ") = "ab c" * </pre> * * @param str the String to be stripped, may be null * @return the trimmed String, or an empty String if <code>null</code> input * @since 2.0 */ public static String stripToEmpty(String str) { return (str == null ? EMPTY : strip(str, null)); } /** * <p>Strips any of a set of characters from the start and end of a String. * This is similar to {@link String#trim()} but allows the characters * to be stripped to be controlled.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}. * Alternatively use {@link #strip(String)}.</p> * * <pre> * StringUtils.strip(null, *) = null * StringUtils.strip("", *) = "" * StringUtils.strip("abc", null) = "abc" * StringUtils.strip(" abc", null) = "abc" * StringUtils.strip("abc ", null) = "abc" * StringUtils.strip(" abc ", null) = "abc" * StringUtils.strip(" abcyx", "xyz") = " abc" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String strip(String str, String stripChars) { if (str == null || str.length() == 0) { return str; } str = stripStart(str, stripChars); return stripEnd(str, stripChars); } /** * <p>Strips any of a set of characters from the start of a String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripStart(null, *) = null * StringUtils.stripStart("", *) = "" * StringUtils.stripStart("abc", "") = "abc" * StringUtils.stripStart("abc", null) = "abc" * StringUtils.stripStart(" abc", null) = "abc" * StringUtils.stripStart("abc ", null) = "abc " * StringUtils.stripStart(" abc ", null) = "abc " * StringUtils.stripStart("yxabc ", "xyz") = "abc " * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String stripStart(String str, String stripChars) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } int start = 0; if (stripChars == null) { while ((start != strLen) && Character.isWhitespace(str.charAt(start))) { start++; } } else if (stripChars.length() == 0) { return str; } else { while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) { start++; } } return str.substring(start); } /** * <p>Strips any of a set of characters from the end of a String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * An empty string ("") input returns the empty string.</p> * * <p>If the stripChars String is <code>null</code>, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripEnd(null, *) = null * StringUtils.stripEnd("", *) = "" * StringUtils.stripEnd("abc", "") = "abc" * StringUtils.stripEnd("abc", null) = "abc" * StringUtils.stripEnd(" abc", null) = " abc" * StringUtils.stripEnd("abc ", null) = "abc" * StringUtils.stripEnd(" abc ", null) = " abc" * StringUtils.stripEnd(" abcyx", "xyz") = " abc" * </pre> * * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, <code>null</code> if null String input */ public static String stripEnd(String str, String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end } } else if (stripChars.length() == 0) { return str; } else { while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) { end } } return str.substring(0, end); } // StripAll /** * <p>Strips whitespace from the start and end of every String in an array. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <p>A new array is returned each time, except for length zero. * A <code>null</code> array will return <code>null</code>. * An empty array will return itself. * A <code>null</code> array entry will be ignored.</p> * * <pre> * StringUtils.stripAll(null) = null * StringUtils.stripAll([]) = [] * StringUtils.stripAll(["abc", " abc"]) = ["abc", "abc"] * StringUtils.stripAll(["abc ", null]) = ["abc", null] * </pre> * * @param strs the array to remove whitespace from, may be null * @return the stripped Strings, <code>null</code> if null array input */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** * <p>Strips any of a set of characters from the start and end of every * String in an array.</p> * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <p>A new array is returned each time, except for length zero. * A <code>null</code> array will return <code>null</code>. * An empty array will return itself. * A <code>null</code> array entry will be ignored. * A <code>null</code> stripChars will strip whitespace as defined by * {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.stripAll(null, *) = null * StringUtils.stripAll([], *) = [] * StringUtils.stripAll(["abc", " abc"], null) = ["abc", "abc"] * StringUtils.stripAll(["abc ", null], null) = ["abc", null] * StringUtils.stripAll(["abc ", null], "yz") = ["abc ", null] * StringUtils.stripAll(["yabcz", null], "yz") = ["abc", null] * </pre> * * @param strs the array to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped Strings, <code>null</code> if null array input */ public static String[] stripAll(String[] strs, String stripChars) { int strsLen; if (strs == null || (strsLen = strs.length) == 0) { return strs; } String[] newArr = new String[strsLen]; for (int i = 0; i < strsLen; i++) { newArr[i] = strip(strs[i], stripChars); } return newArr; } // Equals /** * <p>Compares two Strings, returning <code>true</code> if they are equal.</p> * * <p><code>null</code>s are handled without exceptions. Two <code>null</code> * references are considered to be equal. The comparison is case sensitive.</p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, "abc") = false * StringUtils.equals("abc", null) = false * StringUtils.equals("abc", "abc") = true * StringUtils.equals("abc", "ABC") = false * </pre> * * @see java.lang.String#equals(Object) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return <code>true</code> if the Strings are equal, case sensitive, or * both <code>null</code> */ public static boolean equals(String str1, String str2) { return (str1 == null ? str2 == null : str1.equals(str2)); } /** * <p>Compares two Strings, returning <code>true</code> if they are equal ignoring * the case.</p> * * <p><code>null</code>s are handled without exceptions. Two <code>null</code> * references are considered equal. Comparison is case insensitive.</p> * * <pre> * StringUtils.equalsIgnoreCase(null, null) = true * StringUtils.equalsIgnoreCase(null, "abc") = false * StringUtils.equalsIgnoreCase("abc", null) = false * StringUtils.equalsIgnoreCase("abc", "abc") = true * StringUtils.equalsIgnoreCase("abc", "ABC") = true * </pre> * * @see java.lang.String#equalsIgnoreCase(String) * @param str1 the first String, may be null * @param str2 the second String, may be null * @return <code>true</code> if the Strings are equal, case insensitive, or * both <code>null</code> */ public static boolean equalsIgnoreCase(String str1, String str2) { return (str1 == null ? str2 == null : str1.equalsIgnoreCase(str2)); } // IndexOf /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOf(null, *) = -1 * StringUtils.indexOf("", *) = -1 * StringUtils.indexOf("aabaabaa", 'a') = 0 * StringUtils.indexOf("aabaabaa", 'b') = 2 * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @return the first index of the search character, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, char searchChar) { if (str == null || str.length() == 0) { return -1; } return str.indexOf(searchChar); } /** * <p>Finds the first index within a String from a start position, * handling <code>null</code>. * This method uses {@link String#indexOf(int, int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>-1</code>. * A negative start position is treated as zero. * A start position greater than the string length returns <code>-1</code>.</p> * * <pre> * StringUtils.indexOf(null, *, *) = -1 * StringUtils.indexOf("", *, *) = -1 * StringUtils.indexOf("aabaabaa", 'b', 0) = 2 * StringUtils.indexOf("aabaabaa", 'b', 3) = 5 * StringUtils.indexOf("aabaabaa", 'b', 9) = -1 * StringUtils.indexOf("aabaabaa", 'b', -1) = 2 * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position, negative treated as zero * @return the first index of the search character, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, char searchChar, int startPos) { if (str == null || str.length() == 0) { return -1; } return str.indexOf(searchChar, startPos); } /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOf(null, *) = -1 * StringUtils.indexOf(*, null) = -1 * StringUtils.indexOf("", "") = 0 * StringUtils.indexOf("aabaabaa", "a") = 0 * StringUtils.indexOf("aabaabaa", "b") = 2 * StringUtils.indexOf("aabaabaa", "ab") = 1 * StringUtils.indexOf("aabaabaa", "") = 0 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, String searchStr) { if (str == null || searchStr == null) { return -1; } return str.indexOf(searchStr); } /** * <p>Finds the n-th index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * StringUtils.ordinalIndexOf(null, *, *) = -1 * StringUtils.ordinalIndexOf(*, null, *) = -1 * StringUtils.ordinalIndexOf("", "", *) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "a", 1) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "a", 2) = 1 * StringUtils.ordinalIndexOf("aabaabaa", "b", 1) = 2 * StringUtils.ordinalIndexOf("aabaabaa", "b", 2) = 5 * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1 * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4 * StringUtils.ordinalIndexOf("aabaabaa", "", 1) = 0 * StringUtils.ordinalIndexOf("aabaabaa", "", 2) = 0 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th <code>searchStr</code> to find * @return the n-th index of the search String, * <code>-1</code> (<code>INDEX_NOT_FOUND</code>) if no match or <code>null</code> string input * @since 2.?.? */ public static int ordinalIndexOf(String str, String searchStr, int ordinal) { if (str == null || searchStr == null || ordinal <= 0) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return 0; } int found = 0; int index = INDEX_NOT_FOUND; do { index = str.indexOf(searchStr, index + 1); if (index < 0) { return index; } found++; } while (found < ordinal); return index; } /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#indexOf(String, int)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A negative start position is treated as zero. * An empty ("") search String always matches. * A start position greater than the string length only matches * an empty search String.</p> * * <pre> * StringUtils.indexOf(null, *, *) = -1 * StringUtils.indexOf(*, null, *) = -1 * StringUtils.indexOf("", "", 0) = 0 * StringUtils.indexOf("aabaabaa", "a", 0) = 0 * StringUtils.indexOf("aabaabaa", "b", 0) = 2 * StringUtils.indexOf("aabaabaa", "ab", 0) = 1 * StringUtils.indexOf("aabaabaa", "b", 3) = 5 * StringUtils.indexOf("aabaabaa", "b", 9) = -1 * StringUtils.indexOf("aabaabaa", "b", -1) = 2 * StringUtils.indexOf("aabaabaa", "", 2) = 2 * StringUtils.indexOf("abc", "", 9) = 3 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int indexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return -1; } // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence if (searchStr.length() == 0 && startPos >= str.length()) { return str.length(); } return str.indexOf(searchStr, startPos); } // LastIndexOf /** * <p>Finds the last index within a String, handling <code>null</code>. * This method uses {@link String#lastIndexOf(int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>-1</code>.</p> * * <pre> * StringUtils.lastIndexOf(null, *) = -1 * StringUtils.lastIndexOf("", *) = -1 * StringUtils.lastIndexOf("aabaabaa", 'a') = 7 * StringUtils.lastIndexOf("aabaabaa", 'b') = 5 * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @return the last index of the search character, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar) { if (str == null || str.length() == 0) { return -1; } return str.lastIndexOf(searchChar); } /** * <p>Finds the last index within a String from a start position, * handling <code>null</code>. * This method uses {@link String#lastIndexOf(int, int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>-1</code>. * A negative start position returns <code>-1</code>. * A start position greater than the string length searches the whole string.</p> * * <pre> * StringUtils.lastIndexOf(null, *, *) = -1 * StringUtils.lastIndexOf("", *, *) = -1 * StringUtils.lastIndexOf("aabaabaa", 'b', 8) = 5 * StringUtils.lastIndexOf("aabaabaa", 'b', 4) = 2 * StringUtils.lastIndexOf("aabaabaa", 'b', 0) = -1 * StringUtils.lastIndexOf("aabaabaa", 'b', 9) = 5 * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1 * StringUtils.lastIndexOf("aabaabaa", 'a', 0) = 0 * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position * @return the last index of the search character, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar, int startPos) { if (str == null || str.length() == 0) { return -1; } return str.lastIndexOf(searchChar, startPos); } /** * <p>Finds the last index within a String, handling <code>null</code>. * This method uses {@link String#lastIndexOf(String)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>.</p> * * <pre> * StringUtils.lastIndexOf(null, *) = -1 * StringUtils.lastIndexOf(*, null) = -1 * StringUtils.lastIndexOf("", "") = 0 * StringUtils.lastIndexOf("aabaabaa", "a") = 0 * StringUtils.lastIndexOf("aabaabaa", "b") = 2 * StringUtils.lastIndexOf("aabaabaa", "ab") = 1 * StringUtils.lastIndexOf("aabaabaa", "") = 8 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the last index of the search String, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr) { if (str == null || searchStr == null) { return -1; } return str.lastIndexOf(searchStr); } /** * <p>Finds the first index within a String, handling <code>null</code>. * This method uses {@link String#lastIndexOf(String, int)}.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A negative start position returns <code>-1</code>. * An empty ("") search String always matches unless the start position is negative. * A start position greater than the string length searches the whole string.</p> * * <pre> * StringUtils.lastIndexOf(null, *, *) = -1 * StringUtils.lastIndexOf(*, null, *) = -1 * StringUtils.lastIndexOf("aabaabaa", "a", 8) = 7 * StringUtils.lastIndexOf("aabaabaa", "b", 8) = 5 * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4 * StringUtils.lastIndexOf("aabaabaa", "b", 9) = 5 * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1 * StringUtils.lastIndexOf("aabaabaa", "a", 0) = 0 * StringUtils.lastIndexOf("aabaabaa", "b", 0) = -1 * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or <code>null</code> string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return -1; } return str.lastIndexOf(searchStr, startPos); } // Contains /** * <p>Checks if String contains a search character, handling <code>null</code>. * This method uses {@link String#indexOf(int)}.</p> * * <p>A <code>null</code> or empty ("") String will return <code>false</code>.</p> * * <pre> * StringUtils.contains(null, *) = false * StringUtils.contains("", *) = false * StringUtils.contains("abc", 'a') = true * StringUtils.contains("abc", 'z') = false * </pre> * * @param str the String to check, may be null * @param searchChar the character to find * @return true if the String contains the search character, * false if not or <code>null</code> string input * @since 2.0 */ public static boolean contains(String str, char searchChar) { if (str == null || str.length() == 0) { return false; } return (str.indexOf(searchChar) >= 0); } /** * <p>Checks if String contains a search String, handling <code>null</code>. * This method uses {@link String#indexOf(int)}.</p> * * <p>A <code>null</code> String will return <code>false</code>.</p> * * <pre> * StringUtils.contains(null, *) = false * StringUtils.contains(*, null) = false * StringUtils.contains("", "") = true * StringUtils.contains("abc", "") = true * StringUtils.contains("abc", "a") = true * StringUtils.contains("abc", "z") = false * </pre> * * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return true if the String contains the search String, * false if not or <code>null</code> string input * @since 2.0 */ public static boolean contains(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return (str.indexOf(searchStr) >= 0); } // IndexOfAny chars /** * <p>Search a String to find the first index of any * character in the given set of characters.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> or zero length search array will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOfAny(null, *) = -1 * StringUtils.indexOfAny("", *) = -1 * StringUtils.indexOfAny(*, null) = -1 * StringUtils.indexOfAny(*, []) = -1 * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0 * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3 * StringUtils.indexOfAny("aba", ['z']) = -1 * </pre> * * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAny(String str, char[] searchChars) { if (StringUtils.isEmpty(str) || searchChars == null || searchChars.length == 0) { return -1; } for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); for (int j = 0; j < searchChars.length; j++) { if (searchChars[j] == ch) { return i; } } } return -1; } /** * <p>Search a String to find the first index of any * character in the given set of characters.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> search string will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOfAny(null, *) = -1 * StringUtils.indexOfAny("", *) = -1 * StringUtils.indexOfAny(*, null) = -1 * StringUtils.indexOfAny(*, "") = -1 * StringUtils.indexOfAny("zzabyycdxx", "za") = 0 * StringUtils.indexOfAny("zzabyycdxx", "by") = 3 * StringUtils.indexOfAny("aba","z") = -1 * </pre> * * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAny(String str, String searchChars) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) { return -1; } return indexOfAny(str, searchChars.toCharArray()); } // IndexOfAnyBut chars /** * <p>Search a String to find the first index of any * character not in the given set of characters.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> or zero length search array will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOfAnyBut(null, *) = -1 * StringUtils.indexOfAnyBut("", *) = -1 * StringUtils.indexOfAnyBut(*, null) = -1 * StringUtils.indexOfAnyBut(*, []) = -1 * StringUtils.indexOfAnyBut("zzabyycdxx",'za') = 3 * StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 * StringUtils.indexOfAnyBut("aba", 'ab') = -1 * </pre> * * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAnyBut(String str, char[] searchChars) { if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) { return -1; } outer : for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); for (int j = 0; j < searchChars.length; j++) { if (searchChars[j] == ch) { continue outer; } } return i; } return -1; } /** * <p>Search a String to find the first index of any * character not in the given set of characters.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> search string will return <code>-1</code>.</p> * * <pre> * StringUtils.indexOfAnyBut(null, *) = -1 * StringUtils.indexOfAnyBut("", *) = -1 * StringUtils.indexOfAnyBut(*, null) = -1 * StringUtils.indexOfAnyBut(*, "") = -1 * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3 * StringUtils.indexOfAnyBut("zzabyycdxx", "") = 0 * StringUtils.indexOfAnyBut("aba","ab") = -1 * </pre> * * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAnyBut(String str, String searchChars) { if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; } // ContainsOnly /** * <p>Checks if the String contains only certain characters.</p> * * <p>A <code>null</code> String will return <code>false</code>. * A <code>null</code> valid character array will return <code>false</code>. * An empty String ("") always returns <code>true</code>.</p> * * <pre> * StringUtils.containsOnly(null, *) = false * StringUtils.containsOnly(*, null) = false * StringUtils.containsOnly("", *) = true * StringUtils.containsOnly("ab", '') = false * StringUtils.containsOnly("abab", 'abc') = true * StringUtils.containsOnly("ab1", 'abc') = false * StringUtils.containsOnly("abz", 'abc') = false * </pre> * * @param str the String to check, may be null * @param valid an array of valid chars, may be null * @return true if it only contains valid chars and is non-null */ public static boolean containsOnly(String str, char[] valid) { // All these pre-checks are to maintain API with an older version if ((valid == null) || (str == null)) { return false; } if (str.length() == 0) { return true; } if (valid.length == 0) { return false; } return indexOfAnyBut(str, valid) == -1; } /** * <p>Checks if the String contains only certain characters.</p> * * <p>A <code>null</code> String will return <code>false</code>. * A <code>null</code> valid character String will return <code>false</code>. * An empty String ("") always returns <code>true</code>.</p> * * <pre> * StringUtils.containsOnly(null, *) = false * StringUtils.containsOnly(*, null) = false * StringUtils.containsOnly("", *) = true * StringUtils.containsOnly("ab", "") = false * StringUtils.containsOnly("abab", "abc") = true * StringUtils.containsOnly("ab1", "abc") = false * StringUtils.containsOnly("abz", "abc") = false * </pre> * * @param str the String to check, may be null * @param validChars a String of valid chars, may be null * @return true if it only contains valid chars and is non-null * @since 2.0 */ public static boolean containsOnly(String str, String validChars) { if (str == null || validChars == null) { return false; } return containsOnly(str, validChars.toCharArray()); } // ContainsNone /** * <p>Checks that the String does not contain certain characters.</p> * * <p>A <code>null</code> String will return <code>true</code>. * A <code>null</code> invalid character array will return <code>true</code>. * An empty String ("") always returns true.</p> * * <pre> * StringUtils.containsNone(null, *) = true * StringUtils.containsNone(*, null) = true * StringUtils.containsNone("", *) = true * StringUtils.containsNone("ab", '') = true * StringUtils.containsNone("abab", 'xyz') = true * StringUtils.containsNone("ab1", 'xyz') = true * StringUtils.containsNone("abz", 'xyz') = false * </pre> * * @param str the String to check, may be null * @param invalidChars an array of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, char[] invalidChars) { if (str == null || invalidChars == null) { return true; } int strSize = str.length(); int validSize = invalidChars.length; for (int i = 0; i < strSize; i++) { char ch = str.charAt(i); for (int j = 0; j < validSize; j++) { if (invalidChars[j] == ch) { return false; } } } return true; } /** * <p>Checks that the String does not contain certain characters.</p> * * <p>A <code>null</code> String will return <code>true</code>. * A <code>null</code> invalid character array will return <code>true</code>. * An empty String ("") always returns true.</p> * * <pre> * StringUtils.containsNone(null, *) = true * StringUtils.containsNone(*, null) = true * StringUtils.containsNone("", *) = true * StringUtils.containsNone("ab", "") = true * StringUtils.containsNone("abab", "xyz") = true * StringUtils.containsNone("ab1", "xyz") = true * StringUtils.containsNone("abz", "xyz") = false * </pre> * * @param str the String to check, may be null * @param invalidChars a String of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, String invalidChars) { if (str == null || invalidChars == null) { return true; } return containsNone(str, invalidChars.toCharArray()); } // IndexOfAny strings /** * <p>Find the first index of any of a set of potential substrings.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> or zero length search array will return <code>-1</code>. * A <code>null</code> search array entry will be ignored, but a search * array containing "" will return <code>0</code> if <code>str</code> is not * null. This method uses {@link String#indexOf(String)}.</p> * * <pre> * StringUtils.indexOfAny(null, *) = -1 * StringUtils.indexOfAny(*, null) = -1 * StringUtils.indexOfAny(*, []) = -1 * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2 * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2 * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"]) = -1 * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1 * StringUtils.indexOfAny("zzabyycdxx", [""]) = 0 * StringUtils.indexOfAny("", [""]) = 0 * StringUtils.indexOfAny("", ["a"]) = -1 * </pre> * * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the first index of any of the searchStrs in str, -1 if no match */ public static int indexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; // String's can't have a MAX_VALUEth index. int ret = Integer.MAX_VALUE; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.indexOf(search); if (tmp == -1) { continue; } if (tmp < ret) { ret = tmp; } } return (ret == Integer.MAX_VALUE) ? -1 : ret; } /** * <p>Find the latest index of any of a set of potential substrings.</p> * * <p>A <code>null</code> String will return <code>-1</code>. * A <code>null</code> search array will return <code>-1</code>. * A <code>null</code> or zero length search array entry will be ignored, * but a search array containing "" will return the length of <code>str</code> * if <code>str</code> is not null. This method uses {@link String#indexOf(String)}</p> * * <pre> * StringUtils.lastIndexOfAny(null, *) = -1 * StringUtils.lastIndexOfAny(*, null) = -1 * StringUtils.lastIndexOfAny(*, []) = -1 * StringUtils.lastIndexOfAny(*, [null]) = -1 * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6 * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6 * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1 * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1 * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10 * </pre> * * @param str the String to check, may be null * @param searchStrs the Strings to search for, may be null * @return the last index of any of the Strings, -1 if no match */ public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.lastIndexOf(search); if (tmp > ret) { ret = tmp; } } return ret; } // Substring /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start <code>n</code> * characters from the end of the String.</p> * * <p>A <code>null</code> String will return <code>null</code>. * An empty ("") String will return "".</p> * * <pre> * StringUtils.substring(null, *) = null * StringUtils.substring("", *) = "" * StringUtils.substring("abc", 0) = "abc" * StringUtils.substring("abc", 2) = "c" * StringUtils.substring("abc", 4) = "" * StringUtils.substring("abc", -2) = "bc" * StringUtils.substring("abc", -4) = "abc" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @return substring from start position, <code>null</code> if null String input */ public static String substring(String str, int start) { if (str == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY; } return str.substring(start); } /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start/end <code>n</code> * characters from the end of the String.</p> * * <p>The returned substring starts with the character in the <code>start</code> * position and ends before the <code>end</code> position. All position counting is * zero-based -- i.e., to start at the beginning of the string use * <code>start = 0</code>. Negative start and end positions can be used to * specify offsets relative to the end of the String.</p> * * <p>If <code>start</code> is not strictly to the left of <code>end</code>, "" * is returned.</p> * * <pre> * StringUtils.substring(null, *, *) = null * StringUtils.substring("", * , *) = ""; * StringUtils.substring("abc", 0, 2) = "ab" * StringUtils.substring("abc", 2, 0) = "" * StringUtils.substring("abc", 2, 4) = "c" * StringUtils.substring("abc", 4, 6) = "" * StringUtils.substring("abc", 2, 2) = "" * StringUtils.substring("abc", -2, -1) = "b" * StringUtils.substring("abc", -4, 2) = "ab" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means * count back from the end of the String by this many characters * @param end the position to end at (exclusive), negative means * count back from the end of the String by this many characters * @return substring from start position to end positon, * <code>null</code> if null String input */ public static String substring(String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { end = str.length(); } // if start is greater than end, return "" if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } // Left/Right/Mid /** * <p>Gets the leftmost <code>len</code> characters of a String.</p> * * <p>If <code>len</code> characters are not available, or the * String is <code>null</code>, the String will be returned without * an exception. An exception is thrown if len is negative.</p> * * <pre> * StringUtils.left(null, *) = null * StringUtils.left(*, -ve) = "" * StringUtils.left("", *) = "" * StringUtils.left("abc", 0) = "" * StringUtils.left("abc", 2) = "ab" * StringUtils.left("abc", 4) = "abc" * </pre> * * @param str the String to get the leftmost characters from, may be null * @param len the length of the required String, must be zero or positive * @return the leftmost characters, <code>null</code> if null String input */ public static String left(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } else { return str.substring(0, len); } } /** * <p>Gets the rightmost <code>len</code> characters of a String.</p> * * <p>If <code>len</code> characters are not available, or the String * is <code>null</code>, the String will be returned without an * an exception. An exception is thrown if len is negative.</p> * * <pre> * StringUtils.right(null, *) = null * StringUtils.right(*, -ve) = "" * StringUtils.right("", *) = "" * StringUtils.right("abc", 0) = "" * StringUtils.right("abc", 2) = "bc" * StringUtils.right("abc", 4) = "abc" * </pre> * * @param str the String to get the rightmost characters from, may be null * @param len the length of the required String, must be zero or positive * @return the rightmost characters, <code>null</code> if null String input */ public static String right(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } else { return str.substring(str.length() - len); } } /** * <p>Gets <code>len</code> characters from the middle of a String.</p> * * <p>If <code>len</code> characters are not available, the remainder * of the String will be returned without an exception. If the * String is <code>null</code>, <code>null</code> will be returned. * An exception is thrown if len is negative.</p> * * <pre> * StringUtils.mid(null, *, *) = null * StringUtils.mid(*, *, -ve) = "" * StringUtils.mid("", 0, *) = "" * StringUtils.mid("abc", 0, 2) = "ab" * StringUtils.mid("abc", 0, 4) = "abc" * StringUtils.mid("abc", 2, 4) = "c" * StringUtils.mid("abc", 4, 2) = "" * StringUtils.mid("abc", -2, 2) = "ab" * </pre> * * @param str the String to get the characters from, may be null * @param pos the position to start from, negative treated as zero * @param len the length of the required String, must be zero or positive * @return the middle characters, <code>null</code> if null String input */ public static String mid(String str, int pos, int len) { if (str == null) { return null; } if (len < 0 || pos > str.length()) { return EMPTY; } if (pos < 0) { pos = 0; } if (str.length() <= (pos + len)) { return str.substring(pos); } else { return str.substring(pos, pos + len); } } // SubStringAfter/SubStringBefore /** * <p>Gets the substring before the first occurrence of a separator. * The separator is not returned.</p> * * <p>A <code>null</code> string input will return <code>null</code>. * An empty ("") string input will return the empty string. * A <code>null</code> separator will return the input string.</p> * * <pre> * StringUtils.substringBefore(null, *) = null * StringUtils.substringBefore("", *) = "" * StringUtils.substringBefore("abc", "a") = "" * StringUtils.substringBefore("abcba", "b") = "a" * StringUtils.substringBefore("abc", "c") = "ab" * StringUtils.substringBefore("abc", "d") = "abc" * StringUtils.substringBefore("abc", "") = "" * StringUtils.substringBefore("abc", null) = "abc" * </pre> * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the first occurrence of the separator, * <code>null</code> if null String input * @since 2.0 */ public static String substringBefore(String str, String separator) { if (str == null || separator == null || str.length() == 0) { return str; } if (separator.length() == 0) { return EMPTY; } int pos = str.indexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } /** * <p>Gets the substring after the first occurrence of a separator. * The separator is not returned.</p> * * <p>A <code>null</code> string input will return <code>null</code>. * An empty ("") string input will return the empty string. * A <code>null</code> separator will return the empty string if the * input string is not <code>null</code>.</p> * * <pre> * StringUtils.substringAfter(null, *) = null * StringUtils.substringAfter("", *) = "" * StringUtils.substringAfter(*, null) = "" * StringUtils.substringAfter("abc", "a") = "bc" * StringUtils.substringAfter("abcba", "b") = "cba" * StringUtils.substringAfter("abc", "c") = "" * StringUtils.substringAfter("abc", "d") = "" * StringUtils.substringAfter("abc", "") = "abc" * </pre> * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the first occurrence of the separator, * <code>null</code> if null String input * @since 2.0 */ public static String substringAfter(String str, String separator) { if (str == null || str.length() == 0) { return str; } if (separator == null) { return EMPTY; } int pos = str.indexOf(separator); if (pos == -1) { return EMPTY; } return str.substring(pos + separator.length()); } /** * <p>Gets the substring before the last occurrence of a separator. * The separator is not returned.</p> * * <p>A <code>null</code> string input will return <code>null</code>. * An empty ("") string input will return the empty string. * An empty or <code>null</code> separator will return the input string.</p> * * <pre> * StringUtils.substringBeforeLast(null, *) = null * StringUtils.substringBeforeLast("", *) = "" * StringUtils.substringBeforeLast("abcba", "b") = "abc" * StringUtils.substringBeforeLast("abc", "c") = "ab" * StringUtils.substringBeforeLast("a", "a") = "" * StringUtils.substringBeforeLast("a", "z") = "a" * StringUtils.substringBeforeLast("a", null) = "a" * StringUtils.substringBeforeLast("a", "") = "a" * </pre> * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the last occurrence of the separator, * <code>null</code> if null String input * @since 2.0 */ public static String substringBeforeLast(String str, String separator) { if (str == null || separator == null || str.length() == 0 || separator.length() == 0) { return str; } int pos = str.lastIndexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } /** * <p>Gets the substring after the last occurrence of a separator. * The separator is not returned.</p> * * <p>A <code>null</code> string input will return <code>null</code>. * An empty ("") string input will return the empty string. * An empty or <code>null</code> separator will return the empty string if * the input string is not <code>null</code>.</p> * * <pre> * StringUtils.substringAfterLast(null, *) = null * StringUtils.substringAfterLast("", *) = "" * StringUtils.substringAfterLast(*, "") = "" * StringUtils.substringAfterLast(*, null) = "" * StringUtils.substringAfterLast("abc", "a") = "bc" * StringUtils.substringAfterLast("abcba", "b") = "a" * StringUtils.substringAfterLast("abc", "c") = "" * StringUtils.substringAfterLast("a", "a") = "" * StringUtils.substringAfterLast("a", "z") = "" * </pre> * * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the last occurrence of the separator, * <code>null</code> if null String input * @since 2.0 */ public static String substringAfterLast(String str, String separator) { if (str == null || str.length() == 0) { return str; } if (separator == null || separator.length() == 0) { return EMPTY; } int pos = str.lastIndexOf(separator); if (pos == -1 || pos == (str.length() - separator.length())) { return EMPTY; } return str.substring(pos + separator.length()); } // Substring between /** * <p>Gets the String that is nested in between two instances of the * same String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> tag returns <code>null</code>.</p> * * <pre> * StringUtils.substringBetween(null, *) = null * StringUtils.substringBetween("", "") = "" * StringUtils.substringBetween("", "tag") = null * StringUtils.substringBetween("tagabctag", null) = null * StringUtils.substringBetween("tagabctag", "") = "" * StringUtils.substringBetween("tagabctag", "tag") = "abc" * </pre> * * @param str the String containing the substring, may be null * @param tag the String before and after the substring, may be null * @return the substring, <code>null</code> if no match * @since 2.0 */ public static String substringBetween(String str, String tag) { return substringBetween(str, tag, tag); } /** * <p>Gets the String that is nested in between two Strings. * Only the first match is returned.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> open/close returns <code>null</code> (no match). * An empty ("") open/close returns an empty string.</p> * * <pre> * StringUtils.substringBetween(null, *, *) = null * StringUtils.substringBetween("", "", "") = "" * StringUtils.substringBetween("", "", "tag") = null * StringUtils.substringBetween("", "tag", "tag") = null * StringUtils.substringBetween("yabcz", null, null) = null * StringUtils.substringBetween("yabcz", "", "") = "" * StringUtils.substringBetween("yabcz", "y", "z") = "abc" * StringUtils.substringBetween("yabczyabcz", "y", "z") = "abc" * </pre> * * @param str the String containing the substring, may be null * @param open the String before the substring, may be null * @param close the String after the substring, may be null * @return the substring, <code>null</code> if no match * @since 2.0 */ public static String substringBetween(String str, String open, String close) { if (str == null || open == null || close == null) { return null; } int start = str.indexOf(open); if (start != -1) { int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } // Nested extraction /** * <p>Gets the String that is nested in between two instances of the * same String.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> tag returns <code>null</code>.</p> * * <pre> * StringUtils.getNestedString(null, *) = null * StringUtils.getNestedString("", "") = "" * StringUtils.getNestedString("", "tag") = null * StringUtils.getNestedString("tagabctag", null) = null * StringUtils.getNestedString("tagabctag", "") = "" * StringUtils.getNestedString("tagabctag", "tag") = "abc" * </pre> * * @param str the String containing nested-string, may be null * @param tag the String before and after nested-string, may be null * @return the nested String, <code>null</code> if no match * @deprecated Use the better named {@link #substringBetween(String, String)}. * Method will be removed in Commons Lang 3.0. */ public static String getNestedString(String str, String tag) { return substringBetween(str, tag, tag); } /** * <p>Gets the String that is nested in between two Strings. * Only the first match is returned.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> open/close returns <code>null</code> (no match). * An empty ("") open/close returns an empty string.</p> * * <pre> * StringUtils.getNestedString(null, *, *) = null * StringUtils.getNestedString("", "", "") = "" * StringUtils.getNestedString("", "", "tag") = null * StringUtils.getNestedString("", "tag", "tag") = null * StringUtils.getNestedString("yabcz", null, null) = null * StringUtils.getNestedString("yabcz", "", "") = "" * StringUtils.getNestedString("yabcz", "y", "z") = "abc" * StringUtils.getNestedString("yabczyabcz", "y", "z") = "abc" * </pre> * * @param str the String containing nested-string, may be null * @param open the String before nested-string, may be null * @param close the String after nested-string, may be null * @return the nested String, <code>null</code> if no match * @deprecated Use the better named {@link #substringBetween(String, String, String)}. * Method will be removed in Commons Lang 3.0. */ public static String getNestedString(String str, String open, String close) { return substringBetween(str, open, close); } // Splitting /** * <p>Splits the provided text into an array, using whitespace as the * separator. * Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <p>The separator is not included in the returned String array. * Adjacent separators are treated as one separator.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.split(null) = null * StringUtils.split("") = [] * StringUtils.split("abc def") = ["abc", "def"] * StringUtils.split("abc def") = ["abc", "def"] * StringUtils.split(" abc ") = ["abc"] * </pre> * * @param str the String to parse, may be null * @return an array of parsed Strings, <code>null</code> if null String input */ public static String[] split(String str) { return split(str, null, -1); } /** * <p>Splits the provided text into an array, separator specified. * This is an alternative to using StringTokenizer.</p> * * <p>The separator is not included in the returned String array. * Adjacent separators are treated as one separator.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.split(null, *) = null * StringUtils.split("", *) = [] * StringUtils.split("a.b.c", '.') = ["a", "b", "c"] * StringUtils.split("a..b.c", '.') = ["a", "b", "c"] * StringUtils.split("a:b:c", '.') = ["a:b:c"] * StringUtils.split("a\tb\nc", null) = ["a", "b", "c"] * StringUtils.split("a b c", ' ') = ["a", "b", "c"] * </pre> * * @param str the String to parse, may be null * @param separatorChar the character used as the delimiter, * <code>null</code> splits on whitespace * @return an array of parsed Strings, <code>null</code> if null String input * @since 2.0 */ public static String[] split(String str, char separatorChar) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List list = new ArrayList(); int i = 0, start = 0; boolean match = false; while (i < len) { if (str.charAt(i) == separatorChar) { if (match) { list.add(str.substring(start, i)); match = false; } start = ++i; continue; } match = true; i++; } if (match) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } /** * <p>Splits the provided text into an array, separators specified. * This is an alternative to using StringTokenizer.</p> * * <p>The separator is not included in the returned String array. * Adjacent separators are treated as one separator.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> separatorChars splits on whitespace.</p> * * <pre> * StringUtils.split(null, *) = null * StringUtils.split("", *) = [] * StringUtils.split("abc def", null) = ["abc", "def"] * StringUtils.split("abc def", " ") = ["abc", "def"] * StringUtils.split("abc def", " ") = ["abc", "def"] * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"] * </pre> * * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * <code>null</code> splits on whitespace * @return an array of parsed Strings, <code>null</code> if null String input */ public static String[] split(String str, String separatorChars) { return split(str, separatorChars, -1); } /** * <p>Splits the provided text into an array with a maximum length, * separators specified.</p> * * <p>The separator is not included in the returned String array. * Adjacent separators are treated as one separator.</p> * * <p>A <code>null</code> input String returns <code>null</code>. * A <code>null</code> separatorChars splits on whitespace.</p> * * <p>If more than <code>max</code> delimited substrings are found, the last * returned string includes all characters after the first <code>max - 1</code> * returned strings (including separator characters).</p> * * <pre> * StringUtils.split(null, *, *) = null * StringUtils.split("", *, *) = [] * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"] * StringUtils.split("ab de fg", null, 0) = ["ab", "cd", "ef"] * StringUtils.split("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] * StringUtils.split("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] * </pre> * * @param str the String to parse, may be null * @param separatorChars the characters used as the delimiters, * <code>null</code> splits on whitespace * @param max the maximum number of elements to include in the * array. A zero or negative value implies no limit * @return an array of parsed Strings, <code>null</code> if null String input */ public static String[] split(String str, String separatorChars, int max) { // Performance tuned for 2.0 (JDK1.4) // Direct code is quicker than StringTokenizer. // Also, StringTokenizer uses isSpace() not isWhitespace() if (str == null) { return null; } int len = str.length(); if (len == 0) { return ArrayUtils.EMPTY_STRING_ARRAY; } List list = new ArrayList(); int sizePlus1 = 1; int i = 0, start = 0; boolean match = false; if (separatorChars == null) { // Null separator means use whitespace while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match) { if (sizePlus1++ == max) { i = len; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } match = true; i++; } } else if (separatorChars.length() == 1) { // Optimise 1 character case char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match) { if (sizePlus1++ == max) { i = len; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } match = true; i++; } } else { // standard case while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) { if (match) { if (sizePlus1++ == max) { i = len; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } match = true; i++; } } if (match) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } // Joining /** * <p>Concatenates elements of an array into a single String. * Null objects or empty strings within the array are represented by * empty strings.</p> * * <pre> * StringUtils.concatenate(null) = null * StringUtils.concatenate([]) = "" * StringUtils.concatenate([null]) = "" * StringUtils.concatenate(["a", "b", "c"]) = "abc" * StringUtils.concatenate([null, "", "a"]) = "a" * </pre> * * @param array the array of values to concatenate, may be null * @return the concatenated String, <code>null</code> if null array input * @deprecated Use the better named {@link #join(Object[])} instead. * Method will be removed in Commons Lang 3.0. */ public static String concatenate(Object[] array) { return join(array, null); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No separator is added to the joined String. * Null objects or empty strings within the array are represented by * empty strings.</p> * * <pre> * StringUtils.join(null) = null * StringUtils.join([]) = "" * StringUtils.join([null]) = "" * StringUtils.join(["a", "b", "c"]) = "abc" * StringUtils.join([null, "", "a"]) = "a" * </pre> * * @param array the array of values to join together, may be null * @return the joined String, <code>null</code> if null array input * @since 2.0 */ public static String join(Object[] array) { return join(array, null); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.</p> * * <pre> * StringUtils.join(null, *) = null * StringUtils.join([], *) = "" * StringUtils.join([null], *) = "" * StringUtils.join(["a", "b", "c"], ';') = "a;b;c" * StringUtils.join(["a", "b", "c"], null) = "abc" * StringUtils.join([null, "", "a"], ';') = ";;a" * </pre> * * @param array the array of values to join together, may be null * @param separator the separator character to use * @return the joined String, <code>null</code> if null array input * @since 2.0 */ public static String join(Object[] array, char separator) { if (array == null) { return null; } int arraySize = array.length; int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize); StringBuffer buf = new StringBuffer(bufSize); for (int i = 0; i < arraySize; i++) { if (i > 0) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. * A <code>null</code> separator is the same as an empty String (""). * Null objects or empty strings within the array are represented by * empty strings.</p> * * <pre> * StringUtils.join(null, *) = null * StringUtils.join([], *) = "" * StringUtils.join([null], *) = "" * StringUtils.join(["a", "b", "c"], "--") = "a--b--c" * StringUtils.join(["a", "b", "c"], null) = "abc" * StringUtils.join(["a", "b", "c"], "") = "abc" * StringUtils.join([null, "", "a"], ',') = ",,a" * </pre> * * @param array the array of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, <code>null</code> if null array input */ public static String join(Object[] array, String separator) { if (array == null) { return null; } if (separator == null) { separator = EMPTY; } int arraySize = array.length; // ArraySize == 0: Len = 0 // ArraySize > 0: Len = NofStrings *(len(firstString) + len(separator)) // (Assuming that all Strings are roughly equally long) int bufSize = ((arraySize == 0) ? 0 : arraySize * ((array[0] == null ? 16 : array[0].toString().length()) + ((separator != null) ? separator.length() : 0))); StringBuffer buf = new StringBuffer(bufSize); for (int i = 0; i < arraySize; i++) { if ((separator != null) && (i > 0)) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. Null objects or empty * strings within the iteration are represented by empty strings.</p> * * <p>See the examples here: {@link #join(Object[],char)}. </p> * * @param iterator the <code>Iterator</code> of values to join together, may be null * @param separator the separator character to use * @return the joined String, <code>null</code> if null iterator input * @since 2.0 */ public static String join(Iterator iterator, char separator) { if (iterator == null) { return null; } StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small while (iterator.hasNext()) { Object obj = iterator.next(); if (obj != null) { buf.append(obj); } if (iterator.hasNext()) { buf.append(separator); } } return buf.toString(); } /** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. * A <code>null</code> separator is the same as an empty String ("").</p> * * <p>See the examples here: {@link #join(Object[],String)}. </p> * * @param iterator the <code>Iterator</code> of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, <code>null</code> if null iterator input */ public static String join(Iterator iterator, String separator) { if (iterator == null) { return null; } StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small while (iterator.hasNext()) { Object obj = iterator.next(); if (obj != null) { buf.append(obj); } if ((separator != null) && iterator.hasNext()) { buf.append(separator); } } return buf.toString(); } // Delete /** * <p>Deletes all 'space' characters from a String as defined by * {@link Character#isSpace(char)}.</p> * * <p>This is the only StringUtils method that uses the * <code>isSpace</code> definition. You are advised to use * {@link #deleteWhitespace(String)} instead as whitespace is much * better localized.</p> * * <pre> * StringUtils.deleteSpaces(null) = null * StringUtils.deleteSpaces("") = "" * StringUtils.deleteSpaces("abc") = "abc" * StringUtils.deleteSpaces(" \t abc \n ") = "abc" * StringUtils.deleteSpaces("ab c") = "abc" * StringUtils.deleteSpaces("a\nb\tc ") = "abc" * </pre> * * <p>Spaces are defined as <code>{' ', '\t', '\r', '\n', '\b'}</code> * in line with the deprecated <code>isSpace</code> method.</p> * * @param str the String to delete spaces from, may be null * @return the String without 'spaces', <code>null</code> if null String input * @deprecated Use the better localized {@link #deleteWhitespace(String)}. * Method will be removed in Commons Lang 3.0. */ public static String deleteSpaces(String str) { if (str == null) { return null; } return CharSetUtils.delete(str, " \t\r\n\b"); } /** * <p>Deletes all whitespaces from a String as defined by * {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.deleteWhitespace(null) = null * StringUtils.deleteWhitespace("") = "" * StringUtils.deleteWhitespace("abc") = "abc" * StringUtils.deleteWhitespace(" ab c ") = "abc" * </pre> * * @param str the String to delete whitespace from, may be null * @return the String without whitespaces, <code>null</code> if null String input */ public static String deleteWhitespace(String str) { if (str == null || str.length() == 0) { return str; } int sz = str.length(); char[] chs = new char[sz]; int count = 0; for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { chs[count++] = str.charAt(i); } } if (count == sz) { return str; } return new String(chs, 0, count); } // Remove public static String removeStart(String str, String remove) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) { return str; } if (str.startsWith(remove)){ return str.substring(remove.length()); } return str; } public static String removeEnd(String str, String remove) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - remove.length()); } return str; } // Replacing /** * <p>Replaces a String with another String inside a larger String, once.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replaceOnce(null, *, *) = null * StringUtils.replaceOnce("", *, *) = "" * StringUtils.replaceOnce("any", null, *) = "any" * StringUtils.replaceOnce("any", *, null) = "any" * StringUtils.replaceOnce("any", "", *) = "any" * StringUtils.replaceOnce("aba", "a", null) = "aba" * StringUtils.replaceOnce("aba", "a", "") = "ba" * StringUtils.replaceOnce("aba", "a", "z") = "zba" * </pre> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @return the text with any replacements processed, * <code>null</code> if null String input */ public static String replaceOnce(String text, String repl, String with) { return replace(text, repl, with, 1); } /** * <p>Replaces all occurrences of a String within another String.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *) = null * StringUtils.replace("", *, *) = "" * StringUtils.replace("any", null, *) = "any" * StringUtils.replace("any", *, null) = "any" * StringUtils.replace("any", "", *) = "any" * StringUtils.replace("aba", "a", null) = "aba" * StringUtils.replace("aba", "a", "") = "b" * StringUtils.replace("aba", "a", "z") = "zbz" * </pre> * * @see #replace(String text, String repl, String with, int max) * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @return the text with any replacements processed, * <code>null</code> if null String input */ public static String replace(String text, String repl, String with) { return replace(text, repl, with, -1); } /** * <p>Replaces a String with another String inside a larger String, * for the first <code>max</code> values of the search String.</p> * * <p>A <code>null</code> reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *, *) = null * StringUtils.replace("", *, *, *) = "" * StringUtils.replace("any", null, *, *) = "any" * StringUtils.replace("any", *, null, *) = "any" * StringUtils.replace("any", "", *, *) = "any" * StringUtils.replace("any", *, *, 0) = "any" * StringUtils.replace("abaa", "a", null, -1) = "abaa" * StringUtils.replace("abaa", "a", "", -1) = "b" * StringUtils.replace("abaa", "a", "z", 0) = "abaa" * StringUtils.replace("abaa", "a", "z", 1) = "zbaa" * StringUtils.replace("abaa", "a", "z", 2) = "zbza" * StringUtils.replace("abaa", "a", "z", -1) = "zbzz" * </pre> * * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @param max maximum number of values to replace, or <code>-1</code> if no maximum * @return the text with any replacements processed, * <code>null</code> if null String input */ public static String replace(String text, String repl, String with, int max) { if (text == null || repl == null || with == null || repl.length() == 0 || max == 0) { return text; } StringBuffer buf = new StringBuffer(text.length()); int start = 0, end = 0; while ((end = text.indexOf(repl, start)) != -1) { buf.append(text.substring(start, end)).append(with); start = end + repl.length(); if (--max == 0) { break; } } buf.append(text.substring(start)); return buf.toString(); } // Replace, character based /** * <p>Replaces all occurrences of a character in a String with another. * This is a null-safe version of {@link String#replace(char, char)}.</p> * * <p>A <code>null</code> string input returns <code>null</code>. * An empty ("") string input returns an empty string.</p> * * <pre> * StringUtils.replaceChars(null, *, *) = null * StringUtils.replaceChars("", *, *) = "" * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya" * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba" * </pre> * * @param str String to replace characters in, may be null * @param searchChar the character to search for, may be null * @param replaceChar the character to replace, may be null * @return modified String, <code>null</code> if null string input * @since 2.0 */ public static String replaceChars(String str, char searchChar, char replaceChar) { if (str == null) { return null; } return str.replace(searchChar, replaceChar); } /** * <p>Replaces multiple characters in a String in one go. * This method can also be used to delete characters.</p> * * <p>For example:<br /> * <code>replaceChars(&quot;hello&quot;, &quot;ho&quot;, &quot;jy&quot;) = jelly</code>.</p> * * <p>A <code>null</code> string input returns <code>null</code>. * An empty ("") string input returns an empty string. * A null or empty set of search characters returns the input string.</p> * * <p>The length of the search characters should normally equal the length * of the replace characters. * If the search characters is longer, then the extra search characters * are deleted. * If the search characters is shorter, then the extra replace characters * are ignored.</p> * * <pre> * StringUtils.replaceChars(null, *, *) = null * StringUtils.replaceChars("", *, *) = "" * StringUtils.replaceChars("abc", null, *) = "abc" * StringUtils.replaceChars("abc", "", *) = "abc" * StringUtils.replaceChars("abc", "b", null) = "ac" * StringUtils.replaceChars("abc", "b", "") = "ac" * StringUtils.replaceChars("abcba", "bc", "yz") = "ayzya" * StringUtils.replaceChars("abcba", "bc", "y") = "ayya" * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya" * </pre> * * @param str String to replace characters in, may be null * @param searchChars a set of characters to search for, may be null * @param replaceChars a set of characters to replace, may be null * @return modified String, <code>null</code> if null string input * @since 2.0 */ public static String replaceChars(String str, String searchChars, String replaceChars) { if (StringUtils.isEmpty(str) || StringUtils.isEmpty(searchChars)) { return str; } if (replaceChars == null) { replaceChars = ""; } StringBuffer buffer = new StringBuffer(str.length()); for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); int index = searchChars.indexOf(ch); if (index >= 0) { if (index < replaceChars.length()) { buffer.append(replaceChars.charAt(index)); } } else { buffer.append(ch); } } return buffer.toString(); } // Overlay /** * <p>Overlays part of a String with another String.</p> * * <pre> * StringUtils.overlayString(null, *, *, *) = NullPointerException * StringUtils.overlayString(*, null, *, *) = NullPointerException * StringUtils.overlayString("", "abc", 0, 0) = "abc" * StringUtils.overlayString("abcdef", null, 2, 4) = "abef" * StringUtils.overlayString("abcdef", "", 2, 4) = "abef" * StringUtils.overlayString("abcdef", "zzzz", 2, 4) = "abzzzzef" * StringUtils.overlayString("abcdef", "zzzz", 4, 2) = "abcdzzzzcdef" * StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException * StringUtils.overlayString("abcdef", "zzzz", 2, 8) = IndexOutOfBoundsException * </pre> * * @param text the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at, must be valid * @param end the position to stop overlaying before, must be valid * @return overlayed String, <code>null</code> if null String input * @throws NullPointerException if text or overlay is null * @throws IndexOutOfBoundsException if either position is invalid * @deprecated Use better named {@link #overlay(String, String, int, int)} instead. * Method will be removed in Commons Lang 3.0. */ public static String overlayString(String text, String overlay, int start, int end) { return new StringBuffer(start + overlay.length() + text.length() - end + 1) .append(text.substring(0, start)) .append(overlay) .append(text.substring(end)) .toString(); } /** * <p>Overlays part of a String with another String.</p> * * <p>A <code>null</code> string input returns <code>null</code>. * A negative index is treated as zero. * An index greater than the string length is treated as the string length. * The start index is always the smaller of the two indices.</p> * * <pre> * StringUtils.overlay(null, *, *, *) = null * StringUtils.overlay("", "abc", 0, 0) = "abc" * StringUtils.overlay("abcdef", null, 2, 4) = "abef" * StringUtils.overlay("abcdef", "", 2, 4) = "abef" * StringUtils.overlay("abcdef", "", 4, 2) = "abef" * StringUtils.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef" * StringUtils.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef" * StringUtils.overlay("abcdef", "zzzz", -1, 4) = "zzzzef" * StringUtils.overlay("abcdef", "zzzz", 2, 8) = "abzzzz" * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef" * StringUtils.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz" * </pre> * * @param str the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at * @param end the position to stop overlaying before * @return overlayed String, <code>null</code> if null String input * @since 2.0 */ public static String overlay(String str, String overlay, int start, int end) { if (str == null) { return null; } if (overlay == null) { overlay = EMPTY; } int len = str.length(); if (start < 0) { start = 0; } if (start > len) { start = len; } if (end < 0) { end = 0; } if (end > len) { end = len; } if (start > end) { int temp = start; start = end; end = temp; } return new StringBuffer(len + start - end + overlay.length() + 1) .append(str.substring(0, start)) .append(overlay) .append(str.substring(end)) .toString(); } // Chomping /** * <p>Removes one newline from end of a String if it's there, * otherwise leave it alone. A newline is &quot;<code>\n</code>&quot;, * &quot;<code>\r</code>&quot;, or &quot;<code>\r\n</code>&quot;.</p> * * <p>NOTE: This method changed in 2.0. * It now more closely matches Perl chomp.</p> * * <pre> * StringUtils.chomp(null) = null * StringUtils.chomp("") = "" * StringUtils.chomp("abc \r") = "abc " * StringUtils.chomp("abc\n") = "abc" * StringUtils.chomp("abc\r\n") = "abc" * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n" * StringUtils.chomp("abc\n\r") = "abc\n" * StringUtils.chomp("abc\n\rabc") = "abc\n\rabc" * StringUtils.chomp("\r") = "" * StringUtils.chomp("\n") = "" * StringUtils.chomp("\r\n") = "" * </pre> * * @param str the String to chomp a newline from, may be null * @return String without newline, <code>null</code> if null String input */ public static String chomp(String str) { if (str == null || str.length() == 0) { return str; } if (str.length() == 1) { char ch = str.charAt(0); if (ch == '\r' || ch == '\n') { return EMPTY; } else { return str; } } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); if (last == '\n') { if (str.charAt(lastIdx - 1) == '\r') { lastIdx } } else if (last == '\r') { // why is this block empty? // just to skip incrementing the index? } else { lastIdx++; } return str.substring(0, lastIdx); } /** * <p>Removes <code>separator</code> from the end of * <code>str</code> if it's there, otherwise leave it alone.</p> * * <p>NOTE: This method changed in version 2.0. * It now more closely matches Perl chomp. * For the previous behavior, use {@link #substringBeforeLast(String, String)}. * This method uses {@link String#endsWith(String)}.</p> * * <pre> * StringUtils.chomp(null, *) = null * StringUtils.chomp("", *) = "" * StringUtils.chomp("foobar", "bar") = "foo" * StringUtils.chomp("foobar", "baz") = "foobar" * StringUtils.chomp("foo", "foo") = "" * StringUtils.chomp("foo ", "foo") = "foo" * StringUtils.chomp(" foo", "foo") = " " * StringUtils.chomp("foo", "foooo") = "foo" * StringUtils.chomp("foo", "") = "foo" * StringUtils.chomp("foo", null) = "foo" * </pre> * * @param str the String to chomp from, may be null * @param separator separator String, may be null * @return String without trailing separator, <code>null</code> if null String input */ public static String chomp(String str, String separator) { if (str == null || str.length() == 0 || separator == null) { return str; } if (str.endsWith(separator)) { return str.substring(0, str.length() - separator.length()); } return str; } /** * <p>Remove any &quot;\n&quot; if and only if it is at the end * of the supplied String.</p> * * @param str the String to chomp from, must not be null * @return String without chomped ending * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str) { return chompLast(str, "\n"); } /** * <p>Remove a value if and only if the String ends with that value.</p> * * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String without chomped ending * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #chomp(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chompLast(String str, String sep) { if (str.length() == 0) { return str; } String sub = str.substring(str.length() - sep.length()); if (sep.equals(sub)) { return str.substring(0, str.length() - sep.length()); } else { return str; } } /** * <p>Remove everything and return the last value of a supplied String, and * everything after it from a String.</p> * * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String chomped * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #substringAfterLast(String, String)} instead * (although this doesn't include the separator) * Method will be removed in Commons Lang 3.0. */ public static String getChomp(String str, String sep) { int idx = str.lastIndexOf(sep); if (idx == str.length() - sep.length()) { return sep; } else if (idx != -1) { return str.substring(idx); } else { return EMPTY; } } /** * <p>Remove the first value of a supplied String, and everything before it * from a String.</p> * * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String without chomped beginning * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #substringAfter(String,String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String prechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(idx + sep.length()); } else { return str; } } /** * <p>Remove and return everything before the first value of a * supplied String from another String.</p> * * @param str the String to chomp from, must not be null * @param sep the String to chomp, must not be null * @return String prechomped * @throws NullPointerException if str or sep is <code>null</code> * @deprecated Use {@link #substringBefore(String,String)} instead * (although this doesn't include the separator). * Method will be removed in Commons Lang 3.0. */ public static String getPrechomp(String str, String sep) { int idx = str.indexOf(sep); if (idx != -1) { return str.substring(0, idx + sep.length()); } else { return EMPTY; } } // Chopping /** * <p>Remove the last character from a String.</p> * * <p>If the String ends in <code>\r\n</code>, then remove both * of them.</p> * * <pre> * StringUtils.chop(null) = null * StringUtils.chop("") = "" * StringUtils.chop("abc \r") = "abc " * StringUtils.chop("abc\n") = "abc" * StringUtils.chop("abc\r\n") = "abc" * StringUtils.chop("abc") = "ab" * StringUtils.chop("abc\nabc") = "abc\nab" * StringUtils.chop("a") = "" * StringUtils.chop("\r") = "" * StringUtils.chop("\n") = "" * StringUtils.chop("\r\n") = "" * </pre> * * @param str the String to chop last character from, may be null * @return String without last character, <code>null</code> if null String input */ public static String chop(String str) { if (str == null) { return null; } int strLen = str.length(); if (strLen < 2) { return EMPTY; } int lastIdx = strLen - 1; String ret = str.substring(0, lastIdx); char last = str.charAt(lastIdx); if (last == '\n') { if (ret.charAt(lastIdx - 1) == '\r') { return ret.substring(0, lastIdx - 1); } } return ret; } /** * <p>Removes <code>\n</code> from end of a String if it's there. * If a <code>\r</code> precedes it, then remove that too.</p> * * @param str the String to chop a newline from, must not be null * @return String without newline * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link #chomp(String)} instead. * Method will be removed in Commons Lang 3.0. */ public static String chopNewline(String str) { int lastIdx = str.length() - 1; if (lastIdx <= 0) { return EMPTY; } char last = str.charAt(lastIdx); if (last == '\n') { if (str.charAt(lastIdx - 1) == '\r') { lastIdx } } else { lastIdx++; } return str.substring(0, lastIdx); } // Conversion /** * <p>Escapes any values it finds into their String form.</p> * * <p>So a tab becomes the characters <code>'\\'</code> and * <code>'t'</code>.</p> * * <p>As of Lang 2.0, this calls {@link StringEscapeUtils#escapeJava(String)} * behind the scenes. * </p> * @see StringEscapeUtils#escapeJava(java.lang.String) * @param str String to escape values in * @return String with escaped values * @throws NullPointerException if str is <code>null</code> * @deprecated Use {@link StringEscapeUtils#escapeJava(String)} * This method will be removed in Commons Lang 3.0 */ public static String escape(String str) { return StringEscapeUtils.escapeJava(str); } // Padding /** * <p>Repeat a String <code>repeat</code> times to form a * new String.</p> * * <pre> * StringUtils.repeat(null, 2) = null * StringUtils.repeat("", 0) = "" * StringUtils.repeat("", 2) = "" * StringUtils.repeat("a", 3) = "aaa" * StringUtils.repeat("ab", 2) = "abab" * StringUtils.repeat("a", -2) = "" * </pre> * * @param str the String to repeat, may be null * @param repeat number of times to repeat str, negative treated as zero * @return a new String consisting of the original String repeated, * <code>null</code> if null String input */ public static String repeat(String str, int repeat) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } if (repeat <= 0) { return EMPTY; } int inputLength = str.length(); if (repeat == 1 || inputLength == 0) { return str; } if (inputLength == 1 && repeat <= PAD_LIMIT) { return padding(repeat, str.charAt(0)); } int outputLength = inputLength * repeat; switch (inputLength) { case 1 : char ch = str.charAt(0); char[] output1 = new char[outputLength]; for (int i = repeat - 1; i >= 0; i output1[i] = ch; } return new String(output1); case 2 : char ch0 = str.charAt(0); char ch1 = str.charAt(1); char[] output2 = new char[outputLength]; for (int i = repeat * 2 - 2; i >= 0; i output2[i] = ch0; output2[i + 1] = ch1; } return new String(output2); default : StringBuffer buf = new StringBuffer(outputLength); for (int i = 0; i < repeat; i++) { buf.append(str); } return buf.toString(); } } /** * <p>Returns padding using the specified delimiter repeated * to a given length.</p> * * <pre> * StringUtils.padding(0, 'e') = "" * StringUtils.padding(3, 'e') = "eee" * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException * </pre> * * @param repeat number of times to repeat delim * @param padChar character to repeat * @return String with repeated character * @throws IndexOutOfBoundsException if <code>repeat &lt; 0</code> */ private static String padding(int repeat, char padChar) { // be careful of synchronization in this method // we are assuming that get and set from an array index is atomic String pad = PADDING[padChar]; if (pad == null) { pad = String.valueOf(padChar); } while (pad.length() < repeat) { pad = pad.concat(pad); } PADDING[padChar] = pad; return pad.substring(0, repeat); } /** * <p>Right pad a String with spaces (' ').</p> * * <p>The String is padded to the size of <code>size</code>.</p> * * <pre> * StringUtils.rightPad(null, *) = null * StringUtils.rightPad("", 3) = " " * StringUtils.rightPad("bat", 3) = "bat" * StringUtils.rightPad("bat", 5) = "bat " * StringUtils.rightPad("bat", 1) = "bat" * StringUtils.rightPad("bat", -1) = "bat" * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @return right padded String or original String if no padding is necessary, * <code>null</code> if null String input */ public static String rightPad(String str, int size) { return rightPad(str, size, ' '); } /** * <p>Right pad a String with a specified character.</p> * * <p>The String is padded to the size of <code>size</code>.</p> * * <pre> * StringUtils.rightPad(null, *, *) = null * StringUtils.rightPad("", 3, 'z') = "zzz" * StringUtils.rightPad("bat", 3, 'z') = "bat" * StringUtils.rightPad("bat", 5, 'z') = "batzz" * StringUtils.rightPad("bat", 1, 'z') = "bat" * StringUtils.rightPad("bat", -1, 'z') = "bat" * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @param padChar the character to pad with * @return right padded String or original String if no padding is necessary, * <code>null</code> if null String input * @since 2.0 */ public static String rightPad(String str, int size, char padChar) { if (str == null) { return null; } int pads = size - str.length(); if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return rightPad(str, size, String.valueOf(padChar)); } return str.concat(padding(pads, padChar)); } /** * <p>Right pad a String with a specified String.</p> * * <p>The String is padded to the size of <code>size</code>.</p> * * <pre> * StringUtils.rightPad(null, *, *) = null * StringUtils.rightPad("", 3, "z") = "zzz" * StringUtils.rightPad("bat", 3, "yz") = "bat" * StringUtils.rightPad("bat", 5, "yz") = "batyz" * StringUtils.rightPad("bat", 8, "yz") = "batyzyzy" * StringUtils.rightPad("bat", 1, "yz") = "bat" * StringUtils.rightPad("bat", -1, "yz") = "bat" * StringUtils.rightPad("bat", 5, null) = "bat " * StringUtils.rightPad("bat", 5, "") = "bat " * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return right padded String or original String if no padding is necessary, * <code>null</code> if null String input */ public static String rightPad(String str, int size, String padStr) { if (str == null) { return null; } if (padStr == null || padStr.length() == 0) { padStr = " "; } int padLen = padStr.length(); int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return rightPad(str, size, padStr.charAt(0)); } if (pads == padLen) { return str.concat(padStr); } else if (pads < padLen) { return str.concat(padStr.substring(0, pads)); } else { char[] padding = new char[pads]; char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return str.concat(new String(padding)); } } /** * <p>Left pad a String with spaces (' ').</p> * * <p>The String is padded to the size of <code>size<code>.</p> * * <pre> * StringUtils.leftPad(null, *) = null * StringUtils.leftPad("", 3) = " " * StringUtils.leftPad("bat", 3) = "bat" * StringUtils.leftPad("bat", 5) = " bat" * StringUtils.leftPad("bat", 1) = "bat" * StringUtils.leftPad("bat", -1) = "bat" * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @return left padded String or original String if no padding is necessary, * <code>null</code> if null String input */ public static String leftPad(String str, int size) { return leftPad(str, size, ' '); } /** * <p>Left pad a String with a specified character.</p> * * <p>Pad to a size of <code>size</code>.</p> * * <pre> * StringUtils.leftPad(null, *, *) = null * StringUtils.leftPad("", 3, 'z') = "zzz" * StringUtils.leftPad("bat", 3, 'z') = "bat" * StringUtils.leftPad("bat", 5, 'z') = "zzbat" * StringUtils.leftPad("bat", 1, 'z') = "bat" * StringUtils.leftPad("bat", -1, 'z') = "bat" * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @param padChar the character to pad with * @return left padded String or original String if no padding is necessary, * <code>null</code> if null String input * @since 2.0 */ public static String leftPad(String str, int size, char padChar) { if (str == null) { return null; } int pads = size - str.length(); if (pads <= 0) { return str; // returns original String when possible } if (pads > PAD_LIMIT) { return leftPad(str, size, String.valueOf(padChar)); } return padding(pads, padChar).concat(str); } /** * <p>Left pad a String with a specified String.</p> * * <p>Pad to a size of <code>size</code>.</p> * * <pre> * StringUtils.leftPad(null, *, *) = null * StringUtils.leftPad("", 3, "z") = "zzz" * StringUtils.leftPad("bat", 3, "yz") = "bat" * StringUtils.leftPad("bat", 5, "yz") = "yzbat" * StringUtils.leftPad("bat", 8, "yz") = "yzyzybat" * StringUtils.leftPad("bat", 1, "yz") = "bat" * StringUtils.leftPad("bat", -1, "yz") = "bat" * StringUtils.leftPad("bat", 5, null) = " bat" * StringUtils.leftPad("bat", 5, "") = " bat" * </pre> * * @param str the String to pad out, may be null * @param size the size to pad to * @param padStr the String to pad with, null or empty treated as single space * @return left padded String or original String if no padding is necessary, * <code>null</code> if null String input */ public static String leftPad(String str, int size, String padStr) { if (str == null) { return null; } if (padStr == null || padStr.length() == 0) { padStr = " "; } int padLen = padStr.length(); int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; // returns original String when possible } if (padLen == 1 && pads <= PAD_LIMIT) { return leftPad(str, size, padStr.charAt(0)); } if (pads == padLen) { return padStr.concat(str); } else if (pads < padLen) { return padStr.substring(0, pads).concat(str); } else { char[] padding = new char[pads]; char[] padChars = padStr.toCharArray(); for (int i = 0; i < pads; i++) { padding[i] = padChars[i % padLen]; } return new String(padding).concat(str); } } // Centering /** * <p>Centers a String in a larger String of size <code>size</code> * using the space character (' ').<p> * * <p>If the size is less than the String length, the String is returned. * A <code>null</code> String returns <code>null</code>. * A negative size is treated as zero.</p> * * <p>Equivalent to <code>center(str, size, " ")</code>.</p> * * <pre> * StringUtils.center(null, *) = null * StringUtils.center("", 4) = " " * StringUtils.center("ab", -1) = "ab" * StringUtils.center("ab", 4) = " ab " * StringUtils.center("abcd", 2) = "abcd" * StringUtils.center("a", 4) = " a " * </pre> * * @param str the String to center, may be null * @param size the int size of new String, negative treated as zero * @return centered String, <code>null</code> if null String input */ public static String center(String str, int size) { return center(str, size, ' '); } /** * <p>Centers a String in a larger String of size <code>size</code>. * Uses a supplied character as the value to pad the String with.</p> * * <p>If the size is less than the String length, the String is returned. * A <code>null</code> String returns <code>null</code>. * A negative size is treated as zero.</p> * * <pre> * StringUtils.center(null, *, *) = null * StringUtils.center("", 4, ' ') = " " * StringUtils.center("ab", -1, ' ') = "ab" * StringUtils.center("ab", 4, ' ') = " ab" * StringUtils.center("abcd", 2, ' ') = "abcd" * StringUtils.center("a", 4, ' ') = " a " * StringUtils.center("a", 4, 'y') = "yayy" * </pre> * * @param str the String to center, may be null * @param size the int size of new String, negative treated as zero * @param padChar the character to pad the new String with * @return centered String, <code>null</code> if null String input * @since 2.0 */ public static String center(String str, int size, char padChar) { if (str == null || size <= 0) { return str; } int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padChar); str = rightPad(str, size, padChar); return str; } public static String center(String str, int size, String padStr) { if (str == null || size <= 0) { return str; } if (padStr == null || padStr.length() == 0) { padStr = " "; } int strLen = str.length(); int pads = size - strLen; if (pads <= 0) { return str; } str = leftPad(str, strLen + pads / 2, padStr); str = rightPad(str, size, padStr); return str; } // Case conversion /** * <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.upperCase(null) = null * StringUtils.upperCase("") = "" * StringUtils.upperCase("aBc") = "ABC" * </pre> * * @param str the String to upper case, may be null * @return the upper cased String, <code>null</code> if null String input */ public static String upperCase(String str) { if (str == null) { return null; } return str.toUpperCase(); } /** * <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p> * * <p>A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.lowerCase(null) = null * StringUtils.lowerCase("") = "" * StringUtils.lowerCase("aBc") = "abc" * </pre> * * @param str the String to lower case, may be null * @return the lower cased String, <code>null</code> if null String input */ public static String lowerCase(String str) { if (str == null) { return null; } return str.toLowerCase(); } /** * <p>Capitalizes a String changing the first letter to title case as * per {@link Character#toTitleCase(char)}. No other letters are changed.</p> * * <p>For a word based algorithm, see {@link WordUtils#capitalize(String)}. * A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.capitalize(null) = null * StringUtils.capitalize("") = "" * StringUtils.capitalize("cat") = "Cat" * StringUtils.capitalize("cAt") = "CAt" * </pre> * * @param str the String to capitalize, may be null * @return the capitalized String, <code>null</code> if null String input * @see WordUtils#capitalize(String) * @see #uncapitalize(String) * @since 2.0 */ public static String capitalize(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } return new StringBuffer(strLen) .append(Character.toTitleCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** * <p>Capitalizes a String changing the first letter to title case as * per {@link Character#toTitleCase(char)}. No other letters are changed.</p> * * @param str the String to capitalize, may be null * @return the capitalized String, <code>null</code> if null String input * @deprecated Use the standardly named {@link #capitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String capitalise(String str) { return capitalize(str); } /** * <p>Uncapitalizes a String changing the first letter to title case as * per {@link Character#toLowerCase(char)}. No other letters are changed.</p> * * <p>For a word based algorithm, see {@link WordUtils#uncapitalize(String)}. * A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.uncapitalize(null) = null * StringUtils.uncapitalize("") = "" * StringUtils.uncapitalize("Cat") = "cat" * StringUtils.uncapitalize("CAT") = "cAT" * </pre> * * @param str the String to uncapitalize, may be null * @return the uncapitalized String, <code>null</code> if null String input * @see WordUtils#uncapitalize(String) * @see #capitalize(String) * @since 2.0 */ public static String uncapitalize(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } return new StringBuffer(strLen) .append(Character.toLowerCase(str.charAt(0))) .append(str.substring(1)) .toString(); } /** * <p>Uncapitalizes a String changing the first letter to title case as * per {@link Character#toLowerCase(char)}. No other letters are changed.</p> * * @param str the String to uncapitalize, may be null * @return the uncapitalized String, <code>null</code> if null String input * @deprecated Use the standardly named {@link #uncapitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String uncapitalise(String str) { return uncapitalize(str); } /** * <p>Swaps the case of a String changing upper and title case to * lower case, and lower case to upper case.</p> * * <ul> * <li>Upper case character converts to Lower case</li> * <li>Title case character converts to Lower case</li> * <li>Lower case character converts to Upper case</li> * </ul> * * <p>For a word based algorithm, see {@link WordUtils#swapCase(String)}. * A <code>null</code> input String returns <code>null</code>.</p> * * <pre> * StringUtils.swapCase(null) = null * StringUtils.swapCase("") = "" * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone" * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer performs a word based algorithm. * If you only use ASCII, you will notice no change. * That functionality is available in WordUtils.</p> * * @param str the String to swap case, may be null * @return the changed String, <code>null</code> if null String input */ public static String swapCase(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } StringBuffer buffer = new StringBuffer(strLen); char ch = 0; for (int i = 0; i < strLen; i++) { ch = str.charAt(i); if (Character.isUpperCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { ch = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { ch = Character.toUpperCase(ch); } buffer.append(ch); } return buffer.toString(); } /** * <p>Capitalizes all the whitespace separated words in a String. * Only the first letter of each word is changed.</p> * * <p>Whitespace is defined by {@link Character#isWhitespace(char)}. * A <code>null</code> input String returns <code>null</code>.</p> * * @param str the String to capitalize, may be null * @return capitalized String, <code>null</code> if null String input * @deprecated Use the relocated {@link WordUtils#capitalize(String)}. * Method will be removed in Commons Lang 3.0. */ public static String capitaliseAllWords(String str) { return WordUtils.capitalize(str); } // Count matches /** * <p>Counts how many times the substring appears in the larger String.</p> * * <p>A <code>null</code> or empty ("") String input returns <code>0</code>.</p> * * <pre> * StringUtils.countMatches(null, *) = 0 * StringUtils.countMatches("", *) = 0 * StringUtils.countMatches("abba", null) = 0 * StringUtils.countMatches("abba", "") = 0 * StringUtils.countMatches("abba", "a") = 2 * StringUtils.countMatches("abba", "ab") = 1 * StringUtils.countMatches("abba", "xxx") = 0 * </pre> * * @param str the String to check, may be null * @param sub the substring to count, may be null * @return the number of occurrences, 0 if either String is <code>null</code> */ public static int countMatches(String str, String sub) { if (str == null || str.length() == 0 || sub == null || sub.length() == 0) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != -1) { count++; idx += sub.length(); } return count; } // Character Tests /** * <p>Checks if the String contains only unicode letters.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isAlpha(null) = false * StringUtils.isAlpha("") = true * StringUtils.isAlpha(" ") = false * StringUtils.isAlpha("abc") = true * StringUtils.isAlpha("ab2c") = false * StringUtils.isAlpha("ab-c") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains letters, and is non-null */ public static boolean isAlpha(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetter(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters and * space (' ').</p> * * <p><code>null</code> will return <code>false</code> * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isAlphaSpace(null) = false * StringUtils.isAlphaSpace("") = true * StringUtils.isAlphaSpace(" ") = true * StringUtils.isAlphaSpace("abc") = true * StringUtils.isAlphaSpace("ab c") = true * StringUtils.isAlphaSpace("ab2c") = false * StringUtils.isAlphaSpace("ab-c") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains letters and space, * and is non-null */ public static boolean isAlphaSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetter(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters or digits.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isAlphanumeric(null) = false * StringUtils.isAlphanumeric("") = true * StringUtils.isAlphanumeric(" ") = false * StringUtils.isAlphanumeric("abc") = true * StringUtils.isAlphanumeric("ab c") = false * StringUtils.isAlphanumeric("ab2c") = true * StringUtils.isAlphanumeric("ab-c") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains letters or digits, * and is non-null */ public static boolean isAlphanumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isLetterOrDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode letters, digits * or space (<code>' '</code>).</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isAlphanumeric(null) = false * StringUtils.isAlphanumeric("") = true * StringUtils.isAlphanumeric(" ") = true * StringUtils.isAlphanumeric("abc") = true * StringUtils.isAlphanumeric("ab c") = true * StringUtils.isAlphanumeric("ab2c") = true * StringUtils.isAlphanumeric("ab-c") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains letters, digits or space, * and is non-null */ public static boolean isAlphanumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isLetterOrDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits. * A decimal point is not a unicode digit and returns false.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = true * StringUtils.isNumeric(" ") = false * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("12 3") = false * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains digits, and is non-null */ public static boolean isNumeric(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if (Character.isDigit(str.charAt(i)) == false) { return false; } } return true; } /** * <p>Checks if the String contains only unicode digits or space * (<code>' '</code>). * A decimal point is not a unicode digit and returns false.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = true * StringUtils.isNumeric(" ") = true * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("12 3") = true * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains digits or space, * and is non-null */ public static boolean isNumericSpace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) { return false; } } return true; } /** * <p>Checks if the String contains only whitespace.</p> * * <p><code>null</code> will return <code>false</code>. * An empty String ("") will return <code>true</code>.</p> * * <pre> * StringUtils.isWhitespace(null) = false * StringUtils.isWhitespace("") = true * StringUtils.isWhitespace(" ") = true * StringUtils.isWhitespace("abc") = false * StringUtils.isWhitespace("ab2c") = false * StringUtils.isWhitespace("ab-c") = false * </pre> * * @param str the String to check, may be null * @return <code>true</code> if only contains whitespace, and is non-null * @since 2.0 */ public static boolean isWhitespace(String str) { if (str == null) { return false; } int sz = str.length(); for (int i = 0; i < sz; i++) { if ((Character.isWhitespace(str.charAt(i)) == false)) { return false; } } return true; } // Defaults /** * <p>Returns either the passed in String, * or if the String is <code>null</code>, an empty String ("").</p> * * <pre> * StringUtils.defaultString(null) = "" * StringUtils.defaultString("") = "" * StringUtils.defaultString("bat") = "bat" * </pre> * * @see ObjectUtils#toString(Object) * @see String#valueOf(Object) * @param str the String to check, may be null * @return the passed in String, or the empty String if it * was <code>null</code> */ public static String defaultString(String str) { return (str == null ? EMPTY : str); } /** * <p>Returns either the passed in String, * or if the String is <code>null</code>, an empty String ("").</p> * * <pre> * StringUtils.defaultString(null, "null") = "null" * StringUtils.defaultString("", "null") = "" * StringUtils.defaultString("bat", "null") = "bat" * </pre> * * @see ObjectUtils#toString(Object,String) * @see String#valueOf(Object) * @param str the String to check, may be null * @param defaultStr the default String to return * if the input is <code>null</code>, may be null * @return the passed in String, or the default if it was <code>null</code> */ public static String defaultString(String str, String defaultStr) { return (str == null ? defaultStr : str); } // Reversing /** * <p>Reverses a String as per {@link StringBuffer#reverse()}.</p> * * <p><A code>null</code> String returns <code>null</code>.</p> * * <pre> * StringUtils.reverse(null) = null * StringUtils.reverse("") = "" * StringUtils.reverse("bat") = "tab" * </pre> * * @param str the String to reverse, may be null * @return the reversed String, <code>null</code> if null String input */ public static String reverse(String str) { if (str == null) { return null; } return new StringBuffer(str).reverse().toString(); } /** * <p>Reverses a String that is delimited by a specific character.</p> * * <p>The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is <code>'.'</code>).</p> * * <pre> * StringUtils.reverseDelimited(null, *) = null * StringUtils.reverseDelimited("", *) = "" * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c" * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a" * </pre> * * @param str the String to reverse, may be null * @param separatorChar the separator character to use * @return the reversed String, <code>null</code> if null String input * @since 2.0 */ public static String reverseDelimited(String str, char separatorChar) { if (str == null) { return null; } // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, separatorChar); ArrayUtils.reverse(strs); return join(strs, separatorChar); } /** * <p>Reverses a String that is delimited by a specific character.</p> * * <p>The Strings between the delimiters are not reversed. * Thus java.lang.String becomes String.lang.java (if the delimiter * is <code>"."</code>).</p> * * <pre> * StringUtils.reverseDelimitedString(null, *) = null * StringUtils.reverseDelimitedString("",*) = "" * StringUtils.reverseDelimitedString("a.b.c", null) = "a.b.c" * StringUtils.reverseDelimitedString("a.b.c", ".") = "c.b.a" * </pre> * * @param str the String to reverse, may be null * @param separatorChars the separator characters to use, null treated as whitespace * @return the reversed String, <code>null</code> if null String input * @deprecated Use {@link #reverseDelimited(String, char)} instead. * This method is broken as the join doesn't know which char to use. * Method will be removed in Commons Lang 3.0. * */ public static String reverseDelimitedString(String str, String separatorChars) { if (str == null) { return null; } // could implement manually, but simple way is to reuse other, // probably slower, methods. String[] strs = split(str, separatorChars); ArrayUtils.reverse(strs); if (separatorChars == null) { return join(strs, ' '); } return join(strs, separatorChars); } // Abbreviating public static String abbreviate(String str, int maxWidth) { return abbreviate(str, 0, maxWidth); } public static String abbreviate(String str, int offset, int maxWidth) { if (str == null) { return null; } if (maxWidth < 4) { throw new IllegalArgumentException("Minimum abbreviation width is 4"); } if (str.length() <= maxWidth) { return str; } if (offset > str.length()) { offset = str.length(); } if ((str.length() - offset) < (maxWidth - 3)) { offset = str.length() - (maxWidth - 3); } if (offset <= 4) { return str.substring(0, maxWidth - 3) + "..."; } if (maxWidth < 7) { throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); } if ((offset + (maxWidth - 3)) < str.length()) { return "..." + abbreviate(str.substring(offset), maxWidth - 3); } return "..." + str.substring(str.length() - (maxWidth - 3)); } // Difference /** * <p>Compares two Strings, and returns the portion where they differ. * (More precisely, return the remainder of the second String, * starting from where it's different from the first.)</p> * * <p>For example, * <code>difference("i am a machine", "i am a robot") -> "robot"</code>.</p> * * <pre> * StringUtils.difference(null, null) = null * StringUtils.difference("", "") = "" * StringUtils.difference("", "abc") = "abc" * StringUtils.difference("abc", "") = "" * StringUtils.difference("abc", "abc") = "" * StringUtils.difference("ab", "abxyz") = "xyz" * StringUtils.difference("abcde", "abxyz") = "xyz" * StringUtils.difference("abcde", "xyz") = "xyz" * </pre> * * @param str1 the first String, may be null * @param str2 the second String, may be null * @return the portion of str2 where it differs from str1; returns the * empty String if they are equal * @since 2.0 */ public static String difference(String str1, String str2) { if (str1 == null) { return str2; } if (str2 == null) { return str1; } int at = indexOfDifference(str1, str2); if (at == -1) { return EMPTY; } return str2.substring(at); } /** * <p>Compares two Strings, and returns the index at which the * Strings begin to differ.</p> * * <p>For example, * <code>indexOfDifference("i am a machine", "i am a robot") -> 7</code></p> * * <pre> * StringUtils.indexOfDifference(null, null) = -1 * StringUtils.indexOfDifference("", "") = -1 * StringUtils.indexOfDifference("", "abc") = 0 * StringUtils.indexOfDifference("abc", "") = 0 * StringUtils.indexOfDifference("abc", "abc") = -1 * StringUtils.indexOfDifference("ab", "abxyz") = 2 * StringUtils.indexOfDifference("abcde", "abxyz") = 2 * StringUtils.indexOfDifference("abcde", "xyz") = 0 * </pre> * * @param str1 the first String, may be null * @param str2 the second String, may be null * @return the index where str2 and str1 begin to differ; -1 if they are equal * @since 2.0 */ public static int indexOfDifference(String str1, String str2) { if (str1 == str2) { return -1; } if (str1 == null || str2 == null) { return 0; } int i; for (i = 0; i < str1.length() && i < str2.length(); ++i) { if (str1.charAt(i) != str2.charAt(i)) { break; } } if (i < str2.length() || i < str1.length()) { return i; } return -1; } // Misc public static int getLevenshteinDistance(String s, String t) { if (s == null || t == null) { throw new IllegalArgumentException("Strings must not be null"); } int d[][]; // matrix int n; // length of s int m; // length of t int i; // iterates through s int j; // iterates through t char s_i; // ith character of s char t_j; // jth character of t int cost; // cost // Step 1 n = s.length(); m = t.length(); if (n == 0) { return m; } if (m == 0) { return n; } d = new int[n + 1][m + 1]; // Step 2 for (i = 0; i <= n; i++) { d[i][0] = i; } for (j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (i = 1; i <= n; i++) { s_i = s.charAt(i - 1); // Step 4 for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); // Step 5 if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); } } // Step 7 return d[n][m]; } /** * <p>Gets the minimum of three <code>int</code> values.</p> * * @param a value 1 * @param b value 2 * @param c value 3 * @return the smallest of the values */ private static int min(int a, int b, int c) { // Method copied from NumberUtils to avoid dependency on subpackage if (b < a) { a = b; } if (c < a) { a = c; } return a; } }
package com.redhat.ceylon.eclipse.code.resolve; import static com.redhat.ceylon.eclipse.code.editor.Navigation.gotoNode; import static com.redhat.ceylon.eclipse.util.Nodes.findNode; import static com.redhat.ceylon.eclipse.util.Nodes.getIdentifyingNode; import static com.redhat.ceylon.eclipse.util.Nodes.getReferencedModel; import static com.redhat.ceylon.eclipse.util.Nodes.getReferencedNode; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getNativeDeclaration; import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getNativeHeader; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.eclipse.jface.text.hyperlink.IHyperlinkDetector; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.eclipse.code.editor.CeylonEditor; import com.redhat.ceylon.eclipse.code.parse.CeylonParseController; import com.redhat.ceylon.eclipse.core.model.CeylonBinaryUnit; import com.redhat.ceylon.eclipse.core.model.ExternalSourceFile; import com.redhat.ceylon.eclipse.core.typechecker.ExternalPhasedUnit; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Referenceable; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Unit; public class CeylonHyperlinkDetector implements IHyperlinkDetector { private CeylonEditor editor; private CeylonParseController controller; public CeylonHyperlinkDetector(CeylonEditor editor, CeylonParseController controller) { this.editor = editor; this.controller = controller; } private final class CeylonNodeLink implements IHyperlink { private final Node node; private final Node id; private CeylonNodeLink(Node node, Node id) { this.node = node; this.id = id; } @Override public void open() { gotoNode(node, editor); } @Override public String getTypeLabel() { return null; } @Override public String getHyperlinkText() { Backend supportedBackend = supportedBackend(); return "Ceylon Declaration" + (supportedBackend == null ? "" : " \u2014 " + (Backend.None.equals(supportedBackend) ? "native header" : supportedBackend.name() + " backend implementation")); } @Override public IRegion getHyperlinkRegion() { return new Region(id.getStartIndex(), id.getDistance()); } } @Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { if (controller==null || controller.getLastCompilationUnit()==null) { return null; } else { Node node = findNode(controller.getLastCompilationUnit(), controller.getTokens(), region.getOffset(), region.getOffset() + region.getLength()); if (node==null) { return null; } else { Node id = getIdentifyingNode(node); if (id==null) { return null; } else { Referenceable referenceable = getReferencedModel(node); if (referenceable instanceof Declaration) { Declaration dec = (Declaration) referenceable; Backend supportedBackend = supportedBackend(); if (dec.isNative()) { if (supportedBackend==null) { return null; } else { referenceable = resolveNative(referenceable, dec, supportedBackend); } } else { if (supportedBackend!=null) { return null; } } } Node r = getReferencedNode(referenceable); if (r==null) { return null; } else { return new IHyperlink[] { new CeylonNodeLink(r, id) }; } } } } } private Referenceable resolveNative( Referenceable referenceable, Declaration dec, Backend backend) { Unit unit = dec.getUnit(); Scope containerToSearchHeaderIn = null; if (unit instanceof CeylonBinaryUnit) { CeylonBinaryUnit binaryUnit = (CeylonBinaryUnit) unit; ExternalPhasedUnit phasedUnit = binaryUnit.getPhasedUnit(); if (phasedUnit != null) { ExternalSourceFile sourceFile = phasedUnit.getUnit(); if (sourceFile != null) { String sourceRelativePath = binaryUnit.getModule() .toSourceUnitRelativePath( unit.getRelativePath()); if (sourceRelativePath != null && sourceRelativePath.endsWith(".ceylon")) { for (Declaration sourceDecl: sourceFile.getDeclarations()) { if (sourceDecl.equals(dec)) { containerToSearchHeaderIn = sourceDecl.getContainer(); break; } } } else { for (Declaration sourceDecl: sourceFile.getDeclarations()) { if (sourceDecl.getQualifiedNameString() .equals(dec.getQualifiedNameString())) { containerToSearchHeaderIn = sourceDecl.getContainer(); break; } } } } } } else { containerToSearchHeaderIn = dec.getContainer(); } if (containerToSearchHeaderIn != null) { Declaration headerDeclaration = getNativeHeader(containerToSearchHeaderIn, dec.getName()); if (headerDeclaration == null || ! headerDeclaration.isNative()) return null; if (Backend.None.equals(backend)) { referenceable = headerDeclaration; } else { if (headerDeclaration != null) { referenceable = getNativeDeclaration(headerDeclaration, supportedBackend()); } } } return referenceable; } public Backend supportedBackend() { return null; } }
package net.mybluemix.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class PushServlet */ @WebServlet("/PushServlet") public class PushServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static int counter = 0 ; /** * @see HttpServlet#HttpServlet() */ public PushServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub if(counter < 10 ){ response.getWriter().append("No "); counter++; }else{ response.getWriter().append("Alter: There is a threat.... "); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package org.lucubrate.mirrortracker; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.util.Log; import android.view.View; import android.widget.Switch; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.lucubrate.mirrortracker.BR; // KEEP: needed for Android Studio. /** * Firebase realtime database data binding. */ public class FirebaseDB implements SignedInHandler { /** Android databinding object that connects to Firebase realtime database. */ public static class Model extends BaseObservable { private Model(boolean showPrivateInfo) { this.showPrivateInfo = showPrivateInfo; } /** * @return Whether private/sensitive info on the mirror display should be shown. */ @Bindable public boolean isShowPrivateInfo() { return showPrivateInfo; } public void setShowPrivateInfo(boolean showPrivateInfo) { this.showPrivateInfo = showPrivateInfo; notifyPropertyChanged(BR.showPrivateInfo); } private boolean showPrivateInfo; } final private static String TAG = "FirebaseDB"; private FirebaseDatabase mDB; private Model mModel; private DatabaseReference showPrivateInfo; FirebaseDB() { mDB = FirebaseDatabase.getInstance(); mDB.setPersistenceEnabled(true); mModel = new Model(false); showPrivateInfo = mDB.getReference("mirror/config/showPrivateInfo"); showPrivateInfo.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mModel.setShowPrivateInfo(dataSnapshot.getValue(Boolean.class)); } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "Failed to read value.", databaseError.toException()); } }); } /** * @return Android SignedInActivity databinding model, bound to FirebaseDB. */ public Model getModel() { return mModel; } @Override public void onShowPrivateInfoChecked(View view) { showPrivateInfo.setValue(((Switch) view).isChecked()); } }
package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter; import com.joelapenna.foursquared.widget.VenueView; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnCancelListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class UserActivity extends Activity { private static final String TAG = "UserActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER = "com.joelapenna.foursquared.UserId"; private Dialog mProgressDialog; private AlertDialog mBadgeDialog; private String mUserId = null; private User mUser = null; private UserObservable mUserObservable = new UserObservable(); private UserObserver mUserObserver = new UserObserver(); private GridView mBadgesGrid; private VenueView mVenueView; private AsyncTask<Void, Void, User> mUserTask = null; private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.user_activity); registerReceiver(mLoggedInReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mVenueView = (VenueView)findViewById(R.id.venue); mBadgesGrid = (GridView)findViewById(R.id.badgesGrid); if (getIntent().hasExtra(EXTRA_USER)) { mUserId = getIntent().getExtras().getString(EXTRA_USER); } else { mUserId = null; } mUserObservable.addObserver(mUserObserver); if (getLastNonConfigurationInstance() == null) { mUserTask = new UserTask().execute(); } else { User user = (User)getLastNonConfigurationInstance(); setUser(user); } } @Override public void onStop() { super.onStop(); if (DEBUG) Log.d(TAG, "onStop()"); if (mUserTask != null) { mUserTask.cancel(true); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedInReceiver); } @Override public void onNewIntent(Intent intent) { if (DEBUG) Log.d(TAG, "onNewIntent: " + intent); } @Override public Object onRetainNonConfigurationInstance() { return mUser; } private Dialog showProgressDialog() { if (mProgressDialog == null) { ProgressDialog dialog = new ProgressDialog(this); dialog.setTitle("Loading"); dialog.setMessage("Please wait while we retrieve some information"); dialog.setIndeterminate(true); dialog.setCancelable(true); dialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { finish(); } }); mProgressDialog = dialog; } mProgressDialog.show(); return mProgressDialog; } private Dialog showBadgeDialog(Badge badge) { if (mBadgeDialog == null) { AlertDialog dialog = new AlertDialog.Builder(UserActivity.this) .setTitle("Loading") .setMessage("Please wait while retrieve some information") .setCancelable(true) .create(); mBadgeDialog = dialog; } mBadgeDialog.setTitle(badge.getName()); mBadgeDialog.setMessage(badge.getDescription()); try { Uri icon = Uri.parse(badge.getIcon()); if (DEBUG) Log.d(TAG, icon.toString()); mBadgeDialog.setIcon(new BitmapDrawable(((Foursquared)getApplication()) .getBadgeIconManager().getInputStream(icon))); } catch (IOException e) { if (DEBUG) Log.d(TAG, "IOException", e); mBadgeDialog.setIcon(R.drawable.default_on); } mBadgeDialog.show(); return mBadgeDialog; } private void dismissProgressDialog() { try { mProgressDialog.dismiss(); } catch (IllegalArgumentException e) { // We don't mind. android cleared it for us. } } private void setUser(User user) { mUser = user; mUserObservable.notifyObservers(user); } private void ensureUserPhoto(final User user) { final ImageView photo = (ImageView)findViewById(R.id.photo); if (user.getPhoto() == null) { photo.setImageResource(R.drawable.blank_boy); return; } final Uri photoUri = Uri.parse(user.getPhoto()); if (photoUri != null) { RemoteResourceManager userPhotosManager = ((Foursquared)getApplication()) .getUserPhotosManager(); try { Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager .getInputStream(photoUri)); photo.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.d(TAG, "photo not already retrieved, requesting: " + photoUri); userPhotosManager.addObserver(new RemoteResourceManager.ResourceRequestObserver( photoUri) { @Override public void requestReceived(Observable observable, Uri uri) { observable.deleteObserver(this); updateUserPhoto(photo, uri, user); } }); userPhotosManager.request(photoUri); } } } private void updateUserPhoto(final ImageView photo, final Uri uri, final User user) { runOnUiThread(new Runnable() { @Override public void run() { try { if (DEBUG) Log.d(TAG, "Loading user photo: " + uri); RemoteResourceManager userPhotosManager = ((Foursquared)getApplication()) .getUserPhotosManager(); Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager .getInputStream(uri)); photo.setImageBitmap(bitmap); if (DEBUG) Log.d(TAG, "Loaded user photo: " + uri); } catch (IOException e) { if (DEBUG) Log.d(TAG, "Unable to load user photo: " + uri); if (Foursquare.MALE.equals(user.getGender())) { photo.setImageResource(R.drawable.blank_boy); } else { photo.setImageResource(R.drawable.blank_girl); } } catch (Exception e) { Log.d(TAG, "Ummm............", e); } } }); } private class UserTask extends AsyncTask<Void, Void, User> { private Exception mReason; @Override protected void onPreExecute() { setProgressBarIndeterminateVisibility(true); showProgressDialog(); } @Override protected User doInBackground(Void... params) { try { return ((Foursquared)getApplication()).getFoursquare().user(mUserId, false, true); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { setProgressBarIndeterminateVisibility(false); if (user == null) { NotificationsUtil.ToastReasonForFailure(UserActivity.this, mReason); finish(); } else { setUser(user); } dismissProgressDialog(); } @Override protected void onCancelled() { setProgressBarIndeterminateVisibility(false); dismissProgressDialog(); } } private class UserObservable extends Observable { public void notifyObservers(Object data) { setChanged(); super.notifyObservers(data); } } private class UserObserver implements Observer { @Override public void update(Observable observable, Object data) { User user = (User)data; displayUser(user); displayBadges(user); displayCheckin(user); } private void displayBadges(User user) { if (user.getBadges() != null) { mBadgesGrid.setAdapter(new BadgeWithIconListAdapter(UserActivity.this, user .getBadges(), ((Foursquared)getApplication()).getBadgeIconManager())); ((TextView)findViewById(R.id.badgesHeader)).setVisibility(TextView.VISIBLE); mBadgesGrid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Badge badge = (Badge)parent.getAdapter().getItem(position); showBadgeDialog(badge); } }); } } private void displayCheckin(User user) { Checkin checkin = user.getCheckin(); if (checkin != null && !TextUtils.isEmpty(checkin.getShout())) { ((TextView)findViewById(R.id.secondLine)).setText(checkin.getShout()); } if (checkin != null && checkin.getVenue() != null) { final Venue venue = user.getCheckin().getVenue(); mVenueView.setVenue(venue); ((TextView)findViewById(R.id.venueHeader)).setVisibility(TextView.VISIBLE); // Hell, I'm not even sure if this is the right place to put this... Whatever. mVenueView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(UserActivity.this, VenueActivity.class); intent.putExtra(Foursquared.EXTRA_VENUE_ID, venue.getId()); startActivity(intent); } }); } else { // If we don't have a checkin location, clear it from the UI so it doesn't take up // space. LayoutParams params = mVenueView.getLayoutParams(); params.height = 0; mVenueView.setLayoutParams(params); } } private void displayUser(User user) { if (DEBUG) Log.d(TAG, "loading user"); String fullName = user.getFirstname() + " " + user.getLastname(); TextView name = (TextView)findViewById(R.id.name); name.setText(fullName); ensureUserPhoto(user); Checkin checkin = user.getCheckin(); if (checkin == null || TextUtils.isEmpty(checkin.getShout())) { ((TextView)findViewById(R.id.secondLine)).setText(user.getCity().getName()); } } } }
package org.ops4j.pax.web.itest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.cleanCaches; import static org.ops4j.pax.exam.CoreOptions.frameworkProperty; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemPackages; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.workingDirectory; import static org.ops4j.pax.exam.CoreOptions.wrappedBundle; import static org.ops4j.pax.exam.MavenUtils.asInProject; import static org.ops4j.pax.exam.OptionUtils.combine; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.List; import javax.inject.Inject; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.X509HostnameVerifier; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import org.junit.After; import org.junit.Before; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.web.itest.support.ServletListenerImpl; import org.ops4j.pax.web.itest.support.WaitCondition; import org.ops4j.pax.web.itest.support.WebListenerImpl; import org.ops4j.pax.web.service.spi.ServletListener; import org.ops4j.pax.web.service.spi.WebListener; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ExamReactorStrategy(PerClass.class) public class ITestBase { protected static final String WEB_CONTEXT_PATH = "Web-ContextPath"; protected static final String WEB_CONNECTORS = "Web-Connectors"; protected static final String WEB_VIRTUAL_HOSTS = "Web-VirtualHosts"; protected static final String WEB_BUNDLE = "webbundle:"; protected static final String REALM_NAME = "realm.properties"; private static final Logger LOG = LoggerFactory.getLogger(ITestBase.class); @Inject protected BundleContext bundleContext; protected DefaultHttpClient httpclient; protected WebListener webListener; protected ServletListener servletListener; public static Option[] baseConfigure() { return options( workingDirectory("target/paxexam/"), cleanCaches(true), junitBundles(), frameworkProperty("osgi.console").value("6666"), frameworkProperty("osgi.console.enable.builtin").value("true"), frameworkProperty("felix.bootdelegation.implicit").value( "false"), // frameworkProperty("felix.log.level").value("4"), systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level") .value("INFO"), systemProperty("org.osgi.service.http.hostname").value( "127.0.0.1"), systemProperty("org.osgi.service.http.port").value("8181"), systemProperty("java.protocol.handler.pkgs").value( "org.ops4j.pax.url"), systemProperty("org.ops4j.pax.url.war.importPaxLoggingPackages") .value("true"), systemProperty("org.ops4j.pax.web.log.ncsa.enabled").value( "true"), systemProperty("org.ops4j.pax.web.log.ncsa.directory").value( "target/logs"), systemProperty("ProjectVersion").value(getProjectVersion()), // javax.servlet may be on the system classpath so we need to // make sure // that all bundles load it from there systemPackages("javax.servlet;version=2.6.0", "javax.servlet;version=3.0.0"), // mavenBundle().groupId("org.apache.felix") // .artifactId("org.apache.felix.framework.security") // .version("2.0.1"), // do not include pax-logging-api, this is already provisioned // by Pax Exam mavenBundle().groupId("org.ops4j.pax.logging") .artifactId("pax-logging-service").version("1.6.4"), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-war").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-wrap").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-commons").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.swissbox") .artifactId("pax-swissbox-bnd").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.swissbox") .artifactId("pax-swissbox-property") .version(asInProject()), mavenBundle().groupId("biz.aQute").artifactId("bndlib") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.swissbox") .artifactId("pax-swissbox-optional-jcl") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-spi").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-api").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-extender-war") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-extender-whiteboard") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-runtime").version(asInProject()), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-jsp").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty.orbit") .artifactId("org.eclipse.jdt.core").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-servlet_3.0_spec") .version(asInProject()), mavenBundle().groupId("org.ops4j.pax.url") .artifactId("pax-url-aether").version(asInProject()), mavenBundle().groupId("org.apache.xbean") .artifactId("xbean-finder").version(asInProject()), mavenBundle().groupId("org.apache.xbean") .artifactId("xbean-bundleutils").version(asInProject()), mavenBundle().groupId("org.apache.servicemix.bundles") .artifactId("org.apache.servicemix.bundles.asm").version(asInProject()), mavenBundle("commons-codec", "commons-codec").version( asInProject()), wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpclient", "4.1")), wrappedBundle(mavenBundle("org.apache.httpcomponents", "httpcore", "4.1"))); } public static Option[] configureJetty() { return combine( baseConfigure(), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-jetty").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-util").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-io").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-http").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-continuation") .version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-server").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-security").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-xml").version(asInProject()), mavenBundle().groupId("org.eclipse.jetty") .artifactId("jetty-servlet").version(asInProject())); } public static Option[] configureTomcat() { return combine( baseConfigure(), systemPackages("javax.xml.namespace;version=1.0.0", "javax.transaction;version=1.1.0", "javax.servlet;version=2.6.0", "javax.servlet;version=3.0.0", "javax.servlet.descriptor;version=2.6.0", "javax.servlet.descriptor;version=3.0.0", "javax.annotation.processing;uses:=javax.tools,javax.lang.model,javax.lang.model.element,javax.lang.model.util;version=1.1", "javax.annotation;version=1.1", "javax.annotation.security;version=1.1" ), systemProperty("org.osgi.service.http.hostname").value("127.0.0.1"), systemProperty("org.osgi.service.http.port").value("8282"), mavenBundle().groupId("org.ops4j.pax.web") .artifactId("pax-web-tomcat").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("catalina").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("shared").version(asInProject()), mavenBundle().groupId("org.apache.geronimo.ext.tomcat") .artifactId("util").version(asInProject()), mavenBundle().groupId("org.apache.servicemix.specs") .artifactId("org.apache.servicemix.specs.saaj-api-1.3") .version(asInProject()), mavenBundle().groupId("org.apache.servicemix.specs") .artifactId("org.apache.servicemix.specs.jaxb-api-2.2") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jaxws_2.2_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jaxrpc_1.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-servlet_3.0_spec") .version(asInProject()), mavenBundle() .groupId("org.apache.servicemix.specs") .artifactId( "org.apache.servicemix.specs.jsr303-api-1.0.0") .version(asInProject()), // mavenBundle().groupId("org.apache.geronimo.specs") // .artifactId("geronimo-annotation_1.1_spec") // .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-activation_1.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-stax-api_1.2_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-ejb_3.1_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-jpa_2.0_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-javamail_1.4_spec") .version(asInProject()), mavenBundle().groupId("org.apache.geronimo.specs") .artifactId("geronimo-osgi-registry") .version(asInProject())); } @Before public void setUpITestBase() throws Exception { httpclient = new DefaultHttpClient(); } @After public void tearDownITestBase() throws Exception { httpclient.clearRequestInterceptors(); httpclient.clearResponseInterceptors(); httpclient = null; } public static String getProjectVersion() { String projectVersion = System.getProperty("ProjectVersion"); LOG.info("*** The ProjectVersion is {} ***", projectVersion); return projectVersion; } public static String getMyFacesVersion() { String myFacesVersion = System.getProperty("MyFacesVersion"); System.out.println("*** The MyFacesVersion is " + myFacesVersion + " ***"); return myFacesVersion; } protected String testWebPath(String path, String expectedContent) throws Exception { return testWebPath(path, expectedContent, 200, false); } protected String testWebPath(String path, int httpRC) throws Exception { return testWebPath(path, null, httpRC, false); } protected String testWebPath(String path, String expectedContent, int httpRC, boolean authenticate) throws Exception { return testWebPath(path, expectedContent, httpRC, authenticate, null); } protected String testWebPath(String path, String expectedContent, int httpRC, boolean authenticate, BasicHttpContext basicHttpContext) throws Exception { int count = 0; while (!checkServer(path) && count++ < 5) { if (count > 5) { break; } } HttpResponse response = null; response = getHttpResponse(path, authenticate, basicHttpContext); assertEquals("HttpResponseCode", httpRC, response.getStatusLine() .getStatusCode()); String responseBodyAsString = null; if (expectedContent != null) { responseBodyAsString = EntityUtils.toString(response.getEntity()); assertTrue("Content: " + responseBodyAsString,responseBodyAsString.contains(expectedContent)); } return responseBodyAsString; } private boolean isSecuredConnection(String path) { int schemeSeperator = path.indexOf(":"); String scheme = path.substring(0, schemeSeperator); if ("https".equalsIgnoreCase(scheme)) { return true; } return false; } protected void testPost(String path, List<NameValuePair> nameValuePairs, String expectedContent, int httpRC) throws IOException { HttpPost post = new HttpPost(path); post.setEntity(new UrlEncodedFormEntity( (List<NameValuePair>) nameValuePairs)); HttpResponse response = httpclient.execute(post); assertEquals("HttpResponseCode", httpRC, response.getStatusLine() .getStatusCode()); if (expectedContent != null) { String responseBodyAsString = EntityUtils.toString(response .getEntity()); assertTrue(responseBodyAsString.contains(expectedContent)); } } protected HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext) throws IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException { HttpGet httpget = null; HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("src/test/resources/keystore")); try { trustStore.load(instream, "password".toCharArray()); } finally { try { instream.close(); } catch (Exception ignore) {}//CHECKSTYLE:SKIP } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", 443, socketFactory); httpclient.getConnectionManager().getSchemeRegistry().register(sch); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); HttpHost targetHost = getHttpHost(path); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext; if (authenticate) { ((DefaultHttpClient) httpclient).getCredentialsProvider() .setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); } httpget = new HttpGet(path); LOG.info("calling remote {} ...", path); HttpResponse response = null; if (!authenticate && basicHttpContext == null) { response = httpclient.execute(httpget); } else { response = httpclient.execute(targetHost, httpget, localcontext); } LOG.info("... responded with: {}", response.getStatusLine().getStatusCode()); return response; } private HttpHost getHttpHost(String path) { int schemeSeperator = path.indexOf(":"); String scheme = path.substring(0, schemeSeperator); int portSeperator = path.lastIndexOf(":"); String hostname = path.substring(schemeSeperator + 3, portSeperator); int port = Integer.parseInt(path.substring(portSeperator + 1, portSeperator + 5)); HttpHost targetHost = new HttpHost(hostname, port, scheme); return targetHost; } protected boolean checkServer(String path) throws Exception { LOG.info("checking server path {}", path); HttpGet httpget = null; HttpClient myHttpClient = new DefaultHttpClient(); HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("src/test/resources/keystore")); try { trustStore.load(instream, "password".toCharArray()); } finally { try { instream.close(); } catch (Exception ignore) {}//CHECKSTYLE:SKIP } SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore); Scheme sch = new Scheme("https", 443, socketFactory); myHttpClient.getConnectionManager().getSchemeRegistry().register(sch); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); HttpHost targetHost = getHttpHost(path); // Set verifier HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); httpget = new HttpGet("/"); LOG.info("calling remote {}://{}:{}/ ...", new Object[] { targetHost.getSchemeName(), targetHost.getHostName(), targetHost.getPort() }); HttpResponse response = null; try { response = myHttpClient.execute(targetHost, httpget); } catch (IOException ioe) { LOG.info("... caught IOException"); return false; } int statusCode = response.getStatusLine().getStatusCode(); LOG.info("... responded with: {}", statusCode); return statusCode == 404 || statusCode == 200; } protected void initWebListener() { webListener = new WebListenerImpl(); bundleContext.registerService(WebListener.class, webListener, null); } protected void initServletListener() { servletListener = new ServletListenerImpl(); bundleContext.registerService(ServletListener.class, servletListener, null); } protected void waitForWebListener() throws InterruptedException { new WaitCondition("webapp startup") { @Override protected boolean isFulfilled() { return ((WebListenerImpl)webListener).gotEvent(); } }.waitForCondition(); //CHECKSTYLE:SKIP } protected void waitForServletListener() throws InterruptedException { new WaitCondition("servlet startup") { @Override protected boolean isFulfilled() { return ((ServletListenerImpl)servletListener).gotEvent(); } }.waitForCondition(); //CHECKSTYLE:SKIP } protected void waitForServer(final String path) throws InterruptedException { new WaitCondition("server") { @Override protected boolean isFulfilled() throws Exception { return checkServer(path); } }.waitForCondition(); //CHECKSTYLE:SKIP } protected Bundle installAndStartBundle(String bundlePath) throws BundleException, InterruptedException { final Bundle bundle = bundleContext.installBundle(bundlePath); bundle.start(); new WaitCondition("bundle startup") { @Override protected boolean isFulfilled() { return bundle.getState() == Bundle.ACTIVE; } }.waitForCondition(); //CHECKSTYLE:SKIP return bundle; } }
package org.animotron.statement.query; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import org.animotron.Executor; import org.animotron.graph.AnimoGraph; import org.animotron.graph.GraphOperation; import org.animotron.graph.index.Order; import org.animotron.io.PipedInput; import org.animotron.manipulator.Evaluator; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.*; import org.animotron.statement.relation.SHALL; import org.jetlang.channels.Subscribable; import org.jetlang.core.DisposingExecutor; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import static org.animotron.Properties.RID; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.animotron.graph.RelationshipTypes.RESULT; /** * Query operator 'Get'. Return 'have' relations on provided context. * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class GET extends AbstractQuery implements Shift { public static final GET _ = new GET(); private static boolean debug = false; private GET() { super("get", "<~"); } protected GET(String... name) { super(name); } TraversalDescription td = Traversal.description(). depthFirst().uniqueness(Uniqueness.RELATIONSHIP_PATH); private static TraversalDescription td_eval_ic = Traversal.description(). breadthFirst(). relationships(AN._, OUTGOING). relationships(SHALL._, OUTGOING); public OnQuestion onCalcQuestion() { return question; } private OnQuestion question = new OnQuestion() { @Override public void onMessage(final PFlow pf) { final Relationship op = pf.getOP(); final Node node = op.getEndNode(); final Set<Relationship> visitedREFs = new FastSet<Relationship>(); final Set<Node> thes = new FastSet<Node>(); Relationship r = null; for (QCAVector theNode : AN.getREFs(pf, op)) { r = theNode.getAnswer(); if (r.isType(AN._)) { try { for (QCAVector rr : Utils.eval(pf, theNode)) { thes.add(rr.getAnswer().getEndNode()); } } catch (IOException e) { pf.sendException(e); return; } } else thes.add(r.getEndNode()); } evalGet(pf, op, node, thes, visitedREFs); pf.await(); pf.done(); } private void evalGet( final PFlow pf, final Relationship op, final Node node, final Set<Node> thes, final Set<Relationship> visitedREFs) { //Utils.debug(GET._, op, thes); //check, maybe, result was already calculated if (!Utils.results(pf)) { //no pre-calculated result, calculate it Subscribable<QCAVector> onContext = new Subscribable<QCAVector>() { @Override public void onMessage(QCAVector vector) { if (debug) System.out.println("GET ["+op+"] vector "+vector); if (vector == null) { pf.countDown(); return; } final Set<QCAVector> rSet = get(pf, op, vector, thes, visitedREFs); if (rSet != null) { for (QCAVector v : rSet) { pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN } } } @Override public DisposingExecutor getQueue() { return Executor.getFiber(); } }; pf.answer.subscribe(onContext); if (Utils.haveContext(pf)) { super.onMessage(pf); } else { boolean first = true; Set<QCAVector> rSet = null; for (QCAVector vector : pf.getPFlowPath()) { //System.out.println("CHECK PFLOW "+vector); if (first) { first = false; if (vector.getContext() == null) continue; Set<QCAVector> refs = new FastSet<QCAVector>(); for (QCAVector v : vector.getContext()) { refs.add(v); } rSet = get(pf, op, refs, thes, visitedREFs); } else { rSet = get(pf, op, vector, thes, visitedREFs); } if (rSet != null) { for (QCAVector v : rSet) { pf.sendAnswer(v, RESULT);//, AN._); //XXX: change to AN } break; } } } } }; }; public Set<QCAVector> get(PFlow pf, Relationship op, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) { Set<QCAVector> refs = new FastSet<QCAVector>(); refs.add(vector); return get(pf, op, refs, thes, visitedREFs); } public Set<QCAVector> get(final PFlow pf, Relationship op, Node ref, final Set<Node> thes, final Set<Relationship> visitedREFs) { Set<QCAVector> set = new FastSet<QCAVector>(); Relationship[] have = searchForHAVE(pf, null, ref, thes); if (have != null) { for (int i = 0; i < have.length; i++) { if (!pf.isInStack(have[i])) set.add(new QCAVector(pf.getOP(), have[i])); } } if (!set.isEmpty()) return set; Set<QCAVector> newREFs = new FastSet<QCAVector>(); getOutgoingReferences(pf, pf.getVector(), null, ref, newREFs, null); return get(pf, op, newREFs, thes, visitedREFs); } private boolean check(Set<QCAVector> set, final PFlow pf, final Relationship op, final QCAVector v, final Relationship toCheck, final Set<Node> thes, Set<Relationship> visitedREFs) { if (toCheck == null) return false; visitedREFs.add(toCheck); Relationship[] have = searchForHAVE(pf, toCheck, v, thes); if (have != null) { boolean added = false; for (int i = 0; i < have.length; i++) { if (!pf.isInStack(have[i])) { set.add(new QCAVector(op, v, have[i])); added = true; } } return added; } return false; } public Set<QCAVector> get( final PFlow pf, final Relationship op, final Set<QCAVector> REFs, final Set<Node> thes, Set<Relationship> visitedREFs) { //System.out.println("GET context = "+ref); if (visitedREFs == null) visitedREFs = new FastSet<Relationship>(); Set<QCAVector> set = new FastSet<QCAVector>(); Set<QCAVector> nextREFs = new FastSet<QCAVector>(); nextREFs.addAll(REFs); //boolean first = true; Relationship t = null; while (true) { if (debug) System.out.println("nextREFs ");//+Arrays.toString(nextREFs.toArray())); for (QCAVector v : nextREFs) { if (debug) System.out.println("checking "+v); QCAVector next = v; while (next != null) { if (!check(set, pf, op, v, v.getUnrelaxedAnswer(), thes, visitedREFs)) { check(set, pf, op, v, v.getQuestion(), thes, visitedREFs); } next = next.getPrecedingSibling(); } } if (set.size() > 0) return set; Set<QCAVector> newREFs = new FastSet<QCAVector>(); for (QCAVector vector : nextREFs) { List<QCAVector> cs = vector.getContext(); if (cs != null) { for (QCAVector c : cs) { t = c.getUnrelaxedAnswer(); if (t != null && !visitedREFs.contains(t)) newREFs.add(c); else { t = c.getQuestion(); if (!visitedREFs.contains(t)) newREFs.add(c); } } } QCAVector next = vector; while (next != null) { t = next.getUnrelaxedAnswer(); if (t != null) { if (! t.isType(AN._)) getOutgoingReferences(pf, next, t, t.getStartNode(), newREFs, visitedREFs); getOutgoingReferences(pf, next, t, t.getEndNode(), newREFs, visitedREFs); } next = next.getPrecedingSibling(); } } if (newREFs.size() == 0) return null; nextREFs = newREFs; } } private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) { QCAVector prev = null; IndexHits<Relationship> it = Order.queryDown(node); try { boolean first = rr == null || !rr.isType(REF._); for (Relationship r : it) { //System.out.println(r); if (first) { first = false; continue; } if (r.isType(REF._)) continue; prev = vector.question(r, prev); Statement st = Statements.relationshipType(r); if (st instanceof AN) { //System.out.println(r); for (QCAVector v : AN.getREFs(pf, r)) { Relationship t = v.getAnswer(); prev.addAnswer(v); //System.out.println(t); if (visitedREFs != null && !visitedREFs.contains(t)) { v.setPrecedingSibling(prev); prev = v; newREFs.add(v); } } } else if (st instanceof Reference) { if (!pf.isInStack(r)) { try { PipedInput<QCAVector> in = Evaluator._.execute(new PFlow(pf), prev); for (QCAVector v : in) { prev.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(v.getAnswer())) newREFs.add(v); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } catch (Exception e) { pf.sendException(e); } finally { it.close(); } } private Relationship[] searchForHAVE( final PFlow pf, final Relationship ref, final QCAVector v, final Set<Node> thes) { if (ref.isType(REF._) && thes.contains(ref.getEndNode())) { return new Relationship[] {v.getQuestion()}; } boolean checkStart = true; if (ref.isType(AN._)) { checkStart = false; } Relationship[] have = null; //search for inside 'HAVE' //return searchForHAVE(pf, ref, ref.getEndNode(), thes); have = getByHave(pf, ref, ref.getEndNode(), thes); if (have != null) return have; //search for local 'HAVE' if (checkStart) { have = getByHave(pf, null, ref.getStartNode(), thes); if (have != null) return have; } return null; } private Relationship[] searchForHAVE(final PFlow pflow, Relationship op, final Node ref, final Set<Node> thes) { Relationship[] have = null; //search for inside 'HAVE' have = getByHave(pflow, op, ref, thes); if (have != null) return have; //search 'IC' by 'IS' topology for (Relationship tdR : Utils.td_eval_IS.traverse(ref).relationships()) { //System.out.println("GET IC -> IS "+tdR); Relationship r = getShall(tdR.getEndNode(), thes); if (r != null) { final Node sNode = ref; final Node eNode = r.getEndNode(); final long id = r.getId(); return new Relationship[] { AnimoGraph.execute(new GraphOperation<Relationship>() { @Override public Relationship execute() { Relationship res = sNode.createRelationshipTo(eNode, AN._); RID.set(res, id); return res; } }) }; } //search for have have = getByHave(pflow, tdR, tdR.getEndNode(), thes); if (have != null) return have; } return null; } //XXX: in-use by SELF public Relationship[] getBySELF(final PFlow pf, Node context, final Set<Node> thes) { //System.out.println("GET get context = "+context); //search for local 'HAVE' Relationship[] have = getByHave(pf, null, context, thes); if (have != null) return have; Node instance = Utils.getSingleREF(context); if (instance != null) { //change context to the-instance by REF context = instance; //search for have have = getByHave(pf, null, context, thes); if (have != null) return have; } Relationship prevTHE = null; //search 'IC' by 'IS' topology for (Relationship tdR : td_eval_ic.traverse(context).relationships()) { Statement st = Statements.relationshipType(tdR); if (st instanceof AN) { //System.out.println("GET IC -> IS "+tdR); if (prevTHE != null) { //search for have have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes); if (have != null) return have; } prevTHE = tdR; } else if (st instanceof SHALL) { //System.out.print("GET IC -> "+tdR); if (thes.contains(Utils.getSingleREF(tdR.getEndNode()))) { //System.out.println(" MATCH"); //store final Node sNode = context; final Relationship r = tdR; return new Relationship[] { AnimoGraph.execute(new GraphOperation<Relationship>() { @Override public Relationship execute() { Relationship res = sNode.createRelationshipTo(r.getEndNode(), AN._); //RID.set(res, r.getId()); return res; } }) }; //in-memory //Relationship res = new InMemoryRelationship(context, tdR.getEndNode(), AN._.relationshipType()); //RID.set(res, tdR.getId()); //return res; //as it //return tdR; } //System.out.println(); } } if (prevTHE != null) { //search for have have = getByHave(pf, prevTHE, prevTHE.getEndNode(), thes); if (have != null) return have; } return null; } private Relationship[] getByHave(final PFlow pflow, Relationship op, final Node context, final Set<Node> thes) { if (context == null) return null; TraversalDescription trav = td. relationships(AN._, OUTGOING). relationships(REF._, OUTGOING). relationships(SHALL._, OUTGOING). evaluator(new Searcher(){ @Override public Evaluation evaluate(Path path) { //System.out.println(path); return _evaluate_(path, thes); } }); Map<Relationship, Path> paths = new FastMap<Relationship, Path>(); for (Path path : trav.traverse(context)) { //System.out.println("* "+path); if (path.length() == 1) { if (op == null) { System.out.println("WARNING: DONT KNOW OP"); continue; } paths.put(op, path); //break; } if (path.length() == 2) { //UNDERSTAND: should we check context return new Relationship[] {path.relationships().iterator().next()}; } Relationship fR = path.relationships().iterator().next(); Path p = paths.get(fR); if (p == null || p.length() > path.length()) { paths.put(fR, path); } } Relationship startBy = null; Relationship res = null; List<Relationship> resByHAVE = new FastList<Relationship>(); List<Relationship> resByIS = new FastList<Relationship>(); for (Path path : paths.values()) { for (Relationship r : path.relationships()) { if (startBy == null) startBy = r; if (!pflow.isInStack(r)) { if (r.isType(AN._)) { if (Utils.haveContext(r.getEndNode())) { res = r; //break; } } else if (r.isType(SHALL._)) { res = r; //break; } } } if (res != null) { if (startBy != null && startBy.isType(REF._)) resByIS.add(res); else resByHAVE.add(res); } startBy = null; } if (!resByHAVE.isEmpty()) return resByHAVE.toArray(new Relationship[resByHAVE.size()]); return resByIS.toArray(new Relationship[resByIS.size()]); } private Relationship getShall(final Node context, final Set<Node> thes) { // TraversalDescription trav = td. // evaluator(new Searcher(){ // @Override // public Evaluation evaluate(Path path) { // return _evaluate_(path, thes); //, IC._ // Relationship res = null; // for (Path path : trav.traverse(context)) { // //TODO: check that this is only one answer // //System.out.println(path); // for (Relationship r : path.relationships()) { // res = r; // break; for (Relationship r : context.getRelationships(OUTGOING, SHALL._)) { for (QCAVector rr : Utils.getByREF(null, r)) { if (thes.contains(rr.getAnswer().getEndNode())) return r; } } return null; } }
package org.apache.lucene.index; import java.io.IOException; import java.io.File; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.Lock; import org.apache.lucene.document.Document; /** IndexReader is an abstract class, providing an interface for accessing an index. Search of an index is done entirely through this abstract interface, so that any subclass which implements it is searchable. <p> Concrete subclasses of IndexReader are usually constructed with a call to the static method {@link #open}. <p> For efficiency, in this API documents are often referred to via <i>document numbers</i>, non-negative integers which each name a unique document in the index. These document numbers are ephemeral--they may change as documents are added to and deleted from an index. Clients should thus not rely on a given document having the same number between sessions. */ abstract public class IndexReader { protected IndexReader(Directory directory) { this.directory = directory; } Directory directory; private Lock writeLock; /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(String path) throws IOException { return open(FSDirectory.getDirectory(path, false)); } /** Returns an IndexReader reading the index in an FSDirectory in the named path. */ public static IndexReader open(File path) throws IOException { return open(FSDirectory.getDirectory(path, false)); } /** Returns an IndexReader reading the index in the given Directory. */ public static IndexReader open(final Directory directory) throws IOException{ synchronized (directory) { // in- & inter-process sync return (IndexReader)new Lock.With(directory.makeLock("commit.lock")) { public Object doBody() throws IOException { SegmentInfos infos = new SegmentInfos(); infos.read(directory); if (infos.size() == 1) // index is optimized return new SegmentReader(infos.info(0), true); SegmentReader[] readers = new SegmentReader[infos.size()]; for (int i = 0; i < infos.size(); i++) readers[i] = new SegmentReader(infos.info(i), i==infos.size()-1); return new SegmentsReader(directory, readers); } }.run(); } } /** Returns the time the index in the named directory was last modified. */ public static long lastModified(String directory) throws IOException { return lastModified(new File(directory)); } /** Returns the time the index in the named directory was last modified. */ public static long lastModified(File directory) throws IOException { return FSDirectory.fileModified(directory, "segments"); } /** Returns the time the index in this directory was last modified. */ public static long lastModified(Directory directory) throws IOException { return directory.fileModified("segments"); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * <code>false</code> is returned. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(String directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise */ public static boolean indexExists(File directory) { return (new File(directory, "segments")).exists(); } /** * Returns <code>true</code> if an index exists at the specified directory. * If the directory does not exist or if there is no index in it. * @param directory the directory to check for an index * @return <code>true</code> if an index exists; <code>false</code> otherwise * @throws IOException if there is a problem with accessing the index */ public static boolean indexExists(Directory directory) throws IOException { return directory.fileExists("segments"); } /** Returns the number of documents in this index. */ abstract public int numDocs(); /** Returns one greater than the largest possible document number. This may be used to, e.g., determine how big to allocate an array which will have an element for every document number in an index. */ abstract public int maxDoc(); /** Returns the stored fields of the <code>n</code><sup>th</sup> <code>Document</code> in this index. */ abstract public Document document(int n) throws IOException; /** Returns true if document <i>n</i> has been deleted */ abstract public boolean isDeleted(int n); /** Returns the byte-encoded normalization factor for the named field of every document. This is used by the search code to score documents. @see org.apache.lucene.search.Similarity#norm */ abstract public byte[] norms(String field) throws IOException; /** Returns an enumeration of all the terms in the index. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ abstract public TermEnum terms() throws IOException; /** Returns an enumeration of all terms after a given term. The enumeration is ordered by Term.compareTo(). Each term is greater than all that precede it in the enumeration. */ abstract public TermEnum terms(Term t) throws IOException; /** Returns the number of documents containing the term <code>t</code>. */ abstract public int docFreq(Term t) throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, the document number, the frequency of the term in that document is also provided, for use in search scoring. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq&gt;<sup>*</sup> </ul> <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermDocs termDocs(Term term) throws IOException { TermDocs termDocs = termDocs(); termDocs.seek(term); return termDocs; } /** Returns an unpositioned {@link TermDocs} enumerator. */ abstract public TermDocs termDocs() throws IOException; /** Returns an enumeration of all the documents which contain <code>term</code>. For each document, in addition to the document number and frequency of the term in that document, a list of all of the ordinal positions of the term in the document is available. Thus, this method implements the mapping: <p><ul> Term &nbsp;&nbsp; =&gt; &nbsp;&nbsp; &lt;docNum, freq, &lt;pos<sub>1</sub>, pos<sub>2</sub>, ... pos<sub>freq-1</sub>&gt; &gt;<sup>*</sup> </ul> <p> This positional information faciliates phrase and proximity searching. <p>The enumeration is ordered by document number. Each document number is greater than all that precede it in the enumeration. */ public TermPositions termPositions(Term term) throws IOException { TermPositions termPositions = termPositions(); termPositions.seek(term); return termPositions; } /** Returns an unpositioned {@link TermPositions} enumerator. */ abstract public TermPositions termPositions() throws IOException; /** Deletes the document numbered <code>docNum</code>. Once a document is deleted it will not appear in TermDocs or TermPostitions enumerations. Attempts to read its field with the {@link #document} method will result in an error. The presence of this document may still be reflected in the {@link #docFreq} statistic, though this will be corrected eventually as the index is further modified. */ public synchronized final void delete(int docNum) throws IOException { if (writeLock == null) { Lock writeLock = directory.makeLock("write.lock"); if (!writeLock.obtain()) // obtain write lock throw new IOException("Index locked for write: " + writeLock); this.writeLock = writeLock; } doDelete(docNum); } abstract void doDelete(int docNum) throws IOException; /** Deletes all documents containing <code>term</code>. This is useful if one uses a document field to hold a unique ID string for the document. Then to delete such a document, one merely constructs a term with the appropriate field and the unique ID string as its text and passes it to this method. Returns the number of documents deleted. */ public final int delete(Term term) throws IOException { TermDocs docs = termDocs(term); if ( docs == null ) return 0; int n = 0; try { while (docs.next()) { delete(docs.doc()); n++; } } finally { docs.close(); } return n; } /** * Closes files associated with this index. * Also saves any new deletions to disk. * No other methods should be called after this has been called. */ public final synchronized void close() throws IOException { doClose(); if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } /** Implements close. */ abstract void doClose() throws IOException; /** Release the write lock, if needed. */ protected final void finalize() throws IOException { if (writeLock != null) { writeLock.release(); // release write lock writeLock = null; } } /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(Directory directory) throws IOException { return directory.fileExists("write.lock"); } /** * Returns <code>true</code> iff the index in the named directory is * currently locked. * @param directory the directory to check for a lock * @throws IOException if there is a problem with accessing the index */ public static boolean isLocked(String directory) throws IOException { return (new File(directory, "write.lock")).exists(); } /** * Forcibly unlocks the index in the named directory. * <P> * Caution: this should only be used by failure recovery code, * when it is known that no other process nor thread is in fact * currently accessing this index. */ public static void unlock(Directory directory) throws IOException { directory.deleteFile("write.lock"); directory.deleteFile("commit.lock"); } }
package se.z_app.stb.api.zenterio; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import se.z_app.stb.WebTVItem; import se.z_app.stb.api.MonoDirectionalCmdInterface; import se.z_app.stb.api.RemoteControl.Button; public class RCCommand implements MonoDirectionalCmdInterface { private String iPAdress; private enum Method{ SENDTEXT, SENDBUTTON, LAUNCH, PLAYWEBTV, QUEUEWEBTV, FACEBOOKAUTH, RAWPOST, RAWGET; } /** * Constructor that takes the IP adress of the STB as in argument. * @param iP */ public RCCommand(String iP){ iPAdress = iP.trim(); } /** * Sends a text string to the STB. */ public void sendText(String text) { new Thread(new RCCommandRunnable(Method.SENDTEXT, iPAdress, text)).start(); } /** * Sends a button command to the STB. */ public void sendButton(Button button) { new Thread(new RCCommandRunnable(Method.SENDBUTTON, iPAdress, buttonToString(button))).start(); } /** * Launches the note corresponding to the url. Whatever that is. */ public void launch(String url) { new Thread(new RCCommandRunnable(Method.LAUNCH, iPAdress, url)).start(); } /** * Plays the webtvitem. */ public void playWebTV(WebTVItem item) { new Thread(new RCCommandRunnable(Method.PLAYWEBTV, iPAdress, item.getId())).start(); } /** * Queues the webtv item. */ public void queueWebTV(WebTVItem item) { new Thread(new RCCommandRunnable(Method.QUEUEWEBTV, iPAdress, item.getId())).start(); } /** * Sends the facebook authorisation. */ public void facebookAuth(String accesstoken, String expires, String uid) { new Thread(new RCCommandRunnable(Method.FACEBOOKAUTH, iPAdress, accesstoken, expires, uid)).start(); } /** * Sends a rawpost. */ public void rawPost(String rawPostData, String uri) { new Thread(new RCCommandRunnable(Method.RAWPOST, iPAdress, rawPostData, uri)).start(); } /** * Sends a raw get. */ public void rawGet(String uri) { new Thread(new RCCommandRunnable(Method.RAWGET, iPAdress, uri)).start(); } /** * Private function translating * @param button * @return */ private String buttonToString(Button button){ String returnString = button.toString(); if(!returnString.startsWith("P")) returnString = "P"+returnString; returnString = returnString.toLowerCase(); return returnString; } /** * Private class that sends the command to the box. * The reason for this class is that it needs to be able to access * variables. And therefore you need a customized constructor. * @author Linus * */ private class RCCommandRunnable implements Runnable{ private String arg1 = null; private String arg2 = null; private String arg3 = null; private String address = null; private Method method; private HttpClient httpclient; private HttpPost httppost; private HttpGet httpGet; /** * Constructor with 1 argument. * @param method * @param address * @param arg1 */ public RCCommandRunnable(Method method, String address, String arg1){ this.method = method; this.address = address; this.arg1 = arg1; } /** * Constructor with 2 arguments. * @param method * @param address * @param arg1 * @param arg2 */ public RCCommandRunnable(Method method, String address, String arg1, String arg2){ this.method = method; this.address = address; this.arg1 = arg1; this.arg2 = arg2; } /** * Constructor with 3 arguments. * @param method * @param address * @param arg1 * @param arg2 * @param arg3 */ public RCCommandRunnable(Method method, String address, String arg1, String arg2, String arg3){ this.method = method; this.address = address; this.arg1 = arg1; this.arg2 = arg2; this.arg3 = arg3; } @Override /** * Sends the command to the box */ public void run() { switch(method){ case FACEBOOKAUTH: httpclient = new DefaultHttpClient(); httpGet = new HttpGet("http://" + address +"/mdio/facebook?accesstoken="+arg1+"&expires="+arg2+"&uid="+arg3); try { httpclient.execute(httpGet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case LAUNCH: httpclient = new DefaultHttpClient(); httpGet = new HttpGet("http://" + address +"mdio/launchurl?url="+arg1); try { httpclient.execute(httpGet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case PLAYWEBTV: httpclient = new DefaultHttpClient(); httpGet = new HttpGet("http://" + address +"/mdio/webtv/play?url="+arg1); try { httpclient.execute(httpGet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case QUEUEWEBTV: httpclient = new DefaultHttpClient(); httpGet = new HttpGet("http://" + address +"/mdio/webtv/play?url="+arg1+"&queue=1"); try { httpclient.execute(httpGet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case RAWGET: httpclient = new DefaultHttpClient(); httpGet = new HttpGet("http://" + address + arg1); try { httpclient.execute(httpGet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case RAWPOST: httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://" + address + arg2); try { httppost.setEntity(new StringEntity(arg1)); httpclient.execute(httppost); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case SENDBUTTON: httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://" + address + "/cgi-bin/writepipe_key"); try { httppost.setEntity(new StringEntity(arg1)); httpclient.execute(httppost); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case SENDTEXT: httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://" + address + "/cgi-bin/writepipe_text"); try { httppost.setEntity(new StringEntity(arg1)); httpclient.execute(httppost); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } } } }
package org.animotron.statement.query; import javolution.util.FastList; import javolution.util.FastMap; import javolution.util.FastSet; import javolution.util.FastTable; import org.animotron.graph.index.Order; import org.animotron.io.Pipe; import org.animotron.manipulator.Evaluator; import org.animotron.manipulator.OnContext; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.Statement; import org.animotron.statement.Statements; import org.animotron.statement.operator.*; import org.animotron.statement.relation.SHALL; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexHits; import org.neo4j.graphdb.traversal.Evaluation; import org.neo4j.graphdb.traversal.TraversalDescription; import org.neo4j.kernel.Traversal; import org.neo4j.kernel.Uniqueness; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.neo4j.graphdb.Direction.OUTGOING; import static org.animotron.graph.RelationshipTypes.RESULT; /** * Query operator 'Get'. Return 'have' relations on provided context. * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> */ public class GET extends AbstractQuery implements Shift { public static final GET _ = new GET(); private static boolean debug = true; private GET() { super("get", "<~"); } protected GET(String... name) { super(name); } public OnQuestion onCalcQuestion() { return new Calc(); } class Calc extends OnQuestion { @Override public void act(final PFlow pf) throws IOException { //if (debug) System.out.println("GET "+Thread.currentThread()); final Relationship op = pf.getOP(); final Node node = op.getEndNode(); final FastSet<Relationship> visitedREFs = FastSet.newInstance(); final FastSet<Node> thes = FastSet.newInstance(); try { Relationship r = null; Pipe p = AN.getREFs(pf, pf.getVector()); QCAVector theNode; while ((theNode = p.take()) != null) { r = theNode.getClosest(); if (r.isType(AN._)) { try { Pipe pp = Utils.eval(pf.getController(), theNode); QCAVector rr; while ((rr = pp.take()) != null) { thes.add(rr.getClosestEndNode()); } } catch (Throwable t) { pf.sendException(t); return; } } else thes.add(r.getEndNode()); } evalGet(pf, op, node, thes, visitedREFs); } finally { FastSet.recycle(thes); FastSet.recycle(visitedREFs); } } private void evalGet( final PFlow pf, final Relationship op, final Node node, final Set<Node> thes, final Set<Relationship> visitedREFs) throws IOException { if (debug) { Utils.debug(GET._, op, thes); } //check, maybe, result was already calculated if (!Utils.results(pf)) { //no pre-calculated result, calculate it OnContext onContext = new OnContext() { @Override public void onMessage(QCAVector vector) { super.onMessage(vector); if (vector == null) return; if (debug) { System.out.println("GET on context "+Thread.currentThread()); System.out.println("GET ["+op+"] vector "+vector); } get(pf, vector, thes, visitedREFs); } }; //pf.answerChannel().subscribe(onContext); if (Utils.haveContext(pf)) { Evaluator.sendQuestion(pf.getController(), onContext, pf.getVector(), node); onContext.isDone(); } else { if (debug) System.out.println("\nGET ["+op+"] empty "); FastSet<QCAVector> refs = FastSet.newInstance(); try { QCAVector vector = pf.getVector(); if (vector.getContext() != null) { for (QCAVector v : vector.getContext()) { refs.add(v); } } // vector = vector.getPrecedingSibling(); // while (vector != null) { // refs.add(vector); // vector = vector.getPrecedingSibling(); get(pf, refs, thes, visitedREFs, false); } finally { FastSet.recycle(refs); } } } }; } public boolean get(PFlow pf, QCAVector vector, final Set<Node> thes, Set<Relationship> visitedREFs) { FastSet<QCAVector> refs = FastSet.newInstance(); try { refs.add(vector); return get(pf, refs, thes, visitedREFs, true); } finally { FastSet.recycle(refs); } } private boolean check( final PFlow pf, final QCAVector v, final Relationship toCheck, final Node middle, final Set<Node> thes, final Set<Relationship> visitedREFs, final boolean onContext) { if (toCheck == null) return false; if (visitedREFs.contains(toCheck)) return false; //if (toCheck.isType(REF._) && visitedREFs.contains(v.getQuestion())) return false; visitedREFs.add(toCheck); if (searchForHAVE(pf, toCheck, v, middle, thes, onContext)) return true; //if (!pf.isInStack(have[i])) { //set.add(new QCAVector(op, v, have[i])); return false; } public boolean get( final PFlow pf, final Set<QCAVector> REFs, final Set<Node> thes, Set<Relationship> visitedREFs, final boolean onContext) { if (visitedREFs == null) visitedREFs = new FastSet<Relationship>(); FastSet<QCAVector> nextREFs = FastSet.newInstance(); FastSet<QCAVector> newREFs = FastSet.newInstance(); FastSet<QCAVector> tmp = null; try { nextREFs.addAll(REFs); boolean found = false; Relationship t = null; while (true) { if (debug) System.out.println("["+pf.getOP()+"] nextREFs "); QCAVector v = null; for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); if (debug) System.out.println("checking "+v); QCAVector next = v; while (next != null) { if (next.getQuestion() != null && next.hasAnswer()) { Node middle = null; Statement s = Statements.relationshipType(next.getQuestion()); if (s instanceof ANY) { try { middle = next.getQuestion().getEndNode().getSingleRelationship(REF._, OUTGOING).getEndNode(); } catch (Exception e) { e.printStackTrace(); } } if (!check(pf, next, next.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) { if (next.getAnswers() != null) for (QCAVector vv : next.getAnswers()) { if (check(pf, next, vv.getUnrelaxedAnswer(), middle, thes, visitedREFs, onContext)) found = true; } } else { found = true; } } visitedREFs.add(next.getQuestion()); next = null;//next.getPrecedingSibling(); } } if (found) return true; //newREFs = new FastSet<QCAVector>(); for (FastSet.Record r = nextREFs.head(), end = nextREFs.tail(); (r = r.getNext()) != end;) { v = nextREFs.valueOf(r); List<QCAVector> cs = v.getContext(); if (cs != null) { for (QCAVector c : cs) { checkVector(c, newREFs, visitedREFs); } } QCAVector next = v; while (next != null) { t = next.getUnrelaxedAnswer(); if (t != null && !t.equals(next.getQuestion())) { if (! t.isType(AN._)) getOutgoingReferences(pf, next, t, t.getStartNode(), newREFs, visitedREFs); getOutgoingReferences(pf, next, t, t.getEndNode(), newREFs, visitedREFs); } //cs = next.getContext(); //if (cs != null) { // for (QCAVector c : cs) { // checkVector(c, newREFs, visitedREFs); next = null;//next.getPrecedingSibling(); } } if (newREFs.size() == 0) return false; //swap tmp = nextREFs; nextREFs = newREFs; newREFs = tmp; newREFs.clear(); } } finally { FastSet.recycle(nextREFs); FastSet.recycle(newREFs); } } private void checkVector(final QCAVector c, final Set<QCAVector> newREFs, final Set<Relationship> visitedREFs) { Relationship t = c.getUnrelaxedAnswer(); if (t != null && !visitedREFs.contains(t)) newREFs.add(c); else { t = c.getQuestion(); if (!visitedREFs.contains(t)) newREFs.add(c); } } private void getOutgoingReferences(PFlow pf, QCAVector vector, Relationship rr, Node node, Set<QCAVector> newREFs, Set<Relationship> visitedREFs) { QCAVector prev = null; IndexHits<Relationship> it = Order._.context(node); try { for (Relationship r : it) { if (visitedREFs != null && visitedREFs.contains(r)) { continue; } prev = vector.question(r, prev); Statement st = Statements.relationshipType(r); if (st instanceof AN) { Pipe p = AN.getREFs(pf, prev); QCAVector v; while ((v = p.take()) != null) { Relationship t = v.getClosest(); prev.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(t)) { newREFs.add(v); } } } else if (st instanceof Reference) { // if (!pf.isInStack(r)) { //System.out.println("["+pf.getOP()+"] evaluate "+prev); Pipe in = Evaluator._.execute(pf.getController(), prev); QCAVector v; while ((v = in.take()) != null) { prev.addAnswer(v); if (visitedREFs != null && !visitedREFs.contains(v.getAnswer())) newREFs.add(v); } } } } catch (Throwable t) { pf.sendException(t); } finally { it.close(); } } private boolean searchForHAVE( final PFlow pf, final Relationship ref, final QCAVector v, final Node middle, final Set<Node> thes, final boolean onContext) { //search for inside 'HAVE' //return searchForHAVE(pf, ref, ref.getEndNode(), thes); if (getByHave(pf, v, ref, THE._.getActualEndNode(ref), middle, thes, onContext)) return true; //search for local 'HAVE' if (ref.isType(REF._)) { if (getByHave(pf, v, v.getQuestion(), ref.getStartNode(), middle, thes, onContext)) return true; } return false; } private boolean relaxReference(PFlow pf, QCAVector vector, Relationship op) { try{ if (!(op.isType(ANY._) || op.isType(GET._))) { if (debug) System.out.println("["+pf.getOP()+"] answered "+op); pf.sendAnswer(pf.getVector().answered(op, vector), RESULT); //pf.sendAnswer(op); return true; } if (debug) System.out.println("["+pf.getOP()+"] Relaxing "+op+" @ "+vector); try { Pipe in = Evaluator._.execute(pf.getController(), vector.question(op)); //if (!in.hasNext()) return false; boolean answered = false; Relationship res = null; QCAVector v; while ((v = in.take()) != null) { res = v.getAnswer(); if (!pf.isInStack(res)) { if (debug) System.out.println("["+pf.getOP()+"] Relaxing answered "+v.getAnswer()); pf.sendAnswer(vector.answered(v.getAnswer(), v), RESULT); answered = true; } } return answered; } catch (IOException e) { pf.sendException(e); } } catch (Throwable t) { pf.sendException(t); } return false; } private boolean haveMiddle(Path path, Node middle) { for (Node n : path.nodes()) { if (n.equals(middle)) return true; } return false; } private static TraversalDescription prepared = Traversal.description(). depthFirst(). uniqueness(Uniqueness.RELATIONSHIP_PATH). relationships(ANY._, OUTGOING). relationships(AN._, OUTGOING). relationships(REF._, OUTGOING). relationships(GET._, OUTGOING). relationships(SHALL._, OUTGOING); private boolean getByHave( final PFlow pf, QCAVector vector, Relationship op, final Node context, final Node middle, final Set<Node> thes, final boolean onContext) { if (context == null) return false; System.out.println("middle "+middle); TraversalDescription trav = prepared. evaluator(new Searcher(){ @Override public Evaluation evaluate(Path path) { return _evaluate_(path, thes); } }); FastMap<Relationship, List<Path>> paths = FastMap.newInstance(); try { boolean middlePresent = false; List<Path> l; for (Path path : trav.traverse(context)) { if (debug) System.out.println("["+pf.getOP()+"] * "+path); if (path.length() == 1) { if (op == null) { System.out.println("WARNING: DONT KNOW OP"); continue; } if (pf.getOP().equals(op)) continue; l = new FastList<Path>(); l.add(path); paths.put(op, l); continue; } if (path.length() == 2) { //UNDERSTAND: should we check context Relationship r = path.relationships().iterator().next(); if (pf.getVector().getQuestion().getId() == r.getId()) continue; if (relaxReference(pf, vector, r)) return true; } Relationship fR = path.relationships().iterator().next(); List<Path> ps = paths.get(fR); if (ps == null) {// || p.length() > path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) { l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { if (thisMiddle) { middlePresent = thisMiddle; paths.clear(); } l = new FastList<Path>(); l.add(path); paths.put(fR, l); } } else { l = paths.get(fR); if (l.get(0).length() > path.length()) { middlePresent = haveMiddle(path, middle); l.clear(); l.add(path); } else if (l.get(0).length() == path.length()) { boolean thisMiddle = haveMiddle(path, middle); if (middlePresent) { if (thisMiddle) l.add(path); } else { if (thisMiddle) { middlePresent = thisMiddle; l.clear(); l.add(path); } else { l.add(path); } } } } } if (paths.isEmpty()) return false; Relationship startBy = null; int refs = 0; int ANs = 0; //if (op.isType(RESULT)) ANs++; Relationship res = null; Relationship prevRes = null; Relationship prevPrevRes = null; FastTable<Relationship> resByHAVE = FastTable.newInstance(); FastTable<Relationship> resByIS = FastTable.newInstance(); try { for (List<Path> ps : paths.values()) { for (Path path : ps) { res = null; prevRes = null; prevPrevRes = null; if (path.length() == 1 && path.lastRelationship().isType(REF._)) { res = op; } else { Iterator<Relationship> it = path.relationships().iterator(); for (Relationship r = null; it.hasNext(); ) { r = it.next(); if (startBy == null) startBy = r; if (!pf.isInStack(r)) { if (r.isType(AN._)) { res = r; ANs++; } else { if (ANs > 1) { //check is it pseudo HAVE or IS topology. on HAVE return it else last of top if (r.isType(REF._) && it.hasNext()) { r = it.next(); if (r.isType(AN._) && Utils.haveContext(r.getEndNode())) res = r; } break; } ANs = 0; if (r.isType(ANY._)) { if (it.hasNext() && it.next().isType(REF._) && !it.hasNext()) { res = r; } else { res = null; } break; } else if (r.isType(GET._)) { if (it.hasNext()) if (it.next().isType(REF._) && !it.hasNext()) res = r; break; } else if (r.isType(SHALL._)) { res = r; } else if (r.isType(REF._)) { //ignore pseudo IS if (Utils.haveContext(r.getStartNode())) { prevRes = null; if (onContext) break; else if (refs > 1) break; refs++; } else { prevPrevRes = prevRes; prevRes = res; } } } } } } if (prevPrevRes != null) res = prevPrevRes; if (res != null) { if (startBy != null && startBy.isType(REF._)) resByIS.add(res); else resByHAVE.add(res); } startBy = null; } } if (!resByHAVE.isEmpty()) { for (Relationship r : resByHAVE) { relaxReference(pf, vector, r); } } else { if (resByIS.isEmpty()) return false; for (Relationship r : resByIS) { relaxReference(pf, vector, r); } } } finally{ FastTable.recycle(resByHAVE); FastTable.recycle(resByIS); } return true; } finally { FastMap.recycle(paths); } } }
package org.apache.velocity.runtime; import java.io.InputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Hashtable; import java.util.Properties; import java.util.Stack; import java.util.Enumeration; import java.util.TreeMap; import java.util.Vector; import org.apache.log.Logger; import org.apache.velocity.Template; import org.apache.velocity.runtime.log.LogManager; import org.apache.velocity.runtime.log.LogSystem; import org.apache.velocity.runtime.parser.Parser; import org.apache.velocity.runtime.parser.ParseException; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.runtime.directive.Directive; import org.apache.velocity.runtime.VelocimacroFactory; import org.apache.velocity.runtime.resource.Resource; import org.apache.velocity.runtime.resource.ContentResource; import org.apache.velocity.runtime.resource.ResourceManager; import org.apache.velocity.util.SimplePool; import org.apache.velocity.util.StringUtils; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.runtime.configuration.Configuration; public class Runtime implements RuntimeConstants { /** * VelocimacroFactory object to manage VMs */ private static VelocimacroFactory vmFactory = new VelocimacroFactory(); /** * The Runtime logger. */ private static LogSystem logSystem = null; /** * The caching system used by the Velocity Runtime */ private static Hashtable globalCache; /** * The Runtime parser pool */ private static SimplePool parserPool; /** * Indicate whether the Runtime has been fully initialized. */ private static boolean initialized; /** * These are the properties that are laid down over top * of the default properties when requested. */ private static Configuration overridingProperties = null; /** * The logging systems initialization may be defered if * it is to be initialized by an external system. There * may be messages that need to be stored until the * logger is instantiated. They will be stored here * until the logger is alive. */ private static Vector pendingMessages = new Vector(); /** * This is a hashtable of initialized directives. * The directives that populate this hashtable are * taken from the RUNTIME_DEFAULT_DIRECTIVES * property file. This hashtable is passed * to each parser that is created. */ private static Hashtable runtimeDirectives; /** * Object that houses the configuration options for * the velocity runtime. The Configuration object allows * the convenient retrieval of a subset of properties. * For example all the properties for a resource loader * can be retrieved from the main Configuration object * using something like the following: * * Configuration loaderConfiguration = * configuration.subset(loaderID); * * And a configuration is a lot more convenient to deal * with then conventional properties objects, or Maps. */ private static Configuration configuration = new Configuration(); /* * This is the primary initialization method in the Velocity * Runtime. The systems that are setup/initialized here are * as follows: * * <ul> * <li>Logging System</li> * <li>ResourceManager</li> * <li>Parser Pool</li> * <li>Global Cache</li> * <li>Static Content Include System</li> * <li>Velocimacro System</li> * </ul> */ public synchronized static void init() throws Exception { if (initialized == false) { try { initializeProperties(); initializeLogger(); ResourceManager.initialize(); initializeDirectives(); initializeParserPool(); initializeGlobalCache(); /* * initialize the VM Factory. It will use the properties * accessable from Runtime, so keep this here at the end. */ vmFactory.initVelocimacro(); info("Velocity successfully started."); initialized = true; } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } } /** * Initializes the Velocity Runtime with properties file. * The properties file may be in the file system proper, * or the properties file may be in the classpath. */ private static void setDefaultProperties() { ClassLoader classLoader = Runtime.class.getClassLoader(); try { InputStream inputStream = classLoader .getResourceAsStream( DEFAULT_RUNTIME_PROPERTIES ); configuration.load( inputStream ); info ("Default Properties File: " + new File(DEFAULT_RUNTIME_PROPERTIES).getPath()); } catch (IOException ioe) { System.err.println("Cannot get Velocity Runtime default properties!"); } } /** * Allows an external system to set a property in * the Velocity Runtime. * * @param String property key * @param String property value */ public static void setProperty(String key, Object value) { if (overridingProperties == null) { overridingProperties = new Configuration(); } overridingProperties.setProperty( key, value ); } /** * Allow an external system to set a Configuration * object to use. This is useful where the external * system also uses the Configuration class and * the velocity configuration is a subset of * parent application's configuration. This is * the case with Turbine. * * @param Configuration configuration */ public static void setConfiguration(Configuration configuration) { if (overridingProperties == null) { overridingProperties = configuration; } else { overridingProperties.combine(configuration); } } /** * Add a property to the configuration. If it already * exists then the value stated here will be added * to the configuration entry. For example, if * * resource.loader = file * * is already present in the configuration and you * * addProperty("resource.loader", "classpath") * * Then you will end up with a Vector like the * following: * * ["file", "classpath"] * * @param String key * @param String value */ public static void addProperty(String key, Object value) { if (overridingProperties == null) { overridingProperties = new Configuration(); } overridingProperties.addProperty( key, value ); } /** * Allows an external caller to get a property. The calling * routine is required to know the type, as this routine * will return an Object, as that is what properties can be. * * @param key property to return */ public static Object getProperty( String key ) { return configuration.getProperty( key ); } /** * Initialize Velocity properties, if the default * properties have not been laid down first then * do so. Then proceed to process any overriding * properties. Laying down the default properties * gives a much greater chance of having a * working system. */ private static void initializeProperties() { /* * Always lay down the default properties first as * to provide a solid base. */ if (configuration.isInitialized() == false) { setDefaultProperties(); } if( overridingProperties != null) { configuration.combine(overridingProperties); } } /** * Initialize the Velocity Runtime with a Properties * object. * * @param Properties */ public static void init(Properties p) throws Exception { overridingProperties = Configuration.convertProperties(p); init(); } /** * Initialize the Velocity Runtime with the name of * Configuration object. * * @param Properties */ public static void init(String configurationFile) throws Exception { overridingProperties = new Configuration(configurationFile); init(); } /** * Initialize the Velocity logging system. * * @throws Exception */ private static void initializeLogger() throws Exception { /* * Initialize the logger. We will eventually move all * logging into the logging manager. */ if (logSystem == null) { logSystem = LogManager.createLogSystem(); } /* * Dump the pending messages */ dumpPendingMessages(); } /* * Dump the pending messages */ private static void dumpPendingMessages() { if ( !pendingMessages.isEmpty()) { /* * iterate and log each individual message... */ for( Enumeration e = pendingMessages.elements(); e.hasMoreElements(); ) { Object[] data = (Object[]) e.nextElement(); log(((Integer) data[0]).intValue(), data[1]); } pendingMessages = new Vector(); } } /** * This methods initializes all the directives * that are used by the Velocity Runtime. The * directives to be initialized are listed in * the RUNTIME_DEFAULT_DIRECTIVES properties * file. * * @throws Exception */ private static void initializeDirectives() throws Exception { /* * Initialize the runtime directive table. * This will be used for creating parsers. */ runtimeDirectives = new Hashtable(); Properties directiveProperties = new Properties(); /* * Grab the properties file with the list of directives * that we should initialize. */ ClassLoader classLoader = Runtime.class.getClassLoader(); InputStream inputStream = classLoader .getResourceAsStream(DEFAULT_RUNTIME_DIRECTIVES); if (inputStream == null) throw new Exception("Error loading directive.properties! " + "Something is very wrong if these properties " + "aren't being located. Either your Velocity " + "distribution is incomplete or your Velocity " + "jar file is corrupted!"); directiveProperties.load(inputStream); /* * Grab all the values of the properties. These * are all class names for example: * * org.apache.velocity.runtime.directive.Foreach */ Enumeration directiveClasses = directiveProperties.elements(); while (directiveClasses.hasMoreElements()) { String directiveClass = (String) directiveClasses.nextElement(); try { /* * Attempt to instantiate the directive class. This * should usually happen without error because the * properties file that lists the directives is * not visible. It's in a package that isn't * readily accessible. */ Class clazz = Class.forName(directiveClass); Directive directive = (Directive) clazz.newInstance(); runtimeDirectives.put(directive.getName(), directive); Runtime.info("Loaded Pluggable Directive: " + directiveClass); } catch (Exception e) { Runtime.error("Error Loading Pluggable Directive: " + directiveClass); } } } /** * Initializes the Velocity parser pool. * This still needs to be implemented. */ private static void initializeParserPool() { parserPool = new SimplePool(NUMBER_OF_PARSERS); for (int i=0;i<NUMBER_OF_PARSERS ;i++ ) { parserPool.put (createNewParser()); } Runtime.info ("Created: " + NUMBER_OF_PARSERS + " parsers."); } /** * Returns a JavaCC generated Parser. * * @return Parser javacc generated parser */ public static Parser createNewParser() { Parser parser = new Parser(); parser.setDirectives(runtimeDirectives); return parser; } /** * Parse the input stream and return the root of * AST node structure. * * @param InputStream inputstream retrieved by a resource loader * @param String name of the template being parsed */ public static SimpleNode parse(InputStream inputStream, String templateName ) throws ParseException { SimpleNode ast = null; Parser parser = (Parser) parserPool.get(); if (parser != null) { try { ast = parser.parse(inputStream, templateName); } finally { parserPool.put(parser); } } else { error("Runtime : ran out of parsers!"); } return ast; } /** * Initialize the global cache use by the Velocity * runtime. Cached templates will be stored here, * as well as cached content pulled in by the #include * directive. Who knows what else we'll find to * cache. */ private static void initializeGlobalCache() { globalCache = new Hashtable(); } /** * Returns a <code>Template</code> from the resource manager * * @param name The file name of the desired template. * @return The template. * @throws ResourceNotFoundException if template not found * from any available source. * @throws ParseErrorException if template cannot be parsed due * to syntax (or other) error. * @throws Exception if an error occurs in template initialization */ public static Template getTemplate(String name) throws ResourceNotFoundException, ParseErrorException, Exception { return (Template) ResourceManager .getResource(name,ResourceManager.RESOURCE_TEMPLATE); } /** * Returns a static content resource from the * resource manager. * * @param name Name of content resource to get * @return parsed ContentResource object ready for use * @throws ResourceNotFoundException if template not found * from any available source. */ public static ContentResource getContent(String name) throws ResourceNotFoundException, ParseErrorException, Exception { return (ContentResource) ResourceManager .getResource(name,ResourceManager.RESOURCE_CONTENT); } /** * Added this to check and make sure that the configuration * is initialized before trying to get properties from it. * This occurs when there are errors during initialization * and the default properties have yet to be layed down. */ private static boolean showStackTrace() { if (configuration.isInitialized()) { return getBoolean(RUNTIME_LOG_WARN_STACKTRACE, false); } else { return false; } } /** * Handle logging. * * @param String message to log */ private static void log(int level, Object message) { String out = ""; /* * Start with the appropriate prefix */ switch( level ) { case LogSystem.DEBUG_ID : out = DEBUG_PREFIX; break; case LogSystem.INFO_ID : out = INFO_PREFIX; break; case LogSystem.WARN_ID : out = WARN_PREFIX; break; case LogSystem.ERROR_ID : out = ERROR_PREFIX; break; default : out = UNKNOWN_PREFIX; break; } /* * now, see if the logging stacktrace is on * and modify the message to suit */ if ( showStackTrace() && (message instanceof Throwable || message instanceof Exception) ) { out += StringUtils.stackTrace((Throwable)message); } else { out += message.toString(); } /* * now, if we have a log system, log it * otherwise, queue it up for later */ if (logSystem != null) { logSystem.logVelocityMessage( level, out); } else { Object[] data = new Object[2]; data[0] = new Integer(level); data[1] = out; pendingMessages.addElement(data); } } /** * Log a warning message. * * @param Object message to log */ public static void warn(Object message) { log(LogSystem.WARN_ID, message); } /** * Log an info message. * * @param Object message to log */ public static void info(Object message) { log(LogSystem.INFO_ID, message); } /** * Log an error message. * * @param Object message to log */ public static void error(Object message) { log(LogSystem.ERROR_ID, message); } /** * Log a debug message. * * @param Object message to log */ public static void debug(Object message) { log(LogSystem.DEBUG_ID, message); } /** * String property accessor method with default to hide the * configuration implementation. * * @param String key property key * @param String defaultValue default value to return if key not * found in resource manager. * @return String value of key or default */ public static String getString( String key, String defaultValue) { return configuration.getString(key, defaultValue); } /** * Returns the appropriate VelocimacroProxy object if strVMname * is a valid current Velocimacro. * * @param String vmName Name of velocimacro requested * @return String VelocimacroProxy */ public static Directive getVelocimacro( String vmName, String templateName ) { return vmFactory.getVelocimacro( vmName, templateName ); } public static boolean addVelocimacro( String name, String macro, String argArray[], String sourceTemplate ) { return vmFactory.addVelocimacro( name, macro, argArray, sourceTemplate ); } /** * Checks to see if a VM exists * * @param name Name of velocimacro * @return boolean True if VM by that name exists, false if not */ public static boolean isVelocimacro( String vmName, String templateName ) { return vmFactory.isVelocimacro( vmName, templateName ); } /** * tells the vmFactory to dump the specified namespace. This is to support * clearing the VM list when in inline-VM-local-scope mode */ public static boolean dumpVMNamespace( String namespace ) { return vmFactory.dumpVMNamespace( namespace ); } /** * String property accessor method to hide the configuration implementation * @param key property key * @return value of key or null */ public static String getString(String key) { return configuration.getString( key ); } /** * Int property accessor method to hide the configuration implementation. * * @param String key property key * @return int value */ public static int getInt( String key ) { return configuration.getInt( key ); } /** * Int property accessor method to hide the configuration implementation. * * @param key property key * @param int default value * @return int value */ public static int getInt( String key, int defaultValue ) { return configuration.getInt( key, defaultValue ); } /** * Boolean property accessor method to hide the configuration implementation. * * @param String key property key * @param boolean default default value if property not found * @return boolean value of key or default value */ public static boolean getBoolean( String key, boolean def ) { return configuration.getBoolean( key, def ); } /** * Return the velocity runtime configuration object. * * @return Configuration configuration object which houses * the velocity runtime properties. */ public static Configuration getConfiguration() { return configuration; } }
package fi.nls.paikkatietoikkuna.terrainprofile; import static org.junit.Assert.assertEquals; import fi.nls.oskari.control.ActionException; import fi.nls.oskari.service.ServiceException; import java.io.IOException; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.junit.Ignore; import org.junit.Test; import org.xml.sax.SAXException; public class TerrainProfileServiceTest { @Test @Ignore("Depends on an outside API") public void offsetIsCorrect() throws IOException, ActionException, ParserConfigurationException, SAXException, ServiceException { String endPoint = "http://avoindata.maanmittauslaitos.fi/geoserver/wcs"; String coverageId = "korkeusmalli_10m__korkeusmalli_10m"; TerrainProfileService tps = new TerrainProfileService(endPoint, coverageId); double[] coordinates = new double[] { 500002, 6822001, 501003, 6821004, 502006, 6823007, 501003, 6822509, 500502, 6823206 }; List<DataPoint> points = tps.getTerrainProfile(coordinates, 0); for (DataPoint p : points) { double e = p.getE(); double n = p.getN(); DataPoint single = tps.getTerrainProfile(new double[] { e, n }, 0).get(0); assertEquals(e, single.getE(), 0.0); assertEquals(n, single.getN(), 0.0); assertEquals(p.getAltitude(), single.getAltitude(), 0.0); } } }
package org.cejug.yougi.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; public class TextUtilsTest { Date date; SimpleDateFormat sdf, sdft; @Before public void setUp(){ date = new Date(); sdf = new SimpleDateFormat("HH:mm:ss"); sdft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); } @Test public void testCapitalizeFirstCharWords() throws Exception { Assert.assertEquals("First Char", TextUtils.INSTANCE.capitalizeFirstCharWords("first char")); } @Test public void testGetFormattedDate() throws Exception { Assert.assertEquals(new SimpleDateFormat("dd-M-yyyy").format(date), TextUtils.INSTANCE.getFormattedDate(date, "dd-L-Y")); } @Test public void testGetFormattedTime() throws Exception { sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Assert.assertEquals(sdf.format(date), TextUtils.INSTANCE.getFormattedTime(date, "HH:mm:ss", "UTC")); } @Test public void testGetFormattedDateTime() throws Exception { sdft.setTimeZone(TimeZone.getTimeZone("GMT-8:00")); Assert.assertEquals(sdft.format(date), TextUtils.INSTANCE.getFormattedTime(date, "yyyy/MM/dd HH:mm:ss", "GMT-8:00")); } }
package io.confluent.examples.streams.microservices; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.errors.InvalidStateStoreException; import org.apache.kafka.streams.kstream.Consumed; import org.apache.kafka.streams.KafkaStreams.State; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.Predicate; import org.apache.kafka.streams.state.QueryableStoreTypes; import org.apache.kafka.streams.state.ReadOnlyKeyValueStore; import org.apache.kafka.streams.StreamsConfig; import org.eclipse.jetty.server.Server; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ManagedAsync; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.net.URISyntaxException; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import io.confluent.examples.streams.avro.microservices.Order; import io.confluent.examples.streams.avro.microservices.OrderState; import io.confluent.examples.streams.interactivequeries.HostStoreInfo; import io.confluent.examples.streams.interactivequeries.MetadataService; import io.confluent.examples.streams.microservices.domain.Schemas; import io.confluent.examples.streams.microservices.domain.beans.OrderBean; import io.confluent.examples.streams.microservices.util.Paths; import static io.confluent.examples.streams.microservices.domain.Schemas.Topics.ORDERS; import static io.confluent.examples.streams.microservices.domain.beans.OrderBean.fromBean; import static io.confluent.examples.streams.microservices.domain.beans.OrderBean.toBean; import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.addShutdownHookAndBlock; import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.baseStreamsConfig; import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.setTimeout; import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.startJetty; import static io.confluent.examples.streams.microservices.util.MicroserviceUtils.startProducer; import static org.apache.kafka.streams.state.StreamsMetadata.NOT_AVAILABLE; @Path("v1") public class OrdersService implements Service { private static final Logger log = LoggerFactory.getLogger(OrdersService.class); private static final String CALL_TIMEOUT = "10000"; private static final String ORDERS_STORE_NAME = "orders-store"; private final String SERVICE_APP_ID = getClass().getSimpleName(); private final Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build(); private Server jettyServer; private final String host; private int port; private KafkaStreams streams = null; private MetadataService metadataService; private KafkaProducer<String, Order> producer; //In a real implementation we would need to (a) support outstanding requests for the same Id/filter from // different users and (b) periodically purge old entries from this map. private final Map<String, FilteredResponse<String, Order>> outstandingRequests = new ConcurrentHashMap<>(); public OrdersService(final String host, final int port) { this.host = host; this.port = port; } public OrdersService(final String host) { this(host, 0); } /** * Create a table of orders which we can query. When the table is updated * we check to see if there is an outstanding HTTP GET request waiting to be * fulfilled. */ private StreamsBuilder createOrdersMaterializedView() { final StreamsBuilder builder = new StreamsBuilder(); builder.table(ORDERS.name(), Consumed.with(ORDERS.keySerde(), ORDERS.valueSerde()), Materialized.as(ORDERS_STORE_NAME)) .toStream().foreach(this::maybeCompleteLongPollGet); return builder; } private void maybeCompleteLongPollGet(final String id, final Order order) { final FilteredResponse<String, Order> callback = outstandingRequests.get(id); if (callback != null && callback.predicate.test(id, order)) { callback.asyncResponse.resume(toBean(order)); } } /** * Perform a "Long-Poll" styled get. This method will attempt to get the value for the passed key * blocking until the key is available or passed timeout is reached. Non-blocking IO is used to * implement this, but the API will block the calling thread if no metastore data is available * (for example on startup or during a rebalance) * * @param id - the key of the value to retrieve * @param timeout - the timeout for the long-poll * @param asyncResponse - async response used to trigger the poll early should the appropriate * value become available */ @GET @ManagedAsync @Path("/orders/{id}") @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public void getWithTimeout(@PathParam("id") final String id, @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) final Long timeout, @Suspended final AsyncResponse asyncResponse) { setTimeout(timeout, asyncResponse); final HostStoreInfo hostForKey = getKeyLocationOrBlock(id, asyncResponse); if (hostForKey == null) { //request timed out so return return; } //Retrieve the order locally or reach out to a different instance if the required partition is hosted elsewhere. if (thisHost(hostForKey)) { fetchLocal(id, asyncResponse, (k, v) -> true); } else { final String path = new Paths(hostForKey.getHost(), hostForKey.getPort()).urlGet(id); fetchFromOtherHost(path, asyncResponse, timeout); } } static class FilteredResponse<K, V> { private final AsyncResponse asyncResponse; private final Predicate<K, V> predicate; FilteredResponse(final AsyncResponse asyncResponse, final Predicate<K, V> predicate) { this.asyncResponse = asyncResponse; this.predicate = predicate; } } /** * Fetch the order from the local materialized view * * @param id ID to fetch * @param asyncResponse the response to call once completed * @param predicate a filter that for this fetch, so for example we might fetch only VALIDATED * orders. */ private void fetchLocal(final String id, final AsyncResponse asyncResponse, final Predicate<String, Order> predicate) { log.info("running GET on this node"); try { final Order order = ordersStore().get(id); if (order == null || !predicate.test(id, order)) { log.info("Delaying get as order not present for id " + id); outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, predicate)); } else { asyncResponse.resume(toBean(order)); } } catch (final InvalidStateStoreException e) { //Store not ready so delay outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, predicate)); } } private ReadOnlyKeyValueStore<String, Order> ordersStore() { return streams.store(ORDERS_STORE_NAME, QueryableStoreTypes.keyValueStore()); } /** * Use Kafka Streams' Queryable State API to work out if a key/value pair is located on * this node, or on another Kafka Streams node. This returned HostStoreInfo can be used * to redirect an HTTP request to the node that has the data. * <p> * If metadata is available, which can happen on startup, or during a rebalance, block until it is. */ private HostStoreInfo getKeyLocationOrBlock(final String id, final AsyncResponse asyncResponse) { HostStoreInfo locationOfKey; while (locationMetadataIsUnavailable(locationOfKey = getHostForOrderId(id))) { //The metastore is not available. This can happen on startup/rebalance. if (asyncResponse.isDone()) { //The response timed out so return return null; } try { //Sleep a bit until metadata becomes available Thread.sleep(Math.min(Long.parseLong(CALL_TIMEOUT), 200)); } catch (final InterruptedException e) { e.printStackTrace(); } } return locationOfKey; } private boolean locationMetadataIsUnavailable(final HostStoreInfo hostWithKey) { return NOT_AVAILABLE.host().equals(hostWithKey.getHost()) && NOT_AVAILABLE.port() == hostWithKey.getPort(); } private boolean thisHost(final HostStoreInfo host) { return host.getHost().equals(this.host) && host.getPort() == port; } private void fetchFromOtherHost(final String path, final AsyncResponse asyncResponse, final long timeout) { log.info("Chaining GET to a different instance: " + path); try { final OrderBean bean = client.target(path) .queryParam("timeout", timeout) .request(MediaType.APPLICATION_JSON_TYPE) .get(new GenericType<OrderBean>() { }); asyncResponse.resume(bean); } catch (final Exception swallowed) { } } @GET @ManagedAsync @Path("orders/{id}/validated") public void getPostValidationWithTimeout(@PathParam("id") final String id, @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) final Long timeout, @Suspended final AsyncResponse asyncResponse) { setTimeout(timeout, asyncResponse); final HostStoreInfo hostForKey = getKeyLocationOrBlock(id, asyncResponse); if (hostForKey == null) { //request timed out so return return; } //Retrieve the order locally or reach out to a different instance if the required partition is hosted elsewhere. if (thisHost(hostForKey)) { fetchLocal(id, asyncResponse, (k, v) -> (v.getState() == OrderState.VALIDATED || v.getState() == OrderState.FAILED)); } else { fetchFromOtherHost(new Paths(hostForKey.getHost(), hostForKey.getPort()).urlGetValidated(id), asyncResponse, timeout); } } /** * Persist an Order to Kafka. Returns once the order is successfully written to R nodes where * R is the replication factor configured in Kafka. * * @param order the order to add * @param timeout the max time to wait for the response from Kafka before timing out the POST */ @POST @ManagedAsync @Path("/orders") @Consumes(MediaType.APPLICATION_JSON) public void submitOrder(final OrderBean order, @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) final Long timeout, @Suspended final AsyncResponse response) { setTimeout(timeout, response); final Order bean = fromBean(order); // TODO 1.1: create a new `ProducerRecord` with a key specified by `bean.getId()` and value of the bean, to the orders topic whose name is specified by `ORDERS.name()` // TODO 1.2: produce the newly created record using the existing `producer` and pass use the `OrdersService#callback` function to send the `response` and the record key } @SuppressWarnings("unchecked") @Override public void start(final String bootstrapServers, final String stateDir) { jettyServer = startJetty(port, this); port = jettyServer.getURI().getPort(); // update port, in case port was zero producer = startProducer(bootstrapServers, ORDERS); streams = startKStreams(bootstrapServers); log.info("Started Service " + getClass().getSimpleName()); } private KafkaStreams startKStreams(final String bootstrapServers) { final KafkaStreams streams = new KafkaStreams( createOrdersMaterializedView().build(), config(bootstrapServers)); metadataService = new MetadataService(streams); streams.cleanUp(); //don't do this in prod as it clears your state stores final CountDownLatch startLatch = new CountDownLatch(1); streams.setStateListener((newState, oldState) -> { if (newState == State.RUNNING && oldState != KafkaStreams.State.RUNNING) { startLatch.countDown(); } }); streams.start(); try { if (!startLatch.await(60, TimeUnit.SECONDS)) { throw new RuntimeException("Streams never finished rebalancing on startup"); } } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } return streams; } private Properties config(final String bootstrapServers) { final Properties props = baseStreamsConfig(bootstrapServers, "/tmp/kafka-streams", SERVICE_APP_ID); props.put(StreamsConfig.APPLICATION_SERVER_CONFIG, host + ":" + port); return props; } @Override public void stop() { if (streams != null) { streams.close(); } if (producer != null) { producer.close(); } if (jettyServer != null) { try { jettyServer.stop(); } catch (final Exception e) { e.printStackTrace(); } } } // for testing only void cleanLocalState() { if (streams != null) { streams.cleanUp(); } } public int port() { return port; } private HostStoreInfo getHostForOrderId(final String orderId) { return metadataService .streamsMetadataForStoreAndKey(ORDERS_STORE_NAME, orderId, Serdes.String().serializer()); } private Callback callback(final AsyncResponse response, final String orderId) { return (recordMetadata, e) -> { if (e != null) { response.resume(e); } else { try { //Return the location of the newly created resource final Response uri = Response.created(new URI("/v1/orders/" + orderId)).build(); response.resume(uri); } catch (final URISyntaxException e2) { e2.printStackTrace(); } } }; } public static void main(final String[] args) throws Exception { final String bootstrapServers = args.length > 0 ? args[0] : "localhost:9092"; final String schemaRegistryUrl = args.length > 1 ? args[1] : "http://localhost:8081"; final String restHostname = args.length > 2 ? args[2] : "localhost"; final String restPort = args.length > 3 ? args[3] : null; Schemas.configureSerdesWithSchemaRegistryUrl(schemaRegistryUrl); final OrdersService service = new OrdersService(restHostname, restPort == null ? 0 : Integer.parseInt(restPort)); service.start(bootstrapServers, "/tmp/kafka-streams"); addShutdownHookAndBlock(service); } }
package org.b3log.symphony.util; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.profiles.pegdown.Extensions; import com.vladsch.flexmark.profiles.pegdown.PegdownOptionsAdapter; import com.vladsch.flexmark.util.options.DataHolder; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Latkes; import org.b3log.latke.cache.Cache; import org.b3log.latke.cache.CacheFactory; import org.b3log.latke.ioc.LatkeBeanManager; import org.b3log.latke.ioc.LatkeBeanManagerImpl; import org.b3log.latke.ioc.Lifecycle; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.repository.jdbc.JdbcRepository; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.LangPropsServiceImpl; import org.b3log.latke.util.Callstacks; import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Common; import org.b3log.symphony.service.UserQueryService; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Parser; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.*; public final class Markdowns { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Markdowns.class); /** * Language service. */ private static final LangPropsService LANG_PROPS_SERVICE = LatkeBeanManagerImpl.getInstance().getReference(LangPropsServiceImpl.class); /** * Bean manager. */ private static final LatkeBeanManager beanManager = Lifecycle.getBeanManager(); /** * User query service. */ private static final UserQueryService userQueryService; /** * Markdown cache. */ private static final Cache MD_CACHE = CacheFactory.getCache("markdown"); /** * Markdown to HTML timeout. */ private static final int MD_TIMEOUT = 2000; /** * Marked engine serve path. */ private static final String MARKED_ENGINE_URL = "http://localhost:8250"; /** * Built-in MD engine options. */ private static final DataHolder OPTIONS = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL_WITH_OPTIONALS); /** * Built-in MD engine parser. */ private static final com.vladsch.flexmark.parser.Parser PARSER = com.vladsch.flexmark.parser.Parser.builder(OPTIONS).build(); /** * Built-in MD engine HTML renderer. */ private static final HtmlRenderer RENDERER = HtmlRenderer.builder(OPTIONS).build(); /** * Whether marked is available. */ public static boolean MARKED_AVAILABLE; static { MD_CACHE.setMaxCount(1024 * 10 * 4); if (null != beanManager) { userQueryService = beanManager.getReference(UserQueryService.class); } else { userQueryService = null; } } static { try { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write("Symphony ", outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); MARKED_AVAILABLE = StringUtils.contains(html, "<p>Symphony </p>"); if (MARKED_AVAILABLE) { LOGGER.log(Level.INFO, "[marked] is available, uses it for markdown processing"); } else { LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [flexmark] for markdown processing"); } } catch (final Exception e) { LOGGER.log(Level.INFO, "[marked] is not available caused by [" + e.getMessage() + "], uses built-in [flexmark] for markdown processing"); } } /** * Private constructor. */ private Markdowns() { } /** * Gets the safe HTML content of the specified content. * * @param content the specified content * @param baseURI the specified base URI, the relative path value of href will starts with this URL * @return safe HTML content */ public static String clean(final String content, final String baseURI) { final Document.OutputSettings outputSettings = new Document.OutputSettings(); outputSettings.prettyPrint(false); final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed(). addAttributes(":all", "id", "target", "class"). addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u"). addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight"). addAttributes("audio", "controls", "src"). addAttributes("video", "controls", "src", "width", "height"). addAttributes("source", "src", "media", "type"). addAttributes("object", "width", "height", "data", "type"). addAttributes("param", "name", "value"). addAttributes("input", "type", "disabled", "checked"). addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"), outputSettings); final Document doc = Jsoup.parse(tmp, baseURI, Parser.htmlParser()); final Elements ps = doc.getElementsByTag("p"); for (final Element p : ps) { p.removeAttr("style"); } final Elements iframes = doc.getElementsByTag("iframe"); for (final Element iframe : iframes) { final String src = StringUtils.deleteWhitespace(iframe.attr("src")); if (StringUtils.startsWithIgnoreCase(src, "javascript") || StringUtils.startsWithIgnoreCase(src, "data:")) { iframe.remove(); } } final Elements objs = doc.getElementsByTag("object"); for (final Element obj : objs) { final String data = StringUtils.deleteWhitespace(obj.attr("data")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { obj.remove(); continue; } final String type = StringUtils.deleteWhitespace(obj.attr("type")); if (StringUtils.containsIgnoreCase(type, "script")) { obj.remove(); } } final Elements embeds = doc.getElementsByTag("embed"); for (final Element embed : embeds) { final String data = StringUtils.deleteWhitespace(embed.attr("src")); if (StringUtils.startsWithIgnoreCase(data, "data:") || StringUtils.startsWithIgnoreCase(data, "javascript")) { embed.remove(); continue; } } final Elements as = doc.getElementsByTag("a"); for (final Element a : as) { a.attr("rel", "nofollow"); final String href = a.attr("href"); if (href.startsWith(Latkes.getServePath())) { continue; } a.attr("target", "_blank"); } final Elements audios = doc.getElementsByTag("audio"); for (final Element audio : audios) { audio.attr("preload", "none"); } final Elements videos = doc.getElementsByTag("video"); for (final Element video : videos) { video.attr("preload", "none"); } String ret = doc.body().html(); ret = ret.replaceAll("(</?br\\s*/?>\\s*)+", "<br>"); // patch for Jsoup issue return ret; } /** * Converts the specified markdown text to HTML. * * @param markdownText the specified markdown text * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns * 'markdownErrorLabel' if exception */ public static String toHTML(final String markdownText) { if (Strings.isEmptyOrNull(markdownText)) { return ""; } final String cachedHTML = getHTML(markdownText); if (null != cachedHTML) { return cachedHTML; } final ExecutorService pool = Executors.newSingleThreadExecutor(); final long[] threadId = new long[1]; final Callable<String> call = () -> { threadId[0] = Thread.currentThread().getId(); String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); if (MARKED_AVAILABLE) { html = toHtmlByMarked(markdownText); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } else { com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText); html = RENDERER.render(document); if (!StringUtils.startsWith(html, "<p>")) { html = "<p>" + html + "</p>"; } } final Document doc = Jsoup.parse(html); final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>(); doc.traverse(new NodeVisitor() { @Override public void head(final org.jsoup.nodes.Node node, int depth) { if (node instanceof org.jsoup.nodes.TextNode) { final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node; final org.jsoup.nodes.Node parent = textNode.parent(); if (parent instanceof Element) { final Element parentElem = (Element) parent; if (!parentElem.tagName().equals("code")) { String text = textNode.getWholeText(); boolean nextIsBr = false; final org.jsoup.nodes.Node nextSibling = textNode.nextSibling(); if (nextSibling instanceof Element) { nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName()); } if (null != userQueryService) { try { final Set<String> userNames = userQueryService.getUserNames(text); for (final String userName : userNames) { text = text.replace('@' + userName + (nextIsBr ? "" : " "), "@<a href='" + Latkes.getServePath() + "/member/" + userName + "'>" + userName + "</a> "); } text = text.replace("@participants ", "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> "); } finally { JdbcRepository.dispose(); } } if (text.contains("@<a href=")) { final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem, ""); final int index = textNode.siblingIndex(); parentElem.insertChildren(index, nodes); toRemove.add(node); } else { textNode.text(Pangu.spacingText(text)); } } } } } @Override public void tail(org.jsoup.nodes.Node node, int depth) { } }); toRemove.forEach(node -> node.remove()); doc.select("pre>code").addClass("hljs"); doc.select("a").forEach(a -> { final String src = a.attr("href"); if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) { a.attr("href", Latkes.getServePath() + "/forward?goto=" + src); } }); doc.outputSettings().prettyPrint(false); String ret = doc.select("body").html(); ret = StringUtils.trim(ret); // cache it putHTML(markdownText, ret); return ret; }; Stopwatchs.start("Md to HTML"); try { final Future<String> future = pool.submit(call); return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS); } catch (final TimeoutException e) { LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]"); Callstacks.printCallstack(Level.ERROR, new String[]{"org.b3log"}, null); final Set<Thread> threads = Thread.getAllStackTraces().keySet(); for (final Thread thread : threads) { if (thread.getId() == threadId[0]) { thread.stop(); break; } } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e); } finally { pool.shutdownNow(); Stopwatchs.end(); } return LANG_PROPS_SERVICE.get("contentRenderFailedLabel"); } private static String toHtmlByMarked(final String markdownText) throws Exception { final URL url = new URL(MARKED_ENGINE_URL); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); final OutputStream outputStream = conn.getOutputStream(); IOUtils.write(markdownText, outputStream, "UTF-8"); IOUtils.closeQuietly(outputStream); final InputStream inputStream = conn.getInputStream(); final String html = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); //conn.disconnect(); return html; } /** * Gets HTML for the specified markdown text. * * @param markdownText the specified markdown text * @return HTML */ private static String getHTML(final String markdownText) { final String hash = DigestUtils.md5Hex(markdownText); final JSONObject value = MD_CACHE.get(hash); if (null == value) { return null; } return value.optString(Common.DATA); } /** * Puts the specified HTML into cache. * * @param markdownText the specified markdown text * @param html the specified HTML */ private static void putHTML(final String markdownText, final String html) { final String hash = DigestUtils.md5Hex(markdownText); final JSONObject value = new JSONObject(); value.put(Common.DATA, html); MD_CACHE.put(hash, value); } }
package PHRED2014; import edu.wpi.first.wpilibj.*; /** * * @author PHRED */ public class ObjM implements RobotMap{ //Instance variables: Motors, Sensors, etc private Relay omMotors1; //Could be a Victor, or a spike. Same with the other victors below. private Relay omMotors2; private Relay omMotors3; private Relay omMotors4; private Ultrasonic soundSensor; private Gyro GG; //This is the Guidance Gyro //Constructor(s) public ObjM(){ omMotors1 = new Relay(SpikeI); omMotors2 = new Relay(SpikeII); omMotors3 = new Relay(SpikeIII); omMotors4 = new Relay(SpikeIV); soundSensor = new Ultrasonic(3,4); GG = new Gyro(1); //etc } public double getGyroAngle() { return GG.getAngle(); } //Methods //test whether GIT works }
package org.javasimon.jdbc4; import org.javasimon.utils.Replacer; import java.util.List; /** * SqlNormalizer takes SQL statement and replaces parameters with question marks. It is * important to realize, that normalizer IS NOT SQL analyzer. It makes as simple replacement * as possible (with my coding skill ;-)) to still truly represent the original statement. * Normalized statement is merely used to recognize the original one and also to merge * the same statements with various arguments. Its primary purpose is to limit count of * distinct per-statement Simons. It doesn't suppose to be perfect or proof to all dialects. * <p/> * Usage is simple, you create normalizer with SQL statement and than you can ask the * object for normalizedSql and type via respective getters. * * @author Radovan Sninsky * @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a> * @since 2.4 */ public final class SqlNormalizer { private static final Replacer[] FIRST_REPLACERS; private static final Replacer[] SECOND_REPLACERS; private static final Replacer FUNCTION_REPLACER = new Replacer("([-(=<>!+*/,]+\\s?)\\w+\\([^()]*\\)", "$1?", Replacer.Modificator.REPEAT_UNTIL_UNCHANGED); private static final Replacer TYPE_SELECTOR = new Replacer("^\\W*(\\w+)\\W.*", "$1"); static { FIRST_REPLACERS = new Replacer[]{ new Replacer("''", "?"), // replace empty strings and '' inside other strings new Replacer(" *([-=<>!+*/,]+) *", "$1"), // remove spaces around various operators and commas new Replacer("([-=<>!+*/]+)", " $1 "), // put spaces back (results in one space everywhere new Replacer("\\s+", " "), // normalize white spaces new Replacer("(create|alter|drop) (\\S+) ([^ (]+).*$", "$1 $2 $3"), // shring DLL to first three tokens new Replacer("([-=<>!+*/,.(]+\\s?)(?:(?:'[^']+')|(?:[0-9.]+))", "$1?"), // replace arguments after =, ( and , with ? new Replacer("like '[^']+'", "like ?"), // replace like arguments new Replacer("between \\S+ and \\S+", "between ? and ?"), // replace between arguments new Replacer(" in\\(", " in ("), // put space before ( in "in(" new Replacer("^\\{|\\}$", ""), // remove { and } at the start/end new Replacer("^\\s*begin", "call"), // replace begin with call new Replacer(";?\\s*end;?$", ""), // remove final end }; SECOND_REPLACERS = new Replacer[]{ new Replacer(",", ", "), // put spaces after , new Replacer(" in \\(\\?(?:, \\?)*\\)", " in (?)"), // shrink more ? in "in" to one }; } private final String sql; private String normalizedSql; private String type; /** * Creates SQL normalizer and performs the normalization. * * @param sql SQL to normalize */ public SqlNormalizer(String sql) { this.sql = sql; if (sql != null) { normalize(sql); } } /** * Constructor for batch normalization. Type of the "statement" will be "batch". * * @param batch list of statements */ public SqlNormalizer(List<String> batch) { sql = "batch"; StringBuilder sqlBuilder = new StringBuilder(); String lastStmt = null; int stmtCounter = 0; for (String statement : batch) { normalize(statement); if (lastStmt == null) { lastStmt = normalizedSql; } if (!lastStmt.equalsIgnoreCase(normalizedSql)) { sqlBuilder.append(stmtCounter == 1 ? "" : stmtCounter + "x ").append(lastStmt).append("; "); lastStmt = normalizedSql; stmtCounter = 1; } else { stmtCounter++; } } sqlBuilder.append(stmtCounter == 1 ? "" : stmtCounter + "x ").append(lastStmt); type = "batch"; this.normalizedSql = sqlBuilder.toString(); } private void normalize(String sql) { normalizedSql = sql.toLowerCase().trim(); applyReplacers(FIRST_REPLACERS); type = TYPE_SELECTOR.process(normalizedSql); // phase two - complications ;-) if (type.equals("select")) { String[] sa = normalizedSql.split(" from ", 2); if (sa.length == 2) { normalizedSql = sa[0] + " from " + FUNCTION_REPLACER.process(sa[1]); } } else { normalizedSql = FUNCTION_REPLACER.process(normalizedSql); } applyReplacers(SECOND_REPLACERS); } private void applyReplacers(Replacer[] replacers) { for (Replacer replacer : replacers) { normalizedSql = replacer.process(normalizedSql); } } /** * Returns the original SQL. * * @return original SQL */ public String getSql() { return sql; } /** * Returns the normalized SQL. * * @return normalized SQL */ public String getNormalizedSql() { return normalizedSql; } /** * Returns SQL type which is typicaly first word of the SQL (insert, select, etc). Returns batch for batches. * * @return SQL statement type or "batch" */ public String getType() { return type; } /** * Returns human readable string describing this SQL normalizer. * * @return original SQL, normalized SQL, SQL type */ @Override public String toString() { return "SqlNormalizer{" + "\n sql='" + sql + '\'' + ",\n normalizedSql='" + normalizedSql + '\'' + ",\n type='" + type + '\'' + '}'; } }
package org.cejug.yougi.util; import org.cejug.yougi.business.UserAccountBean; import org.cejug.yougi.entity.UserAccount; import org.cejug.yougi.qualifier.UserName; import javax.enterprise.inject.Produces; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; /** * @author Daniel Cunha - danielsoro@gmail.com */ public class ProducesUtil { @Inject private UserAccountBean userAccountBean; @Produces @Named @UserName public String getUserName() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); return request.getRemoteUser(); } @Produces @Named public String getFirstName() { String username = getUserName(); UserAccount userAccount = userAccountBean.findByUsername(username); return userAccount == null ? "" : userAccount.getFirstName(); } }
package de.javagl.jgltf.model; import de.javagl.jgltf.impl.Node; /** * Utility methods related to {@link Node}s. */ class Nodes { /** * Compute the local transform of the given {@link Node}. The transform * is either taken from the {@link Node#getMatrix()} (if it is not * <code>null</code>), or computed from the {@link Node#getTranslation()}, * {@link Node#getRotation()} and {@link Node#getScale()}, if they * are not <code>null</code>, respectively.<br> * <br> * The result will be written to the given array, as a 4x4 matrix in * column major order. If the given array is <code>null</code>, then * a new array with length 16 will be created and returned. Otherwise, * the given array must at least have a length of 16. * * @param node The node. May not be <code>null</code>. * @param localTransform The optional array that will store the result * @return The result */ static float[] computeLocalTransform( Node node, float localTransform[]) { float result[] = localTransform; if (localTransform == null) { result = new float[16]; } else { if (localTransform.length < 16) { throw new IllegalArgumentException( "Array length must at least be 16, but is " + localTransform.length); } } if (node.getMatrix() != null) { float m[] = node.getMatrix(); System.arraycopy(m, 0, result, 0, m.length); return result; } MathUtils.setIdentity4x4(result); if (node.getTranslation() != null) { float t[] = node.getTranslation(); result[12] = t[0]; result[13] = t[1]; result[14] = t[2]; } if (node.getRotation() != null) { float q[] = node.getRotation(); float m[] = new float[16]; MathUtils.quaternionToMatrix4x4(q, m); MathUtils.mul4x4(result, m, result); } if (node.getScale() != null) { float s[] = node.getScale(); float m[] = new float[16]; m[ 0] = s[0]; m[ 5] = s[1]; m[10] = s[2]; m[15] = 1.0f; MathUtils.mul4x4(result, m, result); } return result; } /** * Private constructor to prevent instantiation */ private Nodes() { // Private constructor to prevent instantiation } }
package matt.lyoko.entities.projectile; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.util.List; import matt.lyoko.CodeLyoko; import matt.lyoko.lib.PlayerInformation; import net.minecraft.block.Block; import net.minecraft.enchantment.EnchantmentThorns; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IProjectile; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.network.packet.Packet70GameEvent; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; import cpw.mods.fml.common.network.PacketDispatcher; import cpw.mods.fml.common.network.Player; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public abstract class EntityLyokoRanged extends Entity implements IProjectile { private int xTile = -1; private int yTile = -1; private int zTile = -1; private int inTile = 0; private int inData = 0; private boolean inGround = false; /** 1 if the player can pick up the arrow */ public int canBePickedUp = 0; /** Seems to be some sort of timer for animating an arrow. */ public int arrowShake = 0; /** The owner of this arrow. */ public Entity shootingEntity; private int ticksInGround; private int ticksInAir = 0; private double damage = 2.0D; /** The amount of knockback an arrow applies when it hits a mob. */ private int knockbackStrength; public EntityLyokoRanged(World par1World) { super(par1World); this.renderDistanceWeight = 10.0D; this.setSize(0.5F, 0.5F); } public EntityLyokoRanged(World par1World, double par2, double par4, double par6) { super(par1World); this.renderDistanceWeight = 10.0D; this.setSize(0.5F, 0.5F); this.setPosition(par2, par4, par6); this.yOffset = 0.0F; } public EntityLyokoRanged(World par1World, EntityLivingBase par2EntityLiving, EntityLivingBase par3EntityLiving, float par4, float par5) { super(par1World); this.renderDistanceWeight = 10.0D; this.shootingEntity = par2EntityLiving; if (par2EntityLiving instanceof EntityPlayer) { this.canBePickedUp = 1; } this.posY = par2EntityLiving.posY + (double)par2EntityLiving.getEyeHeight() - 0.10000000149011612D; double var6 = par3EntityLiving.posX - par2EntityLiving.posX; double var8 = par3EntityLiving.posY + (double)par3EntityLiving.getEyeHeight() - 0.699999988079071D - this.posY; double var10 = par3EntityLiving.posZ - par2EntityLiving.posZ; double var12 = (double)MathHelper.sqrt_double(var6 * var6 + var10 * var10); if (var12 >= 1.0E-7D) { float var14 = (float)(Math.atan2(var10, var6) * 180.0D / Math.PI) - 90.0F; float var15 = (float)(-(Math.atan2(var8, var12) * 180.0D / Math.PI)); double var16 = var6 / var12; double var18 = var10 / var12; this.setLocationAndAngles(par2EntityLiving.posX + var16, this.posY, par2EntityLiving.posZ + var18, var14, var15); this.yOffset = 0.0F; float var20 = (float)var12 * 0.2F; this.setThrowableHeading(var6, var8 + (double)var20, var10, par4, par5); } } public EntityLyokoRanged(World par1World, EntityLivingBase par2EntityLiving, float par3) { super(par1World); this.renderDistanceWeight = 10.0D; this.shootingEntity = par2EntityLiving; if (par2EntityLiving instanceof EntityPlayer) { this.canBePickedUp = 1; } this.setSize(0.5F, 0.5F); this.setLocationAndAngles(par2EntityLiving.posX, par2EntityLiving.posY + (double)par2EntityLiving.getEyeHeight(), par2EntityLiving.posZ, par2EntityLiving.rotationYaw, par2EntityLiving.rotationPitch); this.posX -= (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F); this.posY -= 0.10000000149011612D; this.posZ -= (double)(MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F); this.setPosition(this.posX, this.posY, this.posZ); this.yOffset = 0.0F; this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI)); this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI)); this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI)); this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, par3 * 1.5F, 1.0F); } protected void entityInit() { this.dataWatcher.addObject(16, Byte.valueOf((byte)0)); } /** * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction. */ public void setThrowableHeading(double par1, double par3, double par5, float par7, float par8) { float var9 = MathHelper.sqrt_double(par1 * par1 + par3 * par3 + par5 * par5); par1 /= (double)var9; par3 /= (double)var9; par5 /= (double)var9; par1 += this.rand.nextGaussian() * 0.007499999832361937D * (double)par8; par3 += this.rand.nextGaussian() * 0.007499999832361937D * (double)par8; par5 += this.rand.nextGaussian() * 0.007499999832361937D * (double)par8; par1 *= (double)par7; par3 *= (double)par7; par5 *= (double)par7; this.motionX = par1; this.motionY = par3; this.motionZ = par5; float var10 = MathHelper.sqrt_double(par1 * par1 + par5 * par5); this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI); this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)var10) * 180.0D / Math.PI); this.ticksInGround = 0; } @SideOnly(Side.CLIENT) /** * Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX, * posY, posZ, yaw, pitch */ public void setPositionAndRotation2(double par1, double par3, double par5, float par7, float par8, int par9) { this.setPosition(par1, par3, par5); this.setRotation(par7, par8); } @SideOnly(Side.CLIENT) /** * Sets the velocity to the args. Args: x, y, z */ public void setVelocity(double par1, double par3, double par5) { this.motionX = par1; this.motionY = par3; this.motionZ = par5; if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { float var7 = MathHelper.sqrt_double(par1 * par1 + par5 * par5); this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(par1, par5) * 180.0D / Math.PI); this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(par3, (double)var7) * 180.0D / Math.PI); this.prevRotationPitch = this.rotationPitch; this.prevRotationYaw = this.rotationYaw; this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); this.ticksInGround = 0; } } /** * Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); if(CodeLyoko.entityInLyoko(this)) { this.setDamage(0.0D); } else { this.setDamage(2.0D); } if(this.ticksExisted >= 200) { this.setDead(); return; } if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { float var1 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, (double)var1) * 180.0D / Math.PI); } int var16 = this.worldObj.getBlockId(this.xTile, this.yTile, this.zTile); if (var16 > 0) { Block.blocksList[var16].setBlockBoundsBasedOnState(this.worldObj, this.xTile, this.yTile, this.zTile); AxisAlignedBB var2 = Block.blocksList[var16].getCollisionBoundingBoxFromPool(this.worldObj, this.xTile, this.yTile, this.zTile); if (var2 != null && var2.isVecInside(this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ))) { this.inGround = true; } } if (this.arrowShake > 0) { --this.arrowShake; } if (this.inGround) { this.setDead(); } else { ++this.ticksInAir; Vec3 var17 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ); Vec3 var3 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); MovingObjectPosition var4 = this.worldObj.rayTraceBlocks_do_do(var17, var3, false, true); var17 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX, this.posY, this.posZ); var3 = this.worldObj.getWorldVec3Pool().getVecFromPool(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); if (var4 != null) { var3 = this.worldObj.getWorldVec3Pool().getVecFromPool(var4.hitVec.xCoord, var4.hitVec.yCoord, var4.hitVec.zCoord); } Entity var5 = null; List var6 = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); double var7 = 0.0D; int var9; float var11; for (var9 = 0; var9 < var6.size(); ++var9) { Entity var10 = (Entity)var6.get(var9); if (var10.canBeCollidedWith() && (var10 != this.shootingEntity || this.ticksInAir >= 5)) { var11 = 0.3F; AxisAlignedBB var12 = var10.boundingBox.expand((double)var11, (double)var11, (double)var11); MovingObjectPosition var13 = var12.calculateIntercept(var17, var3); if (var13 != null) { double var14 = var17.distanceTo(var13.hitVec); if (var14 < var7 || var7 == 0.0D) { var5 = var10; var7 = var14; } } } } if (var5 != null) { var4 = new MovingObjectPosition(var5); } float var20; float var26; if (var4 != null) { if (var4.entityHit != null) { var20 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); int var23 = MathHelper.ceiling_double_int((double)var20 * this.damage); if (this.getIsCritical()) { var23 += this.rand.nextInt(var23 / 2 + 2); } DamageSource var21 = null; if (this.shootingEntity == null) { var21 = CodeLyoko.causeLyokoRangedDamage(this, this); } else { var21 = CodeLyoko.causeLyokoRangedDamage(this, this.shootingEntity); } if (this.isBurning() && !(var4.entityHit instanceof EntityEnderman)) { var4.entityHit.setFire(5); } if (var4.entityHit.attackEntityFrom(var21, var23)) { if (var4.entityHit instanceof EntityLivingBase) { EntityLivingBase var24 = (EntityLivingBase)var4.entityHit; if (this.knockbackStrength > 0) { var26 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); if (var26 > 0.0F) { var4.entityHit.addVelocity(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)var26, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)var26); } } EnchantmentThorns.func_92096_a(this.shootingEntity, var24, this.rand); if (this.shootingEntity != null && var4.entityHit != this.shootingEntity && var4.entityHit instanceof EntityPlayer && this.shootingEntity instanceof EntityPlayerMP) { ((EntityPlayerMP)this.shootingEntity).playerNetServerHandler.sendPacketToPlayer(new Packet70GameEvent(6, 0)); } } this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); if (!(var4.entityHit instanceof EntityEnderman)) { this.setDead(); } } else { this.motionX *= -0.10000000149011612D; this.motionY *= -0.10000000149011612D; this.motionZ *= -0.10000000149011612D; this.rotationYaw += 180.0F; this.prevRotationYaw += 180.0F; this.ticksInAir = 0; } } else { this.xTile = var4.blockX; this.yTile = var4.blockY; this.zTile = var4.blockZ; this.inTile = this.worldObj.getBlockId(this.xTile, this.yTile, this.zTile); this.inData = this.worldObj.getBlockMetadata(this.xTile, this.yTile, this.zTile); this.motionX = (double)((float)(var4.hitVec.xCoord - this.posX)); this.motionY = (double)((float)(var4.hitVec.yCoord - this.posY)); this.motionZ = (double)((float)(var4.hitVec.zCoord - this.posZ)); var20 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); this.posX -= this.motionX / (double)var20 * 0.05000000074505806D; this.posY -= this.motionY / (double)var20 * 0.05000000074505806D; this.posZ -= this.motionZ / (double)var20 * 0.05000000074505806D; this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F)); this.inGround = true; this.arrowShake = 7; this.setIsCritical(false); if (this.inTile != 0) { Block.blocksList[this.inTile].onEntityCollidedWithBlock(this.worldObj, this.xTile, this.yTile, this.zTile, this); } } } if (this.getIsCritical()) { for (var9 = 0; var9 < 4; ++var9) { this.worldObj.spawnParticle("crit", this.posX + this.motionX * (double)var9 / 4.0D, this.posY + this.motionY * (double)var9 / 4.0D, this.posZ + this.motionZ * (double)var9 / 4.0D, -this.motionX, -this.motionY + 0.2D, -this.motionZ); } } this.posX += this.motionX; this.posY += this.motionY; this.posZ += this.motionZ; var20 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); for (this.rotationPitch = (float)(Math.atan2(this.motionY, (double)var20) * 180.0D / Math.PI); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F) { ; } while (this.rotationPitch - this.prevRotationPitch >= 180.0F) { this.prevRotationPitch += 360.0F; } while (this.rotationYaw - this.prevRotationYaw < -180.0F) { this.prevRotationYaw -= 360.0F; } while (this.rotationYaw - this.prevRotationYaw >= 180.0F) { this.prevRotationYaw += 360.0F; } this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F; this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F; float var22 = 0.99F; var11 = 0.05F; if (this.isInWater()) { for (int var25 = 0; var25 < 4; ++var25) { var26 = 0.25F; this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)var26, this.posY - this.motionY * (double)var26, this.posZ - this.motionZ * (double)var26, this.motionX, this.motionY, this.motionZ); } var22 = 0.8F; } this.motionX *= (double)var22; this.motionY *= (double)var22; this.motionZ *= (double)var22; this.motionY -= (double)var11; this.setPosition(this.posX, this.posY, this.posZ); this.doBlockCollisions(); } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound) { par1NBTTagCompound.setShort("xTile", (short)this.xTile); par1NBTTagCompound.setShort("yTile", (short)this.yTile); par1NBTTagCompound.setShort("zTile", (short)this.zTile); par1NBTTagCompound.setByte("inTile", (byte)this.inTile); par1NBTTagCompound.setByte("inData", (byte)this.inData); par1NBTTagCompound.setByte("shake", (byte)this.arrowShake); par1NBTTagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); par1NBTTagCompound.setByte("pickup", (byte)this.canBePickedUp); par1NBTTagCompound.setDouble("damage", this.damage); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound) { this.xTile = par1NBTTagCompound.getShort("xTile"); this.yTile = par1NBTTagCompound.getShort("yTile"); this.zTile = par1NBTTagCompound.getShort("zTile"); this.inTile = par1NBTTagCompound.getByte("inTile") & 255; this.inData = par1NBTTagCompound.getByte("inData") & 255; this.arrowShake = par1NBTTagCompound.getByte("shake") & 255; this.inGround = par1NBTTagCompound.getByte("inGround") == 1; if (par1NBTTagCompound.hasKey("damage")) { this.damage = par1NBTTagCompound.getDouble("damage"); } if (par1NBTTagCompound.hasKey("pickup")) { this.canBePickedUp = par1NBTTagCompound.getByte("pickup"); } else if (par1NBTTagCompound.hasKey("player")) { this.canBePickedUp = par1NBTTagCompound.getBoolean("player") ? 1 : 0; } } /** * Called by a player entity when they collide with an entity */ public void onCollideWithPlayer(EntityPlayer player) { if(!this.worldObj.isRemote) { this.setDead(); } if(!player.capabilities.isCreativeMode && !player.worldObj.isRemote && CodeLyoko.entityInLyoko(this)) { this.playSound("random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); PlayerInformation pi = PlayerInformation.forPlayer(player); pi.decreaseLifePoints(10); if(pi.dirty) { ByteArrayOutputStream bos = new ByteArrayOutputStream(4); DataOutputStream outputStream = new DataOutputStream(bos); try { outputStream.writeInt(pi.getLifePoints()); } catch (Exception ex) { ex.printStackTrace(); } Packet250CustomPayload packet = new Packet250CustomPayload(); packet.channel = "LifePoints"; packet.data = bos.toByteArray(); packet.length = bos.size(); PacketDispatcher.sendPacketToPlayer(packet,(Player) player); } } } /** * returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to * prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } @SideOnly(Side.CLIENT) public float getShadowSize() { return 0.0F; } public void setDamage(double par1) { this.damage = par1; } public double getDamage() { return this.damage; } /** * Sets the amount of knockback the arrow applies when it hits a mob. */ public void setKnockbackStrength(int par1) { this.knockbackStrength = par1; } /** * If returns false, the item will not inflict any damage against entities. */ public boolean canAttackWithItem() { return false; } /** * Whether the arrow has a stream of critical hit particles flying behind it. */ public void setIsCritical(boolean par1) { byte var2 = this.dataWatcher.getWatchableObjectByte(16); if (par1) { this.dataWatcher.updateObject(16, Byte.valueOf((byte)(var2 | 1))); } else { this.dataWatcher.updateObject(16, Byte.valueOf((byte)(var2 & -2))); } } /** * Whether the arrow has a stream of critical hit particles flying behind it. */ public boolean getIsCritical() { byte var1 = this.dataWatcher.getWatchableObjectByte(16); return (var1 & 1) != 0; } }
package org.cojen.tupl.core; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.IOException; import java.io.OutputStream; import java.lang.invoke.MethodHandles; import java.lang.invoke.VarHandle; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.LongConsumer; import static java.lang.System.arraycopy; import static java.util.Arrays.fill; import org.cojen.tupl.CacheExhaustedException; import org.cojen.tupl.ClosedIndexException; import org.cojen.tupl.CompactionObserver; import org.cojen.tupl.CorruptDatabaseException; import org.cojen.tupl.Crypto; import org.cojen.tupl.Cursor; import org.cojen.tupl.Database; import org.cojen.tupl.DatabaseException; import org.cojen.tupl.DatabaseFullException; import org.cojen.tupl.DurabilityMode; import org.cojen.tupl.EventListener; import org.cojen.tupl.EventType; import org.cojen.tupl.Index; import org.cojen.tupl.LargeKeyException; import org.cojen.tupl.LargeValueException; import org.cojen.tupl.LockFailureException; import org.cojen.tupl.LockMode; import org.cojen.tupl.LockResult; import org.cojen.tupl.Snapshot; import org.cojen.tupl.Sorter; import org.cojen.tupl.Transaction; import org.cojen.tupl.UnmodifiableReplicaException; import org.cojen.tupl.VerificationObserver; import org.cojen.tupl.View; import org.cojen.tupl.ev.SafeEventListener; import org.cojen.tupl.ext.CustomHandler; import org.cojen.tupl.ext.Handler; import org.cojen.tupl.ext.PrepareHandler; import org.cojen.tupl.io.FileFactory; import org.cojen.tupl.io.OpenOption; import org.cojen.tupl.io.PageArray; import org.cojen.tupl.repl.StreamReplicator; import org.cojen.tupl.util.Latch; import static org.cojen.tupl.core.Node.*; import static org.cojen.tupl.core.PageOps.*; import static org.cojen.tupl.core.Utils.*; /** * Standard database implementation. The name "LocalDatabase" is used to imply that the * database is local to the current machine and not remotely accessed, although no remote * database layer exists. This class could just as well have been named "DatabaseImpl". * * @author Brian S O'Neill */ public final class LocalDatabase extends CoreDatabase { private static final int DEFAULT_CACHE_NODES = 1000; // +2 for registry and key map root nodes, +1 for one user index, and +2 for at least one // usage list to function correctly. private static final int MIN_CACHE_NODES = 5; private static final long PRIMER_MAGIC_NUMBER = 4943712973215968399L; private static final String LOCK_FILE_SUFFIX = ".lock"; static final String PRIMER_FILE_SUFFIX = ".primer"; static final String REDO_FILE_SUFFIX = ".redo."; private static int nodeCountFromBytes(long bytes, int pageSize) { if (bytes <= 0) { return 0; } pageSize += NODE_OVERHEAD; bytes += pageSize - 1; if (bytes <= 0) { // Overflow. return Integer.MAX_VALUE; } long count = bytes / pageSize; return count <= Integer.MAX_VALUE ? (int) count : Integer.MAX_VALUE; } private static long byteCountFromNodes(int nodes, int pageSize) { return nodes * (long) (pageSize + NODE_OVERHEAD); } private static final int ENCODING_VERSION = 20130112; private static final int I_ENCODING_VERSION = 0; private static final int I_ROOT_PAGE_ID = I_ENCODING_VERSION + 4; private static final int I_MASTER_UNDO_LOG_PAGE_ID = I_ROOT_PAGE_ID + 8; private static final int I_TRANSACTION_ID = I_MASTER_UNDO_LOG_PAGE_ID + 8; private static final int I_CHECKPOINT_NUMBER = I_TRANSACTION_ID + 8; private static final int I_REDO_TXN_ID = I_CHECKPOINT_NUMBER + 8; private static final int I_REDO_POSITION = I_REDO_TXN_ID + 8; private static final int I_REPL_ENCODING = I_REDO_POSITION + 8; private static final int HEADER_SIZE = I_REPL_ENCODING + 8; private static final int DEFAULT_PAGE_SIZE = 4096; private static final int MINIMUM_PAGE_SIZE = 512; private static final int MAXIMUM_PAGE_SIZE = 65536; private static final int OPEN_REGULAR = 0, OPEN_DESTROY = 1, OPEN_TEMP = 2; final EventListener mEventListener; private final File mBaseFile; private final boolean mReadOnly; private final LockedFile mLockFile; final DurabilityMode mDurabilityMode; final long mDefaultLockTimeoutNanos; final LockManager mLockManager; private final ThreadLocal<SoftReference<LocalTransaction>> mLocalTransaction; final RedoWriter mRedoWriter; final PageDb mPageDb; final int mPageSize; private final Object mArena; private final NodeGroup[] mNodeGroups; private final CommitLock mCommitLock; // Is either CACHED_DIRTY_0 or CACHED_DIRTY_1. Access is guarded by commit lock. private byte mCommitState; // State to apply to nodes which have just been read. Is CACHED_DIRTY_0 for empty databases // which have never checkpointed, but is CACHED_CLEAN otherwise. private volatile byte mInitialReadState = CACHED_CLEAN; // Set during checkpoint after commit state has switched. If checkpoint aborts, next // checkpoint will resume with this commit header and master undo log. // [ private byte[] mCommitHeader; // | // private long mCommitHeader = p_null(); // private static final VarHandle cCommitHeaderHandle; // ] private UndoLog mCommitMasterUndoLog; // Typically opposite of mCommitState, or negative if checkpoint is not in // progress. Indicates which nodes are being flushed by the checkpoint. private volatile int mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; private static final int CHECKPOINT_FLUSH_PREPARE = -2, CHECKPOINT_NOT_FLUSHING = -1; // The root tree, which maps tree ids to other tree root node ids. private final BTree mRegistry; // RK == Registry Key prefixes used with mRegistryKeyMap. static final byte RK_INDEX_NAME = 0; // name to id mapping for user trees static final byte RK_INDEX_ID = 1; // id to name mapping for user trees static final byte RK_TREE_ID_MASK = 2; // full key for random tree id mask static final byte RK_NEXT_TREE_ID = 3; // full key for tree id sequence static final byte RK_TRASH_ID = 4; // id to name mapping of trash static final byte RK_CUSTOM_NAME = 5; // name to id mapping for custom handlers static final byte RK_CUSTOM_ID = 6; // id to name mapping for custom handlers static final byte RK_PREPARE_NAME = 7; // name to id mapping for prepare handlers static final byte RK_PREPARE_ID = 8; // id to name mapping for prepare handlers static final byte RK_NEXT_TEMP_ID = 9; // full key for temporary tree id sequence // Various mappings, defined by RK_ fields. private final BTree mRegistryKeyMap; private final Latch mOpenTreesLatch; // Maps tree names to open trees. // Must be a concurrent map because we rely on concurrent iteration. private final Map<byte[], TreeRef> mOpenTrees; private final LHashTable.Obj<TreeRef> mOpenTreesById; private final ReferenceQueue<Object> mOpenTreesRefQueue; // Map of all loaded nodes. private Node[] mNodeMapTable; private static final Node NM_LOCK = new Node(); private static final VarHandle cNodeMapElementHandle; final int mMaxKeySize; final int mMaxEntrySize; final int mMaxFragmentedEntrySize; // Fragmented values which are transactionally deleted go here. private BTree mFragmentedTrash; // Pre-calculated maximum capacities for inode levels. private final long[] mFragmentInodeLevelCaps; // Stripe the transaction contexts, for improved concurrency. private final TransactionContext[] mTxnContexts; // Checkpoint lock is fair, to ensure that user checkpoint requests are not stalled for too // long by checkpoint thread. private final ReentrantLock mCheckpointLock = new ReentrantLock(true); private long mLastCheckpointNanos; private final Checkpointer mCheckpointer; final TempFileManager mTempFileManager; // [| // final boolean mFullyMapped; // ] private volatile ExecutorService mSorterExecutor; // Maps registered cursor ids to index ids. private BTree mCursorRegistry; // Registered custom handlers. private final Map<String, CustomHandler> mCustomHandlers; private final LHashTable.Obj<CustomHandler> mCustomHandlersById; // Registered prepare handlers. private final Map<String, PrepareHandler> mPrepareHandlers; private final LHashTable.Obj<PrepareHandler> mPrepareHandlersById; // Maps transaction id to the handler id and optional message. private BTree mPreparedTxns; private volatile int mClosed; private volatile Throwable mClosedCause; private static final VarHandle cClosedHandle; static { try { cClosedHandle = MethodHandles.lookup().findVarHandle (LocalDatabase.class, "mClosed", int.class); // [| // cCommitHeaderHandle = // MethodHandles.lookup().findVarHandle // (LocalDatabase.class, "mCommitHeader", long.class); // ] cNodeMapElementHandle = MethodHandles.arrayElementVarHandle(Node[].class); } catch (Throwable e) { throw rethrow(e); } } /** * Open a database, creating it if necessary. */ static LocalDatabase open(Launcher launcher) throws IOException { var db = new LocalDatabase(launcher, OPEN_REGULAR); try { db.finishInit(launcher); return db; } catch (Throwable e) { closeQuietly(db); throw e; } } /** * Delete the contents of an existing database, and replace it with an * empty one. When using a raw block device for the data file, this method * must be used to format it. */ static LocalDatabase destroy(Launcher launcher) throws IOException { if (launcher.mReadOnly) { throw new IllegalArgumentException("Cannot destroy read-only database"); } var db = new LocalDatabase(launcher, OPEN_DESTROY); try { db.finishInit(launcher); return db; } catch (Throwable e) { closeQuietly(db); throw e; } } /** * @param launcher base file is set as a side-effect */ static BTree openTemp(TempFileManager tfm, Launcher launcher) throws IOException { File file = tfm.createTempFile(); launcher.baseFile(file); launcher.dataFiles(file); launcher.createFilePath(false); launcher.durabilityMode(DurabilityMode.NO_FLUSH); var db = new LocalDatabase(launcher, OPEN_TEMP); tfm.register(file, db); db.mCheckpointer.start(false); return db.mRegistry; } /** * @param launcher unshared launcher */ private LocalDatabase(Launcher launcher, int openMode) throws IOException { launcher.mEventListener = mEventListener = SafeEventListener.makeSafe(launcher.mEventListener); mCustomHandlers = Launcher.mapClone(launcher.mCustomHandlers); mCustomHandlersById = Launcher.newByIdMap(mCustomHandlers); mPrepareHandlers = Launcher.mapClone(launcher.mPrepareHandlers); mPrepareHandlersById = Launcher.newByIdMap(mPrepareHandlers); mBaseFile = launcher.mBaseFile; mReadOnly = launcher.mReadOnly; final File[] dataFiles = launcher.dataFiles(); int pageSize = launcher.mPageSize; boolean explicitPageSize = true; if (pageSize <= 0) { launcher.pageSize(pageSize = DEFAULT_PAGE_SIZE); explicitPageSize = false; } else if (pageSize < MINIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too small: " + pageSize + " < " + MINIMUM_PAGE_SIZE); } else if (pageSize > MAXIMUM_PAGE_SIZE) { throw new IllegalArgumentException ("Page size is too large: " + pageSize + " > " + MAXIMUM_PAGE_SIZE); } else if ((pageSize & 1) != 0) { throw new IllegalArgumentException("Page size must be even: " + pageSize); } int minCache, maxCache; cacheSize: { long minCacheBytes = Math.max(0, launcher.mMinCacheBytes); long maxCacheBytes = Math.max(0, launcher.mMaxCacheBytes); if (maxCacheBytes == 0) { maxCacheBytes = minCacheBytes; if (maxCacheBytes == 0) { minCache = maxCache = DEFAULT_CACHE_NODES; break cacheSize; } } if (minCacheBytes > maxCacheBytes) { throw new IllegalArgumentException ("Minimum cache size exceeds maximum: " + minCacheBytes + " > " + maxCacheBytes); } minCache = nodeCountFromBytes(minCacheBytes, pageSize); maxCache = nodeCountFromBytes(maxCacheBytes, pageSize); minCache = Math.max(MIN_CACHE_NODES, minCache); maxCache = Math.max(MIN_CACHE_NODES, maxCache); } // Update launcher such that info file is correct. launcher.mMinCacheBytes = byteCountFromNodes(minCache, pageSize); launcher.mMaxCacheBytes = byteCountFromNodes(maxCache, pageSize); mDurabilityMode = launcher.mDurabilityMode; mDefaultLockTimeoutNanos = launcher.mLockTimeoutNanos; mLockManager = new LockManager(this, launcher.mLockUpgradeRule, mDefaultLockTimeoutNanos); mLocalTransaction = new ThreadLocal<>(); // Initialize NodeMapTable, the primary cache of Nodes. { int capacity = Utils.roundUpPower2(maxCache); if (capacity < 0) { capacity = 0x40000000; } mNodeMapTable = new Node[capacity]; } if (mBaseFile != null && !mReadOnly && launcher.mMkdirs) { FileFactory factory = launcher.mFileFactory; final boolean baseDirectoriesCreated; File baseDir = mBaseFile.getParentFile(); if (factory == null) { baseDirectoriesCreated = baseDir.mkdirs(); } else { baseDirectoriesCreated = factory.createDirectories(baseDir); } if (!baseDirectoriesCreated && !baseDir.exists()) { throw new FileNotFoundException("Could not create directory: " + baseDir); } if (dataFiles != null) { for (File f : dataFiles) { final boolean dataDirectoriesCreated; File dataDir = f.getParentFile(); if (factory == null) { dataDirectoriesCreated = dataDir.mkdirs(); } else { dataDirectoriesCreated = factory.createDirectories(dataDir); } if (!dataDirectoriesCreated && !dataDir.exists()) { throw new FileNotFoundException("Could not create directory: " + dataDir); } } } } final int procCount = Runtime.getRuntime().availableProcessors(); LockedFile attemptCreate = null; try { // Create lock file, preventing database from being opened multiple times. if (mBaseFile == null || openMode == OPEN_TEMP) { mLockFile = null; } else { var lockFile = new File(lockFilePath()); FileFactory factory = launcher.mFileFactory; if (factory != null && !mReadOnly) { factory.createFile(lockFile); } boolean didExist = lockFile.exists(); mLockFile = new LockedFile(lockFile, mReadOnly); if (!didExist) { attemptCreate = mLockFile; } } if (openMode == OPEN_DESTROY) { deleteRedoLogFiles(); } final long cacheInitStart = System.nanoTime(); // Create or retrieve optional page cache. PageCache cache = launcher.pageCache(mEventListener); if (cache != null) { // Update launcher such that info file is correct. launcher.mSecondaryCacheSize = cache.capacity(); } // [| // boolean fullyMapped = false; // ] EventListener debugListener = null; if (launcher.mDebugOpen != null) { debugListener = mEventListener; } if (dataFiles == null) { PageArray dataPageArray = launcher.mDataPageArray; if (dataPageArray == null) { mPageDb = new NonPageDb(pageSize, cache); } else { dataPageArray = dataPageArray.open(); Crypto crypto = launcher.mCrypto; mPageDb = DurablePageDb.open (debugListener, dataPageArray, cache, crypto, openMode == OPEN_DESTROY); // [| // fullyMapped = crypto == null && cache == null // && dataPageArray.isFullyMapped(); // ] } } else { EnumSet<OpenOption> options = launcher.createOpenOptions(); PageDb pageDb; try { pageDb = DurablePageDb.open (debugListener, explicitPageSize, pageSize, dataFiles, launcher.mFileFactory, options, cache, launcher.mCrypto, openMode == OPEN_DESTROY); } catch (FileNotFoundException e) { if (!mReadOnly) { throw e; } pageDb = new NonPageDb(pageSize, cache); } mPageDb = pageDb; } // [| // mFullyMapped = fullyMapped; // ] // Actual page size might differ from configured size. launcher.pageSize(pageSize = mPageSize = mPageDb.pageSize()); // [ launcher.mDirectPageAccess = false; // | // launcher.mDirectPageAccess = true; // ] mCommitLock = mPageDb.commitLock(); // Pre-allocate nodes. They are automatically added to the node group usage lists, // and so nothing special needs to be done to allow them to get used. Since the // initial state is clean, evicting these nodes does nothing. if (mEventListener != null) { mEventListener.notify(EventType.CACHE_INIT_BEGIN, "Initializing %1$d cache nodes", minCache); } NodeGroup[] groups; try { // Try to allocate the minimum cache size into an arena, which has lower memory // overhead, is page aligned, and takes less time to zero-fill. arenaAlloc: { // If database is fully mapped, then no cache pages are allocated at all. // Nodes point directly to a mapped region of memory. // [| // if (mFullyMapped) { // mArena = null; // break arenaAlloc; // } // ] try { mArena = p_arenaAlloc(pageSize, minCache); } catch (IOException e) { var oom = new OutOfMemoryError(); oom.initCause(e); throw oom; } } long usedRate; if (mPageDb.isDurable()) { // Magic constant was determined empirically against the G1 collector. A // higher constant increases memory thrashing. usedRate = Utils.roundUpPower2((long) Math.ceil(maxCache / 32768.0)) - 1; } else { // Nothing gets evicted, so no need to ever adjust usage order. usedRate = -1; } int stripes = roundUpPower2(procCount * 16); int stripeSize; while (true) { stripeSize = maxCache / stripes; if (stripes <= 1 || stripeSize >= 100) { break; } stripes >>= 1; } int rem = maxCache % stripes; groups = new NodeGroup[stripes]; for (int i=0; i<stripes; i++) { int size = stripeSize; if (rem > 0) { size++; rem } groups[i] = new NodeGroup(this, usedRate, size); } stripeSize = minCache / stripes; rem = minCache % stripes; for (NodeGroup group : groups) { int size = stripeSize; if (rem > 0) { size++; rem } group.initialize(mArena, size); } } catch (OutOfMemoryError e) { groups = null; var oom = new OutOfMemoryError ("Unable to allocate the minimum required number of cache nodes: " + minCache + " (" + (minCache * (long) (pageSize + NODE_OVERHEAD)) + " bytes)"); oom.initCause(e.getCause()); throw oom; } mNodeGroups = groups; if (mEventListener != null) { double duration = (System.nanoTime() - cacheInitStart) / 1_000_000_000.0; mEventListener.notify(EventType.CACHE_INIT_COMPLETE, "Cache initialization completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } mTxnContexts = new TransactionContext[procCount * 4]; for (int i=0; i<mTxnContexts.length; i++) { mTxnContexts[i] = new TransactionContext(mTxnContexts.length, 4096); }; mCommitLock.acquireExclusive(); try { mCommitState = CACHED_DIRTY_0; } finally { mCommitLock.releaseExclusive(); } var header = new byte[HEADER_SIZE]; mPageDb.readExtraCommitData(header); // Also verifies the database and replication encodings. Node rootNode = loadRegistryRoot(launcher, header); // Cannot call newBTreeInstance because mRedoWriter isn't set yet. if (launcher.mRepl != null) { mRegistry = new BTree.Repl(this, Tree.REGISTRY_ID, null, rootNode); } else { mRegistry = new BTree(this, Tree.REGISTRY_ID, null, rootNode); } mOpenTreesLatch = new Latch(); if (openMode == OPEN_TEMP) { mOpenTrees = Collections.emptyMap(); mOpenTreesById = new LHashTable.Obj<>(0); mOpenTreesRefQueue = null; } else { mOpenTrees = new ConcurrentSkipListMap<>(KeyComparator.THE); mOpenTreesById = new LHashTable.Obj<>(16); mOpenTreesRefQueue = new ReferenceQueue<>(); } long txnId = decodeLongLE(header, I_TRANSACTION_ID); if (txnId < 0) { throw new CorruptDatabaseException("Invalid transaction id: " + txnId); } long redoNum = decodeLongLE(header, I_CHECKPOINT_NUMBER); long redoPos = decodeLongLE(header, I_REDO_POSITION); long redoTxnId = decodeLongLE(header, I_REDO_TXN_ID); if (debugListener != null) { debugListener.notify(EventType.DEBUG, "MASTER_UNDO_LOG_PAGE_ID: %1$d", decodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID)); debugListener.notify(EventType.DEBUG, "TRANSACTION_ID: %1$d", txnId); debugListener.notify(EventType.DEBUG, "CHECKPOINT_NUMBER: %1$d", redoNum); debugListener.notify(EventType.DEBUG, "REDO_TXN_ID: %1$d", redoTxnId); debugListener.notify(EventType.DEBUG, "REDO_POSITION: %1$d", redoPos); } if (openMode == OPEN_TEMP) { mRegistryKeyMap = null; } else { mRegistryKeyMap = openInternalTree(Tree.REGISTRY_KEY_MAP_ID, IX_CREATE, launcher); if (debugListener != null) { Cursor c = indexRegistryById().newCursor(Transaction.BOGUS); try { for (c.first(); c.key() != null; c.next()) { long indexId = decodeLongBE(c.key(), 0); var nameStr = new String(c.value(), StandardCharsets.UTF_8); debugListener.notify(EventType.DEBUG, "Index: id=%1$d, name=%2$s", indexId, nameStr); } } finally { c.reset(); } } } BTree cursorRegistry = null; if (openMode != OPEN_TEMP) { cursorRegistry = openInternalTree(Tree.CURSOR_REGISTRY_ID, IX_FIND, launcher); } // Limit maximum non-fragmented entry size to 0.75 of usable node size. mMaxEntrySize = ((pageSize - Node.TN_HEADER_SIZE) * 3) >> 2; // Limit maximum fragmented entry size to guarantee that 2 entries fit. Each also // requires 2 bytes for pointer and up to 3 bytes for value length field. mMaxFragmentedEntrySize = (pageSize - Node.TN_HEADER_SIZE - (2 + 3 + 2 + 3)) >> 1; // Limit the maximum key size to allow enough room for a fragmented value. It might // require up to 11 bytes for fragment encoding (when length is >= 65536), and // additional bytes are required for the value header inside the tree node. mMaxKeySize = Math.min(16383, mMaxFragmentedEntrySize - (2 + 11)); mFragmentInodeLevelCaps = calculateInodeLevelCaps(mPageSize); // Enable caching of PageQueue nodes before recovery begins, because it will be // deleting pages, and caching helps performance. mPageDb.pageCache(this); if (mBaseFile == null || openMode == OPEN_TEMP || debugListener != null) { mTempFileManager = null; } else { mTempFileManager = new TempFileManager(mBaseFile, launcher.mFileFactory); } long recoveryStart = 0; if (mBaseFile == null) { mRedoWriter = null; mCheckpointer = null; } else if (openMode == OPEN_TEMP) { mRedoWriter = null; mCheckpointer = new Checkpointer(this, launcher, mNodeGroups.length); } else { if (debugListener != null) { mCheckpointer = null; } else { mCheckpointer = new Checkpointer(this, launcher, mNodeGroups.length); } // Perform recovery by examining redo and undo logs. if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_BEGIN, "Database recovery begin"); recoveryStart = System.nanoTime(); } var txns = new LHashTable.Obj<LocalTransaction>(16); { long masterNodeId = decodeLongLE(header, I_MASTER_UNDO_LOG_PAGE_ID); if (masterNodeId != 0) { if (mEventListener != null) { mEventListener.notify (EventType.RECOVERY_LOAD_UNDO_LOGS, "Loading undo logs"); } UndoLog master = UndoLog.recoverMasterUndoLog(this, masterNodeId); boolean trace = debugListener != null && Boolean.TRUE.equals(launcher.mDebugOpen.get("traceUndo")); master.recoverTransactions(debugListener, trace, txns); } } var cursors = new LHashTable.Obj<BTreeCursor>(4); if (cursorRegistry != null) { Cursor c = cursorRegistry.newCursor(Transaction.BOGUS); for (c.first(); c.key() != null; c.next()) { long cursorId = decodeLongBE(c.key(), 0); byte[] regValue = c.value(); long indexId = decodeLongBE(regValue, 0); BTree tree = (BTree) anyIndexById(indexId); var cursor = new BTreeCursor(tree, Transaction.BOGUS); cursor.mKeyOnly = true; if (regValue.length >= 9) { // Cursor key was registered too. var key = new byte[regValue.length - 9]; System.arraycopy(regValue, 9, key, 0, key.length); cursor.find(key); } // Assign after any find operation, because it will reset the cursor id. cursor.mCursorId = cursorId; cursors.insert(cursorId).value = cursor; } cursorRegistry.forceClose(); } // Although the handlers shouldn't access the database yet, be safe and call // this method at the point that the database is mostly functional. The handler // methods will be called soon to perform recovery. initHandlers(this, mCustomHandlers, mPrepareHandlers); // Must tag the trashed trees before starting replication and recovery. // Otherwise, trees recently deleted might get double deleted. tagTrashedTrees(); StreamReplicator repl = launcher.mRepl; if (repl != null) { if (mEventListener != null) { mEventListener.notify(EventType.REPLICATION_DEBUG, "Starting at: %1$d", redoPos); } repl.start(); if (mReadOnly) { mRedoWriter = null; if (debugListener != null && Boolean.TRUE.equals(launcher.mDebugOpen.get("traceRedo"))) { var printer = new RedoEventPrinter(debugListener, EventType.DEBUG); new ReplDecoder(repl, redoPos, redoTxnId, new Latch()).run(printer); } } else { var engine = new ReplEngine (repl, launcher.mMaxReplicaThreads, this, txns, cursors); mRedoWriter = engine.initWriter(redoNum); // Cannot start recovery until constructor is finished and final field // values are visible to other threads. Pass the state to the caller // through the launcher object. launcher.mReplRecoveryStartNanos = recoveryStart; launcher.mReplInitialPostion = redoPos; launcher.mReplInitialTxnId = redoTxnId; } } else { // Apply cache primer before applying redo logs. applyCachePrimer(launcher); final long logId = redoNum; if (mReadOnly) { mRedoWriter = null; if (debugListener != null && Boolean.TRUE.equals(launcher.mDebugOpen.get("traceRedo"))) { var printer = new RedoEventPrinter(debugListener, EventType.DEBUG); var replayLog = new RedoLog(launcher, logId, redoPos); replayLog.replay (printer, debugListener, EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d"); } } else { // Make sure old redo logs are deleted. Process might have exited // before last checkpoint could delete them. deleteNumberedFiles(mBaseFile, REDO_FILE_SUFFIX, 0, logId - 1); boolean doCheckpoint = txns.size() != 0; var applier = new RedoLogApplier (launcher.mMaxReplicaThreads, this, txns, cursors); var replayLog = new RedoLog(launcher, logId, redoPos); // As a side-effect, log id is set one higher than last file scanned. TreeMap<Long, File> redoFiles = replayLog.replay (applier, mEventListener, EventType.RECOVERY_APPLY_REDO_LOG, "Applying redo log: %1$d"); doCheckpoint |= !redoFiles.isEmpty(); // Finish recovery and collect unfinished prepared transactions. launcher.mUnfinished = applier.finish(); // Check if any exceptions were caught by recovery worker threads. checkClosedCause(); // Avoid re-using transaction ids used by recovery. txnId = applier.highestTxnId(txnId); // New redo logs begin with identifiers one higher than last scanned. var log = new RedoLog(launcher, replayLog, mTxnContexts[0]); mRedoWriter = log; if (doCheckpoint) { // Do this early for checkpoint to store correct transaction id. resetTransactionContexts(txnId); txnId = -1; try { forceCheckpoint(); } catch (Throwable e) { // Delete the newly created redo log files. log.initialCheckpointFailed(e); throw e; } // Only cleanup after successful checkpoint. deleteReverseOrder(redoFiles); } } recoveryComplete(recoveryStart); } } if (txnId >= 0) { resetTransactionContexts(txnId); } } catch (Throwable e) { // Close, but don't double report the exception since construction never finished. closeQuietly(this); // Clean up the mess by deleting the lock file if it was just created. deleteLockFile(attemptCreate, null); throw e; } } private String lockFilePath() { return mBaseFile.getPath() + LOCK_FILE_SUFFIX; } private IOException deleteLockFile(LockedFile file, IOException ex) { if (file != null) { ex = file.delete(lockFilePath(), ex); } return ex; } /** * Post construction, allow additional threads access to the database. */ @SuppressWarnings("unchecked") private void finishInit(Launcher launcher) throws IOException { if (mCheckpointer == null) { // Nothing is durable and nothing to ever clean up. return; } // Register objects to automatically shutdown. mCheckpointer.register(new RedoClose(this)); mCheckpointer.register(mTempFileManager); if (mRedoWriter instanceof ReplWriter) { // Need to do this after mRedoWriter is assigned, ensuring that trees are opened as // BTree.Repl instances. applyCachePrimer(launcher); } if (launcher.mCachePriming && mPageDb.isDurable() && !mReadOnly) { mCheckpointer.register(new ShutdownPrimer(this)); } BTree trashed = openNextTrashedTree(null); if (trashed != null) { var deletion = new Thread (new Deletion(trashed, true, mEventListener), "IndexDeletion"); deletion.setDaemon(true); deletion.start(); } mCheckpointer.start(false); emptyLingeringTrash(null); // only for non-replicated transactions if (!(mRedoWriter instanceof ReplController)) { LHashTable.Obj<LocalTransaction> unfinished = launcher.mUnfinished; if (unfinished != null) { new Thread(() -> invokeRecoveryHandler(unfinished, mRedoWriter)).start(); launcher.mUnfinished = null; } } else { // Start replication and recovery. var controller = (ReplController) mRedoWriter; if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_PROGRESS, "Starting replication recovery"); } try { controller.ready(launcher.mReplInitialPostion, launcher.mReplInitialTxnId); } catch (Throwable e) { closeQuietly(this, e); throw e; } recoveryComplete(launcher.mReplRecoveryStartNanos); } } /** * Called by ReplManager. */ @Override long writeControlMessage(byte[] message) throws IOException { // Commit lock must be held to prevent a checkpoint from starting. If the control // message fails to be applied, panic the database. If the database is kept open after // a failure and then a checkpoint completes, the control message would be dropped. // Normal transactional operations aren't so sensitive, because they have an undo log. CommitLock.Shared shared = mCommitLock.acquireShared(); try { RedoWriter redo = txnRedoWriter(); TransactionContext context = anyTransactionContext(); long commitPos = context.redoControl(redo, message); // Waiting for confirmation with the shared lock held isn't ideal, but control // messages aren't that frequent. redo.txnCommitSync(commitPos); try { ((ReplController) mRedoWriter).mRepl.controlMessageReceived(commitPos, message); } catch (Throwable e) { // Panic. closeQuietly(this, e); throw e; } return commitPos; } finally { shared.release(); } } /** * @param txns must not be null * @param redo RedoWriter assigned to each transaction; pass null to perform partial * rollback but don't invoke the handler */ void invokeRecoveryHandler(LHashTable.Obj<LocalTransaction> txns, RedoWriter redo) { // Note: Even if the recovery handler isn't called, looking it up performs validation. txns.traverse(entry -> { LocalTransaction txn = entry.value; try { UndoLog.RTP rtp = txn.rollbackForRecovery (redo, mDurabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); int handlerId = rtp.handlerId; byte[] message = rtp.message; PrepareHandler recovery = findPrepareRecoveryHandler(handlerId); if (redo != null) { try { if (rtp.commit) { recovery.prepareCommit(txn, message); } else { recovery.prepare(txn, message); } } catch (UnmodifiableReplicaException e) { // Ensure that it can be handed off again. txn.reset(e); } } } catch (Throwable e) { if (!isClosed()) { e = new CorruptDatabaseException("Malformed prepared transaction: " + txn, e); EventListener listener = mEventListener; if (listener == null) { uncaught(e); } else { listener.notify (EventType.RECOVERY_HANDLER_UNCAUGHT, "Uncaught exception when recovering a prepared transaction: %1$s", e); } } } return true; }); } private void applyCachePrimer(Launcher launcher) { if (mPageDb.isDurable()) { File primer = primerFile(); try { if (launcher.mCachePriming && primer.exists()) { if (mEventListener != null) { mEventListener.notify(EventType.RECOVERY_CACHE_PRIMING, "Cache priming"); } FileInputStream fin; try { fin = new FileInputStream(primer); try (var bin = new BufferedInputStream(fin)) { applyCachePrimer(bin); } catch (IOException e) { fin.close(); } } catch (IOException e) { } } } finally { if (!mReadOnly) { primer.delete(); } } } } static class ShutdownPrimer extends ShutdownHook.Weak<LocalDatabase> { ShutdownPrimer(LocalDatabase db) { super(db); } @Override void doShutdown(LocalDatabase db) { if (db.mReadOnly) { return; } File primer = db.primerFile(); FileOutputStream fout; try { fout = new FileOutputStream(primer); try { try (var bout = new BufferedOutputStream(fout)) { db.createCachePrimer(bout); } } catch (IOException e) { fout.close(); primer.delete(); } } catch (IOException e) { } } } File primerFile() { return new File(mBaseFile.getPath() + PRIMER_FILE_SUFFIX); } private void recoveryComplete(long recoveryStart) { if (mEventListener != null) { double duration = (System.nanoTime() - recoveryStart) / 1_000_000_000.0; mEventListener.notify(EventType.RECOVERY_COMPLETE, "Recovery completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } } private void deleteRedoLogFiles() throws IOException { if (mBaseFile != null && !mReadOnly) { deleteNumberedFiles(mBaseFile, REDO_FILE_SUFFIX); } } private boolean hasRedoLogFiles() throws IOException { return mBaseFile != null && !findNumberedFiles(mBaseFile, REDO_FILE_SUFFIX, 0, Long.MAX_VALUE).isEmpty(); } @Override public Index findIndex(byte[] name) throws IOException { return openTree(name.clone(), IX_FIND); } @Override public Index openIndex(byte[] name) throws IOException { return openTree(name.clone(), IX_CREATE); } @Override public Index indexById(long id) throws IOException { return indexById(null, id); } private Index indexById(Transaction txn, long id) throws IOException { if (Tree.isInternal(id)) { throw new IllegalArgumentException("Invalid id: " + id); } Index index = lookupIndexById(id); if (index != null) { return index; } var idKey = new byte[9]; idKey[0] = RK_INDEX_ID; encodeLongBE(idKey, 1, id); CommitLock.Shared shared = mCommitLock.acquireShared(); try { byte[] name; if (txn != null) { name = mRegistryKeyMap.load(txn, idKey); } else { // Lookup name with exclusive lock, to prevent races with concurrent index // creation. If a replicated operation which requires the newly created index // merely acquired a shared lock, then it might not find the index at all. Locker locker = mLockManager.localLocker(); while (true) { if (locker.doTryLockExclusive(mRegistryKeyMap.id(), idKey, 0).isHeld()) { break; } // Release locks and retry, avoiding possible deadlock if the checkpointer // has suspended replica decoding in the middle of tree creation. shared.release(); Thread.yield(); mCommitLock.acquireShared(shared); } try { name = mRegistryKeyMap.load(Transaction.BOGUS, idKey); } finally { locker.doUnlock(); } } if (name == null) { checkClosed(); return null; } var treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, id); index = openTree(txn, treeIdBytes, name, IX_FIND); } catch (Throwable e) { rethrowIfRecoverable(e); throw closeOnFailure(this, e); } finally { shared.release(); } if (index == null) { // Registry needs to be repaired to fix this. throw new DatabaseException("Unable to find index in registry"); } return index; } /** * @return null if index is not open */ private Tree lookupIndexById(long id) { mOpenTreesLatch.acquireShared(); try { LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(id); return entry == null ? null : entry.value.get(); } finally { mOpenTreesLatch.releaseShared(); } } /** * Allows access to internal indexes which can use the redo log. */ Index anyIndexById(long id) throws IOException { return anyIndexById(null, id); } /** * Allows access to internal indexes which can use the redo log. */ Index anyIndexById(Transaction txn, long id) throws IOException { return Tree.isInternal(id) ? internalIndex(id) : indexById(txn, id); } /** * @param id must be an internal index */ private Index internalIndex(long id) throws IOException { if (id == Tree.REGISTRY_KEY_MAP_ID) { return mRegistryKeyMap; } else if (id == Tree.FRAGMENTED_TRASH_ID) { return fragmentedTrash(); } else if (id == Tree.PREPARED_TXNS_ID) { return preparedTxns(); } else { throw new CorruptDatabaseException("Internal index referenced by redo log: " + id); } } @Override public void renameIndex(Index index, byte[] newName) throws IOException { renameIndex(index, newName.clone(), 0); } /** * @param newName not cloned * @param redoTxnId non-zero if rename is performed by recovery */ void renameIndex(final Index index, final byte[] newName, final long redoTxnId) throws IOException { // Design note: Rename is a Database method instead of an Index method because it // offers an extra degree of safety. It's too easy to call rename and pass a byte[] by // an accident when something like remove was desired instead. Requiring access to the // Database instance makes this operation a bit more of a hassle to use, which is // desirable. Rename is not expected to be a common operation. accessTree(index).rename(newName, redoTxnId); } /** * @param newName not cloned * @param redoTxnId non-zero if rename is performed by recovery */ void renameBTree(final BTree tree, final byte[] newName, final long redoTxnId) throws IOException { final byte[] idKey, trashIdKey; final byte[] oldName, oldNameKey; final byte[] newNameKey; final LocalTransaction txn; final Node root = tree.mRoot; root.acquireExclusive(); try { if (root.mPage == p_closedTreePage()) { throw new ClosedIndexException(); } if (Tree.isInternal(tree.mId)) { throw new IllegalStateException("Cannot rename an internal index"); } oldName = tree.mName; if (oldName == null) { throw new IllegalStateException("Cannot rename a temporary index"); } if (Arrays.equals(oldName, newName)) { return; } idKey = newKey(RK_INDEX_ID, tree.mIdBytes); trashIdKey = newKey(RK_TRASH_ID, tree.mIdBytes); oldNameKey = newKey(RK_INDEX_NAME, oldName); newNameKey = newKey(RK_INDEX_NAME, newName); txn = newNoRedoTransaction(redoTxnId); try { txn.lockTimeout(-1, null); txn.doLockExclusive(mRegistryKeyMap.mId, idKey); txn.doLockExclusive(mRegistryKeyMap.mId, trashIdKey); // Lock in a consistent order, avoiding deadlocks. if (Arrays.compareUnsigned(oldNameKey, newNameKey) <= 0) { txn.doLockExclusive(mRegistryKeyMap.mId, oldNameKey); txn.doLockExclusive(mRegistryKeyMap.mId, newNameKey); } else { txn.doLockExclusive(mRegistryKeyMap.mId, newNameKey); txn.doLockExclusive(mRegistryKeyMap.mId, oldNameKey); } } catch (Throwable e) { txn.reset(); throw e; } } finally { // Can release now that registry entries are locked. Those locks will prevent // concurrent renames of the same index. root.releaseExclusive(); } try { Cursor c = mRegistryKeyMap.newCursor(txn); try { c.autoload(false); c.find(trashIdKey); if (c.value() != null) { throw new IllegalStateException("Index is deleted"); } c.find(newNameKey); if (c.value() != null) { throw new IllegalStateException("New name is used by another index"); } c.store(tree.mIdBytes); } finally { c.reset(); } if (redoTxnId == 0 && txn.mRedo != null) { txn.durabilityMode(alwaysRedo(mDurabilityMode)); long commitPos; CommitLock.Shared shared = mCommitLock.acquireShared(); try { txn.check(); commitPos = txn.mContext.redoRenameIndexCommitFinal (txn.mRedo, txn.txnId(), tree.mId, newName, txn.durabilityMode()); } finally { shared.release(); } if (commitPos != 0) { // Must wait for durability confirmation before performing actions below // which cannot be easily rolled back. No global latches or locks are held // while waiting. txn.mRedo.txnCommitSync(commitPos); } } txn.durabilityMode(DurabilityMode.NO_REDO); mRegistryKeyMap.delete(txn, oldNameKey); mRegistryKeyMap.store(txn, idKey, newName); mOpenTreesLatch.acquireExclusive(); try { txn.commit(); tree.mName = newName; mOpenTrees.put(newName, mOpenTrees.remove(oldName)); } finally { mOpenTreesLatch.releaseExclusive(); } } catch (IllegalStateException e) { throw e; } catch (Throwable e) { rethrowIfRecoverable(e); throw closeOnFailure(this, e); } finally { txn.reset(); } } private Tree accessTree(Index index) { try { Tree tree; if ((tree = ((Tree) index)).isMemberOf(this)) { return tree; } } catch (ClassCastException e) { // Cast and catch an exception instead of calling instanceof to cause a // NullPointerException to be thrown if index is null. } throw new IllegalStateException("Index belongs to a different database"); } @Override public Runnable deleteIndex(Index index) throws IOException { // Design note: This is a Database method instead of an Index method because it offers // an extra degree of safety. See notes in renameIndex. return accessTree(index).drop(false); } /** * Returns a deletion task for a tree which just moved to the trash. */ Runnable replicaDeleteTree(long treeId) throws IOException { var treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, treeId); BTree trashed = openTrashedTree(treeIdBytes, false); return new Deletion(trashed, false, null); } /** * Called by BTree.drop with root node latch held exclusively. * * @param shared commit lock held shared; always released by this method */ Runnable deleteTree(BTree tree, CommitLock.Shared shared) throws IOException { try { if (!(tree instanceof BTree.Temp) && !moveToTrash(tree.mId, tree.mIdBytes)) { // Handle concurrent delete attempt. throw new ClosedIndexException(); } } finally { // Always release before calling close, which might require an exclusive lock. shared.release(); } Node root = tree.close(true, true); if (root == null) { // Handle concurrent close attempt. throw new ClosedIndexException(); } BTree trashed = newBTreeInstance(tree.mId, tree.mIdBytes, tree.mName, root); return new Deletion(trashed, false, null); } /** * Quickly delete an empty temporary tree, which has no active threads and cursors. */ void quickDeleteTemporaryTree(BTree tree) throws IOException { mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.removeValue(tree.mId); if (ref == null || ref.get() != tree) { // BTree is likely being closed by a concurrent database close. return; } ref.clear(); } finally { mOpenTreesLatch.releaseExclusive(); } Node root = tree.mRoot; byte[] trashIdKey = newKey(RK_TRASH_ID, tree.mIdBytes); CommitLock.Shared shared = mCommitLock.acquireShared(); try { root.acquireExclusive(); if (!root.hasKeys() && root.mPage != p_closedTreePage()) { // Delete and remove from trash. prepareToDelete(root); deleteNode(root); mRegistryKeyMap.delete(Transaction.BOGUS, trashIdKey); mRegistry.delete(Transaction.BOGUS, tree.mIdBytes); return; } root.releaseExclusive(); } catch (Throwable e) { throw closeOnFailure(this, e); } finally { shared.release(); } // BTree isn't truly empty -- it might be composed of many empty leaf nodes. tree.deleteAll(); removeFromTrash(tree, root); } /** * Returns the view of trashed trees. */ private View trash() { return mRegistryKeyMap.viewPrefix(new byte[] {RK_TRASH_ID}, 1); } private void tagTrashedTrees() throws IOException { // Tag all the entries that should be deleted automatically. Entries created later will // have a different prefix, and so they'll be ignored. try (Cursor c = trash().newCursor(Transaction.BOGUS)) { for (c.first(); c.key() != null; c.next()) { byte[] name = c.value(); if (name.length != 0) { name[0] |= 0x80; c.store(name); } } } } /** * @param lastIdBytes null to start with first * @return null if none available */ private BTree openNextTrashedTree(byte[] lastIdBytes) throws IOException { return openTrashedTree(lastIdBytes, true); } /** * @param idBytes null to start with first * @param next true to find tree with next higher id * @return null if not found */ private BTree openTrashedTree(byte[] idBytes, boolean next) throws IOException { byte[] treeIdBytes, name, rootIdBytes; try (Cursor c = trash().newCursor(Transaction.BOGUS)) { if (idBytes == null) { c.first(); } else if (next) { c.findGt(idBytes); } else { c.find(idBytes); } while (true) { treeIdBytes = c.key(); if (treeIdBytes == null) { return null; } rootIdBytes = mRegistry.load(Transaction.BOGUS, treeIdBytes); if (rootIdBytes == null) { // Clear out bogus entry in the trash. c.store(null); } else { name = c.value(); if (name[0] < 0 || (idBytes != null && next == false)) { // Found a tagged entry, or found the requested entry. break; } } if (next) { c.next(); } else { return null; } } } long rootId = rootIdBytes.length == 0 ? 0 : decodeLongLE(rootIdBytes, 0); if ((name[0] & 0x7f) == 0) { name = null; } else { // Trim off the tag byte. var actual = new byte[name.length - 1]; System.arraycopy(name, 1, actual, 0, actual.length); name = actual; } long treeId = decodeLongBE(treeIdBytes, 0); return newBTreeInstance(treeId, treeIdBytes, name, loadTreeRoot(treeId, rootId)); } private class Deletion implements Runnable { private BTree mTrashed; private final boolean mResumed; private final EventListener mListener; Deletion(BTree trashed, boolean resumed, EventListener listener) { mTrashed = trashed; mResumed = resumed; mListener = listener; } @Override public synchronized void run() { while (mTrashed != null) { delete(); } } private void delete() { if (mListener != null) { mListener.notify(EventType.DELETION_BEGIN, "Index deletion " + (mResumed ? "resumed" : "begin") + ": %1$d, name: %2$s", mTrashed.id(), mTrashed.nameString()); } final byte[] idBytes = mTrashed.mIdBytes; try { long start = System.nanoTime(); if (mTrashed.deleteAll()) { Node root = mTrashed.close(true, false); removeFromTrash(mTrashed, root); } else { // Database is closed. return; } if (mListener != null) { double duration = (System.nanoTime() - start) / 1_000_000_000.0; mListener.notify(EventType.DELETION_COMPLETE, "Index deletion complete: %1$d, name: %2$s, " + "duration: %3$1.3f seconds", mTrashed.id(), mTrashed.nameString(), duration); } } catch (IOException e) { if (!isClosed() && mListener != null) { mListener.notify (EventType.DELETION_FAILED, "Index deletion failed: %1$d, name: %2$s, exception: %3$s", mTrashed.id(), mTrashed.nameString(), rootCause(e)); } closeQuietly(mTrashed); return; } finally { mTrashed = null; } if (mResumed) { try { mTrashed = openNextTrashedTree(idBytes); } catch (IOException e) { if (!isClosed() && mListener != null) { mListener.notify (EventType.DELETION_FAILED, "Unable to resume deletion: %1$s", rootCause(e)); } return; } } } } @Override public BTree newTemporaryIndex() throws IOException { CommitLock.Shared shared = mCommitLock.acquireShared(); try { return newTemporaryTree(false); } finally { shared.release(); } } /** * Caller must hold commit lock. Pass true to preallocate a dirty root node for the tree, * which will be held exclusive. Caller is then responsible for initializing it */ BTree newTemporaryTree(boolean preallocate) throws IOException { checkClosed(); // Cleanup before opening more trees. cleanupUnreferencedTrees(); long treeId; var treeIdBytes = new byte[8]; long rootId; byte[] rootIdBytes; if (preallocate) { rootId = mPageDb.allocPage(); rootIdBytes = new byte[8]; encodeLongLE(rootIdBytes, 0, rootId); } else { rootId = 0; rootIdBytes = EMPTY_BYTES; } try { do { treeId = nextTreeId(RK_NEXT_TEMP_ID); encodeLongBE(treeIdBytes, 0, treeId); } while (!mRegistry.insert(Transaction.BOGUS, treeIdBytes, rootIdBytes)); // Register temporary index as trash, unreplicated. Transaction createTxn = newNoRedoTransaction(); try { createTxn.lockTimeout(-1, null); byte[] trashIdKey = newKey(RK_TRASH_ID, treeIdBytes); if (!mRegistryKeyMap.insert(createTxn, trashIdKey, new byte[1])) { throw new DatabaseException("Unable to register temporary index"); } createTxn.commit(); } finally { createTxn.reset(); } Node root; if (rootId != 0) { root = allocLatchedNode(NodeGroup.MODE_UNEVICTABLE); root.id(rootId); try { // [| // if (mFullyMapped) { // root.mPage = mPageDb.dirtyPage(rootId); // } // ] root.mGroup.addDirty(root, mCommitState); } catch (Throwable e) { root.releaseExclusive(); throw e; } } else { root = loadTreeRoot(treeId, 0); } try { var tree = new BTree.Temp(this, treeId, treeIdBytes, root); var treeRef = new TreeRef(tree, tree, mOpenTreesRefQueue); mOpenTreesLatch.acquireExclusive(); try { mOpenTreesById.insert(treeId).value = treeRef; } finally { mOpenTreesLatch.releaseExclusive(); } return tree; } catch (Throwable e) { if (rootId != 0) { root.releaseExclusive(); } throw e; } } catch (Throwable e) { try { mRegistry.delete(Transaction.BOGUS, treeIdBytes); } catch (Throwable e2) { // Panic. throw closeOnFailure(this, e); } if (rootId != 0) { try { mPageDb.recyclePage(rootId); } catch (Throwable e2) { Utils.suppress(e, e2); } } throw e; } } @Override public View indexRegistryByName() throws IOException { return mRegistryKeyMap.viewPrefix(new byte[] {RK_INDEX_NAME}, 1).viewUnmodifiable(); } @Override public View indexRegistryById() throws IOException { return mRegistryKeyMap.viewPrefix(new byte[] {RK_INDEX_ID}, 1).viewUnmodifiable(); } @Override public Transaction newTransaction() { return doNewTransaction(mDurabilityMode); } @Override public Transaction newTransaction(DurabilityMode durabilityMode) { return doNewTransaction(durabilityMode == null ? mDurabilityMode : durabilityMode); } private LocalTransaction doNewTransaction(DurabilityMode durabilityMode) { RedoWriter redo = txnRedoWriter(); return new LocalTransaction (this, redo, durabilityMode, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); } LocalTransaction newAlwaysRedoTransaction() { return doNewTransaction(alwaysRedo(mDurabilityMode)); } /** * Convenience method which returns a transaction intended for locking and undo. Caller can * make modifications, but they won't go to the redo log. */ private LocalTransaction newNoRedoTransaction() { return doNewTransaction(DurabilityMode.NO_REDO); } /** * Convenience method which returns a transaction intended for locking and undo. Caller can * make modifications, but they won't go to the redo log. * * @param redoTxnId non-zero if operation is performed by recovery */ private LocalTransaction newNoRedoTransaction(long redoTxnId) { return redoTxnId == 0 ? newNoRedoTransaction() : new LocalTransaction(this, redoTxnId, LockMode.UPGRADABLE_READ, mDefaultLockTimeoutNanos); } /** * Returns a transaction which should be briefly used and reset. */ LocalTransaction threadLocalTransaction(DurabilityMode durabilityMode) { SoftReference<LocalTransaction> txnRef = mLocalTransaction.get(); LocalTransaction txn; if (txnRef == null || (txn = txnRef.get()) == null) { txn = doNewTransaction(durabilityMode); mLocalTransaction.set(new SoftReference<>(txn)); } else { txn.mRedo = txnRedoWriter(); txn.mDurabilityMode = durabilityMode; txn.mLockMode = LockMode.UPGRADABLE_READ; txn.mLockTimeoutNanos = mDefaultLockTimeoutNanos; } return txn; } void removeThreadLocalTransaction() { mLocalTransaction.remove(); } /** * Returns a RedoWriter suitable for transactions to write into. */ RedoWriter txnRedoWriter() { RedoWriter redo = mRedoWriter; if (redo != null) { redo = redo.txnRedoWriter(); } return redo; } private void resetTransactionContexts(long txnId) { for (TransactionContext txnContext : mTxnContexts) { txnContext.resetTransactionId(txnId++); } } /** * Used by auto-commit operations that don't have an explicit transaction. */ TransactionContext anyTransactionContext() { return selectTransactionContext(ThreadLocalRandom.current().nextInt()); } /** * Called by transaction constructor after hash code has been assigned. */ TransactionContext selectTransactionContext(LocalTransaction txn) { return selectTransactionContext(txn.hashCode()); } private TransactionContext selectTransactionContext(int num) { return mTxnContexts[(num & 0x7fffffff) % mTxnContexts.length]; } /** * Calls discardRedoWriter on all TransactionContexts. */ void discardRedoWriter(RedoWriter expect) { for (TransactionContext context : mTxnContexts) { context.discardRedoWriter(expect); } } /** * Copies a reference to all active UndoLogs into the given collection. */ void gatherUndoLogs(Collection<? super UndoLog> to) { for (TransactionContext context : mTxnContexts) { context.gatherUndoLogs(to); } } @Override public CustomHandler customWriter(String name) throws IOException { return (CustomHandler) findOrCreateWriter(name, RK_CUSTOM_NAME, mCustomHandlers); } CustomHandler findCustomRecoveryHandler(int handlerId) throws IOException { return findRecoveryHandler(handlerId, RK_CUSTOM_ID, mCustomHandlers, mCustomHandlersById); } @Override public PrepareHandler prepareWriter(String name) throws IOException { return (PrepareHandler) findOrCreateWriter(name, RK_PREPARE_NAME, mPrepareHandlers); } PrepareHandler findPrepareRecoveryHandler(int handlerId) throws IOException { return findRecoveryHandler(handlerId, RK_PREPARE_ID, mPrepareHandlers, mPrepareHandlersById); } /** * @param rkIdPrefix RK_CUSTOM_ID or RK_PREPARE_ID * @return null if not found */ String findHandlerName(int handlerId, byte rkIdPrefix) throws IOException { byte[] idKey = newKey(rkIdPrefix, handlerId); byte[] nameBytes = mRegistryKeyMap.load(null, idKey); if (nameBytes == null) { // Possible race condition with creation of the handler entry by another // transaction during recovery. Try again with an upgradable lock, which will wait // for the entry lock. Transaction txn = newNoRedoTransaction(); try { nameBytes = mRegistryKeyMap.load(txn, idKey); } finally { txn.reset(); } } return nameBytes == null ? null : new String(nameBytes, StandardCharsets.UTF_8); } /** * @param rkNamePrefix RK_CUSTOM_NAME or RK_PREPARE_NAME */ @SuppressWarnings("unchecked") private <H extends Handler> HandlerWriter findOrCreateWriter(String name, byte rkNamePrefix, Map<String, H> handlers) throws IOException { if (handlers == null) { throw new IllegalStateException("Recovery handler not installed: " + name); } Handler handler; synchronized (handlers) { // Can probably cheat and not synchronize access, but the behavior is undefined. handler = handlers.get(name); } if (handler instanceof HandlerWriter) { return (HandlerWriter) handler; } int handlerId = findOrCreateHandlerId(name, rkNamePrefix, handlers); switch (rkNamePrefix) { case RK_CUSTOM_NAME: handler = new CustomWriter(this, handlerId, (CustomHandler) handler); break; case RK_PREPARE_NAME: handler = new PrepareWriter(this, handlerId, (PrepareHandler) handler); break; default: throw new AssertionError(); } synchronized (handlers) { Handler existing = handlers.get(name); if (existing instanceof HandlerWriter) { return (HandlerWriter) existing; } handlers.put(name, (H) handler); } return (HandlerWriter) handler; } /** * @param rkNamePrefix RK_CUSTOM_NAME or RK_PREPARE_NAME * @return handlerId */ private int findOrCreateHandlerId(String name, byte rkNamePrefix, Map<String, ? extends Handler> handlers) throws IOException { final byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); final byte[] nameKey = newKey(rkNamePrefix, nameBytes); byte[] idBytes = mRegistryKeyMap.load(null, nameKey); if (idBytes == null) define: { findRecoveryHandler(name, handlers); // Assume first use, so define a new handler id. final LocalTransaction txn = newAlwaysRedoTransaction(); try (Cursor nameCursor = mRegistryKeyMap.newCursor(txn)) { nameCursor.find(nameKey); idBytes = nameCursor.value(); if (idBytes != null) { // Found it on the second try. break define; } // Assumes that corresponding _ID prefix is one more than _NAME prefix. final byte rkIdPrefix = (byte) (rkNamePrefix + 1); final View byId = mRegistryKeyMap.viewPrefix(new byte[] {rkIdPrefix}, 1); try (Cursor idCursor = byId.newCursor(txn)) { idCursor.autoload(false); while (true) { idCursor.last(); int lastId = idCursor.key() == null ? 0 : decodeIntBE(idCursor.key(), 0); idBytes = new byte[4]; encodeIntBE(idBytes, 0, lastId + 1); idCursor.findNearby(idBytes); if (idCursor.value() == null) { idCursor.store(nameBytes); break; } } } nameCursor.commit(idBytes); } finally { txn.reset(); } } return decodeIntBE(idBytes, 0); } private <H extends Handler> H findRecoveryHandler(int handlerId, byte rkIdPrefix, Map<String, H> handlers, LHashTable.Obj<H> handlersById) throws IOException { long scrambledId = scramble(handlerId); if (handlersById != null) { H handler; synchronized (handlersById) { handler = handlersById.getValue(scrambledId); } if (handler != null) { return handler; } } String name = findHandlerName(handlerId, rkIdPrefix); if (name == null) { String type; switch (rkIdPrefix) { case RK_CUSTOM_ID: type = "custom"; break; case RK_PREPARE_ID: type = "prepare"; break; default: type = String.valueOf(rkIdPrefix); break; } throw new CorruptDatabaseException ("Unable to find " + type + " handler name for id " + handlerId); } H handler = findRecoveryHandler(name, handlers); synchronized (handlersById) { handlersById.insert(scrambledId).value = handler; } return handler; } @SuppressWarnings("unchecked") private static <H extends Handler> H findRecoveryHandler(String name, Map<String, H> handlers) { if (handlers != null) { H handler; synchronized (handlers) { // Can probably cheat and not synchronize access, but the behavior is undefined. handler = handlers.get(name); } if (handler instanceof HandlerWriter) { return (H) ((HandlerWriter) handler).mRecoveryHandler; } else if (handler != null) { return handler; } } throw new IllegalStateException("Recovery handler not installed: " + name); } @Override public long preallocate(long bytes) throws IOException { if (!isClosed() && mPageDb.isDurable()) { int pageSize = mPageSize; long pageCount = (bytes + pageSize - 1) / pageSize; if (pageCount > 0) { pageCount = mPageDb.allocatePages(pageCount); if (pageCount > 0) { try { forceCheckpoint(); } catch (Throwable e) { rethrowIfRecoverable(e); closeQuietly(this, e); throw e; } } return pageCount * pageSize; } } return 0; } @Override public Sorter newSorter(Executor executor) throws IOException { if (executor == null && (executor = mSorterExecutor) == null) { mOpenTreesLatch.acquireExclusive(); try { checkClosed(); executor = mSorterExecutor; if (executor == null) { ExecutorService es = Executors.newCachedThreadPool(r -> { var t = new Thread(r); t.setDaemon(true); t.setName("Sorter-" + Long.toUnsignedString(t.getId())); return t; }); mSorterExecutor = es; executor = es; } } finally { mOpenTreesLatch.releaseExclusive(); } } return new ParallelSorter(this, executor); } @Override public void capacityLimit(long bytes) { mPageDb.pageLimit(bytes < 0 ? -1 : (bytes / mPageSize)); } @Override public long capacityLimit() { long pageLimit = mPageDb.pageLimit(); return pageLimit < 0 ? -1 : (pageLimit * mPageSize); } @Override public void capacityLimitOverride(long bytes) { mPageDb.pageLimitOverride(bytes < 0 ? -1 : (bytes / mPageSize)); } @Override public Snapshot beginSnapshot() throws IOException { if (!(mPageDb.isDurable())) { throw new UnsupportedOperationException("Snapshot only allowed for durable databases"); } checkClosed(); DurablePageDb pageDb = (DurablePageDb) mPageDb; return pageDb.beginSnapshot(this); } /** * Restore from a {@link #beginSnapshot snapshot}, into the data files defined by the given * configuration. All existing data and redo log files at the snapshot destination are * deleted before the restore begins. * * @param in snapshot source; does not require extra buffering; auto-closed */ static Database restoreFromSnapshot(Launcher launcher, InputStream in) throws IOException { if (launcher.mReadOnly) { throw new IllegalArgumentException("Cannot restore into a read-only database"); } PageDb restored; File[] dataFiles = launcher.dataFiles(); if (dataFiles == null) { PageArray dataPageArray = launcher.mDataPageArray; if (dataPageArray == null) { throw new UnsupportedOperationException ("Restore only allowed for durable databases"); } dataPageArray = dataPageArray.open(); dataPageArray.truncatePageCount(0); // Delete old redo log files. deleteNumberedFiles(launcher.mBaseFile, REDO_FILE_SUFFIX); restored = DurablePageDb.restoreFromSnapshot(dataPageArray, null, launcher.mCrypto, in); // Delete the object, but keep the page array open. restored.delete(); } else { for (File f : dataFiles) { // Delete old data file. Utils.delete(f); if (launcher.mMkdirs) { f.getParentFile().mkdirs(); } } FileFactory factory = launcher.mFileFactory; EnumSet<OpenOption> options = launcher.createOpenOptions(); // Delete old redo log files. deleteNumberedFiles(launcher.mBaseFile, REDO_FILE_SUFFIX); int pageSize = launcher.mPageSize; if (pageSize <= 0) { pageSize = DEFAULT_PAGE_SIZE; } restored = DurablePageDb.restoreFromSnapshot (pageSize, dataFiles, factory, options, null, launcher.mCrypto, in); try { restored.close(); } finally { restored.delete(); } } return launcher.open(false, null); } @Override public void createCachePrimer(OutputStream out) throws IOException { if (!(mPageDb.isDurable())) { throw new UnsupportedOperationException ("Cache priming only allowed for durable databases"); } out = ((DurablePageDb) mPageDb).encrypt(out); var dout = new DataOutputStream(out); dout.writeLong(PRIMER_MAGIC_NUMBER); for (TreeRef treeRef : mOpenTrees.values()) { Tree tree = treeRef.get(); if (tree != null && !Tree.isInternal(tree.id())) { tree.writeCachePrimer(dout); } } // Terminator. dout.writeInt(-1); } @Override public void applyCachePrimer(final InputStream fin) throws IOException { try (fin) { if (!(mPageDb.isDurable())) { throw new UnsupportedOperationException ("Cache priming only allowed for durable databases"); } InputStream in = ((DurablePageDb) mPageDb).decrypt(fin); DataInput din; if (in instanceof DataInput) { din = (DataInput) in; } else { din = new DataInputStream(in); } long magic = din.readLong(); if (magic != PRIMER_MAGIC_NUMBER) { throw new DatabaseException("Wrong cache primer magic number: " + magic); } while (true) { int len = din.readInt(); if (len < 0) { break; } var name = new byte[len]; din.readFully(name); Tree tree = openTree(name, IX_FIND); if (tree != null) { tree.applyCachePrimer(din); } else { BTree.skipCachePrimer(din); } } } } @Override public Stats stats() { var stats = new Stats(); stats.pageSize = mPageSize; CommitLock.Shared shared = mCommitLock.acquireShared(); try { long cursorCount = 0; int openTreesCount = 0; for (TreeRef treeRef : mOpenTrees.values()) { Tree tree = treeRef.get(); if (tree != null) { openTreesCount++; cursorCount += tree.countCursors(); } } cursorCount += countCursors(mRegistry) + countCursors(mRegistryKeyMap) + countCursors(mFragmentedTrash) + countCursors(mCursorRegistry) + countCursors(mPreparedTxns); stats.openIndexes = openTreesCount; stats.cursorCount = cursorCount; PageDb.Stats pstats = mPageDb.stats(); stats.freePages = pstats.freePages; stats.totalPages = pstats.totalPages; stats.lockCount = mLockManager.numLocksHeld(); for (TransactionContext txnContext : mTxnContexts) { txnContext.addStats(stats); } } finally { shared.release(); } for (NodeGroup group : mNodeGroups) { stats.cachePages += group.nodeCount(); stats.dirtyPages += group.dirtyCount(); } if (stats.dirtyPages > stats.totalPages) { stats.dirtyPages = stats.totalPages; } return stats; } /** * @param tree can be null */ private static long countCursors(BTree tree) { return tree == null ? 0 : tree.countCursors(); } static class RedoClose extends ShutdownHook.Weak<LocalDatabase> { RedoClose(LocalDatabase db) { super(db); } @Override void doShutdown(LocalDatabase db) { db.redoClose(RedoOps.OP_SHUTDOWN, null); } } /** * @param op OP_CLOSE or OP_SHUTDOWN */ private void redoClose(byte op, Throwable cause) { RedoWriter redo = mRedoWriter; if (redo == null) { return; } redo.closeCause(cause); redo = redo.txnRedoWriter(); redo.closeCause(cause); try { // NO_FLUSH now behaves like NO_SYNC. redo.alwaysFlush(true); } catch (IOException e) { // Ignore. } try { TransactionContext context = anyTransactionContext(); context.redoTimestamp(redo, op); context.flush(); redo.force(true); } catch (IOException e) { // Ignore. } // When shutdown hook is invoked, don't close the redo writer. It may interfere with // other shutdown hooks, causing unexpected exceptions to be thrown during the whole // shutdown sequence. if (op == RedoOps.OP_CLOSE) { Utils.closeQuietly(redo); } } @Override public void flush() throws IOException { flush(0); // flush only } @Override public void sync() throws IOException { flush(1); // flush and sync } /** * @param level 0: flush only, 1: flush and sync, 2: flush and sync metadata */ private void flush(int level) throws IOException { if (!isClosed() && mRedoWriter != null) { mRedoWriter.flush(); if (level > 0) { mRedoWriter.force(level > 1); } } } @Override public void checkpoint() throws IOException { try { checkpoint(0, 0); } catch (Throwable e) { rethrowIfRecoverable(e); closeQuietly(this, e); throw e; } } @Override public void suspendCheckpoints() { Checkpointer c = mCheckpointer; if (c != null) { c.suspend(); } } @Override public void resumeCheckpoints() { Checkpointer c = mCheckpointer; if (c != null) { c.resume(); } } @Override public boolean compactFile(CompactionObserver observer, double target) throws IOException { if (target < 0 || target > 1) { throw new IllegalArgumentException("Illegal compaction target: " + target); } if (target == 0) { // No compaction to do at all, but not aborted. return true; } long targetPageCount; mCheckpointLock.lock(); try { PageDb.Stats stats = mPageDb.stats(); long usedPages = stats.totalPages - stats.freePages; targetPageCount = Math.max(usedPages, (long) (usedPages / target)); // Determine the maximum amount of space required to store the reserve list nodes // and ensure the target includes them. long reserve; { // Total pages freed. long freed = stats.totalPages - targetPageCount; // Scale by the maximum size for encoding page identifiers, assuming no savings // from delta encoding. freed *= calcUnsignedVarLongLength(stats.totalPages << 1); // Divide by the node size, excluding the header (see PageQueue). reserve = freed / (mPageSize - (8 + 8)); // A minimum is required because the regular and free lists need to allocate // one extra node at checkpoint. Up to three checkpoints may be issued, so pad // by 2 * 3 = 6. reserve += 6; } targetPageCount += reserve; if (targetPageCount >= stats.totalPages && targetPageCount >= mPageDb.pageCount()) { return true; } if (!mPageDb.compactionStart(targetPageCount)) { return false; } } finally { mCheckpointLock.unlock(); } boolean completed = mPageDb.compactionScanFreeList(); if (completed) { // Issue a checkpoint to ensure all dirty nodes are flushed out. This ensures that // nodes can be moved out of the compaction zone by simply marking them dirty. If // already dirty, they'll not be in the compaction zone unless compaction aborted. checkpoint(); if (observer == null) { observer = new CompactionObserver(); } final long highestNodeId = targetPageCount - 1; final CompactionObserver fobserver = observer; completed = scanAllIndexes(tree -> { return tree.compactTree(tree.observableView(), highestNodeId, fobserver); }); forceCheckpoint(); if (completed && mPageDb.compactionScanFreeList()) { if (!mPageDb.compactionVerify() && mPageDb.compactionScanFreeList()) { forceCheckpoint(); } } } mCheckpointLock.lock(); try { completed &= mPageDb.compactionEnd(); // Reclaim reserved pages, but only after a checkpoint has been performed. forceCheckpoint(); mPageDb.compactionReclaim(); // Checkpoint again in order for reclaimed pages to be immediately available. forceCheckpoint(); if (completed) { // And now, attempt to actually shrink the file. return mPageDb.truncatePages(); } } finally { mCheckpointLock.unlock(); } return false; } @Override public boolean verify(VerificationObserver observer) throws IOException { var fls = new FreeListScan(); new Thread(fls).start(); if (observer == null) { observer = new VerificationObserver(); } final boolean[] passedRef = {true}; final VerificationObserver fobserver = observer; scanAllIndexes(tree -> { Index view = tree.observableView(); fobserver.failed = false; boolean keepGoing = tree.verifyTree(view, fobserver); passedRef[0] &= !fobserver.failed; if (keepGoing) { keepGoing = fobserver.indexComplete(view, !fobserver.failed, null); } return keepGoing; }); // Throws an exception if it fails. fls.waitFor(); return passedRef[0]; } private class FreeListScan implements Runnable, LongConsumer { private Object mFinished; @Override public void run() { // The free list is scanned with a shared commit lock held. Perform the scan // without interference from a checkpoint, which would attempt to acquire the // exclusive commit lock, causing any other shared lock requests to stall. mCheckpointLock.lock(); Object finished; try { mPageDb.scanFreeList(this); finished = this; } catch (Throwable e) { finished = e; } finally { mCheckpointLock.unlock(); } synchronized (this) { mFinished = finished; notifyAll(); } } @Override public void accept(long id) { // TODO: check for duplicates } synchronized void waitFor() throws IOException { try { while (mFinished == null) { wait(); } } catch (InterruptedException e) { return; } if (mFinished instanceof Throwable) { rethrow((Throwable) mFinished); } } } @FunctionalInterface static interface ScanVisitor { /** * @return false if should stop */ boolean apply(Tree tree) throws IOException; } /** * @return false if stopped */ private boolean scanAllIndexes(ScanVisitor visitor) throws IOException { if (!scan(visitor, mRegistry) || !scan(visitor, mRegistryKeyMap) || !scan(visitor, openFragmentedTrash(IX_FIND)) || !scan(visitor, openCursorRegistry(IX_FIND)) || !scan(visitor, openPreparedTxns(IX_FIND))) { return false; } // Note that temporary indexes aren't scanned. Some operations performed on them (the // sorter) aren't thread-safe, and so verification and compaction cannot examine them. Cursor all = indexRegistryByName().newCursor(null); try { for (all.first(); all.key() != null; all.next()) { long id = decodeLongBE(all.value(), 0); Index index = indexById(id); if (index instanceof Tree && !visitor.apply((Tree) index)) { return false; } } } finally { all.reset(); } return true; } /** * @return false if should stop scanning */ private static boolean scan(ScanVisitor visitor, BTree tree) throws IOException { return tree == null || visitor.apply(tree); } @Override public boolean isLeader() { return mRedoWriter == null ? true : mRedoWriter.isLeader(); } @Override public void uponLeader(Runnable task) { if (mRedoWriter == null) { ForkJoinPool.commonPool().execute(task); } else { mRedoWriter.uponLeader(task); } } @Override public boolean failover() throws IOException { return mRedoWriter == null ? false : mRedoWriter.failover(); } @Override public void close(Throwable cause) throws IOException { close(cause, false); } @Override public void shutdown() throws IOException { close(null, mPageDb.isDurable()); } private void close(Throwable cause, boolean shutdown) throws IOException { if (!cClosedHandle.compareAndSet(this, 0, 1)) { return; } if (cause != null) { mClosedCause = cause; Throwable rootCause = rootCause(cause); if (mEventListener == null) { uncaught(rootCause); } else { mEventListener.notify(EventType.PANIC_UNHANDLED_EXCEPTION, "Closing database due to unhandled exception: %1$s", rootCause); } } boolean lockedCheckpointer = false; try { if (mCheckpointer != null) { mCheckpointer.close(cause); } // Wait for any in-progress checkpoint to complete. if (mCheckpointLock.tryLock()) { lockedCheckpointer = true; } else if (cause == null && !(mRedoWriter instanceof ReplController)) { // Only attempt lock if not panicked and not replicated. If panicked, other // locks might be held and so acquiring checkpoint lock might deadlock. // Replicated databases might stall indefinitely when checkpointing. // Checkpointer should eventually exit after other resources are closed. mCheckpointLock.lock(); lockedCheckpointer = true; } } finally { Thread ct = mCheckpointer == null ? null : mCheckpointer.interrupt(); if (lockedCheckpointer) { mCheckpointLock.unlock(); if (ct != null) { // Wait for checkpointer thread to finish. try { ct.join(); } catch (InterruptedException e) { // Ignore. } } } } try { final CommitLock lock = mCommitLock; if (mOpenTrees != null) { // Clear out open trees with commit lock held, to prevent any trees from being // opened again. Any attempt to open a tree must acquire the commit lock and // then check if the database is closed. final ArrayList<Tree> trees; if (lock == null) { mOpenTreesLatch.acquireExclusive(); } else while (true) { lock.acquireExclusive(); if (mOpenTreesLatch.tryAcquireExclusive()) { break; } // Retry to avoid a potential deadlock. lock.releaseExclusive(); Thread.yield(); } try { trees = new ArrayList<>(mOpenTreesById.size()); mOpenTreesById.traverse(entry -> { Tree tree = entry.value.get(); if (tree != null) { trees.add(tree); } return true; }); mOpenTrees.clear(); trees.add(mRegistryKeyMap); trees.add(mFragmentedTrash); mFragmentedTrash = null; trees.add(mCursorRegistry); mCursorRegistry = null; trees.add(mPreparedTxns); mPreparedTxns = null; } finally { mOpenTreesLatch.releaseExclusive(); if (lock != null) { lock.releaseExclusive(); } } for (Tree tree : trees) { if (tree != null) { tree.forceClose(); } } if (shutdown) { mCheckpointLock.lock(); try { doCheckpoint(-1, 0, 0); // force even if closed } catch (Throwable e) { shutdown = false; } finally { mCheckpointLock.unlock(); } } if (mRegistry != null) { mRegistry.forceClose(); } } if (lock != null) { lock.acquireExclusive(); } try { if (mSorterExecutor != null) { mSorterExecutor.shutdown(); mSorterExecutor = null; } if (mNodeGroups != null) { for (NodeGroup group : mNodeGroups) { if (group != null) { group.delete(); } } } if (mTxnContexts != null) { for (TransactionContext txnContext : mTxnContexts) { if (txnContext != null) { txnContext.deleteUndoLogs(); } } } UndoLog masterUndoLog = mCommitMasterUndoLog; if (masterUndoLog != null) { masterUndoLog.delete(); } nodeMapDeleteAll(); redoClose(RedoOps.OP_CLOSE, cause); IOException ex = null; ex = closeQuietly(ex, mPageDb, cause); ex = closeQuietly(ex, mTempFileManager, cause); if (shutdown && mBaseFile != null && !mReadOnly) { deleteRedoLogFiles(); ex = deleteLockFile(mLockFile, ex); } else { ex = closeQuietly(ex, mLockFile, cause); } if (mLockManager != null) { mLockManager.close(); } if (ex != null) { throw ex; } } finally { if (lock != null) { lock.releaseExclusive(); } } } finally { if (mCheckpointer != null) { mCheckpointer.shutdown(); } if (mPageDb != null) { mPageDb.delete(); } deleteCommitHeader(); p_arenaDelete(mArena); } } private void deleteCommitHeader() { // [ mCommitHeader = null; // | // p_delete((long) cCommitHeaderHandle.getAndSet(this, p_null())); // ] } @Override public boolean isClosed() { return mClosed != 0; } /** * If any closed cause exception, wraps it as a DatabaseException and throws it. */ void checkClosed() throws DatabaseException { checkClosed(null); } /** * If any closed cause exception, wraps it as a DatabaseException and throws it. * * @param caught exception which was caught; will be rethrown if matches the closed cause */ void checkClosed(Throwable caught) throws DatabaseException { if (isClosed()) { if (caught != null && caught == mClosedCause) { throw rethrow(caught); } String message = "Closed"; Throwable cause = mClosedCause; if (cause != null) { message += "; " + rootCause(cause); } throw new DatabaseException(message, cause); } } /** * Tries to directly throw the closed cause exception, wrapping it if necessary. */ void checkClosedCause() throws IOException { Throwable cause = mClosedCause; if (cause != null) { try { throw cause; } catch (IOException | RuntimeException | Error e) { throw e; } catch (Throwable e) { throw new DatabaseException(cause); } } } Throwable closedCause() { return mClosedCause; } void treeClosed(BTree tree) { mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.getValue(tree.mId); if (ref != null) { Tree actual = ref.get(); if (actual != null && actual.isUserOf(tree)) { ref.clear(); if (tree.mName != null) { mOpenTrees.remove(tree.mName); } mOpenTreesById.remove(tree.mId); } } } finally { mOpenTreesLatch.releaseExclusive(); } } /** * @return false if already in the trash */ private boolean moveToTrash(long treeId, byte[] treeIdBytes) throws IOException { final LocalTransaction txn = newNoRedoTransaction(); try { txn.lockTimeout(-1, null); if (!doMoveToTrash(txn, treeId, treeIdBytes)) { return false; } if (txn.mRedo != null) { // Note: No additional operations can appear after OP_DELETE_INDEX. When a // replica reads this operation it immediately commits the transaction in order // for the deletion task to be started immediately. The redo log still contains // a commit operation, which is redundant and harmless. txn.durabilityMode(alwaysRedo(mDurabilityMode)); long commitPos; CommitLock.Shared shared = mCommitLock.acquireShared(); try { txn.check(); commitPos = txn.mContext.redoDeleteIndexCommitFinal (txn.mRedo, txn.txnId(), treeId, txn.durabilityMode()); } finally { shared.release(); } if (commitPos != 0) { // Must wait for durability confirmation before performing actions below // which cannot be easily rolled back. No global latches or locks are held // while waiting. txn.mRedo.txnCommitSync(commitPos); } } txn.commit(); } catch (Throwable e) { rethrowIfRecoverable(e); throw closeOnFailure(this, e); } finally { txn.reset(); } return true; } /** * @param txn must not redo */ void redoMoveToTrash(LocalTransaction txn, long treeId) throws IOException { var treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, treeId); doMoveToTrash(txn, treeId, treeIdBytes); } /** * @param txn must not redo * @return false if already in the trash */ private boolean doMoveToTrash(LocalTransaction txn, long treeId, byte[] treeIdBytes) throws IOException { final byte[] trashIdKey = newKey(RK_TRASH_ID, treeIdBytes); if (mRegistryKeyMap.load(txn, trashIdKey) != null) { // Already in the trash. return false; } final byte[] idKey = newKey(RK_INDEX_ID, treeIdBytes); byte[] treeName = mRegistryKeyMap.exchange(txn, idKey, null); if (treeName == null) { // A trash entry with just a zero indicates that the name is null. mRegistryKeyMap.store(txn, trashIdKey, new byte[1]); } else { byte[] nameKey = newKey(RK_INDEX_NAME, treeName); mRegistryKeyMap.remove(txn, nameKey, treeIdBytes); // Tag the trash entry to indicate that name is non-null. Note that nameKey // instance is modified directly. nameKey[0] = 1; mRegistryKeyMap.store(txn, trashIdKey, nameKey); } return true; } /** * Must be called after all entries in the tree have been deleted and tree is closed. */ void removeFromTrash(BTree tree, Node root) throws IOException { byte[] trashIdKey = newKey(RK_TRASH_ID, tree.mIdBytes); CommitLock.Shared shared = mCommitLock.acquireShared(); try { if (root != null) { root.acquireExclusive(); if (root.mPage == p_closedTreePage()) { // Database has been closed. root.releaseExclusive(); return; } deleteNode(root); } mRegistryKeyMap.delete(Transaction.BOGUS, trashIdKey); mRegistry.delete(Transaction.BOGUS, tree.mIdBytes); } catch (Throwable e) { throw closeOnFailure(this, e); } finally { shared.release(); } } /** * Removes all references to a temporary tree which was grafted to another one. Caller must * hold shared commit lock. */ void removeGraftedTempTree(BTree tree) throws IOException { try { mOpenTreesLatch.acquireExclusive(); try { TreeRef ref = mOpenTreesById.removeValue(tree.mId); if (ref != null && ref.get() == tree) { ref.clear(); } } finally { mOpenTreesLatch.releaseExclusive(); } byte[] trashIdKey = newKey(RK_TRASH_ID, tree.mIdBytes); mRegistryKeyMap.delete(Transaction.BOGUS, trashIdKey); mRegistry.delete(Transaction.BOGUS, tree.mIdBytes); } catch (Throwable e) { throw closeOnFailure(this, e); } } /** * Should be called before attempting to register a cursor, in case an exception is thrown. */ BTree cursorRegistry() throws IOException { BTree cursorRegistry = mCursorRegistry; return cursorRegistry != null ? cursorRegistry : openCursorRegistry(IX_CREATE); } /** * @param ixOption IX_FIND or IX_CREATE */ private BTree openCursorRegistry(long ixOption) throws IOException { BTree cursorRegistry; mOpenTreesLatch.acquireExclusive(); try { if ((cursorRegistry = mCursorRegistry) == null) { mCursorRegistry = cursorRegistry = openInternalTree(Tree.CURSOR_REGISTRY_ID, ixOption); } } finally { mOpenTreesLatch.releaseExclusive(); } return cursorRegistry; } /** * Should be called after the cursor id has been assigned, with the commit lock held. */ void registerCursor(BTree cursorRegistry, BTreeCursor cursor) throws IOException { try { var cursorIdBytes = new byte[8]; encodeLongBE(cursorIdBytes, 0, cursor.mCursorId); byte[] regValue = cursor.mTree.mIdBytes; byte[] key = cursor.key(); if (key != null) { var newReg = new byte[regValue.length + 1 + key.length]; System.arraycopy(regValue, 0, newReg, 0, regValue.length); System.arraycopy(key, 0, newReg, regValue.length + 1, key.length); regValue = newReg; } cursorRegistry.store(Transaction.BOGUS, cursorIdBytes, regValue); } catch (Throwable e) { try { cursor.unregister(); } catch (Throwable e2) { suppress(e, e2); } throw e; } } void unregisterCursor(long cursorId) { try { var cursorIdBytes = new byte[8]; encodeLongBE(cursorIdBytes, 0, cursorId); cursorRegistry().store(Transaction.BOGUS, cursorIdBytes, null); } catch (Throwable e) { // Database is borked, cleanup later. } } BTree preparedTxns() throws IOException { BTree preparedTxns = mPreparedTxns; return preparedTxns != null ? preparedTxns : openPreparedTxns(IX_CREATE); } /** * Returns null if the index doesn't exist. */ BTree tryPreparedTxns() throws IOException { BTree preparedTxns = mPreparedTxns; return preparedTxns != null ? preparedTxns : openPreparedTxns(IX_FIND); } /** * @param ixOption IX_FIND or IX_CREATE */ private BTree openPreparedTxns(long ixOption) throws IOException { BTree preparedTxns; mOpenTreesLatch.acquireExclusive(); try { if ((preparedTxns = mPreparedTxns) == null) { mPreparedTxns = preparedTxns = openInternalTree(Tree.PREPARED_TXNS_ID, ixOption); } } finally { mOpenTreesLatch.releaseExclusive(); } return preparedTxns; } /** * @param treeId pass zero if unknown or not applicable * @param rootId pass zero to create * @return unlatched and unevictable root node */ private Node loadTreeRoot(final long treeId, final long rootId) throws IOException { if (rootId == 0) { Node rootNode = allocLatchedNode(NodeGroup.MODE_UNEVICTABLE); try { // [ rootNode.asEmptyRoot(); // | // if (mFullyMapped) { // rootNode.mPage = p_nonTreePage(); // always an empty leaf node // rootNode.id(0); // rootNode.mCachedState = CACHED_CLEAN; // } else { // rootNode.asEmptyRoot(); // } // ] return rootNode; } finally { rootNode.releaseExclusive(); } } else { // Check if root node is still around after tree was closed. Node rootNode = nodeMapGetAndRemove(rootId); if (rootNode != null) { try { rootNode.makeUnevictable(); return rootNode; } finally { rootNode.releaseExclusive(); } } rootNode = allocLatchedNode(NodeGroup.MODE_UNEVICTABLE); try { try { rootNode.read(this, rootId); } finally { rootNode.releaseExclusive(); } return rootNode; } catch (Throwable e) { rootNode.makeEvictableNow(); throw e; } } } /** * Loads the root registry node, or creates one if store is new. Root node * is not eligible for eviction. */ private Node loadRegistryRoot(Launcher launcher, byte[] header) throws IOException { int version = decodeIntLE(header, I_ENCODING_VERSION); if (launcher.mDebugOpen != null) { mEventListener.notify(EventType.DEBUG, "ENCODING_VERSION: %1$d", version); } long rootId; if (version == 0) { rootId = 0; // No registry; clearly nothing has been checkpointed. mInitialReadState = CACHED_DIRTY_0; } else { if (version != ENCODING_VERSION) { throw new CorruptDatabaseException("Unknown encoding version: " + version); } rootId = decodeLongLE(header, I_ROOT_PAGE_ID); if (launcher.mDebugOpen != null) { mEventListener.notify(EventType.DEBUG, "ROOT_PAGE_ID: %1$d", rootId); } } long replEncoding = decodeLongLE(header, I_REPL_ENCODING); StreamReplicator repl = launcher.mRepl; if ((replEncoding != 0 || repl != null) && launcher.mDebugOpen != null) { mEventListener.notify(EventType.DEBUG, "REPL_ENCODING: %1$d", replEncoding); } if (repl == null) { if (replEncoding != 0 && !hasRedoLogFiles()) { // Conversion to non-replicated mode is allowed by simply touching redo file 0. throw new DatabaseException ("Database must be configured with a replicator, " + "identified by: " + replEncoding); } } else if (replEncoding == 0) { // Check if conversion to replicated mode is allowed. The replication log must have // data starting at position 0, and no redo log files can exist. String msg = "Database was created initially without a replicator. " + "Conversion isn't possible "; if (!repl.isReadable(0)) { msg += "without complete replication data."; throw new DatabaseException(msg); } if (hasRedoLogFiles()) { msg += "when redo log files exist. A clean shutdown is required."; throw new DatabaseException(msg); } // The redo position passed to the ReplManager must be 0, but what's in the header // might be higher. Since we have the header data passed to us already, we can // modify it without persisting it. encodeLongLE(header, I_REDO_POSITION, 0); } else if (replEncoding != repl.encoding()) { throw new DatabaseException ("Database was created initially with a different replicator, " + "identified by: " + replEncoding); } return loadTreeRoot(0, rootId); } private static final byte IX_FIND = 0, IX_CREATE = 1; private BTree openInternalTree(long treeId, long ixOption) throws IOException { return openInternalTree(treeId, ixOption, null); } private BTree openInternalTree(long treeId, long ixOption, Launcher launcher) throws IOException { CommitLock.Shared shared = mCommitLock.acquireShared(); try { checkClosed(); var treeIdBytes = new byte[8]; encodeLongBE(treeIdBytes, 0, treeId); byte[] rootIdBytes = mRegistry.load(Transaction.BOGUS, treeIdBytes); long rootId; if (rootIdBytes != null) { rootId = decodeLongLE(rootIdBytes, 0); } else { if (ixOption == IX_FIND) { return null; } rootId = 0; } Node root = loadTreeRoot(treeId, rootId); // Cannot call newBTreeInstance because mRedoWriter isn't set yet. if (launcher != null && launcher.mRepl != null) { return new BTree.Repl(this, treeId, treeIdBytes, root); } return newBTreeInstance(treeId, treeIdBytes, null, root); } finally { shared.release(); } } /** * @param name required (cannot be null) */ private Tree openTree(byte[] name, long ixOption) throws IOException { return openTree(null, null, name, ixOption); } /** * @param findTxn optional * @param treeIdBytes optional * @param name required (cannot be null) */ private Tree openTree(Transaction findTxn, byte[] treeIdBytes, byte[] name, long ixOption) throws IOException { find: { TreeRef treeRef; mOpenTreesLatch.acquireShared(); try { treeRef = mOpenTrees.get(name); if (treeRef == null) { break find; } Tree tree = treeRef.get(); if (tree != null) { return tree; } } finally { mOpenTreesLatch.releaseShared(); } // Ensure that root node of cleared tree reference is available in the node map // before potentially replacing it. Weak references are cleared before they are // enqueued, and so polling the queue does not guarantee node eviction. Process the // tree directly. cleanupUnreferencedTree(treeRef); } CommitLock.Shared shared = mCommitLock.acquireShared(); try { return doOpenTree(findTxn, treeIdBytes, name, ixOption); } finally { shared.release(); } } /** * Caller must hold commit lock. * * @param findTxn optional * @param treeIdBytes optional * @param name required (cannot be null) */ private Tree doOpenTree(Transaction findTxn, byte[] treeIdBytes, byte[] name, long ixOption) throws IOException { checkClosed(); // Cleanup before opening more trees. cleanupUnreferencedTrees(); byte[] nameKey = newKey(RK_INDEX_NAME, name); if (treeIdBytes == null) { treeIdBytes = mRegistryKeyMap.load(findTxn, nameKey); } long treeId; // Is non-null if tree was created. byte[] idKey; if (treeIdBytes != null) { // Tree already exists. idKey = null; treeId = decodeLongBE(treeIdBytes, 0); } else if (ixOption == IX_FIND) { return null; } else create: { // Transactional find supported only for opens that do not create. if (findTxn != null) { throw new AssertionError(); } Transaction createTxn = null; Locker locker = mLockManager.localLocker(); mOpenTreesLatch.acquireExclusive(); try { while (true) { if (locker.doTryLockShared(mRegistryKeyMap.id(), nameKey, 0).isHeld()) { break; } // Release locks and retry, avoiding possible deadlock if the checkpointer // has suspended replica decoding in the middle of tree creation. mOpenTreesLatch.releaseExclusive(); mCommitLock.releaseShared(); Thread.yield(); mCommitLock.acquireShared(); mOpenTreesLatch.acquireExclusive(); } try { treeIdBytes = mRegistryKeyMap.load(Transaction.BOGUS, nameKey); } finally { locker.doUnlock(); } if (treeIdBytes != null) { // Another thread created it. idKey = null; treeId = decodeLongBE(treeIdBytes, 0); break create; } treeIdBytes = new byte[8]; // Non-transactional operations are critical, in that any failure is treated as // non-recoverable. boolean critical = true; try { do { critical = false; treeId = nextTreeId(RK_NEXT_TREE_ID); encodeLongBE(treeIdBytes, 0, treeId); critical = true; } while (!mRegistry.insert(Transaction.BOGUS, treeIdBytes, EMPTY_BYTES)); critical = false; try { idKey = newKey(RK_INDEX_ID, treeIdBytes); if (mRedoWriter instanceof ReplController) { // Confirmation is required when replicated. createTxn = newTransaction(DurabilityMode.SYNC); } else { createTxn = newAlwaysRedoTransaction(); } createTxn.lockTimeout(-1, null); // Insert order is important for the indexById method to work reliably. if (!mRegistryKeyMap.insert(createTxn, idKey, name)) { throw new DatabaseException("Unable to insert index id"); } if (!mRegistryKeyMap.insert(createTxn, nameKey, treeIdBytes)) { throw new DatabaseException("Unable to insert index name"); } } catch (Throwable e) { critical = true; try { if (createTxn != null) { createTxn.reset(); } mRegistry.delete(Transaction.BOGUS, treeIdBytes); critical = false; } catch (Throwable e2) { Utils.suppress(e, e2); } throw e; } } catch (Throwable e) { if (!critical) { rethrowIfRecoverable(e); } throw closeOnFailure(this, e); } } finally { // Release to allow opening other indexes while blocked on commit. mOpenTreesLatch.releaseExclusive(); } if (createTxn != null) { try { createTxn.commit(); } catch (Throwable e) { try { createTxn.reset(); mRegistry.delete(Transaction.BOGUS, treeIdBytes); } catch (Throwable e2) { Utils.suppress(e, e2); throw closeOnFailure(this, e); } rethrowIfRecoverable(e); throw closeOnFailure(this, e); } } } // Use a transaction to ensure that only one thread loads the requested tree. Nothing // is written into it. Transaction txn = threadLocalTransaction(DurabilityMode.NO_REDO); try { txn.lockTimeout(-1, null); if (txn.lockCheck(mRegistry.id(), treeIdBytes) != LockResult.UNOWNED) { throw new LockFailureException("Index open listener self deadlock"); } // Pass the transaction to acquire the lock. byte[] rootIdBytes = mRegistry.load(txn, treeIdBytes); Tree tree = lookupIndexById(treeId); if (tree != null) { // Another thread got the lock first and loaded the tree. return tree; } long rootId = (rootIdBytes == null || rootIdBytes.length == 0) ? 0 : decodeLongLE(rootIdBytes, 0); Node root = loadTreeRoot(treeId, rootId); BTree btree = newBTreeInstance(treeId, treeIdBytes, name, root); tree = btree; try { var treeRef = new TreeRef(tree, btree, mOpenTreesRefQueue); mOpenTreesLatch.acquireExclusive(); try { mOpenTrees.put(name, treeRef); try { mOpenTreesById.insert(treeId).value = treeRef; } catch (Throwable e) { mOpenTrees.remove(name); throw e; } } finally { mOpenTreesLatch.releaseExclusive(); } } catch (Throwable e) { btree.close(); throw e; } return tree; } catch (Throwable e) { if (idKey != null) { // Rollback create of new tree. try { mRegistryKeyMap.delete(null, idKey); mRegistryKeyMap.delete(null, nameKey); mRegistry.delete(Transaction.BOGUS, treeIdBytes); } catch (Throwable e2) { // Ignore. } } throw e; } finally { txn.reset(); } } private BTree newBTreeInstance(long id, byte[] idBytes, byte[] name, Node root) { BTree tree; if (mRedoWriter instanceof ReplWriter) { // Always need an explcit transaction when using auto-commit, to ensure that // rollback is possible. tree = new BTree.Repl(this, id, idBytes, root); } else { tree = new BTree(this, id, idBytes, root); } tree.mName = name; return tree; } /** * @param type RK_NEXT_TREE_ID or RK_NEXT_TEMP_ID */ private long nextTreeId(byte type) throws IOException { // By generating identifiers from a 64-bit sequence, it's effectively impossible for // them to get re-used after trees are deleted. Use a tree id mask, to make the // identifiers less predictable and non-compatible with other database instances. long treeIdMask = mPageDb.databaseId(); if (treeIdMask == 0) { // Use the old mask for compatibility. byte[] key = {RK_TREE_ID_MASK}; byte[] treeIdMaskBytes = mRegistryKeyMap.load(Transaction.BOGUS, key); treeIdMask = decodeLongLE(treeIdMaskBytes, 0); } Transaction txn; if (type == RK_NEXT_TEMP_ID) { txn = newNoRedoTransaction(); // Apply negative sequence, avoiding collisions. treeIdMask = ~treeIdMask; } else { txn = newAlwaysRedoTransaction(); } // Make only one change in the transaction, using Cursor.commit to only write one redo // operation. This ensures that the decode stream cannot be suspended in the middle of // the operation, preventing replica deadlock. It can be caused when a checkpoint is // starting and another thread is trying to concurrently generate a new identifier. If // the lock is held while the decoder is suspended, and the commit lock cannot be // acquired by the checkpointer, deadlock is possible. try (Cursor c = mRegistryKeyMap.newCursor(txn)) { txn.lockTimeout(-1, null); c.find(new byte[] {type}); byte[] nextTreeIdBytes = c.value(); if (nextTreeIdBytes == null) { nextTreeIdBytes = new byte[8]; } long nextTreeId = decodeLongLE(nextTreeIdBytes, 0); long treeId; do { treeId = scramble((nextTreeId++) ^ treeIdMask); } while (Tree.isInternal(treeId)); encodeLongLE(nextTreeIdBytes, 0, nextTreeId); c.commit(nextTreeIdBytes); return treeId; } finally { txn.reset(); } } /** * BTree instances retain a reference to an unevictable root node. If tree is no longer in * use, allow it to be evicted. */ private void cleanupUnreferencedTrees() throws IOException { final ReferenceQueue queue = mOpenTreesRefQueue; if (queue == null) { return; } try { while (true) { Reference ref = queue.poll(); if (ref == null) { break; } if (ref instanceof TreeRef) { cleanupUnreferencedTree((TreeRef) ref); } } } catch (Exception e) { if (!isClosed()) { throw e; } } } private void cleanupUnreferencedTree(TreeRef ref) throws IOException { Node root = ref.mRoot; root.acquireShared(); try { mOpenTreesLatch.acquireExclusive(); try { LHashTable.ObjEntry<TreeRef> entry = mOpenTreesById.get(ref.mId); if (entry == null || entry.value != ref) { return; } if (ref.mName != null) { mOpenTrees.remove(ref.mName); } mOpenTreesById.remove(ref.mId); root.makeEvictableNow(); if (root.id() > 0) { nodeMapPut(root); } } finally { mOpenTreesLatch.releaseExclusive(); } } finally { root.releaseShared(); } } private static byte[] newKey(byte type, byte[] payload) { var key = new byte[1 + payload.length]; key[0] = type; arraycopy(payload, 0, key, 1, payload.length); return key; } private static byte[] newKey(byte type, int payload) { var key = new byte[1 + 4]; key[0] = type; encodeIntBE(key, 1, payload); return key; } /** * Returns the fixed size of all pages in the store, in bytes. */ int pageSize() { return mPageSize; } private int pageSize( byte[] page) { // [ return page.length; // | // return mPageSize; // ] } /** * Returns the checkpoint commit lock, which can be held to prevent checkpoints from * capturing a safe commit point. In general, it should be acquired before any node * latches, but postponing acquisition reduces the total time held. Checkpoints don't have * to wait as long for the exclusive commit lock. Because node latching first isn't the * canonical ordering, acquiring the shared commit lock later must be prepared to * abort. Try to acquire first, and if it fails, release the node latch and do over. */ @Override public CommitLock commitLock() { return mCommitLock; } /** * @return shared latched node if found; null if not found */ Node nodeMapGetShared(long nodeId) { int hash = Long.hashCode(nodeId); while (true) { Node node = nodeMapGet(nodeId, hash); if (node == null) { return null; } node.acquireShared(); if (nodeId == node.id()) { return node; } node.releaseShared(); } } /** * @return exclusively latched node if found; null if not found */ Node nodeMapGetExclusive(long nodeId) { int hash = Long.hashCode(nodeId); while (true) { Node node = nodeMapGet(nodeId, hash); if (node == null) { return null; } node.acquireExclusive(); if (nodeId == node.id()) { return node; } node.releaseExclusive(); } } /** * Returns unconfirmed node if found. Caller must latch and confirm that the node * identifier matches, in case an eviction snuck in. */ Node nodeMapGet(final long nodeId) { return nodeMapGet(nodeId, Long.hashCode(nodeId)); } /** * Returns unconfirmed node if found. Caller must latch and confirm that the node * identifier matches, in case an eviction snuck in. */ Node nodeMapGet(final long nodeId, final int hash) { final Node[] table = mNodeMapTable; final int slot = hash & (table.length - 1); Node first = (Node) cNodeMapElementHandle.getVolatile(table, slot); if (first == null) { return null; } Node node = first; do { if (node.id() == nodeId) { return node; } node = node.mNodeMapNext; } while (node != null); // Again with lock held. first = nodeMapLock(table, slot, first); if (first == null) { return null; } node = first; do { if (node.id() == nodeId) { break; } node = node.mNodeMapNext; } while (node != null); cNodeMapElementHandle.setVolatile(table, slot, first); return node; } /** * @param first must not be null * @return actual first, which is null if slot is empty and not locked */ private static Node nodeMapLock(final Node[] table, final int slot, Node first) { while (first == NM_LOCK || !cNodeMapElementHandle.compareAndSet(table, slot, first, NM_LOCK)) { Thread.onSpinWait(); first = (Node) cNodeMapElementHandle.getVolatile(table, slot); if (first == null) { return null; } } return first; } /** * Put a node into the map, but caller must confirm that the node isn't already present. * * @param node must be latched */ void nodeMapPut(final Node node) { nodeMapPut(node, Long.hashCode(node.id())); } /** * Put a node into the map, but caller must confirm that the node isn't already present. * * @param node must be latched */ void nodeMapPut(final Node node, final int hash) { final Node[] table = mNodeMapTable; final int slot = hash & (table.length - 1); Node first = (Node) cNodeMapElementHandle.getVolatile(table, slot); while (true) { if (first != null && (first = nodeMapLock(table, slot, first)) != null) { break; } first = (Node) cNodeMapElementHandle.compareAndExchange(table, slot, null, node); if (first == null) { return; } } Node e = first; do { if (e == node) { cNodeMapElementHandle.setVolatile(table, slot, first); return; } if (e.id() == node.id()) { cNodeMapElementHandle.setVolatile(table, slot, first); throw new AssertionError("Already in NodeMap: " + node + ", " + e + ", " + hash); } e = e.mNodeMapNext; } while (e != null); node.mNodeMapNext = first; cNodeMapElementHandle.setVolatile(table, slot, node); } /** * Returns unconfirmed node if an existing node is found. Caller must latch and confirm * that the node identifier matches, in case an eviction snuck in. * * @param node must be latched * @return null if node was inserted, existing node otherwise */ Node nodeMapPutIfAbsent(final Node node) { final int hash = Long.hashCode(node.id()); final Node[] table = mNodeMapTable; final int slot = hash & (table.length - 1); Node first = (Node) cNodeMapElementHandle.getVolatile(table, slot); while (true) { if (first != null && (first = nodeMapLock(table, slot, first)) != null) { break; } first = (Node) cNodeMapElementHandle.compareAndExchange(table, slot, null, node); if (first == null) { return null; } } Node e = first; do { if (e.id() == node.id()) { cNodeMapElementHandle.setVolatile(table, slot, first); return e; } e = e.mNodeMapNext; } while (e != null); node.mNodeMapNext = first; cNodeMapElementHandle.setVolatile(table, slot, node); return null; } /** * Replace a node which must be in the map already. Old and new node MUST have the same id. */ void nodeMapReplace(final Node oldNode, final Node newNode) { final int hash = Long.hashCode(oldNode.id()); final Node[] table = mNodeMapTable; final int slot = hash & (table.length - 1); Node first = (Node) cNodeMapElementHandle.getVolatile(table, slot); if (first == null || (first = nodeMapLock(table, slot, first)) == null) { if (!isClosed()) { throw new AssertionError("Not found: " + oldNode + ", " + newNode); } return; } newNode.mNodeMapNext = oldNode.mNodeMapNext; if (first == oldNode) { first = newNode; } else { Node e = first; while (true) { Node next = e.mNodeMapNext; if (next == oldNode) { e.mNodeMapNext = newNode; break; } e = next; if (e == null) { if (isClosed()) { cNodeMapElementHandle.setVolatile(table, slot, first); return; } throw new AssertionError("Not found: " + oldNode + ", " + newNode); } } } oldNode.mNodeMapNext = null; cNodeMapElementHandle.setVolatile(table, slot, first); } boolean nodeMapRemove(final Node node) { return nodeMapRemove(node, Long.hashCode(node.id())); } boolean nodeMapRemove(final Node node, final int hash) { final Node[] table = mNodeMapTable; final int slot = hash & (table.length - 1); Node first = (Node) cNodeMapElementHandle.getVolatile(table, slot); if (first == null || (first = nodeMapLock(table, slot, first)) == null) { return false; } boolean found; if (first == node) { found = true; first = first.mNodeMapNext; } else { found = false; Node e = first; do { Node next = e.mNodeMapNext; if (next == node) { found = true; e.mNodeMapNext = next.mNodeMapNext; break; } e = next; } while (e != null); } node.mNodeMapNext = null; cNodeMapElementHandle.setVolatile(table, slot, first); return found; } /** * Returns or loads the fragment node with the given id. If loaded, node is put in the cache. * * @return node with shared latch held */ Node nodeMapLoadFragment(long nodeId) throws IOException { Node node = nodeMapGetShared(nodeId); if (node != null) { node.used(); return node; } node = allocLatchedNode(); node.id(nodeId); // node is currently exclusively locked. Insert it into the node map so that no other // thread tries to read it at the same time. If another thread sees it at this point // (before it is actually read), until the node is read, that thread will block trying // to get a shared lock. while (true) { Node existing = nodeMapPutIfAbsent(node); if (existing == null) { break; } // Was already loaded, or is currently being loaded. existing.acquireShared(); if (nodeId == existing.id()) { // The item is already loaded. Throw away the node this thread was trying to // allocate. // Even though node is not currently in the node map, it could have been in // there then got recycled. Other thread may still have a reference to it from // when it was in the node map. So its id needs to be invalidated. node.id(0); // This releases the exclusive latch and makes the node immediately usable for // new allocations. node.unused(); return existing; } existing.releaseShared(); } try { // [ node.type(TYPE_FRAGMENT); // ] readNode(node, nodeId); } catch (Throwable t) { // Something went wrong reading the node. Remove the node from the map, now that // it definitely won't get read. nodeMapRemove(node); node.id(0); node.releaseExclusive(); throw t; } node.downgrade(); return node; } /** * Returns or loads the fragment node with the given id. If loaded, node is put in the * cache. Method is intended for obtaining nodes to write into. * * @param read true if node should be fully read if it needed to be loaded * @return node with exclusive latch held */ Node nodeMapLoadFragmentExclusive(long nodeId, boolean read) throws IOException { // Very similar to the nodeMapLoadFragment method. It has comments which explains // what's going on here. No point in duplicating that as well. Node node = nodeMapGetExclusive(nodeId); if (node != null) { node.used(); return node; } node = allocLatchedNode(); node.id(nodeId); while (true) { Node existing = nodeMapPutIfAbsent(node); if (existing == null) { break; } existing.acquireExclusive(); if (nodeId == existing.id()) { node.id(0); node.unused(); return existing; } existing.releaseExclusive(); } try { // [ node.type(TYPE_FRAGMENT); // ] if (read) { readNode(node, nodeId); } } catch (Throwable t) { nodeMapRemove(node); node.id(0); node.releaseExclusive(); throw t; } return node; } /** * @return exclusively latched node if found; null if not found */ Node nodeMapGetAndRemove(long nodeId) { Node node = nodeMapGetExclusive(nodeId); if (node != null) { nodeMapRemove(node); } return node; } /** * Remove and delete nodes from map, as part of close sequence. */ void nodeMapDeleteAll() { final Node[] table = mNodeMapTable; outer: for (int slot=0; slot<table.length; ) { Node node = (Node) cNodeMapElementHandle.getVolatile(table, slot); if (node != null && (node = nodeMapLock(table, slot, node)) != null) { do { if (!node.tryAcquireExclusive()) { // Deadlock prevention. cNodeMapElementHandle.setVolatile(table, slot, node); Thread.yield(); continue outer; } try { node.doDelete(this); node.releaseExclusive(); } catch (Throwable e) { node.releaseExclusive(); cNodeMapElementHandle.setVolatile(table, slot, node); throw e; } Node next = node.mNodeMapNext; node.mNodeMapNext = null; node = next; } while (node != null); cNodeMapElementHandle.setVolatile(table, slot, null); } slot++; } // Free up more memory in case something refers to this object for a long time. mNodeMapTable = null; } /** * With parent held shared, returns child with shared latch held, releasing the parent * latch. If an exception is thrown, parent and child latches are always released. * * @return child node, possibly split */ final Node latchToChild(Node parent, int childPos) throws IOException { return latchChild(parent, childPos, Node.OPTION_PARENT_RELEASE_SHARED); } /** * With parent held shared, returns child with shared latch held, retaining the parent * latch. If an exception is thrown, parent and child latches are always released. * * @return child node, possibly split */ final Node latchChildRetainParent(Node parent, int childPos) throws IOException { return latchChild(parent, childPos, 0); } /** * With parent held shared, returns child with shared latch held. If an exception is * thrown, parent and child latches are always released. * * @param option Node.OPTION_PARENT_RELEASE_SHARED or 0 to retain latch * @return child node, possibly split */ final Node latchChild(Node parent, int childPos, int option) throws IOException { long childId = parent.retrieveChildRefId(childPos); Node childNode = nodeMapGetShared(childId); tryFind: if (childNode != null) { checkChild: { evictChild: if (childNode.mCachedState != Node.CACHED_CLEAN && parent.mCachedState == Node.CACHED_CLEAN // Must be a valid parent -- not a stub from Node.rootDelete. && parent.id() > 1) { // Parent was evicted before child. Evict child now and mark as clean. If // this isn't done, the notSplitDirty method will short-circuit and not // ensure that all the parent nodes are dirty. The splitting and merging // code assumes that all nodes referenced by the cursor are dirty. The // short-circuit check could be skipped, but then every change would // require a full latch up the tree. Another option is to remark the parent // as dirty, but this is dodgy and also requires a full latch up the tree. // Parent-before-child eviction is infrequent, and so simple is better. if (!childNode.tryUpgrade()) { childNode.releaseShared(); childNode = nodeMapGetExclusive(childId); if (childNode == null) { break tryFind; } if (childNode.mCachedState == Node.CACHED_CLEAN) { // Child state which was checked earlier changed when its latch was // released, and now it shoudn't be evicted. childNode.downgrade(); break evictChild; } } if (option == Node.OPTION_PARENT_RELEASE_SHARED) { parent.releaseShared(); } try { childNode.write(mPageDb); } catch (Throwable e) { childNode.releaseExclusive(); if (option == 0) { // Release due to exception. parent.releaseShared(); } throw e; } childNode.mCachedState = Node.CACHED_CLEAN; childNode.downgrade(); break checkChild; } if (option == Node.OPTION_PARENT_RELEASE_SHARED) { parent.releaseShared(); } } childNode.used(); return childNode; } return parent.loadChild(this, childId, option); } /** * Variant of latchChildRetainParent which uses exclusive latches. With parent held * exclusively, returns child with exclusive latch held, retaining the parent latch. If an * exception is thrown, parent and child latches are always released. * * @param required pass false to allow null to be returned when child isn't immediately * latchable; passing false still permits the child to be loaded if necessary * @return child node, possibly split */ final Node latchChildRetainParentEx(Node parent, int childPos, boolean required) throws IOException { long childId = parent.retrieveChildRefId(childPos); Node childNode; while (true) { childNode = nodeMapGet(childId); if (childNode != null) { if (required) { childNode.acquireExclusive(); } else if (!childNode.tryAcquireExclusive()) { return null; } if (childId == childNode.id()) { break; } childNode.releaseExclusive(); continue; } return parent.loadChild(this, childId, Node.OPTION_CHILD_ACQUIRE_EXCLUSIVE); } if (childNode.mCachedState != Node.CACHED_CLEAN && parent.mCachedState == Node.CACHED_CLEAN // Must be a valid parent -- not a stub from Node.rootDelete. && parent.id() > 1) { // Parent was evicted before child. Evict child now and mark as clean. If // this isn't done, the notSplitDirty method will short-circuit and not // ensure that all the parent nodes are dirty. The splitting and merging // code assumes that all nodes referenced by the cursor are dirty. The // short-circuit check could be skipped, but then every change would // require a full latch up the tree. Another option is to remark the parent // as dirty, but this is dodgy and also requires a full latch up the tree. // Parent-before-child eviction is infrequent, and so simple is better. try { childNode.write(mPageDb); } catch (Throwable e) { childNode.releaseExclusive(); // Release due to exception. parent.releaseExclusive(); throw e; } childNode.mCachedState = Node.CACHED_CLEAN; } childNode.used(); return childNode; } /** * Returns a new or recycled Node instance, latched exclusively, with an undefined id and a * clean state. */ Node allocLatchedNode() throws IOException { return allocLatchedNode(0); } /** * Returns a new or recycled Node instance, latched exclusively, with an undefined id and a * clean state. * * @param mode MODE_UNEVICTABLE if allocated node cannot be automatically evicted */ Node allocLatchedNode(int mode) throws IOException { mode |= mPageDb.allocMode(); NodeGroup[] groups = mNodeGroups; int groupIx = ThreadLocalRandom.current().nextInt() & (groups.length - 1); IOException fail = null; for (int trial = 1; trial <= 3; trial++) { for (int i=0; i<groups.length; i++) { try { Node node = groups[groupIx].tryAllocLatchedNode(trial, mode); if (node != null) { return node; } } catch (IOException e) { if (fail == null) { fail = e; } } if (--groupIx < 0) { groupIx = groups.length - 1; } } checkClosed(); // Try to free up nodes from unreferenced trees. cleanupUnreferencedTrees(); } if (fail == null) { String stats = stats().toString(); if (mPageDb.isDurable()) { throw new CacheExhaustedException(stats); } else { throw new DatabaseFullException(stats); } } if (fail instanceof DatabaseFullException) { throw fail; } else { throw new DatabaseFullException(fail); } } /** * Returns a new or recycled Node instance, latched exclusively, marked dirty, and with the * given id. Caller must be certain that the page with the given id can be written to. * Caller must also hold commit lock. * * The intent of this method is to reduce write stalls when the PageQueue drains full * nodes. If it needs to write another node in the process, then that's obviously not * helpful. * * When running in the fully memory mapped mode, this method always returns null because * writing to a mapped file is just a memory copy anyhow. There's no immediate write stall, * unless out of memory and swapping. * * @return null if another dirty node would need to be evicted */ Node tryAllocRawDirtyNode(long id) throws IOException { // [| // if (mFullyMapped) { // return null; // } // ] NodeGroup[] groups = mNodeGroups; int groupIx = ThreadLocalRandom.current().nextInt(groups.length); Node node = groups[groupIx].tryAllocLatchedNode(1, NodeGroup.MODE_NO_EVICT); if (node != null) { // [ node.type(Node.TYPE_FRAGMENT); // | // node.type(Node.TYPE_NONE); // ] node.id(id); node.mGroup.addDirty(node, mCommitState); } return node; } /** * Returns a new or recycled Node instance, latched exclusively and marked * dirty. Caller must hold commit lock. */ Node allocDirtyNode() throws IOException { return allocDirtyNode(0); } /** * Returns a new or recycled Node instance, latched exclusively, marked * dirty and unevictable. Caller must hold commit lock. * * @param mode MODE_UNEVICTABLE if allocated node cannot be automatically evicted */ Node allocDirtyNode(int mode) throws IOException { Node node = mPageDb.allocLatchedNode(this, mode); // [| // if (mFullyMapped) { // node.mPage = mPageDb.dirtyPage(node.id()); // } // ] node.mGroup.addDirty(node, mCommitState); return node; } /** * Returns a new or recycled Node instance, latched exclusively and marked * dirty. Caller must hold commit lock. */ Node allocDirtyFragmentNode() throws IOException { Node node = allocDirtyNode(); nodeMapPut(node); // [ node.type(TYPE_FRAGMENT); // ] return node; } /** * Caller must hold commit lock and any latch on node. */ boolean isMutable(Node node) { return node.mCachedState == mCommitState && node.id() > 1; } /** * Caller must hold commit lock and any latch on node. */ boolean shouldMarkDirty(Node node) { return node.mCachedState != mCommitState && node.id() >= 0; } /** * Mark a tree node as dirty. Caller must hold commit lock and exclusive latch on * node. Method does nothing if node is already dirty. Latch is never released by this * method, even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markDirty(BTree tree, Node node) throws IOException { if (node.mCachedState == mCommitState || node.id() < 0) { return false; } else { doMarkDirty(tree, node); return true; } } /** * Mark a fragment node as dirty. Caller must hold commit lock and exclusive latch on * node. Method does nothing if node is already dirty. Latch is never released by this * method, even if an exception is thrown. * * @return true if just made dirty and id changed */ boolean markFragmentDirty(Node node) throws IOException { if (node.mCachedState == mCommitState) { return false; } else { if (node.mCachedState != CACHED_CLEAN) { node.write(mPageDb); } long newId = mPageDb.allocPage(); long oldId = node.id(); if (oldId != 0) { // Must be removed from map before page is deleted. It could be recycled too // soon, creating a NodeMap collision. boolean removed = nodeMapRemove(node, Long.hashCode(oldId)); try { // No need to force delete when dirtying. Caller is responsible for // cleaning up. mPageDb.deletePage(oldId, false); } catch (Throwable e) { // Try to undo things. if (removed) { try { nodeMapPut(node); } catch (Throwable e2) { Utils.suppress(e, e2); } } try { mPageDb.recyclePage(newId); } catch (Throwable e2) { // Panic. Utils.suppress(e, e2); close(e); } throw e; } } dirty(node, newId); nodeMapPut(node); return true; } } /** * Mark an unmapped node as dirty (used by UndoLog). Caller must hold commit lock and * exclusive latch on node. Method does nothing if node is already dirty. Latch is never * released by this method, even if an exception is thrown. */ void markUnmappedDirty(Node node) throws IOException { if (node.mCachedState != mCommitState) { if (node.mCachedState != CACHED_CLEAN) { node.write(mPageDb); } long newId = mPageDb.allocPage(); long oldId = node.id(); try { // No need to force delete when dirtying. Caller is responsible for cleaning up. mPageDb.deletePage(oldId, false); } catch (Throwable e) { try { mPageDb.recyclePage(newId); } catch (Throwable e2) { // Panic. Utils.suppress(e, e2); close(e); } throw e; } dirty(node, newId); } } /** * Caller must hold commit lock and exclusive latch on node. Method must * not be called if node is already dirty. Latch is never released by this * method, even if an exception is thrown. */ void doMarkDirty(BTree tree, Node node) throws IOException { if (node.mCachedState != CACHED_CLEAN) { node.write(mPageDb); } long newId = mPageDb.allocPage(); long oldId = node.id(); try { if (node == tree.mRoot) { storeTreeRootId(tree, newId); } } catch (Throwable e) { try { mPageDb.recyclePage(newId); } catch (Throwable e2) { // Panic. Utils.suppress(e, e2); close(e); } throw e; } if (oldId != 0) { // Must be removed from map before page is deleted. It could be recycled too soon, // creating a NodeMap collision. boolean removed = nodeMapRemove(node, Long.hashCode(oldId)); try { // No need to force delete when dirtying. Caller is responsible for cleaning up. mPageDb.deletePage(oldId, false); } catch (Throwable e) { // Try to undo things. if (removed) { try { nodeMapPut(node); } catch (Throwable e2) { Utils.suppress(e, e2); } } try { if (node == tree.mRoot) { storeTreeRootId(tree, oldId); } mPageDb.recyclePage(newId); } catch (Throwable e2) { // Panic. Utils.suppress(e, e2); close(e); } throw e; } } dirty(node, newId); nodeMapPut(node); } private void storeTreeRootId(BTree tree, long id) throws IOException { if (tree.mIdBytes != null) { var encodedId = new byte[8]; encodeLongLE(encodedId, 0, id); mRegistry.store(Transaction.BOGUS, tree.mIdBytes, encodedId); } } /** * Caller must hold commit lock and exclusive latch on node. */ private void dirty(Node node, long newId) throws IOException { // [| // if (mFullyMapped) { // if (node.mPage == p_nonTreePage()) { // node.mPage = mPageDb.dirtyPage(newId); // node.asEmptyRoot(); // } else if (node.mPage != p_closedTreePage()) { // node.mPage = mPageDb.copyPage(node.id(), newId); // copy on write // } // } // ] node.id(newId); node.mGroup.addDirty(node, mCommitState); } /** * Remove the old node from the dirty list and swap in the new node. Caller must hold * commit lock and latched the old node. The cached state of the nodes is not altered. * Both nodes must belong to the same group. */ void swapIfDirty(Node oldNode, Node newNode) { oldNode.mGroup.swapIfDirty(oldNode, newNode); } /** * Caller must hold commit lock and exclusive latch on node. Latch is always released by * this method, even if an exception is thrown. */ void deleteNode(Node node) throws IOException { deleteNode(node, true); } /** * Caller must hold commit lock and exclusive latch on node. Latch is always released by * this method, even if an exception is thrown. */ void deleteNode(Node node, boolean canRecycle) throws IOException { prepareToDelete(node); finishDeleteNode(node, canRecycle); } /** * Similar to markDirty method except no new page is reserved, and old page * is not immediately deleted. Caller must hold commit lock and exclusive * latch on node. Latch is never released by this method, unless an * exception is thrown. */ void prepareToDelete(Node node) throws IOException { // Hello. My name is Inigo Montoya. You killed my father. Prepare to die. if (node.mCachedState == mCheckpointFlushState) { // Node must be committed with the current checkpoint, and so // it must be written out before it can be deleted. try { node.write(mPageDb); } catch (Throwable e) { node.releaseExclusive(); throw e; } } } /** * Caller must hold commit lock and exclusive latch on node. The * prepareToDelete method must have been called first. Latch is always * released by this method, even if an exception is thrown. */ void finishDeleteNode(Node node) throws IOException { finishDeleteNode(node, true); } /** * @param canRecycle true if node's page can be immediately re-used */ void finishDeleteNode(Node node, boolean canRecycle) throws IOException { try { long id = node.id(); if (id != 0) { // Must be removed from map before page is deleted. It could be recycled too // soon, creating a NodeMap collision. boolean removed = nodeMapRemove(node, Long.hashCode(id)); try { if (canRecycle && node.mCachedState == mCommitState) { // Newly reserved page was never used, so recycle it. mPageDb.recyclePage(id); } else { // Old data must survive until after checkpoint. Must force the delete, // because by this point, the caller can't easily clean up. mPageDb.deletePage(id, true); } } catch (Throwable e) { // Try to undo things. if (removed) { try { nodeMapPut(node); } catch (Throwable e2) { Utils.suppress(e, e2); } } throw e; } // When id is <= 1, it won't be moved to a secondary cache. Preserve the // original id for non-durable database to recycle it. Durable database relies // on the free list. node.id(-id); } // When node is re-allocated, it will be evicted. Ensure that eviction // doesn't write anything. node.mCachedState = CACHED_CLEAN; } catch (Throwable e) { node.releaseExclusive(); // Panic. close(e); throw e; } // Always releases the node latch. node.unused(); } final byte[] fragmentKey(byte[] key) throws IOException { return fragment(key, key.length, mMaxKeySize); } final byte[] fragment(final byte[] value, final long vlength, int max) throws IOException { return fragment(value, vlength, max, 65535); } /** * Breakup a large value into separate pages, returning a new value which * encodes the page references. Caller must hold commit lock. * * Returned value begins with a one byte header: * * 0b0000_ffip * * The leading 4 bits define the encoding type, which must be 0. The 'f' bits define the * full value length field size: 2, 4, 6, or 8 bytes. The 'i' bit defines the inline * content length field size: 0 or 2 bytes. The 'p' bit is clear if direct pointers are * used, and set for indirect pointers. Pointers are always 6 bytes. * * @param value can be null if value is all zeros * @param max maximum allowed size for returned byte array; must not be * less than 11 {@literal (can be 9 if full value length is < 65536)} * @param maxInline maximum allowed inline size; must not be more than 65535 * @return null if max is too small */ final byte[] fragment(final byte[] value, final long vlength, int max, int maxInline) throws IOException { final int pageSize = mPageSize; long pageCount = vlength / pageSize; final int remainder = (int) (vlength % pageSize); if (vlength >= 65536) { // Subtract header size, full length field size, and size of one pointer. max -= (1 + 4 + 6); } else if (pageCount == 0 && remainder <= (max - (1 + 2 + 2))) { // Entire value fits inline. It didn't really need to be // encoded this way, but do as we're told. var newValue = new byte[(1 + 2 + 2) + (int) vlength]; newValue[0] = 0x02; // ff=0, i=1, p=0 encodeShortLE(newValue, 1, (int) vlength); // full length encodeShortLE(newValue, 1 + 2, (int) vlength); // inline length arrayCopyOrFill(value, 0, newValue, (1 + 2 + 2), (int) vlength); return newValue; } else { // Subtract header size, full length field size, and size of one pointer. max -= (1 + 2 + 6); } if (max < 0) { return null; } long pointerSpace = pageCount * 6; byte[] newValue; final int inline; // length of inline field size if (remainder <= max && remainder <= maxInline && (pointerSpace <= (max + 6 - (inline = remainder == 0 ? 0 : 2) - remainder))) { // Remainder fits inline, minimizing internal fragmentation. All // extra pages will be full. All pointers fit too; encode direct. // Conveniently, 2 is the header bit and the inline length field size. byte header = (byte) inline; final int offset; if (vlength < (1L << (2 * 8))) { // (2 byte length field) offset = 1 + 2; } else if (vlength < (1L << (4 * 8))) { header |= 0x04; // ff = 1 (4 byte length field) offset = 1 + 4; } else if (vlength < (1L << (6 * 8))) { header |= 0x08; // ff = 2 (6 byte length field) offset = 1 + 6; } else { header |= 0x0c; // ff = 3 (8 byte length field) offset = 1 + 8; } int poffset = offset + inline + remainder; newValue = new byte[poffset + (int) pointerSpace]; if (pageCount > 0) { if (value == null) { // Value is sparse, so just fill with null pointers. fill(newValue, poffset, poffset + ((int) pageCount) * 6, (byte) 0); } else { try { int voffset = remainder; while (true) { Node node = allocDirtyFragmentNode(); try { encodeInt48LE(newValue, poffset, node.id()); p_copyFromArray(value, voffset, node.mPage, 0, pageSize); if (pageCount == 1) { break; } } finally { node.releaseExclusive(); } pageCount poffset += 6; voffset += pageSize; } } catch (DatabaseException e) { if (!e.isRecoverable()) { close(e); } else { try { // Clean up the mess. while ((poffset -= 6) >= (offset + inline + remainder)) { deleteFragment(decodeUnsignedInt48LE(newValue, poffset)); } } catch (Throwable e2) { suppress(e, e2); close(e); } } throw e; } } } newValue[0] = header; if (remainder != 0) { encodeShortLE(newValue, offset, remainder); // inline length arrayCopyOrFill(value, 0, newValue, offset + 2, remainder); } } else { // Remainder doesn't fit inline, so don't encode any inline // content. Last extra page will not be full. pageCount++; pointerSpace += 6; byte header; final int offset; if (vlength < (1L << (2 * 8))) { header = 0x00; // ff = 0, i=0 offset = 1 + 2; } else if (vlength < (1L << (4 * 8))) { header = 0x04; // ff = 1, i=0 offset = 1 + 4; } else if (vlength < (1L << (6 * 8))) { header = 0x08; // ff = 2, i=0 offset = 1 + 6; } else { header = 0x0c; // ff = 3, i=0 offset = 1 + 8; } if (pointerSpace <= (max + 6)) { // All pointers fit, so encode as direct. newValue = new byte[offset + (int) pointerSpace]; if (pageCount > 0) { if (value == null) { // Value is sparse, so just fill with null pointers. fill(newValue, offset, offset + ((int) pageCount) * 6, (byte) 0); } else { int poffset = offset; try { int voffset = 0; while (true) { Node node = allocDirtyFragmentNode(); try { encodeInt48LE(newValue, poffset, node.id()); var page = node.mPage; if (pageCount > 1) { p_copyFromArray(value, voffset, page, 0, pageSize); } else { p_copyFromArray(value, voffset, page, 0, remainder); // Zero fill the rest, making it easier to extend later. p_clear(page, remainder, pageSize(page)); break; } } finally { node.releaseExclusive(); } pageCount poffset += 6; voffset += pageSize; } } catch (DatabaseException e) { if (!e.isRecoverable()) { close(e); } else { try { // Clean up the mess. while ((poffset -= 6) >= offset) { deleteFragment(decodeUnsignedInt48LE(newValue, poffset)); } } catch (Throwable e2) { suppress(e, e2); close(e); } } throw e; } } } } else { // Use indirect pointers. header |= 0x01; newValue = new byte[offset + 6]; if (value == null) { // Value is sparse, so just store a null pointer. encodeInt48LE(newValue, offset, 0); } else { int levels = calculateInodeLevels(vlength); Node inode = allocDirtyFragmentNode(); try { encodeInt48LE(newValue, offset, inode.id()); writeMultilevelFragments(levels, inode, value, 0, vlength); inode.releaseExclusive(); } catch (DatabaseException e) { if (!e.isRecoverable()) { close(e); } else { try { // Clean up the mess. Note that inode is still latched here, // because writeMultilevelFragments never releases it. The call to // deleteMultilevelFragments always releases the inode latch. deleteMultilevelFragments(levels, inode, vlength); } catch (Throwable e2) { suppress(e, e2); close(e); } } throw e; } catch (Throwable e) { close(e); throw e; } } } newValue[0] = header; } // Encode full length field. if (vlength < (1L << (2 * 8))) { encodeShortLE(newValue, 1, (int) vlength); } else if (vlength < (1L << (4 * 8))) { encodeIntLE(newValue, 1, (int) vlength); } else if (vlength < (1L << (6 * 8))) { encodeInt48LE(newValue, 1, vlength); } else { encodeLongLE(newValue, 1, vlength); } return newValue; } int calculateInodeLevels(long vlength) { long[] caps = mFragmentInodeLevelCaps; int levels = 0; while (levels < caps.length) { if (vlength <= caps[levels]) { break; } levels++; } return levels; } static long decodeFullFragmentedValueLength(int header, byte[] fragmented, int off) { switch ((header >> 2) & 0x03) { default: return p_ushortGetLE(fragmented, off); case 1: return p_intGetLE(fragmented, off) & 0xffffffffL; case 2: return p_uint48GetLE(fragmented, off); case 3: return p_longGetLE(fragmented, off); } } /** * @param level inode level; at least 1 * @param inode exclusive latched parent inode; never released by this method * @param value slice of complete value being fragmented */ private void writeMultilevelFragments(int level, Node inode, byte[] value, int voffset, long vlength) throws IOException { var page = inode.mPage; level long levelCap = levelCap(level); int childNodeCount = childNodeCount(vlength, levelCap); int poffset = 0; try { for (int i=0; i<childNodeCount; i++) { Node childNode = allocDirtyFragmentNode(); p_int48PutLE(page, poffset, childNode.id()); poffset += 6; int len = (int) Math.min(levelCap, vlength); if (level <= 0) { var childPage = childNode.mPage; p_copyFromArray(value, voffset, childPage, 0, len); // Zero fill the rest, making it easier to extend later. p_clear(childPage, len, pageSize(childPage)); childNode.releaseExclusive(); } else { try { writeMultilevelFragments(level, childNode, value, voffset, len); } finally { childNode.releaseExclusive(); } } vlength -= len; voffset += len; } } finally { // Zero fill the rest, making it easier to extend later. If an exception was // thrown, this simplies cleanup. All of the allocated pages are referenced, // but the rest are not. p_clear(page, poffset, pageSize(page)); } } /** * Determine the multi-level fragmented value child node count, at a specific level. */ private static int childNodeCount(long vlength, long levelCap) { int count = (int) ((vlength + (levelCap - 1)) / levelCap); if (count < 0) { // Overflowed. count = childNodeCountOverflow(vlength, levelCap); } return count; } private static int childNodeCountOverflow(long vlength, long levelCap) { return BigInteger.valueOf(vlength).add(BigInteger.valueOf(levelCap - 1)) .divide(BigInteger.valueOf(levelCap)).intValue(); } /** * Reconstruct a fragmented key. */ byte[] reconstructKey( byte[] fragmented, int off, int len) throws IOException { try { return reconstruct(fragmented, off, len); } catch (LargeValueException e) { throw new LargeKeyException(e.length(), e.getCause()); } } /** * Reconstruct a fragmented value. */ byte[] reconstruct( byte[] fragmented, int off, int len) throws IOException { return reconstruct(fragmented, off, len, null); } /** * Reconstruct a fragmented value. * * @param stats non-null for stats: [0]: full length, [1]: number of pages * {@literal (>0 if fragmented)} * @return null if stats requested */ byte[] reconstruct( byte[] fragmented, int off, int len, long[] stats) throws IOException { int header = p_byteGet(fragmented, off++); len long vLen; switch ((header >> 2) & 0x03) { default: vLen = p_ushortGetLE(fragmented, off); break; case 1: vLen = p_intGetLE(fragmented, off); if (vLen < 0) { vLen &= 0xffffffffL; if (stats == null) { throw new LargeValueException(vLen); } } break; case 2: vLen = p_uint48GetLE(fragmented, off); if (vLen > Integer.MAX_VALUE && stats == null) { throw new LargeValueException(vLen); } break; case 3: vLen = p_longGetLE(fragmented, off); if (vLen < 0 || (vLen > Integer.MAX_VALUE && stats == null)) { throw new LargeValueException(vLen); } break; } { int vLenFieldSize = 2 + ((header >> 1) & 0x06); off += vLenFieldSize; len -= vLenFieldSize; } byte[] value; if (stats != null) { stats[0] = vLen; value = null; } else { try { value = new byte[(int) vLen]; } catch (OutOfMemoryError e) { throw new LargeValueException(vLen, e); } } int vOff = 0; if ((header & 0x02) != 0) { // Inline content. int inLen = p_ushortGetLE(fragmented, off); off += 2; len -= 2; if (value != null) { p_copyToArray(fragmented, off, value, vOff, inLen); } off += inLen; len -= inLen; vOff += inLen; vLen -= inLen; } long pagesRead = 0; if ((header & 0x01) == 0) { // Direct pointers. while (len >= 6) { long nodeId = p_uint48GetLE(fragmented, off); off += 6; len -= 6; int pLen; if (nodeId == 0) { // Reconstructing a sparse value. Array is already zero-filled. pLen = Math.min((int) vLen, mPageSize); } else { Node node = nodeMapLoadFragment(nodeId); pagesRead++; try { var page = node.mPage; pLen = Math.min((int) vLen, pageSize(page)); if (value != null) { p_copyToArray(page, 0, value, vOff, pLen); } } finally { node.releaseShared(); } } vOff += pLen; vLen -= pLen; } } else { // Indirect pointers. long inodeId = p_uint48GetLE(fragmented, off); if (inodeId != 0) { Node inode = nodeMapLoadFragment(inodeId); pagesRead++; int levels = calculateInodeLevels(vLen); pagesRead += readMultilevelFragments(levels, inode, value, vOff, vLen); } } if (stats != null) { stats[1] = pagesRead; } return value; } /** * @param level inode level; at least 1 * @param inode shared latched parent inode; always released by this method * @param value slice of complete value being reconstructed; initially filled with zeros; * pass null for stats only * @return number of pages read */ private long readMultilevelFragments(int level, Node inode, byte[] value, int voffset, long vlength) throws IOException { try { long pagesRead = 0; var page = inode.mPage; level long levelCap = levelCap(level); int childNodeCount = childNodeCount(vlength, levelCap); for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) { long childNodeId = p_uint48GetLE(page, poffset); int len = (int) Math.min(levelCap, vlength); if (childNodeId != 0) { Node childNode = nodeMapLoadFragment(childNodeId); pagesRead++; if (level <= 0) { if (value != null) { p_copyToArray(childNode.mPage, 0, value, voffset, len); } childNode.releaseShared(); } else { pagesRead += readMultilevelFragments (level, childNode, value, voffset, len); } } vlength -= len; voffset += len; } return pagesRead; } finally { inode.releaseShared(); } } /** * Delete the extra pages of a fragmented value. Caller must hold commit lock. * * @param fragmented page containing fragmented value */ void deleteFragments( byte[] fragmented, int off, int len) throws IOException { int header = p_byteGet(fragmented, off++); len long vLen; if ((header & 0x01) == 0) { // Don't need to read the value length when deleting direct pointers. vLen = 0; } else { switch ((header >> 2) & 0x03) { default: vLen = p_ushortGetLE(fragmented, off); break; case 1: vLen = p_intGetLE(fragmented, off) & 0xffffffffL; break; case 2: vLen = p_uint48GetLE(fragmented, off); break; case 3: vLen = p_longGetLE(fragmented, off); break; } } { int vLenFieldSize = 2 + ((header >> 1) & 0x06); off += vLenFieldSize; len -= vLenFieldSize; } if ((header & 0x02) != 0) { // Skip inline content. int inLen = 2 + p_ushortGetLE(fragmented, off); off += inLen; len -= inLen; } if ((header & 0x01) == 0) { // Direct pointers. while (len >= 6) { long nodeId = p_uint48GetLE(fragmented, off); off += 6; len -= 6; deleteFragment(nodeId); } } else { // Indirect pointers. long inodeId = p_uint48GetLE(fragmented, off); if (inodeId != 0) { Node inode = removeInode(inodeId); int levels = calculateInodeLevels(vLen); deleteMultilevelFragments(levels, inode, vLen); } } } /** * @param level inode level; at least 1 * @param inode exclusive latched parent inode; always released by this method */ private void deleteMultilevelFragments(int level, Node inode, long vlength) throws IOException { var page = inode.mPage; level long levelCap = levelCap(level); // Copy all child node ids and release parent latch early. int childNodeCount = childNodeCount(vlength, levelCap); var childNodeIds = new long[childNodeCount]; for (int poffset = 0, i=0; i<childNodeCount; poffset += 6, i++) { childNodeIds[i] = p_uint48GetLE(page, poffset); } deleteNode(inode); if (level <= 0) for (long childNodeId : childNodeIds) { deleteFragment(childNodeId); } else for (long childNodeId : childNodeIds) { long len = Math.min(levelCap, vlength); if (childNodeId != 0) { Node childNode = removeInode(childNodeId); deleteMultilevelFragments(level, childNode, len); } vlength -= len; } } /** * @param nodeId must not be zero * @return non-null Node with exclusive latch held */ private Node removeInode(long nodeId) throws IOException { Node node = nodeMapGetAndRemove(nodeId); if (node == null) { node = allocLatchedNode(NodeGroup.MODE_UNEVICTABLE); // [ node.type(TYPE_FRAGMENT); // ] try { readNode(node, nodeId); } catch (Throwable e) { node.releaseExclusive(); throw e; } } return node; } /** * @param nodeId can be zero */ void deleteFragment(long nodeId) throws IOException { if (nodeId != 0) { Node node = nodeMapGetAndRemove(nodeId); if (node != null) { deleteNode(node); } else try { if (mInitialReadState != CACHED_CLEAN) { // Page was never used if nothing has ever been checkpointed. mPageDb.recyclePage(nodeId); } else { // Page is clean if not in a Node, and so it must survive until after the // next checkpoint. Must force the delete, because by this point, the // caller can't easily clean up. mPageDb.deletePage(nodeId, true); } } catch (Throwable e) { // Panic. close(e); throw e; } } } private static long[] calculateInodeLevelCaps(int pageSize) { var caps = new long[10]; long cap = pageSize; long scalar = pageSize / 6; // 6-byte pointers int i = 0; while (i < caps.length) { caps[i++] = cap; long next = cap * scalar; if (next / scalar != cap) { caps[i++] = Long.MAX_VALUE; break; } cap = next; } if (i < caps.length) { var newCaps = new long[i]; arraycopy(caps, 0, newCaps, 0, i); caps = newCaps; } return caps; } long levelCap(int level) { return mFragmentInodeLevelCaps[level]; } /** * Obtain the trash for transactionally deleting fragmented values. */ BTree fragmentedTrash() throws IOException { BTree trash = mFragmentedTrash; return trash != null ? trash : openFragmentedTrash(IX_CREATE); } /** * Try to obtain the trash for transactionally deleting fragmented values. Returns null if * it doesn't exist. */ BTree tryFragmentedTrash() throws IOException { BTree trash = mFragmentedTrash; return trash != null ? trash : openFragmentedTrash(IX_FIND); } /** * @param ixOption IX_FIND or IX_CREATE */ private BTree openFragmentedTrash(long ixOption) throws IOException { BTree trash; mOpenTreesLatch.acquireExclusive(); try { if ((trash = mFragmentedTrash) == null) { mFragmentedTrash = trash = openInternalTree(Tree.FRAGMENTED_TRASH_ID, ixOption); } } finally { mOpenTreesLatch.releaseExclusive(); } return trash; } /** * Non-transactionally deletes all fragmented values except for those that are still active. * * @param activeTxns pass null to delete from non-replicated (no redo) transactions; * otherwise, only delete from replicated transactions that aren't in this hashtable */ void emptyLingeringTrash(LHashTable<?> activeTxns) throws IOException { mOpenTreesLatch.acquireExclusive(); BTree trash = mFragmentedTrash; if (trash != null) { mOpenTreesLatch.releaseExclusive(); FragmentedTrash.emptyLingeringTrash(trash, activeTxns); return; } try { trash = openInternalTree(Tree.FRAGMENTED_TRASH_ID, IX_FIND); if (trash == null) { mOpenTreesLatch.releaseExclusive(); return; } } catch (Throwable e) { mOpenTreesLatch.releaseExclusive(); throw e; } mOpenTreesLatch.downgrade(); try { FragmentedTrash.emptyLingeringTrash(trash, activeTxns); } finally { mOpenTreesLatch.releaseShared(); trash.forceClose(); } } /** * Reads the node page, sets the id and cached state. Node must be latched exclusively. */ void readNode(Node node, long id) throws IOException { // [ mPageDb.readPage(id, node.mPage); // | // if (mFullyMapped) { // node.mPage = mPageDb.directPagePointer(id); // } else { // mPageDb.readPage(id, node.mPage); // } // ] node.id(id); // NOTE: If initial state is clean, an optimization is possible, but it's a bit // tricky. Too many pages are allocated when evictions are high, write rate is high, // and commits are bogged down. Keep some sort of cache of ids known to be dirty. If // reloaded before commit, then they're still dirty. // A Bloom filter is not appropriate, because of false positives. A random evicting // cache works well -- it has no collision chains. Evict whatever else was there in // the slot. An array of longs should suffice. // When a child node is loaded with a dirty state, the parent nodes must be updated // as well. This might force them to be evicted, and then the optimization is // lost. A better approach would avoid the optimization if the parent node is clean // or doesn't match the current commit state. if ((node.mCachedState = mInitialReadState) != CACHED_CLEAN) { node.mGroup.addDirty(node, node.mCachedState); } } @Override EventListener eventListener() { return mEventListener; } @Override void checkpoint(long sizeThreshold, long delayThresholdNanos) throws IOException { checkpoint(0, sizeThreshold, delayThresholdNanos); } private void forceCheckpoint() throws IOException { checkpoint(1, 0, 0); } /** * @param force 0: no force, 1: force if not closed, -1: force even if closed */ private void checkpoint(int force, long sizeThreshold, long delayThresholdNanos) throws IOException { while (!isClosed() && mPageDb.isDurable()) { // Checkpoint lock ensures consistent state between page store and logs. mCheckpointLock.lock(); try { doCheckpoint(force, sizeThreshold, delayThresholdNanos); return; } catch (Throwable e) { if (!isRecoverable(e)) { // Panic. closeQuietly(this, e); throw e; } try { cleanupMasterUndoLog(); } catch (Throwable e2) { // Panic. closeQuietly(this, e2); suppress(e2, e); throw e2; } // Retry and don't rethrow if leadership was lost. if (!(e instanceof UnmodifiableReplicaException)) { throw e; } } finally { mCheckpointLock.unlock(); } Thread.yield(); } } /** * Caller must hold mCheckpointLock. */ private void cleanupMasterUndoLog() throws IOException { if (mCommitMasterUndoLog == null) { return; } LHashTable.Obj<Object> committed = mCommitMasterUndoLog.findCommitted(); if (committed == null) { return; } loop: while (true) { checkAll: { for (TransactionContext txnContext : mTxnContexts) { if (txnContext.anyActive(committed)) { break checkAll; } } break loop; } if (isClosed()) { return; } // Wait with a sleep. Crude, but it means that no special condition variable is // required. Considering that this method is only expected to be called when // leadership is lost during a checkpoint, there's no reason to be immediate. try { Thread.sleep(100); } catch (InterruptedException e) { throw new InterruptedIOException(); } } LHashTable.Obj<Object> uncommitted = null; for (TransactionContext txnContext : mTxnContexts) { uncommitted = txnContext.moveUncommitted(uncommitted); } if (uncommitted != null) { mCommitMasterUndoLog.markUncommitted(uncommitted); } } /** * Caller must hold mCheckpointLock. * * @param force 0: no force, 1: force if not closed, -1: force even if closed */ private void doCheckpoint(int force, long sizeThreshold, long delayThresholdNanos) throws IOException { if (force >= 0 && isClosed()) { return; } // Now's a good time to clean things up. cleanupUnreferencedTrees(); final Node root = mRegistry.mRoot; var header = mCommitHeader; long nowNanos = System.nanoTime(); if (force == 0 && header == p_null()) { thresholdCheck : { if (delayThresholdNanos == 0) { break thresholdCheck; } if (delayThresholdNanos > 0 && ((nowNanos - mLastCheckpointNanos) >= delayThresholdNanos)) { break thresholdCheck; } if (mRedoWriter == null || mRedoWriter.shouldCheckpoint(sizeThreshold)) { break thresholdCheck; } // Thresholds not met for a full checkpoint, but fully sync the redo log // for durability. flush(2); // flush and sync metadata return; } // Thresholds for a checkpoint are met, but it might not be necessary. boolean full = false; root.acquireShared(); try { if (root.mCachedState != CACHED_CLEAN) { // Root is dirty, so do a full checkpoint. full = true; } } finally { root.releaseShared(); } if (!full && mRedoWriter != null && (mRedoWriter instanceof ReplController)) { if (mRedoWriter.shouldCheckpoint(1)) { // Clean up the replication log. full = true; } } if (!full) { // No need for full checkpoint, but fully sync the redo log for durability. flush(2); // flush and sync metadata return; } } mLastCheckpointNanos = nowNanos; if (mEventListener != null) { // Note: Events should not be delivered when exclusive commit lock is held. // The listener implementation might introduce extra blocking. mEventListener.notify(EventType.CHECKPOINT_BEGIN, "Checkpoint begin"); } boolean resume = true; UndoLog masterUndoLog = mCommitMasterUndoLog; if (header == p_null()) { // Not resumed. Allocate new header early, before acquiring locks. header = p_callocPage(mPageDb.directPageSize()); resume = false; if (masterUndoLog != null) { // TODO: Thrown when closed? After storage device was full. throw new AssertionError(); } } final RedoWriter redo = mRedoWriter; try { int hoff = mPageDb.extraCommitDataOffset(); p_intPutLE(header, hoff + I_ENCODING_VERSION, ENCODING_VERSION); if (redo != null) { // File-based redo log should create a new file, but not write to it yet. redo.checkpointPrepare(); } while (true) { mCommitLock.acquireExclusive(); // Registry root is infrequently modified, and so shared latch is usually // available. If not, cause might be a deadlock. To be safe, always release // commit lock and start over. if (root.tryAcquireShared()) { break; } mCommitLock.releaseExclusive(); } mCheckpointFlushState = CHECKPOINT_FLUSH_PREPARE; if (!resume) { p_longPutLE(header, hoff + I_ROOT_PAGE_ID, root.id()); } final long redoNum, redoPos, redoTxnId; if (redo == null) { redoNum = 0; redoPos = 0; redoTxnId = 0; } else { // Switch and capture state while commit lock is held. redo.checkpointSwitch(mTxnContexts); redoNum = redo.checkpointNumber(); redoPos = redo.checkpointPosition(); redoTxnId = redo.checkpointTransactionId(); } p_longPutLE(header, hoff + I_CHECKPOINT_NUMBER, redoNum); p_longPutLE(header, hoff + I_REDO_TXN_ID, redoTxnId); p_longPutLE(header, hoff + I_REDO_POSITION, redoPos); p_longPutLE(header, hoff + I_REPL_ENCODING, redo == null ? 0 : redo.encoding()); // TODO: I don't like all this activity with exclusive commit lock held. UndoLog // can be refactored to store into a special Tree, but this requires more features // to be added to Tree first. Specifically, large values and appending to them. if (!resume) { long txnId = 0; byte[] workspace = null; for (TransactionContext txnContext : mTxnContexts) { txnId = txnContext.higherTransactionId(txnId); synchronized (txnContext) { if (txnContext.hasUndoLogs()) { if (masterUndoLog == null) { masterUndoLog = new UndoLog(this, 0); // Stash it to resume after an aborted checkpoint. Assign early // to ensure that the close method can see it and delete it, // even if an exception is thrown. Note that this assignment, // undo log deletion, node allocation, and any accesses into // the undo log acquire the commit lock. This ensures that // deletion is safe from race conditions. Once deleted, the // undo log object can still be used safely, except that it's // empty, and new node allocations fail with an exception. mCommitMasterUndoLog = masterUndoLog; } workspace = txnContext.writeToMaster(masterUndoLog, workspace); } } } final long masterUndoLogId; if (masterUndoLog == null) { masterUndoLogId = 0; } else { masterUndoLogId = masterUndoLog.persistReady(); if (masterUndoLogId == 0) { // Nothing was actually written to the log. mCommitMasterUndoLog = null; masterUndoLog = null; } } p_longPutLE(header, hoff + I_TRANSACTION_ID, txnId); p_longPutLE(header, hoff + I_MASTER_UNDO_LOG_PAGE_ID, masterUndoLogId); } mCommitHeader = header; mPageDb.commit(resume, header, this::checkpointFlush); } catch (Throwable e) { if (mCommitHeader != header) { p_delete(header); } if (mCheckpointFlushState == CHECKPOINT_FLUSH_PREPARE) { // Exception was thrown with locks still held, which means that the commit // state didn't change. The header might not be filled in completely, so don't // attempt to resume the checkpoint later. Fully delete the header and truncate // the master undo log. mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; root.releaseShared(); mCommitLock.releaseExclusive(); if (redo != null) { redo.checkpointAborted(); } deleteCommitHeader(); mCommitMasterUndoLog = null; if (masterUndoLog != null) { try { masterUndoLog.truncate(); } catch (Throwable e2) { // Panic. suppress(e2, e); close(e2); throw e2; } } } throw e; } // Reset for next checkpoint. deleteCommitHeader(); mCommitMasterUndoLog = null; if (masterUndoLog != null) { // Delete the master undo log, which won't take effect until the next checkpoint. CommitLock.Shared shared = mCommitLock.acquireShared(); try { if (!isClosed()) { masterUndoLog.doTruncate(mCommitLock, shared); } } finally { shared.release(); } } // Note: This step is intended to discard old redo data, but it can get skipped if // process exits at this point. Data is discarded again when database is re-opened. if (mRedoWriter != null) { mRedoWriter.checkpointFinished(); } if (mEventListener != null) { double duration = (System.nanoTime() - mLastCheckpointNanos) / 1_000_000_000.0; mEventListener.notify(EventType.CHECKPOINT_COMPLETE, "Checkpoint completed in %1$1.3f seconds", duration, TimeUnit.SECONDS); } } /** * Method is invoked with exclusive commit lock and shared root node latch held. Both are * released by this method. */ private void checkpointFlush(boolean resume, byte[] header) throws IOException { int stateToFlush = mCommitState; if (resume) { // Resume after an aborted checkpoint. if (header != mCommitHeader) { throw new AssertionError(); } stateToFlush ^= 1; } else { if (mInitialReadState != CACHED_CLEAN) { mInitialReadState = CACHED_CLEAN; // Must be set before switching commit state. } mCommitState = (byte) (stateToFlush ^ 1); mCommitHeader = header; } mCheckpointFlushState = stateToFlush; mRegistry.mRoot.releaseShared(); mCommitLock.releaseExclusive(); if (mRedoWriter != null) { mRedoWriter.checkpointStarted(); } if (mEventListener != null) { mEventListener.notify(EventType.CHECKPOINT_FLUSH, "Flushing all dirty nodes"); } try { mCheckpointer.flushDirty(mNodeGroups, stateToFlush); if (mRedoWriter != null) { mRedoWriter.checkpointFlushed(); } } finally { mCheckpointFlushState = CHECKPOINT_NOT_FLUSHING; } if (mEventListener != null) { mEventListener.notify(EventType.CHECKPOINT_SYNC, "Forcibly persisting all changes"); } } // Called by DurablePageDb with header latch held. static long readRedoPosition( byte[] header, int offset) { return p_longGetLE(header, offset + I_REDO_POSITION); } }
package org.jpos.apps.qsp.config; import java.util.Properties; import org.jpos.util.Logger; import org.jpos.util.LogEvent; import org.jpos.util.LogSource; import org.jpos.util.Loggeable; import org.jpos.util.NameRegistrar; import org.jpos.core.SimpleConfiguration; import org.jpos.core.Configurable; import org.jpos.core.ConfigurationException; import org.jpos.core.Sequencer; import org.jpos.apps.qsp.QSP; import org.jpos.apps.qsp.QSPConfigurator; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Configure sequencer * @author <a href="mailto:apr@cs.com.uy">Alejandro P. Revilla</a> * @version $Revision$ $Date$ */ public class ConfigSequencer implements QSPConfigurator { public void config (QSP qsp, Node node) throws ConfigurationException { String className = node.getAttributes().getNamedItem ("class").getNodeValue(); LogEvent evt = new LogEvent (qsp, "config-sequencer", className); try { Class c = Class.forName(className); Sequencer seq = (Sequencer) c.newInstance(); if (seq instanceof LogSource) { ((LogSource)seq).setLogger ( ConfigLogger.getLogger (node), ConfigLogger.getRealm (node) ); } if (seq instanceof Configurable) configureSequencer ((Configurable) seq, node, evt); if (seq instanceof Loggeable) evt.addMessage (seq); NameRegistrar.register ("sequencer."+ node.getAttributes().getNamedItem ("name").getNodeValue(), seq ); } catch (ClassNotFoundException e) { throw new ConfigurationException ("config-task:"+className, e); } catch (InstantiationException e) { throw new ConfigurationException ("config-task:"+className, e); } catch (IllegalAccessException e) { throw new ConfigurationException ("config-task:"+className, e); } Logger.log (evt); } private void configureSequencer (Configurable seq, Node node, LogEvent evt) throws ConfigurationException { seq.setConfiguration (new SimpleConfiguration ( ConfigUtil.addProperties (node, null, evt) ) ); } }
package org.springframework.data.simpledb.core; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.model.CreateDomainRequest; import com.amazonaws.services.simpledb.model.DeleteDomainRequest; import com.amazonaws.services.simpledb.model.ListDomainsRequest; import java.util.List; public class SimpleDBDomainOperations { //TODO private AmazonSimpleDB sdb; public void dropDomain(String domainName) { sdb.deleteDomain(new DeleteDomainRequest(domainName)); } public List<String> fetchDomainNames() { return sdb.listDomains().getDomainNames(); } public void createDomain(String domainName) { sdb.createDomain(new CreateDomainRequest(domainName)); } public void createDomainsIfNotExist(String domainName) { boolean found = false; for(String domain : fetchDomainNames()) { if(domain.equals(domainName)) { found = true; break; } } if(!found) { sdb.createDomain(new CreateDomainRequest(domainName)); } } }
package de.fe1k.game9.events; import de.nerogar.noise.render.GLWindow; public class EventAfterRender implements Event { public GLWindow window; public float deltaTime; public double runTime; public EventAfterRender(GLWindow window, float deltaTime, double runTime) { this.window = window; this.deltaTime = deltaTime; this.runTime = runTime; } }
import java.util.Arrays; public class PlayerSkeleton { public static boolean DEBUG = false; public static boolean PRINT_UTILITY = true; public static boolean PRINT_LINES_CLEARED = false; // Make copies of static variables public static final int ORIENT = State.ORIENT; public static final int SLOT = State.SLOT; public static final int COLS = State.COLS; public static final int ROWS = State.ROWS; public static final int N_PIECES = State.N_PIECES; public static final int[][][] pTop = State.getpTop(); public static final int[][][] pBottom = State.getpBottom(); public static final int[][] pWidth = State.getpWidth(); public static final int[][] pHeight = State.getpHeight(); // Factor for scaling reward against utility private static final double REWARD_FACTOR = 1; // Waiting time between consecutive moves private static final long WAITING_TIME = 0; // Total number of games to be played private static int NO_OF_GAMES = 10; // Weights private static double constant_weight; private static double[] absoulte_column_height_weight; private static double[] relative_column_height_weight; private static double highest_column_height_weight; private static double holes_weight; // Record the utility and reward values of all moves for printing // 22 feature values followed by reward value private static double[][] features; // Record number of board state printed static int number_of_board_states = 1; static int MAX_BOARD_STATE = 4000; // Implement this function to have a working system public int pickMove(State s, int[][] legalMoves) { // initialize value array for all moves features = new double[legalMoves.length][23]; // Record the move that produces max utility and reward int moveWithMaxUtilityAndReward = 0; double maxUtilityAndReward = -9999; int[][] currentField = deepCopy2D(s.getField()); int[] currentColumnHeights = deepCopy(s.getTop()); int[][] simulatedNextField; int[] simulatedColumnHeights; for (int i = 0; i < legalMoves.length; i++) { simulatedNextField = deepCopy2D(currentField); simulatedColumnHeights = deepCopy(currentColumnHeights); int rowRemoved = tryMakeMove(legalMoves[i][ORIENT], legalMoves[i][SLOT], s, simulatedNextField, simulatedColumnHeights); // The move does not result in end game, we proceed to evaluate if (rowRemoved != -1) { double reward = rowRemoved * REWARD_FACTOR; // Update constant and reward value for the move for printing features[i][0] = 1; features[i][22] = rowRemoved; double utility = evalUtility(i, simulatedNextField, simulatedColumnHeights); utility += constant_weight; if (DEBUG) { System.out.println("Eval: Move: " + i + ", Reward: " + reward + ", Utility:" + utility); } if (reward + utility > maxUtilityAndReward) { maxUtilityAndReward = reward + utility; moveWithMaxUtilityAndReward = i; } } } // In the case where all moves lead to losing, it will choose the first // move with index 0 if (DEBUG) { System.out.println(); System.out.println("Choice: " + "Move: " + moveWithMaxUtilityAndReward + ", Reward+Utility:" + maxUtilityAndReward); System.out.println(); } int pick = moveWithMaxUtilityAndReward; // Print the feature and reward values for interfacing with learner // Do not print the last state if (PRINT_UTILITY && features[pick][0] != 0) { number_of_board_states++; for (int i = 0; i < features[pick].length; i++) { System.out.print(features[pick][i]); System.out.print(' '); } System.out.println(); } return pick; } private double evalUtility(int move, int[][] field, int[] columnHeights) { double utility = 0.0; double utility_to_be_added = 0.0; // Add utility for absolute column heights // The more rows left for each column, the higher the utility for (int i = 0; i < columnHeights.length; i++) { utility_to_be_added = absoulte_column_height_weight[i] * columnHeights[i]; // Update index 1 to 10 features[move][i + 1] = columnHeights[i]; utility += utility_to_be_added; } // Add utility for relative heights for neighboring columns int height_diff = 0; for (int i = 0; i < columnHeights.length - 1; i++) { height_diff = Math.abs(columnHeights[i] - columnHeights[i + 1]); utility_to_be_added = relative_column_height_weight[i] * height_diff; // Update index 11 to 19 features[move][i + 11] = height_diff; utility += utility_to_be_added; } // Add utility for max height of column int highest = 0; for (int i = 0; i < columnHeights.length; i++) { if (columnHeights[i] > highest) { highest = columnHeights[i]; } } utility_to_be_added = highest_column_height_weight * highest; // update index 20 features[move][20] = highest; utility += utility_to_be_added; // Add utility for holes int no_of_holes = getNumberOfHoles(field); utility_to_be_added = holes_weight * no_of_holes; if (DEBUG) { System.out.println("Move: " + move + ", No of holes: " + no_of_holes + ", utility added for holes:" + utility_to_be_added); } // Update index 21 features[move][21] = no_of_holes; utility += utility_to_be_added; return utility; } private int getNumberOfHoles(int[][] field) { int count = 0; for (int i = 0; i < field.length; i++) { for (int j = 0; j < field[i].length; j++) { if (isHole(i, j, field)) { count++; } } } return count; } private boolean isHole(int i, int j, int[][] field) { if (field[i][j] != 0) { return false; } int cur_row = i + 1; while (cur_row < ROWS) { if (field[cur_row][j] != 0) { return true; } cur_row += 1; } return false; } /** * Simulate the effect of making a specific move * * Modifies simulated next field and height of each column for further * evaluation * * @param orient * @param slot * @param s * @return number of rows removed, -1 if lost */ public int tryMakeMove(int orient, int slot, State s, int[][] field, int[] top) { // Initialize state-related variables int nextPiece = s.getNextPiece(); int turn = s.getTurnNumber() + 1; // Height if the first column makes contact int height = top[slot] - pBottom[nextPiece][orient][0]; // For each column beyond the first in the piece for (int c = 1; c < pWidth[nextPiece][orient]; c++) { height = Math.max(height, top[slot + c] - pBottom[nextPiece][orient][c]); } // Check if game ended if (height + pHeight[nextPiece][orient] >= ROWS) { return -1; } // For each column in the piece - fill in the appropriate blocks for (int i = 0; i < pWidth[nextPiece][orient]; i++) { // From bottom to top of brick for (int h = height + pBottom[nextPiece][orient][i]; h < height + pTop[nextPiece][orient][i]; h++) { field[h][i + slot] = turn; } } // adjust top for (int c = 0; c < pWidth[nextPiece][orient]; c++) { top[slot + c] = height + pTop[nextPiece][orient][c]; } int rowsCleared = 0; // check for full rows - starting at the top for (int r = height + pHeight[nextPiece][orient] - 1; r >= height; r // check all columns in the row boolean full = true; for (int c = 0; c < COLS; c++) { if (field[r][c] == 0) { full = false; break; } } // if the row was full - remove it and slide above stuff down if (full) { rowsCleared++; // for each column for (int c = 0; c < COLS; c++) { // slide down all bricks for (int i = r; i < top[c]; i++) { field[i][c] = field[i + 1][c]; } // lower the top top[c] while (top[c] >= 1 && field[top[c] - 1][c] == 0) top[c] } } } return rowsCleared; } public static void main(String[] args) { if (args.length == 23) { // Take in weights from the command line if present NO_OF_GAMES = Integer.parseInt(args[0]); initializeWeights(args); } else if (args.length > 0) { System.out.println("Invalid number of arguments, expected 23, got " + args.length); System.exit(0); } else { // Use default weights if arguments are not present initializeWeights(); } State s; TFrame t; for (int i = 0; i < NO_OF_GAMES; i++) { s = new State(); t = new TFrame(s); PlayerSkeleton p = new PlayerSkeleton(); while(!s.hasLost()) { s.makeMove(p.pickMove(s, s.legalMoves())); s.draw(); s.drawNext(0, 0); try { Thread.sleep(WAITING_TIME); } catch (InterruptedException e) { e.printStackTrace(); } } if (number_of_board_states > MAX_BOARD_STATE) { t.dispose(); break; } // Remove the windows as we finish the game if (i < NO_OF_GAMES) { t.dispose(); } // Print signal for next game if (i != NO_OF_GAMES - 1) { System.out.println(" } if (PRINT_LINES_CLEARED) { System.out.println("You have completed " + s.getRowsCleared() + " rows."); } } } private static void initializeWeights(String[] args) { // args[1] for constant constant_weight = Double.parseDouble(args[1]); // args[2] to args[11] for absolute column heights absoulte_column_height_weight = new double[COLS]; for (int i1 = 0; i1 < absoulte_column_height_weight.length; i1++) { absoulte_column_height_weight[i1] = Double .parseDouble(args[2 + i1]); } // args[12] to args[20] for relative column heights relative_column_height_weight = new double[COLS - 1]; for (int i1 = 0; i1 < relative_column_height_weight.length; i1++) { relative_column_height_weight[i1] = Double .parseDouble(args[12 + i1]); } // args[21] for relative column heights highest_column_height_weight = Double.parseDouble(args[21]); // args[22] for relative column heights holes_weight = Double.parseDouble(args[22]); assert (absoulte_column_height_weight.length == 10); assert (relative_column_height_weight.length == 9); } private static void initializeWeights() { constant_weight = 1.0; absoulte_column_height_weight = new double[COLS]; for (int i1 = 0; i1 < absoulte_column_height_weight.length; i1++) { absoulte_column_height_weight[i1] = -0.05; } relative_column_height_weight = new double[COLS - 1]; for (int i1 = 0; i1 < relative_column_height_weight.length; i1++) { relative_column_height_weight[i1] = -0.5; } highest_column_height_weight = -0.5; holes_weight = -1.0; assert (absoulte_column_height_weight.length == 10); assert (relative_column_height_weight.length == 9); } public static int[][] deepCopy2D(int[][] original) { if (original == null) { return null; } final int[][] result = new int[original.length][]; for (int i = 0; i < original.length; i++) { result[i] = Arrays.copyOf(original[i], original[i].length); } return result; } public static int[] deepCopy(int[] original) { if (original == null) { return null; } int[] result = new int[original.length]; result = Arrays.copyOf(original, original.length); return result; } }
package org.dynmap.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import org.bukkit.World; import org.bukkit.Chunk; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.entity.Entity; import org.bukkit.ChunkSnapshot; import org.dynmap.DynmapChunk; import org.dynmap.DynmapPlugin; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.MapManager; import org.dynmap.utils.MapIterator.BlockStep; /** * Container for managing chunks - dependent upon using chunk snapshots, since rendering is off server thread */ public class NewMapChunkCache implements MapChunkCache { private static boolean init = false; private static Method poppreservedchunk = null; private static Method gethandle = null; private static Method removeentities = null; private static Method getworldchunkmgr = null; private static Method getbiomedata = null; private static Method getworldhandle = null; private static Field chunkbiome = null; private static boolean canusebiomefix = false; private static boolean biomefixtested = false; private static boolean biomefixneeded = false; private World w; private List<DynmapChunk> chunks; private ListIterator<DynmapChunk> iterator; private int x_min, x_max, z_min, z_max; private int x_dim; private boolean biome, biomeraw, highesty, blockdata; private HiddenChunkStyle hidestyle = HiddenChunkStyle.FILL_AIR; private List<VisibilityLimit> visible_limits = null; private List<VisibilityLimit> hidden_limits = null; private DynmapWorld.AutoGenerateOption generateopt; private boolean do_generate = false; private boolean do_save = false; private boolean isempty = true; private ChunkSnapshot[] snaparray; /* Index = (x-x_min) + ((z-z_min)*x_dim) */ private static final BlockStep unstep[] = { BlockStep.X_MINUS, BlockStep.Y_MINUS, BlockStep.Z_MINUS, BlockStep.X_PLUS, BlockStep.Y_PLUS, BlockStep.Z_PLUS }; /** * Iterator for traversing map chunk cache (base is for non-snapshot) */ public class OurMapIterator implements MapIterator { private int x, y, z, chunkindex, bx, bz; private ChunkSnapshot snap; private BlockStep laststep; private int typeid = -1; private int blkdata = -1; OurMapIterator(int x0, int y0, int z0) { initialize(x0, y0, z0); } public final void initialize(int x0, int y0, int z0) { this.x = x0; this.y = y0; this.z = z0; this.chunkindex = ((x >> 4) - x_min) + (((z >> 4) - z_min) * x_dim); this.bx = x & 0xF; this.bz = z & 0xF; try { snap = snaparray[chunkindex]; } catch (ArrayIndexOutOfBoundsException aioobx) { snap = EMPTY; } laststep = BlockStep.Y_MINUS; typeid = blkdata = -1; } public final int getBlockTypeID() { if(typeid < 0) typeid = snap.getBlockTypeId(bx, y, bz); return typeid; } public final int getBlockData() { if(blkdata < 0) blkdata = snap.getBlockData(bx, y, bz); return blkdata; } public final int getHighestBlockYAt() { return snap.getHighestBlockYAt(bx, bz); } public final int getBlockSkyLight() { return snap.getBlockSkyLight(bx, y, bz); } public final int getBlockEmittedLight() { return snap.getBlockEmittedLight(bx, y, bz); } public Biome getBiome() { return snap.getBiome(bx, bz); } public double getRawBiomeTemperature() { return snap.getRawBiomeTemperature(bx, bz); } public double getRawBiomeRainfall() { return snap.getRawBiomeRainfall(bx, bz); } /** * Step current position in given direction */ public final void stepPosition(BlockStep step) { switch(step.ordinal()) { case 0: x++; bx++; if(bx == 16) { /* Next chunk? */ try { bx = 0; chunkindex++; snap = snaparray[chunkindex]; } catch (ArrayIndexOutOfBoundsException aioobx) { snap = EMPTY; } } break; case 1: y++; break; case 2: z++; bz++; if(bz == 16) { /* Next chunk? */ try { bz = 0; chunkindex += x_dim; snap = snaparray[chunkindex]; } catch (ArrayIndexOutOfBoundsException aioobx) { snap = EMPTY; } } break; case 3: x bx if(bx == -1) { /* Next chunk? */ try { bx = 15; chunkindex snap = snaparray[chunkindex]; } catch (ArrayIndexOutOfBoundsException aioobx) { snap = EMPTY; } } break; case 4: y break; case 5: z bz if(bz == -1) { /* Next chunk? */ try { bz = 15; chunkindex -= x_dim; snap = snaparray[chunkindex]; } catch (ArrayIndexOutOfBoundsException aioobx) { snap = EMPTY; } } break; } laststep = step; typeid = -1; blkdata = -1; } /** * Unstep current position to previous position */ public BlockStep unstepPosition() { BlockStep ls = laststep; stepPosition(unstep[ls.ordinal()]); return ls; } /** * Unstep current position in oppisite director of given step */ public void unstepPosition(BlockStep s) { stepPosition(unstep[s.ordinal()]); } public final void setY(int y) { if(y > this.y) laststep = BlockStep.Y_PLUS; else laststep = BlockStep.Y_MINUS; this.y = y; typeid = -1; blkdata = -1; } public final int getX() { return x; } public final int getY() { return y; } public final int getZ() { return z; } public final int getBlockTypeIDAt(BlockStep s) { if(s == BlockStep.Y_MINUS) { if(y > 0) return snap.getBlockTypeId(bx, y-1, bz); } else if(s == BlockStep.Y_PLUS) { if(y < 127) return snap.getBlockTypeId(bx, y+1, bz); } else { BlockStep ls = laststep; stepPosition(s); int tid = snap.getBlockTypeId(bx, y, bz); unstepPosition(); laststep = ls; return tid; } return 0; } public BlockStep getLastStep() { return laststep; } } /** * Chunk cache for representing unloaded chunk (or air) */ private static class EmptyChunk implements ChunkSnapshot { /* Need these for interface, but not used */ public int getX() { return 0; } public int getZ() { return 0; } public String getWorldName() { return ""; } public long getCaptureFullTime() { return 0; } public final int getBlockTypeId(int x, int y, int z) { return 0; } public final int getBlockData(int x, int y, int z) { return 0; } public final int getBlockSkyLight(int x, int y, int z) { return 15; } public final int getBlockEmittedLight(int x, int y, int z) { return 0; } public final int getHighestBlockYAt(int x, int z) { return 0; } public Biome getBiome(int x, int z) { return null; } public double getRawBiomeTemperature(int x, int z) { return 0.0; } public double getRawBiomeRainfall(int x, int z) { return 0.0; } } /** * Chunk cache for representing generic stone chunk */ private static class PlainChunk implements ChunkSnapshot { private int fillid; PlainChunk(int fillid) { this.fillid = fillid; } /* Need these for interface, but not used */ public int getX() { return 0; } public int getZ() { return 0; } public String getWorldName() { return ""; } public Biome getBiome(int x, int z) { return null; } public double getRawBiomeTemperature(int x, int z) { return 0.0; } public double getRawBiomeRainfall(int x, int z) { return 0.0; } public long getCaptureFullTime() { return 0; } public final int getBlockTypeId(int x, int y, int z) { if(y < 64) return fillid; return 0; } public final int getBlockData(int x, int y, int z) { return 0; } public final int getBlockSkyLight(int x, int y, int z) { if(y < 64) return 0; return 15; } public final int getBlockEmittedLight(int x, int y, int z) { return 0; } public final int getHighestBlockYAt(int x, int z) { return 64; } } private static final EmptyChunk EMPTY = new EmptyChunk(); private static final PlainChunk STONE = new PlainChunk(1); private static final PlainChunk OCEAN = new PlainChunk(9); /** * Construct empty cache */ @SuppressWarnings({ "rawtypes", "unchecked" }) public NewMapChunkCache() { if(!init) { /* Get CraftWorld.popPreservedChunk(x,z) - reduces memory bloat from map traversals (optional) */ try { Class c = Class.forName("org.bukkit.craftbukkit.CraftWorld"); poppreservedchunk = c.getDeclaredMethod("popPreservedChunk", new Class[] { int.class, int.class }); /* getHandle() */ getworldhandle = c.getDeclaredMethod("getHandle", new Class[0]); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } /* Get CraftChunk.getChunkSnapshot(boolean,boolean,boolean) and CraftChunk.getHandle() */ try { Class c = Class.forName("org.bukkit.craftbukkit.CraftChunk"); gethandle = c.getDeclaredMethod("getHandle", new Class[0]); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } /* Get Chunk.removeEntities() */ try { Class c = Class.forName("net.minecraft.server.Chunk"); removeentities = c.getDeclaredMethod("removeEntities", new Class[0]); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } /* Get WorldChunkManager.b(float[],int,int,int,int) and WorldChunkManager.a(float[],int,int,int,int) */ try { Class c = Class.forName("net.minecraft.server.WorldChunkManager"); Class biomebasearray = Class.forName("[Lnet.minecraft.server.BiomeBase;"); getbiomedata = c.getDeclaredMethod("a", new Class[] { biomebasearray, int.class, int.class, int.class, int.class }); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } /* getWorldChunkManager() */ try { Class c = Class.forName("net.minecraft.server.World"); getworldchunkmgr = c.getDeclaredMethod("getWorldChunkManager", new Class[0]); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } /* Get CraftChunkSnapshot.biome field */ try { Class c = Class.forName("org.bukkit.craftbukkit.CraftChunkSnapshot"); chunkbiome = c.getDeclaredField("biome"); chunkbiome.setAccessible(true); } catch (ClassNotFoundException cnfx) { } catch (NoSuchFieldException nsmx) { } init = true; if((getworldchunkmgr != null) && (getbiomedata != null) && (getworldhandle != null) && (chunkbiome != null)) { canusebiomefix = true; } else { biomefixtested = true; biomefixneeded = false; } } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void setChunks(World w, List<DynmapChunk> chunks) { this.w = w; if(w.getEnvironment() != Environment.NORMAL) { biome = biomeraw = false; } this.chunks = chunks; if(poppreservedchunk == null) { /* Get CraftWorld.popPreservedChunk(x,z) - reduces memory bloat from map traversals (optional) */ try { Class c = Class.forName("org.bukkit.craftbukkit.CraftWorld"); poppreservedchunk = c.getDeclaredMethod("popPreservedChunk", new Class[] { int.class, int.class }); } catch (ClassNotFoundException cnfx) { } catch (NoSuchMethodException nsmx) { } } /* Compute range */ if(chunks.size() == 0) { this.x_min = 0; this.x_max = 0; this.z_min = 0; this.z_max = 0; x_dim = 1; } else { x_min = x_max = chunks.get(0).x; z_min = z_max = chunks.get(0).z; for(DynmapChunk c : chunks) { if(c.x > x_max) x_max = c.x; if(c.x < x_min) x_min = c.x; if(c.z > z_max) z_max = c.z; if(c.z < z_min) z_min = c.z; } x_dim = x_max - x_min + 1; } snaparray = new ChunkSnapshot[x_dim * (z_max-z_min+1)]; } public int loadChunks(int max_to_load) { int cnt = 0; if(iterator == null) iterator = chunks.listIterator(); DynmapPlugin.setIgnoreChunkLoads(true); boolean isnormral = w.getEnvironment() == Environment.NORMAL; // Load the required chunks. while((cnt < max_to_load) && iterator.hasNext()) { DynmapChunk chunk = iterator.next(); boolean vis = true; if(visible_limits != null) { vis = false; for(VisibilityLimit limit : visible_limits) { if((chunk.x >= limit.x0) && (chunk.x <= limit.x1) && (chunk.z >= limit.z0) && (chunk.z <= limit.z1)) { vis = true; break; } } } if(vis && (hidden_limits != null)) { for(VisibilityLimit limit : hidden_limits) { if((chunk.x >= limit.x0) && (chunk.x <= limit.x1) && (chunk.z >= limit.z0) && (chunk.z <= limit.z1)) { vis = false; break; } } } /* Check if cached chunk snapshot found */ ChunkSnapshot ss = MapManager.mapman.sscache.getSnapshot(w.getName(), chunk.x, chunk.z, blockdata, biome, biomeraw, highesty); if(ss != null) { if(!vis) { if(hidestyle == HiddenChunkStyle.FILL_STONE_PLAIN) ss = STONE; else if(hidestyle == HiddenChunkStyle.FILL_OCEAN) ss = OCEAN; else ss = EMPTY; } snaparray[(chunk.x-x_min) + (chunk.z - z_min)*x_dim] = ss; continue; } boolean wasLoaded = w.isChunkLoaded(chunk.x, chunk.z); boolean didload = w.loadChunk(chunk.x, chunk.z, false); boolean didgenerate = false; /* If we didn't load, and we're supposed to generate, do it */ if((!didload) && do_generate && vis) didgenerate = didload = w.loadChunk(chunk.x, chunk.z, true); /* If it did load, make cache of it */ if(didload) { if(!vis) { if(hidestyle == HiddenChunkStyle.FILL_STONE_PLAIN) ss = STONE; else if(hidestyle == HiddenChunkStyle.FILL_OCEAN) ss = OCEAN; else ss = EMPTY; } else { Chunk c = w.getChunkAt(chunk.x, chunk.z); if(blockdata || highesty) ss = c.getChunkSnapshot(highesty, biome, biomeraw); else ss = w.getEmptyChunkSnapshot(chunk.x, chunk.z, biome, biomeraw); if(ss != null) { if((!biomefixtested) && biome) /* Test for biome fix */ testIfBiomeFixNeeded(w, ss); if(biomefixneeded && biome) /* If needed, apply it */ doBiomeFix(w, ss); MapManager.mapman.sscache.putSnapshot(w.getName(), chunk.x, chunk.z, ss, blockdata, biome, biomeraw, highesty); } } snaparray[(chunk.x-x_min) + (chunk.z - z_min)*x_dim] = ss; } if ((!wasLoaded) && didload) { /* It looks like bukkit "leaks" entities - they don't get removed from the world-level table * when chunks are unloaded but not saved - removing them seems to do the trick */ if(!(didgenerate && do_save)) { boolean did_remove = false; Chunk cc = w.getChunkAt(chunk.x, chunk.z); if((gethandle != null) && (removeentities != null)) { try { Object chk = gethandle.invoke(cc); if(chk != null) { removeentities.invoke(chk); did_remove = true; } } catch (InvocationTargetException itx) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } if(!did_remove) { if(cc != null) { for(Entity e: cc.getEntities()) e.remove(); } } } /* Since we only remember ones we loaded, and we're synchronous, no player has * moved, so it must be safe (also prevent chunk leak, which appears to happen * because isChunkInUse defined "in use" as being within 256 blocks of a player, * while the actual in-use chunk area for a player where the chunks are managed * by the MC base server is 21x21 (or about a 160 block radius). * Also, if we did generate it, need to save it */ w.unloadChunk(chunk.x, chunk.z, didgenerate && do_save, false); /* And pop preserved chunk - this is a bad leak in Bukkit for map traversals like us */ try { if(poppreservedchunk != null) poppreservedchunk.invoke(w, chunk.x, chunk.z); } catch (Exception x) { Log.severe("Cannot pop preserved chunk - " + x.toString()); } } cnt++; } DynmapPlugin.setIgnoreChunkLoads(false); if(iterator.hasNext() == false) { /* If we're done */ isempty = true; /* Fill missing chunks with empty dummy chunk */ for(int i = 0; i < snaparray.length; i++) { if(snaparray[i] == null) snaparray[i] = EMPTY; else if(snaparray[i] != EMPTY) isempty = false; } } return cnt; } /** * Test if biome fix needed, using loaded snapshot */ private boolean testIfBiomeFixNeeded(World w, ChunkSnapshot ss) { if(biomefixtested == false) { biomefixtested = true; for(int i = 0; (!biomefixneeded) && (i < 16); i++) { for(int j = 0; j < 16; j++) { if(w.getBiome((ss.getX()<<4)+i, (ss.getZ()<<4)+j) != ss.getBiome(i, j)) { /* Mismatch? */ biomefixneeded = true; Log.info("Biome Snapshot fix active"); break; } } } } return biomefixneeded; } /** * Use biome fix to patch snapshot data */ private void doBiomeFix(World w, ChunkSnapshot ss) { if(biomefixneeded && canusebiomefix) { try { Object wh = getworldhandle.invoke(w); /* World.getHandle() */ Object wcm = getworldchunkmgr.invoke(wh); /* CraftWorld.getWorldChunkManager() */ Object biomefield = chunkbiome.get(ss); /* Get ss.biome */ if(biomefield != null) { getbiomedata.invoke(wcm, biomefield, (int)(ss.getX()<<4), (int)(ss.getZ()<<4), 16, 16); /* Get biome data */ } } catch (InvocationTargetException itx) { } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } } } /** * Test if done loading */ public boolean isDoneLoading() { if(iterator != null) return !iterator.hasNext(); return false; } /** * Test if all empty blocks */ public boolean isEmpty() { return isempty; } /** * Unload chunks */ public void unloadChunks() { if(snaparray != null) { for(int i = 0; i < snaparray.length; i++) { snaparray[i] = null; } snaparray = null; } } /** * Get block ID at coordinates */ public int getBlockTypeID(int x, int y, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getBlockTypeId(x & 0xF, y, z & 0xF); } /** * Get block data at coordiates */ public byte getBlockData(int x, int y, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return (byte)ss.getBlockData(x & 0xF, y, z & 0xF); } /* Get highest block Y * */ public int getHighestBlockYAt(int x, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getHighestBlockYAt(x & 0xF, z & 0xF); } /* Get sky light level */ public int getBlockSkyLight(int x, int y, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getBlockSkyLight(x & 0xF, y, z & 0xF); } /* Get emitted light level */ public int getBlockEmittedLight(int x, int y, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getBlockEmittedLight(x & 0xF, y, z & 0xF); } public Biome getBiome(int x, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getBiome(x & 0xF, z & 0xF); } public double getRawBiomeTemperature(int x, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getRawBiomeTemperature(x & 0xF, z & 0xF); } public double getRawBiomeRainfall(int x, int z) { ChunkSnapshot ss = snaparray[((x>>4) - x_min) + ((z>>4) - z_min) * x_dim]; return ss.getRawBiomeRainfall(x & 0xF, z & 0xF); } /** * Get cache iterator */ public MapIterator getIterator(int x, int y, int z) { return new OurMapIterator(x, y, z); } /** * Set hidden chunk style (default is FILL_AIR) */ public void setHiddenFillStyle(HiddenChunkStyle style) { this.hidestyle = style; } /** * Set autogenerate - must be done after at least one visible range has been set */ public void setAutoGenerateVisbileRanges(DynmapWorld.AutoGenerateOption generateopt) { if((generateopt != DynmapWorld.AutoGenerateOption.NONE) && ((visible_limits == null) || (visible_limits.size() == 0))) { Log.severe("Cannot setAutoGenerateVisibleRanges() without visible ranges defined"); return; } this.generateopt = generateopt; this.do_generate = (generateopt != DynmapWorld.AutoGenerateOption.NONE); this.do_save = (generateopt == DynmapWorld.AutoGenerateOption.PERMANENT); } /** * Add visible area limit - can be called more than once * Needs to be set before chunks are loaded * Coordinates are block coordinates */ public void setVisibleRange(VisibilityLimit lim) { VisibilityLimit limit = new VisibilityLimit(); if(lim.x0 > lim.x1) { limit.x0 = (lim.x1 >> 4); limit.x1 = ((lim.x0+15) >> 4); } else { limit.x0 = (lim.x0 >> 4); limit.x1 = ((lim.x1+15) >> 4); } if(lim.z0 > lim.z1) { limit.z0 = (lim.z1 >> 4); limit.z1 = ((lim.z0+15) >> 4); } else { limit.z0 = (lim.z0 >> 4); limit.z1 = ((lim.z1+15) >> 4); } if(visible_limits == null) visible_limits = new ArrayList<VisibilityLimit>(); visible_limits.add(limit); } /** * Add hidden area limit - can be called more than once * Needs to be set before chunks are loaded * Coordinates are block coordinates */ public void setHiddenRange(VisibilityLimit lim) { VisibilityLimit limit = new VisibilityLimit(); if(lim.x0 > lim.x1) { limit.x0 = (lim.x1 >> 4); limit.x1 = ((lim.x0+15) >> 4); } else { limit.x0 = (lim.x0 >> 4); limit.x1 = ((lim.x1+15) >> 4); } if(lim.z0 > lim.z1) { limit.z0 = (lim.z1 >> 4); limit.z1 = ((lim.z0+15) >> 4); } else { limit.z0 = (lim.z0 >> 4); limit.z1 = ((lim.z1+15) >> 4); } if(hidden_limits == null) hidden_limits = new ArrayList<VisibilityLimit>(); hidden_limits.add(limit); } @Override public boolean setChunkDataTypes(boolean blockdata, boolean biome, boolean highestblocky, boolean rawbiome) { if((w != null) && (w.getEnvironment() != Environment.NORMAL)) { this.biome = this.biomeraw = false; } else { this.biome = biome; this.biomeraw = rawbiome; } this.highesty = highestblocky; this.blockdata = blockdata; return true; } @Override public World getWorld() { return w; } }
package io.bitsquare.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Version { private static final Logger log = LoggerFactory.getLogger(Version.class); // The application versions public static final String VERSION = "0.4.9.3"; // The version nr. for the objects sent over the network. A change will break the serialization of old objects. // If objects are used for both network and database the network version is applied. // VERSION = 0.3.4 -> P2P_NETWORK_VERSION = 1 // VERSION = 0.3.5 -> P2P_NETWORK_VERSION = 2 // VERSION = 0.4.0 -> P2P_NETWORK_VERSION = 3 // VERSION = 0.4.2 -> P2P_NETWORK_VERSION = 4 public static final int P2P_NETWORK_VERSION = DevFlags.STRESS_TEST_MODE ? 100 : 4; // The version nr. of the serialized data stored to disc. A change will break the serialization of old objects. // VERSION = 0.3.4 -> LOCAL_DB_VERSION = 1 // VERSION = 0.3.5 -> LOCAL_DB_VERSION = 2 // VERSION = 0.4.0 -> LOCAL_DB_VERSION = 3 // VERSION = 0.4.2 -> LOCAL_DB_VERSION = 4 public static final int LOCAL_DB_VERSION = 4; // The version nr. of the current protocol. The offer holds that version. // A taker will check the version of the offers to see if his version is compatible. public static final int TRADE_PROTOCOL_VERSION = 1; private static int p2pMessageVersion; public static int getP2PMessageVersion() { // TODO investigate why a changed NETWORK_PROTOCOL_VERSION for the serialized objects does not trigger // reliable a disconnect., but java serialisation should be replaced anyway, so using one existing field // for the version is fine. return p2pMessageVersion; } // The version for the bitcoin network (Mainnet = 0, TestNet = 1, Regtest = 2) private static int BTC_NETWORK_ID; public static void setBtcNetworkId(int btcNetworkId) { BTC_NETWORK_ID = btcNetworkId; // BTC_NETWORK_ID is 0, 1 or 2, we use for changes at NETWORK_PROTOCOL_VERSION a multiplication with 10 // to avoid conflicts: // E.g. btc BTC_NETWORK_ID=1, NETWORK_PROTOCOL_VERSION=1 -> getNetworkId()=2; // BTC_NETWORK_ID=0, NETWORK_PROTOCOL_VERSION=2 -> getNetworkId()=2; -> wrong p2pMessageVersion = BTC_NETWORK_ID + 10 * P2P_NETWORK_VERSION; } public static int getBtcNetworkId() { return BTC_NETWORK_ID; } public static void printVersion() { log.info("Version{" + "VERSION=" + VERSION + ", P2P_NETWORK_VERSION=" + P2P_NETWORK_VERSION + ", LOCAL_DB_VERSION=" + LOCAL_DB_VERSION + ", TRADE_PROTOCOL_VERSION=" + TRADE_PROTOCOL_VERSION + ", BTC_NETWORK_ID=" + BTC_NETWORK_ID + ", getP2PNetworkId()=" + getP2PMessageVersion() + '}'); } }
package com.wilutions.joa.fx; import javafx.application.Platform; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.scene.Scene; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; import com.wilutions.com.AsyncResult; import com.wilutions.com.ComException; import com.wilutions.com.Dispatch; import com.wilutions.com.DispatchImpl; import com.wilutions.com.JoaDll; import com.wilutions.com.WindowHandle; import com.wilutions.joa.OfficeAddin; import com.wilutions.joactrllib.IJoaBridgeDialog; import com.wilutions.joactrllib._IJoaBridgeDialogEvents; /** * This is the base class for all modal dialogs. * * @param <T> * Result type of callback expression. */ public abstract class ModalDialogFX<T> implements WindowHandle, FrameContentFactory { /** * Helper object to show an empty modal dialog in the UI thread of Outlook. */ protected IJoaBridgeDialog joaDlg; /** * JavaFX frame window placed inside the {@link #joaDlg}. */ private EmbeddedFrameFX embeddedFrame = new EmbeddedFrameFX(); /** * Native window handle of the {@link #joaDlg} */ private long hwndParent; /** * JavaFX stage. * If the owner is a JavaFX window, the dialog is created * entirely with JavaFX functionality. * Either {@link #joaDlg} or {@link #fxDlg} is set. */ private Stage fxDlg; /** * Callback expression received from function * {@link #showAsync(Object, AsyncResult)}. */ protected AsyncResult<T> asyncResult; /** * Result that will passed to {@link #asyncResult} when the dialog is * closed. */ private T result; // Dimensions private double x, y, width, height, minWidth, maxWidth, minHeight, maxHeight; /** * Align dialog box in the center of the owner window. */ private boolean centerOnOwner = true; /** * Dialog box is re-sizable. */ private boolean resizable = true; /** * Dialog box has a minimize button. */ private boolean minimizeBox = false; /** * Dialog box has a maximize button. */ private boolean maximizeBox = true; /** * Caption */ private String title; /** * Definition for cancel button ID. */ public final static int CANCEL = 0; /** * Definition for OK button ID. */ public final static int OK = 1; /** * Internal processing state. * */ private enum State { Initialized, HasParentHwnd, IsClosed }; private State state = State.Initialized; /** * Constructor. */ public ModalDialogFX() { } /** * Show the dialog box. * * @param _owner * Owner object, explorer or inspector window, or an * implementation of WindowHandle. * @param asyncResult * Callback expression which is called, when the dialog is * closed. */ public void showAsync(Object _owner, final AsyncResult<T> asyncResult) { if (Platform.isFxApplicationThread()) { internalShowAsync(_owner, asyncResult); } else { Platform.runLater(() -> internalShowAsync(_owner, asyncResult)); } } /** * Close dialog and invoke callback expression. * * @param result * Object to be passed to the callback expression. * @see #showAsync(Object, AsyncResult) */ public void finish(T result) { setResult(result); close(); } /** * Close dialog. Invokes the callback expression with the current value of * {@link #result}. * * @see #finish(Object) * @see #setResult(Object) */ public void close() { Throwable ex = null; if (joaDlg != null) { try { joaDlg.Close(); } catch (Throwable ex1) { ex = ex1; } } if (fxDlg != null) { fxDlg.close(); } if (asyncResult != null) { asyncResult.setAsyncResult(result, ex); } } /** * Called when the dialog is closed over its system menu. */ public void onSystemMenuClose() { this.close(); } /** * Set callback result. * * @param ret * Result object * @throws ComException */ public void setResult(T ret) { this.result = ret; } public T getResult() { return this.result; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public void setCenterOnOwner(boolean v) { this.centerOnOwner = v; } public boolean isCenterOnOwner() { return this.centerOnOwner; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isResizable() { return resizable; } public void setResizable(boolean resizable) { this.resizable = resizable; } public double getMinWidth() { return minWidth; } public void setMinWidth(double minWidth) { this.minWidth = minWidth; } public double getMaxWidth() { return maxWidth; } public void setMaxWidth(double maxWidth) { this.maxWidth = maxWidth; } public double getMinHeight() { return minHeight; } public void setMinHeight(double minHeight) { this.minHeight = minHeight; } public double getMaxHeight() { return maxHeight; } public void setMaxHeight(double maxHeight) { this.maxHeight = maxHeight; } public boolean isMinimizeBox() { return minimizeBox; } public void setMinimizeBox(boolean minimizeBox) { this.minimizeBox = minimizeBox; } public boolean isMaximizeBox() { return maximizeBox; } public void setMaximizeBox(boolean maximizeBox) { this.maximizeBox = maximizeBox; } /** * Set event handler for WindowEvent.WINDOW_SHOWN. Only one hander is * supported. Only the event type WINDOW_SHOWN is supported. The handler * receives null as source parameter. * * @param eventType * must be WindowEvent.WINDOW_SHOWN * @param eventHandler * handler expression */ public <E extends Event> void addEventHandler(EventType<E> eventType, EventHandler<? super E> eventHandler) { embeddedFrame.addEventHandler(eventType, eventHandler); } private Integer toWin(double x) { return Double.valueOf(x).intValue(); } private void internalShowFxDialogAsync(Window fxOwner, AsyncResult<T> asyncResult) { try { this.asyncResult = asyncResult; fxDlg = new Stage(); fxDlg.initOwner(fxOwner); fxDlg.initModality(Modality.WINDOW_MODAL); Scene scene = createScene(); fxDlg.setScene(scene); fxDlg.showAndWait(); } catch (Throwable e) { asyncResult.setAsyncResult(getResult(), e); } } private void internalShowAsync(Object _owner, AsyncResult<T> asyncResult) { // Is the owner a COM object or another WindowHandle? // A COM object has to implement IOleWindow. Dispatch dispOwner = null; long hwndOwner = 0; Window fxOwner = null; if (_owner instanceof WindowHandle) { hwndOwner = ((WindowHandle) _owner).getWindowHandle(); } else if (_owner instanceof Dispatch) { dispOwner = (Dispatch) _owner; } else if (_owner instanceof Window) { fxOwner = (Window) _owner; } if (hwndOwner == 0 && dispOwner == null && fxOwner != null) { if (asyncResult != null) { asyncResult.setAsyncResult(null, new IllegalStateException("Owner must not be null.")); } return; } if (fxOwner != null) { internalShowFxDialogAsync(fxOwner, asyncResult); return; } DialogEventHandler dialogHandler = null; try { // Create the scene. Has to be implemented by subclass. Scene scene = createScene(); // If width and height is not set, make the dialog // as large as the scene. maybeSetWidthAndHightFromSceneExtent(scene); // Create the native dialog object. // This is the task of the JOA Util Add-in. Because // the dialog has to be created in the UI thread // inside Outlook. joaDlg = OfficeAddin.getJoaUtil().CreateBridgeDialog(); joaDlg.setWidth(toWin(width)); joaDlg.setHeight(toWin(height)); joaDlg.setX(toWin(x)); joaDlg.setY(toWin(y)); joaDlg.setTitle(title != null ? title : ""); joaDlg.setCenterOnOwner(centerOnOwner); joaDlg.setResizable(resizable); joaDlg.setMinHeight(toWin(minHeight)); joaDlg.setMaxHeight(toWin(maxHeight)); joaDlg.setMinWidth(toWin(minWidth)); joaDlg.setMaxWidth(toWin(maxWidth)); joaDlg.setMinimizeBox(minimizeBox); joaDlg.setMaximizeBox(maximizeBox); // Assign event handler to native dialog. dialogHandler = new DialogEventHandler(); Dispatch.withEvents(joaDlg, dialogHandler); // Show native dialog if (dispOwner != null) { joaDlg.ShowModal3(dispOwner); } else { joaDlg.ShowModal2(hwndOwner); } // Wait until the native dialog fires the onShow // event which is implemented by the DialogEventHandler. // The hander stores the native dialog's window handle in hwndParent // and sets the state as State.HasParentHwnd synchronized (this) { while (state == State.Initialized) { this.wait(); } } // Native dialog initialized? if (state == State.HasParentHwnd) { // Create a JavaFX frame inside the native dialog embeddedFrame.createAndShowEmbeddedWindowAsync(hwndParent, scene, (succ, ex) -> { if (ex == null) { // Ensure the JavaFX frame is in the foreground. long hwndChild = embeddedFrame.getWindowHandle(); JoaDll.nativeActivateSceneInDialog(hwndChild); } else if (asyncResult != null) { asyncResult.setAsyncResult(null, ex); } }); this.asyncResult = asyncResult; } else { asyncResult.setAsyncResult(null, new IllegalStateException( "Excpected response from Office application.")); dialogHandler.onClosed(); } } catch (Throwable ex) { if (asyncResult != null) { asyncResult.setAsyncResult(null, ex); } if (dialogHandler != null) { dialogHandler.onClosed(); } } } @SuppressWarnings("deprecation") private void maybeSetWidthAndHightFromSceneExtent(Scene scene) { if (width == 0 || height == 0) { scene.impl_preferredSize(); double sceneWidth = scene.getWidth(); double sceneHeight = scene.getHeight(); if (width == 0) { width = sceneWidth + 20; } if (height == 0) { height = sceneHeight + 40; } } } private class DialogEventHandler extends DispatchImpl implements _IJoaBridgeDialogEvents { @Override public void onShow(final Long hwndParent) throws ComException { synchronized (ModalDialogFX.this) { ModalDialogFX.this.hwndParent = hwndParent; ModalDialogFX.this.state = State.HasParentHwnd; ModalDialogFX.this.notify(); } } @Override public void onSystemMenuClose() throws ComException { ModalDialogFX.this.onSystemMenuClose(); } @Override public void onClosed() throws ComException { if (ModalDialogFX.this.joaDlg != null) { Dispatch.releaseEvents(ModalDialogFX.this.joaDlg, this); } if (ModalDialogFX.this.embeddedFrame != null) { ModalDialogFX.this.embeddedFrame.close(); } synchronized (ModalDialogFX.this) { ModalDialogFX.this.state = State.IsClosed; ModalDialogFX.this.notify(); } } } @Override public long getWindowHandle() { return joaDlg.getHWND(); } }
// This code is developed as part of the Java CoG Kit project // This message may not be removed or altered. package org.globus.cog.abstraction.impl.execution.gt2; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Vector; import org.apache.log4j.Logger; import org.globus.cog.abstraction.impl.common.StatusImpl; import org.globus.cog.abstraction.impl.common.execution.WallTime; import org.globus.cog.abstraction.impl.common.task.IllegalSpecException; import org.globus.cog.abstraction.impl.common.task.InvalidSecurityContextException; import org.globus.cog.abstraction.impl.common.task.InvalidServiceContactException; import org.globus.cog.abstraction.impl.common.task.TaskSubmissionException; import org.globus.cog.abstraction.interfaces.DelegatedTaskHandler; import org.globus.cog.abstraction.interfaces.Delegation; import org.globus.cog.abstraction.interfaces.ExecutionService; import org.globus.cog.abstraction.interfaces.FileLocation; import org.globus.cog.abstraction.interfaces.JobSpecification; import org.globus.cog.abstraction.interfaces.SecurityContext; import org.globus.cog.abstraction.interfaces.Service; import org.globus.cog.abstraction.interfaces.ServiceContact; import org.globus.cog.abstraction.interfaces.Status; import org.globus.cog.abstraction.interfaces.Task; import org.globus.gram.GramException; import org.globus.gram.GramJob; import org.globus.gram.GramJobListener; import org.globus.gram.internal.GRAMConstants; import org.globus.io.gass.server.GassServer; import org.globus.io.gass.server.JobOutputListener; import org.globus.io.gass.server.JobOutputStream; import org.globus.rsl.Binding; import org.globus.rsl.Bindings; import org.globus.rsl.NameOpValue; import org.globus.rsl.ParseException; import org.globus.rsl.RSLParser; import org.globus.rsl.RslNode; import org.globus.rsl.Value; import org.globus.rsl.VarRef; import org.gridforum.jgss.ExtendedGSSManager; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; public class JobSubmissionTaskHandler implements DelegatedTaskHandler, GramJobListener, JobOutputListener { static Logger logger = Logger.getLogger(JobSubmissionTaskHandler.class .getName()); private Task task; private GramJob gramJob; private Vector jobList; private boolean startGassServer; private GassServer gassServer; private SecurityContext securityContext; private JobOutputStream stdoutStream; private JobOutputStream stderrStream; private GSSCredential credential; private String jobManager; public void submit(Task task) throws IllegalSpecException, InvalidSecurityContextException, InvalidServiceContactException, TaskSubmissionException { if (this.task != null) { throw new TaskSubmissionException( "JobSubmissionTaskHandler cannot handle two active jobs simultaneously"); } if (task.getStatus().getStatusCode() != Status.UNSUBMITTED) { throw new TaskSubmissionException("This task is already submitted"); } this.task = task; this.task.setStatus(Status.SUBMITTING); String server = getServer(); this.securityContext = getSecurityContext(task); this.credential = (GSSCredential) securityContext.getCredentials(); JobSpecification spec; try { spec = (JobSpecification) this.task.getSpecification(); } catch (Exception e) { throw new IllegalSpecException( "Exception while retreiving Job Specification", e); } RslNode rslTree = null; try { rslTree = prepareSpecification(spec); } catch (Throwable e) { throw new IllegalSpecException("Cannot parse the given RSL", e); } if (logger.isDebugEnabled()) { logger.debug("RSL: " + rslTree); } if (rslTree.getOperator() == RslNode.MULTI) { this.task.setAttribute("jobCount", "multiple"); submitMultipleJobs(rslTree, spec); } else { this.task.setAttribute("jobCount", "single"); submitSingleJob(rslTree, spec, server); } } private void submitSingleJob(RslNode rsl, JobSpecification spec, String server) throws IllegalSpecException, InvalidSecurityContextException, InvalidServiceContactException, TaskSubmissionException { this.gramJob = new GramJob(rsl.toString()); try { this.gramJob.setCredentials(this.credential); } catch (IllegalArgumentException iae) { throw new InvalidSecurityContextException( "Cannot set the SecurityContext twice", iae); } if (!spec.isBatchJob()) { CallbackHandlerManager.increaseUsageCount(this.credential); this.gramJob.addListener(this); } if (logger.isDebugEnabled()) { logger.debug("Execution server: " + server); } boolean limitedDeleg = isLimitedDelegation(this.securityContext); if (spec.getDelegation() == Delegation.FULL_DELEGATION) { limitedDeleg = false; } try { // check if the task has not been canceled after it was // submitted for execution this.gramJob.request(server, spec.isBatchJob(), limitedDeleg); if (logger.isDebugEnabled()) { logger.debug("Submitted job with Globus ID: " + this.gramJob.getIDAsString()); } this.task.setStatus(Status.SUBMITTED); if (spec.isBatchJob()) { this.task.setStatus(Status.COMPLETED); } } catch (GramException ge) { cleanup(); throw new TaskSubmissionException("Cannot submit job", ge); } catch (GSSException gsse) { cleanup(); throw new InvalidSecurityContextException("Invalid GSSCredentials", gsse); } } private String getServer() throws InvalidServiceContactException { ServiceContact serviceContact = this.task.getService(0) .getServiceContact(); String server = serviceContact.getContact(); // if the jobmanager attribute is specified, handle it Service service = this.task.getService(0); if (service instanceof ExecutionService) { jobManager = ((ExecutionService) service).getJobManager(); } else { jobManager = extractJobManager(server); } if (jobManager != null) { jobManager = jobManager.toLowerCase(); server = substituteJobManager(server, jobManager); } return server; } private boolean isLimitedDelegation(SecurityContext sc) { if (sc instanceof GlobusSecurityContextImpl) { return ((GlobusSecurityContextImpl) securityContext) .getDelegation() != Delegation.FULL_DELEGATION; } else { return true; } } private void submitMultipleJobs(RslNode rslTree, JobSpecification spec) throws IllegalSpecException, InvalidSecurityContextException, InvalidServiceContactException, TaskSubmissionException { MultiJobListener listener = new MultiJobListener(this.task); this.jobList = new Vector(); List jobs = rslTree.getSpecifications(); Iterator iter = jobs.iterator(); RslNode node; NameOpValue nv; String rmc; String rsl; while (iter.hasNext()) { node = (RslNode) iter.next(); rsl = node.toRSL(true); nv = node.getParam("resourceManagerContact"); if (nv == null) { throw new IllegalSpecException( "Error: No resource manager contact for job."); } else { Object obj = nv.getFirstValue(); if (obj instanceof Value) { rmc = ((Value) obj).getValue(); multiRunSub(rsl, rmc, listener); } this.task.setStatus(Status.SUBMITTED); } } } private void multiRunSub(String rsl, String rmc, MultiJobListener listener) throws InvalidSecurityContextException, TaskSubmissionException { GramJob job = new GramJob(rsl); job.addListener(listener); try { job.setCredentials(this.credential); } catch (IllegalArgumentException iae) { throw new InvalidSecurityContextException( "Cannot set the SecurityContext twice", iae); } boolean limitedDeleg = isLimitedDelegation(this.securityContext); try { job.request(rmc, false, limitedDeleg); if (logger.isDebugEnabled()) { logger.debug("Submitted job with Globus ID: " + job.getIDAsString()); } } catch (GramException ge) { listener.failed(true); throw new TaskSubmissionException("Cannot submit job", ge); } catch (GSSException gsse) { listener.failed(true); throw new InvalidSecurityContextException("Invalid GSSCredentials", gsse); } listener.runningJob(); } public void suspend() throws InvalidSecurityContextException, TaskSubmissionException { // not implemented yet } public void resume() throws InvalidSecurityContextException, TaskSubmissionException { // not implemented yet } public void cancel() throws InvalidSecurityContextException, TaskSubmissionException { try { if (this.task.getStatus().getStatusCode() == Status.UNSUBMITTED) { this.task.setStatus(Status.CANCELED); return; } String jobCount = (String) this.task.getAttribute("jobCount"); if (jobCount.equalsIgnoreCase("multiple")) { Iterator iterator = this.jobList.iterator(); while (iterator.hasNext()) { GramJob job = (GramJob) iterator.next(); job.cancel(); } } else { this.gramJob.cancel(); } this.task.setStatus(Status.CANCELED); } catch (GramException ge) { cleanup(); throw new TaskSubmissionException("Cannot cancel job", ge); } catch (GSSException gsse) { cleanup(); throw new InvalidSecurityContextException("Invalid GSSCredentials", gsse); } } private RslNode prepareSpecification(JobSpecification spec) throws IllegalSpecException, TaskSubmissionException { RslNode rsl = new RslNode(RslNode.AND); if (spec.getSpecification() != null) { try { return RSLParser.parse(spec.getSpecification()); } catch (ParseException e) { throw new IllegalSpecException("Failed to parse specification", e); } } else { boolean batchJob = spec.isBatchJob(); boolean redirected = spec.getStdOutputLocation().overlaps( FileLocation.MEMORY_AND_LOCAL) || spec.getStdErrorLocation().overlaps( FileLocation.MEMORY_AND_LOCAL); if (batchJob && redirected) { throw new IllegalSpecException( "Cannot redirect the output/error of a batch job"); } if (redirected || FileLocation.LOCAL.equals(spec.getStdInputLocation()) || FileLocation.LOCAL.equals(spec.getExecutableLocation())) { this.startGassServer = true; String gassURL = startGassServer(); Bindings subst = new Bindings("rsl_substitution"); subst.add(new Binding("GLOBUSRUN_GASS_URL", gassURL)); rsl.add(subst); } // sets the executable if (spec.getExecutable() != null) { if (FileLocation.LOCAL.equals(spec.getExecutableLocation())) { rsl.add(new NameOpValue("executable", NameOpValue.EQ, new VarRef("GLOBUSRUN_GASS_URL", null, new Value( fixAbsPath(spec.getExecutable()))))); } else { rsl.add(new NameOpValue("executable", NameOpValue.EQ, spec .getExecutable())); } } else { throw new IllegalSpecException("Missing executable"); } // sets other parameters NameOpValue args = new NameOpValue("arguments", NameOpValue.EQ); if (!spec.getArgumentsAsList().isEmpty()) { Iterator i = spec.getArgumentsAsList().iterator(); while (i.hasNext()) { if ("condor".equals(jobManager)) { args.add(condorify((String) i.next())); } else { args.add((String) i.next()); } } rsl.add(args); } if (spec.getDirectory() != null) { rsl.add(new NameOpValue("directory", NameOpValue.EQ, spec .getDirectory())); } Collection environment = spec.getEnvironmentVariableNames(); if (environment.size() > 0) { NameOpValue env = new NameOpValue("environment", NameOpValue.EQ); Iterator iterator = environment.iterator(); while (iterator.hasNext()) { String name = (String) iterator.next(); String value = spec.getEnvironmentVariable(name); List l = new LinkedList(); l.add(new Value(name)); l.add(new Value(value)); env.add(l); } rsl.add(env); } // sets the stdin if (spec.getStdInput() != null) { if (FileLocation.LOCAL.equals(spec.getStdInputLocation())) { rsl.add(new NameOpValue("stdin", NameOpValue.EQ, new VarRef("GLOBUSRUN_GASS_URL", null, new Value( fixAbsPath(spec.getStdInput()))))); } else { rsl.add(new NameOpValue("stdin", NameOpValue.EQ, spec .getStdInput())); } } // if output is to be redirected if (FileLocation.MEMORY_AND_LOCAL.overlaps(spec .getStdOutputLocation())) { Value v; // if no output file is specified, use the stdout if (FileLocation.MEMORY.overlaps(spec.getStdOutputLocation())) { v = new Value("/dev/stdout-" + this.task.getIdentity().toString()); } else { v = new Value(fixAbsPath(spec.getStdOutput())); } rsl.add(new NameOpValue("stdout", NameOpValue.EQ, new VarRef( "GLOBUSRUN_GASS_URL", null, v))); } else if (spec.getStdOutput() != null) { // output on the remote machine rsl.add(new NameOpValue("stdout", NameOpValue.EQ, spec .getStdOutput())); } // if error is to be redirected if (FileLocation.MEMORY_AND_LOCAL.overlaps(spec .getStdErrorLocation())) { Value v; // if no error file is specified, use the stdout if (FileLocation.MEMORY.overlaps(spec.getStdErrorLocation())) { v = new Value("/dev/stderr-" + this.task.getIdentity().toString()); } else { v = new Value(fixAbsPath(spec.getStdError())); } rsl.add(new NameOpValue("stderr", NameOpValue.EQ, new VarRef( "GLOBUSRUN_GASS_URL", null, v))); } else if (spec.getStdError() != null) { // error on the remote machine rsl.add(new NameOpValue("stderr", NameOpValue.EQ, spec .getStdError())); } if (spec.getAttribute("condor_requirements") != null) { String requirementString = (String) spec .getAttribute("condor_requirements"); NameOpValue req = new NameOpValue("condorsubmit", NameOpValue.EQ); List l = new LinkedList(); l.add(new Value("Requirements")); l.add(new Value(requirementString)); req.add(l); rsl.add(req); } Iterator i = spec.getAttributeNames().iterator(); while (i.hasNext()) { try { String key = (String) i.next(); String value = (String) spec.getAttribute(key); if (key.equals("condor_requirements")) { continue; } if (key.toLowerCase().equals("maxwalltime")) { value = WallTime.normalize(value, jobManager); } rsl.add(new NameOpValue(key, NameOpValue.EQ, value)); } catch (Exception e) { throw new IllegalSpecException( "Cannot parse the user defined attributes", e); } } return rsl; } } public static final char QUOTE = '\''; private String condorify(String s) { if (s.indexOf(' ') != -1) { StringBuffer sb = new StringBuffer(); sb.append(QUOTE); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == QUOTE) { sb.append(QUOTE); } sb.append(c); } sb.append(QUOTE); return sb.toString(); } else { return s; } } private String startGassServer() throws TaskSubmissionException { GlobusSecurityContextImpl securityContext = (GlobusSecurityContextImpl) this.task .getService(0).getSecurityContext(); String gassURL = null; try { this.gassServer = GassServerFactory.getGassServer(this.credential); this.gassServer.registerDefaultDeactivator(); } catch (Exception e) { throw new TaskSubmissionException( "Problems while creating a Gass Server", e); } gassURL = gassServer.getURL(); this.stdoutStream = new JobOutputStream(this); this.stderrStream = new JobOutputStream(this); gassServer.registerJobOutputStream("err-" + this.task.getIdentity().toString(), this.stderrStream); gassServer.registerJobOutputStream("out-" + this.task.getIdentity().toString(), this.stdoutStream); logger.debug("Started the GASS server"); return gassURL; } public void statusChanged(GramJob job) { int status = job.getStatus(); switch (status) { case GRAMConstants.STATUS_ACTIVE: this.task.setStatus(Status.ACTIVE); break; case GRAMConstants.STATUS_FAILED: Status newStatus = new StatusImpl(); Status oldStatus = this.task.getStatus(); newStatus.setPrevStatusCode(oldStatus.getStatusCode()); newStatus.setStatusCode(Status.FAILED); int errorCode = job.getError(); Exception e = new GramException(errorCode); newStatus.setException(e); this.task.setStatus(newStatus); break; case GRAMConstants.STATUS_DONE: this.task.setStatus(Status.COMPLETED); break; case GRAMConstants.STATUS_SUSPENDED: this.task.setStatus(Status.SUSPENDED); break; case GRAMConstants.STATUS_UNSUBMITTED: this.task.setStatus(Status.UNSUBMITTED); break; default: break; } if ((status == 4) || (status == 8)) { cleanup(); } } private synchronized void cleanup() { try { this.gramJob.removeListener(this); CallbackHandlerManager.decreaseUsageCount(this.credential); if (gassServer != null) { GassServerFactory.decreaseUsageCount(gassServer); } } catch (Exception e) { logger.warn("Failed to clean up job", e); } } public void outputChanged(String s) { String output = this.task.getStdOutput(); if (output == null) { output = s; } else { output += s; } this.task.setStdOutput(output); } public void outputClosed() { } private SecurityContext getSecurityContext(Task task) throws InvalidSecurityContextException { SecurityContext sc = task.getService(0).getSecurityContext(); if (sc == null) { // create default credentials sc = new GlobusSecurityContextImpl(); GSSManager manager = ExtendedGSSManager.getInstance(); try { sc.setCredentials(manager .createCredential(GSSCredential.INITIATE_AND_ACCEPT)); } catch (GSSException e) { throw new InvalidSecurityContextException(e); } } return sc; } private String substituteJobManager(String server, String jobmanager) throws InvalidServiceContactException { if (server.indexOf("/jobmanager-") != -1) { // the jobmanager attribute takes precedence server = server.substring(0, server.lastIndexOf("/jobmanager-")); } String lcjm = jobmanager.toLowerCase(); server = server + "/jobmanager-" + lcjm; return server; } private String extractJobManager(String server) { if (server.indexOf("/jobmanager-") != -1) { return server.substring(server.lastIndexOf("/jobmanager-") + 1); } else { return null; } } private String fixAbsPath(String path) { if (path == null) { return null; } else if (path.startsWith("/") && !path.startsWith(" return "//" + path; } else { return path; } } }
package org.filteredpush.qc.sciname; /** A utility class containing the dwc:Taxon terms. * * @author mole * */ public class Taxon { private String taxonID; private String kingdom; private String phylum; private String taxonomic_class; private String order; private String family; private String subfamily; private String genus; private String subgenus; private String scientificName; private String scientificNameAuthorship; private String genericName; private String specificEpithet; private String infraspecificEpithet; private String taxonRank; private String cultivarEpithet; private String higherClassification; private String vernacularName; private String taxonConceptID; private String scientificNameID; private String originalNameUsageID; private String acceptedNameUsageID; public Taxon() { this.taxonID = ""; this.kingdom = ""; this.phylum = ""; this.taxonomic_class = ""; this.order = ""; this.family = ""; this.subfamily = ""; this.genus = ""; this.subgenus = ""; this.scientificName = ""; this.scientificNameAuthorship = ""; this.genericName = ""; this.specificEpithet = ""; this.infraspecificEpithet = ""; this.taxonRank = ""; this.cultivarEpithet = ""; this.higherClassification = ""; this.vernacularName = ""; this.taxonConceptID = ""; this.scientificNameID = ""; this.originalNameUsageID = ""; this.acceptedNameUsageID = ""; } public Taxon(String taxonID, String kingdom, String phylum, String taxonomic_class, String order, String family, String subfamily, String genus, String subgenus, String scientificName, String scientificNameAuthorship, String genericName, String specificEpithet, String infraspecificEpithet, String taxonRank, String cultivarEpithet, String higherClassification, String vernacularName, String taxonConceptID, String scientificNameID, String originalNameUsageID, String acceptedNameUsageID) { this.taxonID = taxonID; this.kingdom = kingdom; this.phylum = phylum; this.taxonomic_class = taxonomic_class; this.order = order; this.family = family; this.subfamily = subfamily; this.genus = genus; this.subgenus = subgenus; this.scientificName = scientificName; this.scientificNameAuthorship = scientificNameAuthorship; this.genericName = genericName; this.specificEpithet = specificEpithet; this.infraspecificEpithet = infraspecificEpithet; this.taxonRank = taxonRank; this.cultivarEpithet = cultivarEpithet; this.higherClassification = higherClassification; this.vernacularName = vernacularName; this.taxonConceptID = taxonConceptID; this.scientificNameID = scientificNameID; this.originalNameUsageID = originalNameUsageID; this.acceptedNameUsageID = acceptedNameUsageID; } public String getTaxonID() { return taxonID; } public void setTaxonID(String taxonID) { this.taxonID = taxonID; } public String getKingdom() { return kingdom; } public void setKingdom(String kingdom) { this.kingdom = kingdom; } public String getPhylum() { return phylum; } public void setPhylum(String phylum) { this.phylum = phylum; } public String getTaxonomic_class() { return taxonomic_class; } public void setTaxonomic_class(String taxonomic_class) { this.taxonomic_class = taxonomic_class; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public String getFamily() { return family; } public void setFamily(String family) { this.family = family; } public String getSubfamily() { return subfamily; } public void setSubfamily(String subfamily) { this.subfamily = subfamily; } public String getGenus() { return genus; } public void setGenus(String genus) { this.genus = genus; } public String getSubgenus() { return subgenus; } public void setSubgenus(String subgenus) { this.subgenus = subgenus; } public String getScientificName() { if (scientificName==null) { return ""; } return scientificName; } public void setScientificName(String scientificName) { this.scientificName = scientificName; } public String getScientificNameAuthorship() { if (scientificNameAuthorship==null) { return ""; } return scientificNameAuthorship; } public void setScientificNameAuthorship(String scientificNameAuthorship) { this.scientificNameAuthorship = scientificNameAuthorship; } public String getGenericName() { return genericName; } public void setGenericName(String genericName) { this.genericName = genericName; } public String getSpecificEpithet() { return specificEpithet; } public void setSpecificEpithet(String specificEpithet) { this.specificEpithet = specificEpithet; } public String getInfraspecificEpithet() { return infraspecificEpithet; } public void setInfraspecificEpithet(String infraspecificEpithet) { this.infraspecificEpithet = infraspecificEpithet; } public String getTaxonRank() { return taxonRank; } public void setTaxonRank(String taxonRank) { this.taxonRank = taxonRank; } public String getCultivarEpithet() { return cultivarEpithet; } public void setCultivarEpithet(String cultivarEpithet) { this.cultivarEpithet = cultivarEpithet; } public String getHigherClassification() { return higherClassification; } public void setHigherClassification(String higherClassification) { this.higherClassification = higherClassification; } public String getVernacularName() { return vernacularName; } public void setVernacularName(String vernacularName) { this.vernacularName = vernacularName; } public String getTaxonConceptID() { return taxonConceptID; } public void setTaxonConceptID(String taxonConceptID) { this.taxonConceptID = taxonConceptID; } public String getScientificNameID() { return scientificNameID; } public void setScientificNameID(String scientificNameID) { this.scientificNameID = scientificNameID; } public String getOriginalNameUsageID() { return originalNameUsageID; } public void setOriginalNameUsageID(String originalNameUsageID) { this.originalNameUsageID = originalNameUsageID; } public String getAcceptedNameUsageID() { return acceptedNameUsageID; } public void setAcceptedNameUsageID(String acceptedNameUsageID) { this.acceptedNameUsageID = acceptedNameUsageID; } public String toString() { StringBuilder result = new StringBuilder(); result.append(taxonID).append(":"); result.append(kingdom).append(":"); result.append(phylum).append(":"); result.append(taxonomic_class).append(":"); result.append(order).append(":"); result.append(family).append(":"); result.append(subfamily).append(":"); result.append(genus).append(":"); result.append(subgenus).append(":"); result.append(scientificName).append(":"); result.append(scientificNameAuthorship).append(":"); result.append(genericName).append(":"); result.append(specificEpithet).append(":"); result.append(infraspecificEpithet).append(":"); result.append(taxonRank).append(":"); result.append(cultivarEpithet).append(":"); result.append(higherClassification).append(":"); result.append(vernacularName).append(":"); result.append(taxonConceptID).append(":"); result.append(scientificNameID).append(":"); result.append(originalNameUsageID).append(":"); result.append(acceptedNameUsageID).append(":"); return result.toString().replaceAll(":[:]+",":"); } }
package com.intellij.ui.stripe; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ShortcutSet; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.components.JBScrollBar; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.RegionPainter; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts; /** * @author Sergey.Malenkov */ public abstract class Updater<Painter extends ErrorStripePainter> implements Disposable { private final Painter myPainter; private final JScrollBar myScrollBar; private final MergingUpdateQueue myQueue; private final MouseAdapter myMouseAdapter = new MouseAdapter() { @Override public void mouseMoved(MouseEvent event) { onMouseMove(myPainter, event.getX(), event.getY()); } @Override public void mouseClicked(MouseEvent event) { onMouseClick(myPainter, event.getX(), event.getY()); } }; protected Updater(@NotNull Painter painter, JScrollPane pane) { this(painter, pane.getVerticalScrollBar()); } protected Updater(@NotNull Painter painter, JScrollBar bar) { myPainter = painter; myScrollBar = bar; myScrollBar.addMouseListener(myMouseAdapter); myScrollBar.addMouseMotionListener(myMouseAdapter); myQueue = new MergingUpdateQueue("ErrorStripeUpdater", 100, true, myScrollBar, this); UIUtil.putClientProperty(myScrollBar, JBScrollBar.TRACK, new RegionPainter<Object>() { @Override public void paint(Graphics2D g, int x, int y, int width, int height, Object object) { DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance(); myPainter.setMinimalThickness(settings == null ? 2 : Math.min(settings.getErrorStripeMarkMinHeight(), JBUI.scale(4))); myPainter.setErrorStripeGap(Registry.intValue("error.stripe.gap", 0)); if (myPainter instanceof ExtraErrorStripePainter) { ExtraErrorStripePainter extra = (ExtraErrorStripePainter)myPainter; extra.setGroupSwap(!myScrollBar.getComponentOrientation().isLeftToRight()); } myPainter.paint(g, x, y, width, height, object); } }); } @Override public void dispose() { myScrollBar.removeMouseListener(myMouseAdapter); myScrollBar.removeMouseMotionListener(myMouseAdapter); UIUtil.putClientProperty(myScrollBar, JBScrollBar.TRACK, null); } private int findErrorStripeIndex(Painter painter, int x, int y) { int index = painter.findIndex(x, y); if (null != painter.getErrorStripe(index)) return index; index = painter.findIndex(x, y + 1); if (null != painter.getErrorStripe(index)) return index; index = painter.findIndex(x, y - 1); if (null != painter.getErrorStripe(index)) return index; index = painter.findIndex(x, y + 2); if (null != painter.getErrorStripe(index)) return index; return -1; } protected void onMouseMove(Painter painter, int x, int y) { onMouseMove(painter, findErrorStripeIndex(painter, x, y)); } protected void onMouseMove(Painter painter, int index) { myScrollBar.setCursor(index < 0 ? null : Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } protected void onMouseClick(Painter painter, int x, int y) { onMouseClick(painter, findErrorStripeIndex(painter, x, y)); } protected void onMouseClick(Painter painter, int index) { onSelect(painter, index); } protected void onSelect(Painter painter, int index) { } protected ShortcutSet getNextErrorShortcut() { return getActiveKeymapShortcuts("GotoNextError"); } public void selectNext(int index) { onSelect(myPainter, findNextIndex(index)); } protected ShortcutSet getPreviousErrorShortcut() { return getActiveKeymapShortcuts("GotoPreviousError"); } public void selectPrevious(int index) { onSelect(myPainter, findPreviousIndex(index)); } protected abstract void update(Painter painter); protected void update(Painter painter, int index, Object object) { painter.setErrorStripe(index, getErrorStripe(object)); } protected ErrorStripe getErrorStripe(Object object) { return object instanceof ErrorStripe ? (ErrorStripe)object : null; } public final void update() { myQueue.cancelAllUpdates(); myQueue.queue(new Update("update") { @Override public void run() { update(myPainter); if (myPainter.isModified()) { myScrollBar.invalidate(); myScrollBar.repaint(); } } }); } public int findNextIndex(int current) { SearchResult result = new SearchResult(); int max = myPainter.getErrorStripeCount() - 1; if (0 <= current && current < max) { result.updateForward(myPainter, current + 1, max); result.updateForward(myPainter, 0, current); } else if (0 <= max) { result.updateForward(myPainter, 0, max); } return result.index; } public int findPreviousIndex(int current) { SearchResult result = new SearchResult(); int max = myPainter.getErrorStripeCount() - 1; if (0 < current && current <= max) { result.updateBackward(myPainter, current - 1, 0); result.updateBackward(myPainter, max, current); } else if (0 <= max) { result.updateBackward(myPainter, max, 0); } return result.index; } private static final class SearchResult { int layer = 0; int index = -1; void updateForward(ErrorStripePainter painter, int index, int max) { while (index <= max) update(painter, index++); } void updateBackward(ErrorStripePainter painter, int index, int min) { while (min <= index) update(painter, index } void update(ErrorStripePainter painter, int index) { ErrorStripe stripe = painter.getErrorStripe(index); if (stripe != null) { int layer = stripe.getLayer(); if (layer > this.layer) { this.layer = layer; this.index = index; } } } } }
package com.fsck.k9.activity; import java.util.Collection; import java.util.List; import android.annotation.SuppressLint; import android.app.FragmentManager; import android.app.FragmentManager.OnBackStackChangedListener; import android.app.FragmentTransaction; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.IntentSender.SendIntentException; import android.content.res.Configuration; import android.net.Uri; import android.support.v7.app.ActionBar; import android.os.Build; import android.os.Bundle; import android.os.Parcelable; import timber.log.Timber; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.SortType; import com.fsck.k9.K9; import com.fsck.k9.K9.SplitViewMode; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.activity.compose.MessageActions; import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.fragment.MessageListFragment; import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener; import com.fsck.k9.helper.ParcelableUtil; import com.fsck.k9.mailstore.StorageManager; import com.fsck.k9.preferences.StorageEditor; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchAccount; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SearchSpecification.Attribute; import com.fsck.k9.search.SearchSpecification.SearchCondition; import com.fsck.k9.search.SearchSpecification.SearchField; import com.fsck.k9.ui.messageview.MessageViewFragment; import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener; import com.fsck.k9.view.MessageHeader; import com.fsck.k9.view.MessageTitleView; import com.fsck.k9.view.ViewSwitcher; import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener; import de.cketti.library.changelog.ChangeLog; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9Activity implements MessageListFragmentListener, MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener, OnSwitchCompleteListener { private static final String EXTRA_SEARCH = "search_bytes"; private static final String EXTRA_NO_THREADING = "no_threading"; private static final String ACTION_SHORTCUT = "shortcut"; private static final String EXTRA_SPECIAL_FOLDER = "special_folder"; private static final String EXTRA_MESSAGE_REFERENCE = "message_reference"; // used for remote search public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account"; private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder"; private static final String STATE_DISPLAY_MODE = "displayMode"; private static final String STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed"; private static final String STATE_FIRST_BACK_STACK_ID = "firstBackstackId"; // Used for navigating to next/previous message private static final int PREVIOUS = 1; private static final int NEXT = 2; public static final int REQUEST_MASK_PENDING_INTENT = 1 << 15; public static void actionDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask) { actionDisplaySearch(context, search, noThreading, newTask, true); } public static void actionDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask, boolean clearTop) { context.startActivity( intentDisplaySearch(context, search, noThreading, newTask, clearTop)); } public static Intent intentDisplaySearch(Context context, SearchSpecification search, boolean noThreading, boolean newTask, boolean clearTop) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search)); intent.putExtra(EXTRA_NO_THREADING, noThreading); if (clearTop) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } if (newTask) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } return intent; } public static Intent shortcutIntent(Context context, String specialFolder) { Intent intent = new Intent(context, MessageList.class); intent.setAction(ACTION_SHORTCUT); intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } public static Intent actionDisplayMessageIntent(Context context, MessageReference messageReference) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference.toIdentityString()); return intent; } private enum DisplayMode { MESSAGE_LIST, MESSAGE_VIEW, SPLIT_VIEW } private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); private ActionBar actionBar; private View actionBarMessageList; private View actionBarMessageView; private MessageTitleView actionBarSubject; private TextView actionBarTitle; private TextView actionBarSubTitle; private TextView actionBarUnread; private Menu menu; private ViewGroup messageViewContainer; private View messageViewPlaceHolder; private MessageListFragment messageListFragment; private MessageViewFragment messageViewFragment; private int firstBackStackId = -1; private Account account; private String folderServerId; private LocalSearch search; private boolean singleFolderMode; private boolean singleAccountMode; private ProgressBar actionBarProgress; private MenuItem menuButtonCheckMail; private View actionButtonIndeterminateProgress; private int lastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS; /** * {@code true} if the message list should be displayed as flat list (i.e. no threading) * regardless whether or not message threading was enabled in the settings. This is used for * filtered views, e.g. when only displaying the unread messages in a folder. */ private boolean noThreading; private DisplayMode displayMode; private MessageReference messageReference; /** * {@code true} when the message list was displayed once. This is used in * {@link #onBackPressed()} to decide whether to go from the message view to the message list or * finish the activity. */ private boolean messageListWasDisplayed = false; private ViewSwitcher viewSwitcher; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) { finish(); return; } if (useSplitView()) { setContentView(R.layout.split_message_list); } else { setContentView(R.layout.message_list); viewSwitcher = (ViewSwitcher) findViewById(R.id.container); viewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left)); viewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right)); viewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right)); viewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left)); viewSwitcher.setOnSwitchCompleteListener(this); } initializeActionBar(); // Enable gesture detection for MessageLists setupGestureDetector(this); if (!decodeExtras(getIntent())) { return; } findFragments(); initializeDisplayMode(savedInstanceState); initializeLayout(); initializeFragments(); displayViews(); ChangeLog cl = new ChangeLog(this); if (cl.isFirstRun()) { cl.getLogDialog().show(); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); if (isFinishing()) { return; } setIntent(intent); if (firstBackStackId >= 0) { getFragmentManager().popBackStackImmediate(firstBackStackId, FragmentManager.POP_BACK_STACK_INCLUSIVE); firstBackStackId = -1; } removeMessageListFragment(); removeMessageViewFragment(); messageReference = null; search = null; folderServerId = null; if (!decodeExtras(intent)) { return; } initializeDisplayMode(null); initializeFragments(); displayViews(); } /** * Get references to existing fragments if the activity was restarted. */ private void findFragments() { FragmentManager fragmentManager = getFragmentManager(); messageListFragment = (MessageListFragment) fragmentManager.findFragmentById( R.id.message_list_container); messageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById( R.id.message_view_container); } /** * Create fragment instances if necessary. * * @see #findFragments() */ private void initializeFragments() { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.addOnBackStackChangedListener(this); boolean hasMessageListFragment = (messageListFragment != null); if (!hasMessageListFragment) { FragmentTransaction ft = fragmentManager.beginTransaction(); messageListFragment = MessageListFragment.newInstance(search, false, (K9.isThreadedViewEnabled() && !noThreading)); ft.add(R.id.message_list_container, messageListFragment); ft.commit(); } // Check if the fragment wasn't restarted and has a MessageReference in the arguments. If // so, open the referenced message. if (!hasMessageListFragment && messageViewFragment == null && messageReference != null) { openMessage(messageReference); } } /** * Set the initial display mode (message list, message view, or split view). * * <p><strong>Note:</strong> * This method has to be called after {@link #findFragments()} because the result depends on * the availability of a {@link MessageViewFragment} instance. * </p> * * @param savedInstanceState * The saved instance state that was passed to the activity as argument to * {@link #onCreate(Bundle)}. May be {@code null}. */ private void initializeDisplayMode(Bundle savedInstanceState) { if (useSplitView()) { displayMode = DisplayMode.SPLIT_VIEW; return; } if (savedInstanceState != null) { DisplayMode savedDisplayMode = (DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE); if (savedDisplayMode != DisplayMode.SPLIT_VIEW) { displayMode = savedDisplayMode; return; } } if (messageViewFragment != null || messageReference != null) { displayMode = DisplayMode.MESSAGE_VIEW; } else { displayMode = DisplayMode.MESSAGE_LIST; } } private boolean useSplitView() { SplitViewMode splitViewMode = K9.getSplitViewMode(); int orientation = getResources().getConfiguration().orientation; return (splitViewMode == SplitViewMode.ALWAYS || (splitViewMode == SplitViewMode.WHEN_IN_LANDSCAPE && orientation == Configuration.ORIENTATION_LANDSCAPE)); } private void initializeLayout() { messageViewContainer = (ViewGroup) findViewById(R.id.message_view_container); LayoutInflater layoutInflater = getLayoutInflater(); messageViewPlaceHolder = layoutInflater.inflate(R.layout.empty_message_view, messageViewContainer, false); } private void displayViews() { switch (displayMode) { case MESSAGE_LIST: { showMessageList(); break; } case MESSAGE_VIEW: { showMessageView(); break; } case SPLIT_VIEW: { messageListWasDisplayed = true; if (messageViewFragment == null) { showMessageViewPlaceHolder(); } else { MessageReference activeMessage = messageViewFragment.getMessageReference(); if (activeMessage != null) { messageListFragment.setActiveMessage(activeMessage); } } break; } } } private boolean decodeExtras(Intent intent) { String action = intent.getAction(); if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) { Uri uri = intent.getData(); List<String> segmentList = uri.getPathSegments(); String accountId = segmentList.get(0); Collection<Account> accounts = Preferences.getPreferences(this).getAvailableAccounts(); for (Account account : accounts) { if (String.valueOf(account.getAccountNumber()).equals(accountId)) { String folderServerId = segmentList.get(1); String messageUid = segmentList.get(2); messageReference = new MessageReference(account.getUuid(), folderServerId, messageUid, null); break; } } } else if (ACTION_SHORTCUT.equals(action)) { // Handle shortcut intents String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER); if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) { search = SearchAccount.createUnifiedInboxAccount(this).getRelatedSearch(); } else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) { search = SearchAccount.createAllMessagesAccount(this).getRelatedSearch(); } } else if (intent.getStringExtra(SearchManager.QUERY) != null) { // check if this intent comes from the system search ( remote ) if (Intent.ACTION_SEARCH.equals(intent.getAction())) { //Query was received from Search Dialog String query = intent.getStringExtra(SearchManager.QUERY).trim(); search = new LocalSearch(getString(R.string.search_results)); search.setManualSearch(true); noThreading = true; search.or(new SearchCondition(SearchField.SENDER, Attribute.CONTAINS, query)); search.or(new SearchCondition(SearchField.SUBJECT, Attribute.CONTAINS, query)); search.or(new SearchCondition(SearchField.MESSAGE_CONTENTS, Attribute.CONTAINS, query)); Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { search.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT)); // searches started from a folder list activity will provide an account, but no folder if (appData.getString(EXTRA_SEARCH_FOLDER) != null) { search.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER)); } } else { search.addAccountUuid(LocalSearch.ALL_ACCOUNTS); } } } else { // regular LocalSearch object was passed search = intent.hasExtra(EXTRA_SEARCH) ? ParcelableUtil.unmarshall(intent.getByteArrayExtra(EXTRA_SEARCH), LocalSearch.CREATOR) : null; noThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false); } if (messageReference == null) { String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE); messageReference = MessageReference.parse(messageReferenceString); } if (messageReference != null) { search = new LocalSearch(); search.addAccountUuid(messageReference.getAccountUuid()); search.addAllowedFolder(messageReference.getFolderServerId()); } if (search == null) { // We've most likely been started by an old unread widget String accountUuid = intent.getStringExtra("account"); String folderServerId = intent.getStringExtra("folder"); search = new LocalSearch(folderServerId); search.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid); if (folderServerId != null) { search.addAllowedFolder(folderServerId); } } Preferences prefs = Preferences.getPreferences(getApplicationContext()); String[] accountUuids = search.getAccountUuids(); if (search.searchAllAccounts()) { List<Account> accounts = prefs.getAccounts(); singleAccountMode = (accounts.size() == 1); if (singleAccountMode) { account = accounts.get(0); } } else { singleAccountMode = (accountUuids.length == 1); if (singleAccountMode) { account = prefs.getAccount(accountUuids[0]); } } singleFolderMode = singleAccountMode && (search.getFolderServerIds().size() == 1); if (singleAccountMode && (account == null || !account.isAvailable(this))) { Timber.i("not opening MessageList of unavailable account"); onAccountUnavailable(); return false; } if (singleFolderMode) { folderServerId = search.getFolderServerIds().get(0); } // now we know if we are in single account mode and need a subtitle actionBarSubTitle.setVisibility((!singleFolderMode) ? View.GONE : View.VISIBLE); return true; } @Override public void onPause() { super.onPause(); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } @Override public void onResume() { super.onResume(); if (!(this instanceof Search)) { //necessary b/c no guarantee Search.onStop will be called before MessageList.onResume //when returning from search results Search.setActive(false); } if (account != null && !account.isAvailable(this)) { onAccountUnavailable(); return; } StorageManager.getInstance(getApplication()).addListener(mStorageListener); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(STATE_DISPLAY_MODE, displayMode); outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, messageListWasDisplayed); outState.putInt(STATE_FIRST_BACK_STACK_ID, firstBackStackId); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); messageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED); firstBackStackId = savedInstanceState.getInt(STATE_FIRST_BACK_STACK_ID); } private void initializeActionBar() { actionBar = getSupportActionBar(); actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(R.layout.actionbar_custom); View customView = actionBar.getCustomView(); actionBarMessageList = customView.findViewById(R.id.actionbar_message_list); actionBarMessageView = customView.findViewById(R.id.actionbar_message_view); actionBarSubject = (MessageTitleView) customView.findViewById(R.id.message_title_view); actionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first); actionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub); actionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count); actionBarProgress = (ProgressBar) customView.findViewById(R.id.actionbar_progress); actionButtonIndeterminateProgress = getActionButtonIndeterminateProgress(); actionBar.setDisplayHomeAsUpEnabled(true); } @SuppressLint("InflateParams") private View getActionButtonIndeterminateProgress() { return getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null); } @Override public boolean dispatchKeyEvent(KeyEvent event) { boolean ret = false; if (KeyEvent.ACTION_DOWN == event.getAction()) { ret = onCustomKeyDown(event.getKeyCode(), event); } if (!ret) { ret = super.dispatchKeyEvent(event); } return ret; } @Override public void onBackPressed() { if (displayMode == DisplayMode.MESSAGE_VIEW && messageListWasDisplayed) { showMessageList(); } else { super.onBackPressed(); } } /** * Handle hotkeys * * <p> * This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance * to consume this key event. * </p> * * @param keyCode * The value in {@code event.getKeyCode()}. * @param event * Description of the key event. * * @return {@code true} if this event was consumed. */ public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: { if (messageViewFragment != null && displayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showPreviousMessage(); return true; } else if (displayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { messageListFragment.onMoveUp(); return true; } break; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (messageViewFragment != null && displayMode != DisplayMode.MESSAGE_LIST && K9.useVolumeKeysForNavigationEnabled()) { showNextMessage(); return true; } else if (displayMode != DisplayMode.MESSAGE_VIEW && K9.useVolumeKeysForListNavigationEnabled()) { messageListFragment.onMoveDown(); return true; } break; } case KeyEvent.KEYCODE_C: { messageListFragment.onCompose(); return true; } case KeyEvent.KEYCODE_Q: { if (messageListFragment != null && messageListFragment.isSingleAccountMode()) { onShowFolderList(); } return true; } case KeyEvent.KEYCODE_O: { messageListFragment.onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { messageListFragment.onReverseSort(); return true; } case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_D: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onDelete(); } else if (messageViewFragment != null) { messageViewFragment.onDelete(); } return true; } case KeyEvent.KEYCODE_S: { messageListFragment.toggleMessageSelect(); return true; } case KeyEvent.KEYCODE_G: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onToggleFlagged(); } else if (messageViewFragment != null) { messageViewFragment.onToggleFlagged(); } return true; } case KeyEvent.KEYCODE_M: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onMove(); } else if (messageViewFragment != null) { messageViewFragment.onMove(); } return true; } case KeyEvent.KEYCODE_V: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onArchive(); } else if (messageViewFragment != null) { messageViewFragment.onArchive(); } return true; } case KeyEvent.KEYCODE_Y: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onCopy(); } else if (messageViewFragment != null) { messageViewFragment.onCopy(); } return true; } case KeyEvent.KEYCODE_Z: { if (displayMode == DisplayMode.MESSAGE_LIST) { messageListFragment.onToggleRead(); } else if (messageViewFragment != null) { messageViewFragment.onToggleRead(); } return true; } case KeyEvent.KEYCODE_F: { if (messageViewFragment != null) { messageViewFragment.onForward(); } return true; } case KeyEvent.KEYCODE_A: { if (messageViewFragment != null) { messageViewFragment.onReplyAll(); } return true; } case KeyEvent.KEYCODE_R: { if (messageViewFragment != null) { messageViewFragment.onReply(); } return true; } case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_P: { if (messageViewFragment != null) { showPreviousMessage(); } return true; } case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_K: { if (messageViewFragment != null) { showNextMessage(); } return true; } /* FIXME case KeyEvent.KEYCODE_Z: { messageViewFragment.zoom(event); return true; }*/ case KeyEvent.KEYCODE_H: { Toast toast; if (displayMode == DisplayMode.MESSAGE_LIST) { toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); } else { toast = Toast.makeText(this, R.string.message_view_help_key, Toast.LENGTH_LONG); } toast.show(); return true; } case KeyEvent.KEYCODE_DPAD_LEFT: { if (messageViewFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) { return showPreviousMessage(); } return false; } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (messageViewFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) { return showNextMessage(); } return false; } } return false; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { Timber.v("Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, account); finish(); } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, account); } @Override public boolean onSearchRequested() { return messageListFragment.onSearchRequested(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case android.R.id.home: { goBack(); return true; } case R.id.compose: { messageListFragment.onCompose(); return true; } case R.id.toggle_message_view_theme: { onToggleTheme(); return true; } // MessageList case R.id.check_mail: { messageListFragment.checkMail(); return true; } case R.id.set_sort_date: { messageListFragment.changeSort(SortType.SORT_DATE); return true; } case R.id.set_sort_arrival: { messageListFragment.changeSort(SortType.SORT_ARRIVAL); return true; } case R.id.set_sort_subject: { messageListFragment.changeSort(SortType.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { messageListFragment.changeSort(SortType.SORT_SENDER); return true; } case R.id.set_sort_flag: { messageListFragment.changeSort(SortType.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { messageListFragment.changeSort(SortType.SORT_UNREAD); return true; } case R.id.set_sort_attach: { messageListFragment.changeSort(SortType.SORT_ATTACHMENT); return true; } case R.id.select_all: { messageListFragment.selectAll(); return true; } case R.id.app_settings: { onEditPrefs(); return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.search: { messageListFragment.onSearchRequested(); return true; } case R.id.search_remote: { messageListFragment.onRemoteSearch(); return true; } case R.id.mark_all_as_read: { messageListFragment.confirmMarkAllAsRead(); return true; } case R.id.show_folder_list: { onShowFolderList(); return true; } // MessageView case R.id.next_message: { showNextMessage(); return true; } case R.id.previous_message: { showPreviousMessage(); return true; } case R.id.delete: { messageViewFragment.onDelete(); return true; } case R.id.reply: { messageViewFragment.onReply(); return true; } case R.id.reply_all: { messageViewFragment.onReplyAll(); return true; } case R.id.forward: { messageViewFragment.onForward(); return true; } case R.id.forward_as_attachment: { messageViewFragment.onForwardAsAttachment(); return true; } case R.id.share: { messageViewFragment.onSendAlternate(); return true; } case R.id.toggle_unread: { messageViewFragment.onToggleRead(); return true; } case R.id.archive: case R.id.refile_archive: { messageViewFragment.onArchive(); return true; } case R.id.spam: case R.id.refile_spam: { messageViewFragment.onSpam(); return true; } case R.id.move: case R.id.refile_move: { messageViewFragment.onMove(); return true; } case R.id.copy: case R.id.refile_copy: { messageViewFragment.onCopy(); return true; } case R.id.select_text: { messageViewFragment.onSelectText(); return true; } case R.id.show_headers: case R.id.hide_headers: { messageViewFragment.onToggleAllHeadersView(); updateMenu(); return true; } } if (!singleFolderMode) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.send_messages: { messageListFragment.onSendPendingMessages(); return true; } case R.id.folder_settings: { if (folderServerId != null) { FolderSettings.actionSettings(this, account, folderServerId); } return true; } case R.id.expunge: { messageListFragment.onExpunge(); return true; } default: { return super.onOptionsItemSelected(item); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.message_list_option, menu); this.menu = menu; menuButtonCheckMail = menu.findItem(R.id.check_mail); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); configureMenu(menu); return true; } /** * Hide menu items not appropriate for the current context. * * <p><strong>Note:</strong> * Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the * visibility of a menu item in this method. * </p> * * @param menu * The {@link Menu} instance that should be modified. May be {@code null}; in that case * the method does nothing and immediately returns. */ private void configureMenu(Menu menu) { if (menu == null) { return; } // Set visibility of account/folder settings menu items if (messageListFragment == null) { menu.findItem(R.id.account_settings).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); } else { menu.findItem(R.id.account_settings).setVisible( messageListFragment.isSingleAccountMode()); menu.findItem(R.id.folder_settings).setVisible( messageListFragment.isSingleFolderMode()); } /* * Set visibility of menu items related to the message view */ if (displayMode == DisplayMode.MESSAGE_LIST || messageViewFragment == null || !messageViewFragment.isInitialized()) { menu.findItem(R.id.next_message).setVisible(false); menu.findItem(R.id.previous_message).setVisible(false); menu.findItem(R.id.single_message_options).setVisible(false); menu.findItem(R.id.delete).setVisible(false); menu.findItem(R.id.compose).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.copy).setVisible(false); menu.findItem(R.id.spam).setVisible(false); menu.findItem(R.id.refile).setVisible(false); menu.findItem(R.id.toggle_unread).setVisible(false); menu.findItem(R.id.select_text).setVisible(false); menu.findItem(R.id.toggle_message_view_theme).setVisible(false); menu.findItem(R.id.show_headers).setVisible(false); menu.findItem(R.id.hide_headers).setVisible(false); } else { // hide prev/next buttons in split mode if (displayMode != DisplayMode.MESSAGE_VIEW) { menu.findItem(R.id.next_message).setVisible(false); menu.findItem(R.id.previous_message).setVisible(false); } else { MessageReference ref = messageViewFragment.getMessageReference(); boolean initialized = (messageListFragment != null && messageListFragment.isLoadFinished()); boolean canDoPrev = (initialized && !messageListFragment.isFirst(ref)); boolean canDoNext = (initialized && !messageListFragment.isLast(ref)); MenuItem prev = menu.findItem(R.id.previous_message); prev.setEnabled(canDoPrev); prev.getIcon().setAlpha(canDoPrev ? 255 : 127); MenuItem next = menu.findItem(R.id.next_message); next.setEnabled(canDoNext); next.getIcon().setAlpha(canDoNext ? 255 : 127); } MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme); if (K9.useFixedMessageViewTheme()) { toggleTheme.setVisible(false); } else { // Set title of menu item to switch to dark/light theme if (K9.getK9MessageViewTheme() == K9.Theme.DARK) { toggleTheme.setTitle(R.string.message_view_theme_action_light); } else { toggleTheme.setTitle(R.string.message_view_theme_action_dark); } toggleTheme.setVisible(true); } // Set title of menu item to toggle the read state of the currently displayed message if (messageViewFragment.isMessageRead()) { menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action); } else { menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action); } // Jellybean has built-in long press selection support menu.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16); menu.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible()); /* * Set visibility of copy, move, archive, spam in action bar and refile submenu */ if (messageViewFragment.isCopyCapable()) { menu.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible()); menu.findItem(R.id.refile_copy).setVisible(true); } else { menu.findItem(R.id.copy).setVisible(false); menu.findItem(R.id.refile_copy).setVisible(false); } if (messageViewFragment.isMoveCapable()) { boolean canMessageBeArchived = messageViewFragment.canMessageBeArchived(); boolean canMessageBeMovedToSpam = messageViewFragment.canMessageBeMovedToSpam(); menu.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible()); menu.findItem(R.id.archive).setVisible(canMessageBeArchived && K9.isMessageViewArchiveActionVisible()); menu.findItem(R.id.spam).setVisible(canMessageBeMovedToSpam && K9.isMessageViewSpamActionVisible()); menu.findItem(R.id.refile_move).setVisible(true); menu.findItem(R.id.refile_archive).setVisible(canMessageBeArchived); menu.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam); } else { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); menu.findItem(R.id.refile).setVisible(false); } if (messageViewFragment.allHeadersVisible()) { menu.findItem(R.id.show_headers).setVisible(false); } else { menu.findItem(R.id.hide_headers).setVisible(false); } } /* * Set visibility of menu items related to the message list */ // Hide both search menu items by default and enable one when appropriate menu.findItem(R.id.search).setVisible(false); menu.findItem(R.id.search_remote).setVisible(false); if (displayMode == DisplayMode.MESSAGE_VIEW || messageListFragment == null || !messageListFragment.isInitialized()) { menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.set_sort).setVisible(false); menu.findItem(R.id.select_all).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.show_folder_list).setVisible(false); } else { menu.findItem(R.id.set_sort).setVisible(true); menu.findItem(R.id.select_all).setVisible(true); menu.findItem(R.id.compose).setVisible(true); menu.findItem(R.id.mark_all_as_read).setVisible( messageListFragment.isMarkAllAsReadSupported()); if (!messageListFragment.isSingleAccountMode()) { menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.show_folder_list).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(messageListFragment.isOutbox()); menu.findItem(R.id.expunge).setVisible(messageListFragment.isRemoteFolder() && messageListFragment.isAccountExpungeCapable()); menu.findItem(R.id.show_folder_list).setVisible(true); } menu.findItem(R.id.check_mail).setVisible(messageListFragment.isCheckMailSupported()); // If this is an explicit local search, show the option to search on the server if (!messageListFragment.isRemoteSearch() && messageListFragment.isRemoteSearchAllowed()) { menu.findItem(R.id.search_remote).setVisible(true); } else if (!messageListFragment.isManualSearch()) { menu.findItem(R.id.search).setVisible(true); } } } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } public void setActionBarTitle(String title) { actionBarTitle.setText(title); } public void setActionBarSubTitle(String subTitle) { actionBarSubTitle.setText(subTitle); } public void setActionBarUnread(int unread) { if (unread == 0) { actionBarUnread.setVisibility(View.GONE); } else { actionBarUnread.setVisibility(View.VISIBLE); actionBarUnread.setText(String.format("%d", unread)); } } @Override public void setMessageListTitle(String title) { setActionBarTitle(title); } @Override public void setMessageListSubTitle(String subTitle) { setActionBarSubTitle(subTitle); } @Override public void setUnreadCount(int unread) { setActionBarUnread(unread); } @Override public void setMessageListProgress(int progress) { setProgress(progress); } @Override public void openMessage(MessageReference messageReference) { Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = prefs.getAccount(messageReference.getAccountUuid()); String folderServerId = messageReference.getFolderServerId(); if (folderServerId.equals(account.getDraftsFolder())) { MessageActions.actionEditDraft(this, messageReference); } else { messageViewContainer.removeView(messageViewPlaceHolder); if (messageListFragment != null) { messageListFragment.setActiveMessage(messageReference); } MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.message_view_container, fragment); messageViewFragment = fragment; ft.commit(); if (displayMode != DisplayMode.SPLIT_VIEW) { showMessageView(); } } } @Override public void onResendMessage(MessageReference messageReference) { MessageActions.actionEditDraft(this, messageReference); } @Override public void onForward(MessageReference messageReference) { onForward(messageReference, null); } @Override public void onForward(MessageReference messageReference, Parcelable decryptionResultForReply) { MessageActions.actionForward(this, messageReference, decryptionResultForReply); } @Override public void onForwardAsAttachment(MessageReference messageReference) { onForwardAsAttachment(messageReference, null); } @Override public void onForwardAsAttachment(MessageReference messageReference, Parcelable decryptionResultForReply) { MessageActions.actionForwardAsAttachment(this, messageReference, decryptionResultForReply); } @Override public void onReply(MessageReference messageReference) { onReply(messageReference, null); } @Override public void onReply(MessageReference messageReference, Parcelable decryptionResultForReply) { MessageActions.actionReply(this, messageReference, false, decryptionResultForReply); } @Override public void onReplyAll(MessageReference messageReference) { onReplyAll(messageReference, null); } @Override public void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply) { MessageActions.actionReply(this, messageReference, true, decryptionResultForReply); } @Override public void onCompose(Account account) { MessageActions.actionCompose(this, account); } @Override public void showMoreFromSameSender(String senderAddress) { LocalSearch tmpSearch = new LocalSearch(getString(R.string.search_from_format, senderAddress)); tmpSearch.addAccountUuids(search.getAccountUuids()); tmpSearch.and(SearchField.SENDER, senderAddress, Attribute.CONTAINS); MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false); addMessageListFragment(fragment, true); } @Override public void onBackStackChanged() { findFragments(); if (displayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder(); } configureMenu(menu); } @Override public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) { if (messageListFragment != null && displayMode != DisplayMode.MESSAGE_VIEW) { messageListFragment.onSwipeRightToLeft(e1, e2); } } @Override public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) { if (messageListFragment != null && displayMode != DisplayMode.MESSAGE_VIEW) { messageListFragment.onSwipeLeftToRight(e1, e2); } } private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (account != null && providerId.equals(account.getLocalStorageProviderId())) { runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } } @Override public void onMount(String providerId) { // no-op } } private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.message_list_container, fragment); if (addToBackStack) ft.addToBackStack(null); messageListFragment = fragment; int transactionId = ft.commit(); if (transactionId >= 0 && firstBackStackId < 0) { firstBackStackId = transactionId; } } @Override public boolean startSearch(Account account, String folderServerId) { // If this search was started from a MessageList of a single folder, pass along that folder info // so that we can enable remote search. if (account != null && folderServerId != null) { final Bundle appData = new Bundle(); appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid()); appData.putString(EXTRA_SEARCH_FOLDER, folderServerId); startSearch(null, false, appData, false); } else { // TODO Handle the case where we're searching from within a search result. startSearch(null, false, null, false); } return true; } @Override public void showThread(Account account, String folderServerId, long threadRootId) { showMessageViewPlaceHolder(); LocalSearch tmpSearch = new LocalSearch(); tmpSearch.addAccountUuid(account.getUuid()); tmpSearch.and(SearchField.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS); MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false); addMessageListFragment(fragment, true); } private void showMessageViewPlaceHolder() { removeMessageViewFragment(); // Add placeholder view if necessary if (messageViewPlaceHolder.getParent() == null) { messageViewContainer.addView(messageViewPlaceHolder); } messageListFragment.setActiveMessage(null); } /** * Remove MessageViewFragment if necessary. */ private void removeMessageViewFragment() { if (messageViewFragment != null) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(messageViewFragment); messageViewFragment = null; ft.commit(); showDefaultTitleView(); } } private void removeMessageListFragment() { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(messageListFragment); messageListFragment = null; ft.commit(); } @Override public void remoteSearchStarted() { // Remove action button for remote search configureMenu(menu); } @Override public void goBack() { FragmentManager fragmentManager = getFragmentManager(); if (displayMode == DisplayMode.MESSAGE_VIEW) { showMessageList(); } else if (fragmentManager.getBackStackEntryCount() > 0) { fragmentManager.popBackStack(); } else if (messageListFragment.isManualSearch()) { finish(); } else if (!singleFolderMode) { onAccounts(); } else { onShowFolderList(); } } @Override public void enableActionBarProgress(boolean enable) { if (menuButtonCheckMail != null && menuButtonCheckMail.isVisible()) { actionBarProgress.setVisibility(ProgressBar.GONE); if (enable) { menuButtonCheckMail .setActionView(actionButtonIndeterminateProgress); } else { menuButtonCheckMail.setActionView(null); } } else { if (menuButtonCheckMail != null) menuButtonCheckMail.setActionView(null); if (enable) { actionBarProgress.setVisibility(ProgressBar.VISIBLE); } else { actionBarProgress.setVisibility(ProgressBar.GONE); } } } @Override public void displayMessageSubject(String subject) { if (displayMode == DisplayMode.MESSAGE_VIEW) { actionBarSubject.setText(subject); } else { actionBarSubject.showSubjectInMessageHeader(); } } @Override public void showNextMessageOrReturn() { if (K9.messageViewReturnToList() || !showLogicalNextMessage()) { if (displayMode == DisplayMode.SPLIT_VIEW) { showMessageViewPlaceHolder(); } else { showMessageList(); } } } /** * Shows the next message in the direction the user was displaying messages. * * @return {@code true} */ private boolean showLogicalNextMessage() { boolean result = false; if (lastDirection == NEXT) { result = showNextMessage(); } else if (lastDirection == PREVIOUS) { result = showPreviousMessage(); } if (!result) { result = showNextMessage() || showPreviousMessage(); } return result; } @Override public void setProgress(boolean enable) { setProgressBarIndeterminateVisibility(enable); } @Override public void messageHeaderViewAvailable(MessageHeader header) { actionBarSubject.setMessageHeader(header); } private boolean showNextMessage() { MessageReference ref = messageViewFragment.getMessageReference(); if (ref != null) { if (messageListFragment.openNext(ref)) { lastDirection = NEXT; return true; } } return false; } private boolean showPreviousMessage() { MessageReference ref = messageViewFragment.getMessageReference(); if (ref != null) { if (messageListFragment.openPrevious(ref)) { lastDirection = PREVIOUS; return true; } } return false; } private void showMessageList() { messageListWasDisplayed = true; displayMode = DisplayMode.MESSAGE_LIST; viewSwitcher.showFirstView(); messageListFragment.setActiveMessage(null); showDefaultTitleView(); configureMenu(menu); } private void showMessageView() { displayMode = DisplayMode.MESSAGE_VIEW; if (!messageListWasDisplayed) { viewSwitcher.setAnimateFirstView(false); } viewSwitcher.showSecondView(); showMessageTitleView(); configureMenu(menu); } @Override public void updateMenu() { invalidateOptionsMenu(); } @Override public void disableDeleteAction() { menu.findItem(R.id.delete).setEnabled(false); } private void onToggleTheme() { if (K9.getK9MessageViewTheme() == K9.Theme.DARK) { K9.setK9MessageViewThemeSetting(K9.Theme.LIGHT); } else { K9.setK9MessageViewThemeSetting(K9.Theme.DARK); } new Thread(new Runnable() { @Override public void run() { Context appContext = getApplicationContext(); Preferences prefs = Preferences.getPreferences(appContext); StorageEditor editor = prefs.getStorage().edit(); K9.save(editor); editor.commit(); } }).start(); recreate(); } private void showDefaultTitleView() { actionBarMessageView.setVisibility(View.GONE); actionBarMessageList.setVisibility(View.VISIBLE); if (messageListFragment != null) { messageListFragment.updateTitle(); } actionBarSubject.setMessageHeader(null); } private void showMessageTitleView() { actionBarMessageList.setVisibility(View.GONE); actionBarMessageView.setVisibility(View.VISIBLE); if (messageViewFragment != null) { displayMessageSubject(null); messageViewFragment.updateTitle(); } } @Override public void onSwitchComplete(int displayedChild) { if (displayedChild == 0) { removeMessageViewFragment(); } } @Override public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws SendIntentException { requestCode |= REQUEST_MASK_PENDING_INTENT; super.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if ((requestCode & REQUEST_MASK_PENDING_INTENT) == REQUEST_MASK_PENDING_INTENT) { requestCode ^= REQUEST_MASK_PENDING_INTENT; if (messageViewFragment != null) { messageViewFragment.onPendingIntentResult(requestCode, resultCode, data); } } } }
package com.sandwell.JavaSimulation3D; import com.sandwell.JavaSimulation.ObjectType; import com.sandwell.JavaSimulation.Package; import java.awt.Cursor; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; public class EntityPallet extends JFrame implements DragGestureListener { private static EntityPallet myInstance; // only one instance allowed to be open private JScrollPane treeView; private static JTree tree; private static DefaultMutableTreeNode top; private static DefaultTreeModel treeModel; private EntityPallet() { super( "Model Builder" ); setIconImage(GUIFrame.getWindowIcon()); // Make the x button do the same as the close button setDefaultCloseOperation(FrameBox.HIDE_ON_CLOSE); tree = new JTree(); tree.setRootVisible(false); tree.setShowsRootHandles(true); DragSource dragSource = new DragSource(); dragSource.createDefaultDragGestureRecognizer(tree, DnDConstants.ACTION_COPY, this); top = EntityPallet.createTree(); treeModel = new DefaultTreeModel(top); tree.setModel(treeModel); tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION ); // Create the tree scroll pane and add the tree to it treeView = new JScrollPane( tree ); getContentPane().add( treeView ); // Set the attributes for the frame setLocation(0, 110); setVisible( true ); tree.setRowHeight(25); tree.setCellRenderer(new TreeCellRenderer()); ToolTipManager.sharedInstance().registerComponent(tree); pack(); setSize(220, 400); } public void dragGestureRecognized(DragGestureEvent event) { TreePath path = tree.getSelectionPath(); if (path != null) { // Dragged node is a DefaultMutableTreeNode if(path.getLastPathComponent() instanceof DefaultMutableTreeNode) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) path.getLastPathComponent(); // This is an ObjectType node if(treeNode.getUserObject() instanceof ObjectType) { ObjectType type = (ObjectType) treeNode.getUserObject(); Cursor cursor = null; if (event.getDragAction() == DnDConstants.ACTION_COPY) { cursor = DragSource.DefaultCopyDrop; } event.startDrag(cursor,new TransferableObjectType(type) ); } } } } private static DefaultMutableTreeNode createTree() { // Create a tree that allows one selection at a time DefaultMutableTreeNode root = new DefaultMutableTreeNode(); for (Package p : Package.getAll()) { DefaultMutableTreeNode packNode = new DefaultMutableTreeNode(p.getName(), true); for( ObjectType type : ObjectType.getAll() ) { if( type.getPackage() != p || ! type.isDragAndDrop() ) continue; DefaultMutableTreeNode classNode = new DefaultMutableTreeNode(type, true); packNode.add(classNode); } root.add(packNode); } return root; } public synchronized static EntityPallet getInstance() { if (myInstance == null) myInstance = new EntityPallet(); return myInstance; } /** * Disposes the only instance of the entity pallet */ public static void clear() { if (myInstance != null) { myInstance.dispose(); myInstance = null; } } }
package com.sunny.grokkingalgorithms.fasttrack.dynamicprogrammingandrecursion; public class MaximumContigousSum { /* Maximum contigous sub array */ /** * * @param input * @return */ public static int maximumContigousSubArrayUsingKadanes(int[] input){ int maxEndingSoFar = 0; int maxSumSoFar = 0; for(int i = 0 ; i < input.length ; i++){ maxEndingSoFar += input[i]; if(maxEndingSoFar < 0){ maxEndingSoFar = 0; } if(maxEndingSoFar > maxSumSoFar){ maxSumSoFar = maxEndingSoFar; } } return maxSumSoFar; } /** * * @param input * @return */ public static String maximumContigousSubArray(int[] input){ String maximumSubArray = null; int maxSum = Integer.MIN_VALUE; for(int i = 0; i < input.length ; i++){ StringBuilder subArray = new StringBuilder(); int curSum = 0; //int prevSum = 0; for(int j = i ; j < input.length ; j++){ curSum += input[j]; subArray.append(input[j]+ " "); if(curSum > maxSum){ maxSum = curSum; maximumSubArray = subArray.toString(); } /*if(prevSum > curSum){ break; }*/ //prevSum = curSum; } } return maximumSubArray; } /** * * @param args */ public static void main(String[] args) { int[] input = new int[]{-2,-3,4,-1,-2,1,5,-3}; System.out.println(maximumContigousSubArray(input)); System.out.println(maximumContigousSubArrayUsingKadanes(input)); } }
package javax.jmdns.impl; import java.io.IOException; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.JmmDNS; import javax.jmdns.JmmDNS.NetworkTopologyDiscovery; import javax.jmdns.NetworkTopologyEvent; import javax.jmdns.NetworkTopologyListener; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import javax.jmdns.ServiceTypeListener; import javax.jmdns.impl.constants.DNSConstants; /** * This class enable multihomming mDNS. It will open a mDNS per IP address of the machine. * * @author C&eacute;drik Lime, Pierre Frisch */ public class JmmDNSImpl implements JmmDNS, NetworkTopologyDiscovery, ServiceInfoImpl.Delegate { private static Logger logger = Logger.getLogger(JmmDNSImpl.class.getName()); private final Set<NetworkTopologyListener> _networkListeners; /** * Every JmDNS created. */ private final ConcurrentMap<InetAddress, JmDNS> _knownMDNS; /** * This enable the service info text update. */ private final ConcurrentMap<String, ServiceInfo> _services; private final ExecutorService _ListenerExecutor; private final ExecutorService _jmDNSExecutor; private final Timer _timer; public JmmDNSImpl() { super(); _networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>()); _knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>(); _services = new ConcurrentHashMap<String, ServiceInfo>(20); _ListenerExecutor = Executors.newSingleThreadExecutor(); _jmDNSExecutor = Executors.newCachedThreadPool(); _timer = new Timer("Multihommed mDNS.Timer", true); (new NetworkChecker(this)).start(_timer); } /* * (non-Javadoc) * * @see java.io.Closeable#close() */ @Override public void close() throws IOException { if (logger.isLoggable(Level.FINER)) { logger.finer("Cancelling JmmDNS: " + this); } _timer.cancel(); _ListenerExecutor.shutdown(); // We need to cancel all the DNS ExecutorService executor = Executors.newCachedThreadPool(); for (final JmDNS mDNS : _knownMDNS.values()) { executor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { try { mDNS.close(); } catch (IOException exception) { // JmDNS never throws this is only because of the closeable interface } } }); } executor.shutdown(); try { executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.WARNING, "Exception ", exception); } _knownMDNS.clear(); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getNames() */ @Override public String[] getNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : _knownMDNS.values()) { result.add(mDNS.getName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getHostNames() */ @Override public String[] getHostNames() { Set<String> result = new HashSet<String>(); for (JmDNS mDNS : _knownMDNS.values()) { result.add(mDNS.getHostName()); } return result.toArray(new String[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getInterfaces() */ @Override public InetAddress[] getInterfaces() throws IOException { Set<InetAddress> result = new HashSet<InetAddress>(); for (JmDNS mDNS : _knownMDNS.values()) { result.add(mDNS.getInterface()); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String) */ @Override public ServiceInfo[] getServiceInfos(String type, String name) { return this.getServiceInfos(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, long) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, long timeout) { return this.getServiceInfos(type, name, false, timeout); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean) */ @Override public ServiceInfo[] getServiceInfos(String type, String name, boolean persistent) { return this.getServiceInfos(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean, long) */ @Override public ServiceInfo[] getServiceInfos(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. final Set<ServiceInfo> result = Collections.synchronizedSet(new HashSet<ServiceInfo>(_knownMDNS.size())); ExecutorService executor = Executors.newCachedThreadPool(); for (final JmDNS mDNS : _knownMDNS.values()) { executor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { result.add(mDNS.getServiceInfo(type, name, persistent, timeout)); } }); } executor.shutdown(); try { executor.awaitTermination(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.WARNING, "Exception ", exception); } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String) */ @Override public void requestServiceInfo(String type, String name) { this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean) */ @Override public void requestServiceInfo(String type, String name, boolean persistent) { this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, long) */ @Override public void requestServiceInfo(String type, String name, long timeout) { this.requestServiceInfo(type, name, false, timeout); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long) */ @Override public void requestServiceInfo(final String type, final String name, final boolean persistent, final long timeout) { // We need to run this in parallel to respect the timeout. for (final JmDNS mDNS : _knownMDNS.values()) { _jmDNSExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { mDNS.requestServiceInfo(type, name, persistent, timeout); } }); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void addServiceTypeListener(ServiceTypeListener listener) throws IOException { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.addServiceTypeListener(listener); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void removeServiceTypeListener(ServiceTypeListener listener) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.removeServiceTypeListener(listener); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void addServiceListener(String type, ServiceListener listener) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.addServiceListener(type, listener); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void removeServiceListener(String type, ServiceListener listener) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.removeServiceListener(type, listener); } } /* * (non-Javadoc) * * @see javax.jmdns.impl.ServiceInfoImpl.Delegate#textValueUpdated(javax.jmdns.ServiceInfo, byte[]) */ @Override public void textValueUpdated(ServiceInfo target, byte[] value) { synchronized (_services) { for (JmDNS mDNS : _knownMDNS.values()) { ServiceInfo info = ((JmDNSImpl) mDNS).getServices().get(target.getQualifiedName()); if (info != null) { info.setText(value); } else { logger.warning("We have a mDNS that does not know about the service info being updated."); } } } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#registerService(javax.jmdns.ServiceInfo) */ @Override public void registerService(ServiceInfo info) throws IOException { // This is really complex. We need to clone the service info for each DNS but then we loose the ability to update it. synchronized (_services) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.registerService((ServiceInfo) info.clone()); } ((ServiceInfoImpl) info).setDelegate(this); _services.put(info.getQualifiedName(), info); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#unregisterService(javax.jmdns.ServiceInfo) */ @Override public void unregisterService(ServiceInfo info) { synchronized (_services) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.unregisterService(info); } ((ServiceInfoImpl) info).setDelegate(null); _services.remove(info.getQualifiedName()); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#unregisterAllServices() */ @Override public void unregisterAllServices() { synchronized (_services) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.unregisterAllServices(); } _services.clear(); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#registerServiceType(java.lang.String) */ @Override public void registerServiceType(String type) { for (JmDNS mDNS : _knownMDNS.values()) { mDNS.registerServiceType(type); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#list(java.lang.String) */ @Override public ServiceInfo[] list(String type) { return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#list(java.lang.String, long) */ @Override public ServiceInfo[] list(final String type, final long timeout) { // We need to run this in parallel to respect the timeout. final Set<ServiceInfo> result = Collections.synchronizedSet(new HashSet<ServiceInfo>(_knownMDNS.size() * 5)); ExecutorService executor = Executors.newCachedThreadPool(); for (final JmDNS mDNS : _knownMDNS.values()) { executor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { result.addAll(Arrays.asList(mDNS.list(type, timeout))); } }); } executor.shutdown(); try { executor.awaitTermination(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException exception) { logger.log(Level.WARNING, "Exception ", exception); } return result.toArray(new ServiceInfo[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String) */ @Override public Map<String, ServiceInfo[]> listBySubtype(String type) { return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String, long) */ @Override public Map<String, ServiceInfo[]> listBySubtype(final String type, final long timeout) { Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5); for (ServiceInfo info : this.list(type, timeout)) { String subtype = info.getSubtype(); if (!map.containsKey(subtype)) { map.put(subtype, new ArrayList<ServiceInfo>(10)); } map.get(subtype).add(info); } Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size()); for (String subtype : map.keySet()) { List<ServiceInfo> infoForSubType = map.get(subtype); result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()])); } return result; } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#addNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void addNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.add(listener); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#removeNetworkTopologyListener(javax.jmdns.NetworkTopologyListener) */ @Override public void removeNetworkTopologyListener(NetworkTopologyListener listener) { _networkListeners.remove(listener); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS#networkListeners() */ @Override public NetworkTopologyListener[] networkListeners() { return _networkListeners.toArray(new NetworkTopologyListener[_networkListeners.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.NetworkTopologyListener#inetAddressAdded(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressAdded(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { synchronized (this) { if (!_knownMDNS.containsKey(address)) { JmDNS mDNS = JmDNS.create(address); _knownMDNS.put(address, mDNS); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _ListenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressAdded(jmdnsEvent); } }); } } } } catch (Exception e) { logger.warning("Unexpected unhandled exception: " + e); } } /* * (non-Javadoc) * * @see javax.jmdns.NetworkTopologyListener#inetAddressRemoved(javax.jmdns.NetworkTopologyEvent) */ @Override public void inetAddressRemoved(NetworkTopologyEvent event) { InetAddress address = event.getInetAddress(); try { synchronized (this) { if (_knownMDNS.containsKey(address)) { JmDNS mDNS = JmDNS.create(address); _knownMDNS.remove(address); mDNS.close(); final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address); for (final NetworkTopologyListener listener : this.networkListeners()) { _ListenerExecutor.submit(new Runnable() { /** * {@inheritDoc} */ @Override public void run() { listener.inetAddressRemoved(jmdnsEvent); } }); } } } } catch (Exception e) { logger.warning("Unexpected unhandled exception: " + e); } } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#getInetAddresses() */ @Override public InetAddress[] getInetAddresses() { Set<InetAddress> result = new HashSet<InetAddress>(); try { for (Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); nifs.hasMoreElements();) { NetworkInterface nif = nifs.nextElement(); for (InterfaceAddress interfaceAddress : nif.getInterfaceAddresses()) { if (logger.isLoggable(Level.FINEST)) { logger.finest("Found NetworkInterface/InetAddress: " + nif + " -- " + interfaceAddress); } if (this.useInetAddress(nif, interfaceAddress)) { result.add(interfaceAddress.getAddress()); } } } } catch (SocketException se) { logger.warning("Error while fetching network interfaces addresses: " + se); } return result.toArray(new InetAddress[result.size()]); } /* * (non-Javadoc) * * @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#useInetAddress(java.net.NetworkInterface, java.net.InetAddress) */ @Override public boolean useInetAddress(NetworkInterface networkInterface, InterfaceAddress interfaceAddress) { try { if (!networkInterface.isUp()) { return false; } if (!networkInterface.supportsMulticast()) { return false; } if (interfaceAddress.getAddress().isLoopbackAddress()) { return false; } return true; } catch (Exception exception) { return false; } } /** * Checks the network state.<br/> * If the network change, this class will reconfigure the list of DNS do adapt to the new configuration. */ static class NetworkChecker extends TimerTask { private static Logger logger1 = Logger.getLogger(NetworkChecker.class.getName()); private final NetworkTopologyDiscovery _mmDNS; private Set<InetAddress> _knownAddresses; public NetworkChecker(NetworkTopologyDiscovery mmDNS) { super(); this._mmDNS = mmDNS; _knownAddresses = Collections.synchronizedSet(new HashSet<InetAddress>()); } public void start(Timer timer) { timer.schedule(this, 0, DNSConstants.NETWORK_CHECK_INTERVAL); } /** * {@inheritDoc} */ @Override public void run() { try { InetAddress[] curentAddresses = _mmDNS.getInetAddresses(); Set<InetAddress> current = new HashSet<InetAddress>(curentAddresses.length); for (InetAddress address : curentAddresses) { current.add(address); if (!_knownAddresses.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressAdded(event); } } for (InetAddress address : _knownAddresses) { if (!current.contains(address)) { final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address); _mmDNS.inetAddressRemoved(event); } } _knownAddresses = current; } catch (Exception e) { logger1.warning("Unexpected unhandled exception: " + e); } } } }
package org.jfree.chart; import java.awt.Graphics2D; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; /** * A class used to represent a chart on the clipboard. * * @since 1.0.13 */ public class ChartTransferable implements Transferable { /** The data flavor. */ final DataFlavor imageFlavor = new DataFlavor( "image/x-java-image; class=java.awt.Image", "Image"); /** The chart. */ private JFreeChart chart; /** The width of the chart on the clipboard. */ private int width; /** The height of the chart on the clipboard. */ private int height; /** * The smallest width at which the chart will be drawn (if necessary, the * chart will then be scaled down to fit the requested width). * * @since 1.0.14 */ private int minDrawWidth; /** * The smallest height at which the chart will be drawn (if necessary, the * chart will then be scaled down to fit the requested height). * * @since 1.0.14 */ private int minDrawHeight; /** * The largest width at which the chart will be drawn (if necessary, the * chart will then be scaled up to fit the requested width). * * @since 1.0.14 */ private int maxDrawWidth; /** * The largest height at which the chart will be drawn (if necessary, the * chart will then be scaled up to fit the requested height). * * @since 1.0.14 */ private int maxDrawHeight; /** * Creates a new chart selection. * * @param chart the chart. * @param width the chart width. * @param height the chart height. */ public ChartTransferable(JFreeChart chart, int width, int height) { this(chart, width, height, true); } /** * Creates a new chart selection. * * @param chart the chart. * @param width the chart width. * @param height the chart height. * @param cloneData clone the dataset(s)? */ public ChartTransferable(JFreeChart chart, int width, int height, boolean cloneData) { this(chart, width, height, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, true); } /** * Creates a new chart selection. The minimum and maximum drawing * dimensions are used to match the scaling behaviour in the * {@link ChartPanel} class. * * @param chart the chart. * @param width the chart width. * @param height the chart height. * @param minDrawW the minimum drawing width. * @param minDrawH the minimum drawing height. * @param maxDrawW the maximum drawing width. * @param maxDrawH the maximum drawing height. * @param cloneData clone the dataset(s)? * * @since 1.0.14 */ public ChartTransferable(JFreeChart chart, int width, int height, int minDrawW, int minDrawH, int maxDrawW, int maxDrawH, boolean cloneData) { // we clone the chart because presumably there can be some delay // between putting this instance on the system clipboard and // actually having the getTransferData() method called... try { this.chart = (JFreeChart) chart.clone(); } catch (CloneNotSupportedException e) { this.chart = chart; } // FIXME: we've cloned the chart, but the dataset(s) aren't cloned // and we should do that this.width = width; this.height = height; this.minDrawWidth = minDrawW; this.minDrawHeight = minDrawH; this.maxDrawWidth = maxDrawW; this.maxDrawHeight = maxDrawH; } /** * Returns the data flavors supported. * * @return The data flavors supported. */ @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] {this.imageFlavor}; } /** * Returns <code>true</code> if the specified flavor is supported. * * @param flavor the flavor. * * @return A boolean. */ @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return this.imageFlavor.equals(flavor); } /** * Returns the content for the requested flavor, if it is supported. * * @param flavor the requested flavor. * * @return The content. * * @throws java.awt.datatransfer.UnsupportedFlavorException * @throws java.io.IOException if there is an IO problem. */ @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (this.imageFlavor.equals(flavor)) { return createBufferedImage(this.chart, this.width, this.height, this.minDrawWidth, this.minDrawHeight, this.maxDrawWidth, this.maxDrawHeight); } else { throw new UnsupportedFlavorException(flavor); } } /** * A utility method that creates an image of a chart, with scaling. * * @param chart the chart. * @param w the image width. * @param h the image height. * @param minDrawW the minimum width for chart drawing. * @param minDrawH the minimum height for chart drawing. * @param maxDrawW the maximum width for chart drawing. * @param maxDrawH the maximum height for chart drawing. * * @return A chart image. * * @since 1.0.14 */ private BufferedImage createBufferedImage(JFreeChart chart, int w, int h, int minDrawW, int minDrawH, int maxDrawW, int maxDrawH) { BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); // work out if scaling is required... boolean scale = false; double drawWidth = w; double drawHeight = h; double scaleX = 1.0; double scaleY = 1.0; if (drawWidth < minDrawW) { scaleX = drawWidth / minDrawW; drawWidth = minDrawW; scale = true; } else if (drawWidth > maxDrawW) { scaleX = drawWidth / maxDrawW; drawWidth = maxDrawW; scale = true; } if (drawHeight < minDrawH) { scaleY = drawHeight / minDrawH; drawHeight = minDrawH; scale = true; } else if (drawHeight > maxDrawH) { scaleY = drawHeight / maxDrawH; drawHeight = maxDrawH; scale = true; } Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight); if (scale) { AffineTransform st = AffineTransform.getScaleInstance(scaleX, scaleY); g2.transform(st); } chart.draw(g2, chartArea, null, null); g2.dispose(); return image; } }
package com.sun.jna; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; /** Exercise a range of native methods. * * @author twall@users.sf.net */ public class RawArgumentsMarshalTest extends ArgumentsMarshalTest { public static class RawTestLibrary implements TestLibrary { /** Dummy. Automatically fail when passed an object. */ public String returnStringArgument(Object arg) {throw new IllegalArgumentException(arg.getClass().getName()); } public native boolean returnBooleanArgument(boolean arg); public native byte returnInt8Argument(byte arg); public native char returnWideCharArgument(char arg); public native short returnInt16Argument(short arg); public native int returnInt32Argument(int i); public native long returnInt64Argument(long l); public native NativeLong returnLongArgument(NativeLong l); public native float returnFloatArgument(float f); public native double returnDoubleArgument(double d); public native String returnStringArgument(String s); public native WString returnWStringArgument(WString s); public native Pointer returnPointerArgument(Pointer p); public String returnStringArrayElement(String[] args, int which) {throw new UnsupportedOperationException();} public WString returnWideStringArrayElement(WString[] args, int which) {throw new UnsupportedOperationException();} public Pointer returnPointerArrayElement(Pointer[] args, int which) {throw new UnsupportedOperationException();} public TestPointerType returnPointerArrayElement(TestPointerType[] args, int which) {throw new UnsupportedOperationException();} public CheckFieldAlignment returnPointerArrayElement(CheckFieldAlignment.ByReference[] args, int which) {throw new UnsupportedOperationException();} public int returnRotatedArgumentCount(String[] args) {throw new UnsupportedOperationException();} public native long checkInt64ArgumentAlignment(int i, long j, int i2, long j2); public native double checkDoubleArgumentAlignment(float i, double j, float i2, double j2); public native Pointer testStructurePointerArgument(CheckFieldAlignment p); public native double testStructureByValueArgument(CheckFieldAlignment.ByValue p); public int testStructureArrayInitialization(CheckFieldAlignment[] p, int len) { throw new UnsupportedOperationException(); } public void modifyStructureArray(CheckFieldAlignment[] p, int length) { throw new UnsupportedOperationException(); } public native int fillInt8Buffer(byte[] buf, int len, byte value); public native int fillInt16Buffer(short[] buf, int len, short value); public native int fillInt32Buffer(int[] buf, int len, int value); public native int fillInt64Buffer(long[] buf, int len, long value); // ByteBuffer alternative definitions public native int fillInt8Buffer(ByteBuffer buf, int len, byte value); public native int fillInt16Buffer(ByteBuffer buf, int len, short value); public native int fillInt32Buffer(ByteBuffer buf, int len, int value); public native int fillInt64Buffer(ByteBuffer buf, int len, long value); // {Short,Int,Long}Buffer alternative definitions public native int fillInt16Buffer(ShortBuffer buf, int len, short value); public native int fillInt32Buffer(IntBuffer buf, int len, int value); public native int fillInt64Buffer(LongBuffer buf, int len, long value); // dummy to avoid causing Native.register to fail public boolean returnBooleanArgument(Object arg) {throw new IllegalArgumentException();} static { Native.register("testlib"); } } /* Override original. */ protected void setUp() { lib = new RawTestLibrary(); } // These tests crash on w32 IBM J9 unless -Xint is used // (jvmwi3260-20080415_18762) //public void testWideCharArgument() { } //public void testWStringArgumentReturn() { } // Override tests not yet supported public void testStringArrayArgument() { } public void testWriteStructureArrayArgumentMemory() { } public void testUninitializedStructureArrayArgument() { } public void testRejectNoncontiguousStructureArrayArgument() { } public void testWideStringArrayArgument() { } public void testPointerArrayArgument() { } public void testNativeMappedArrayArgument() { } public void testStructureByReferenceArrayArgument() { } public void testModifiedCharArrayArgument() { } public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(RawArgumentsMarshalTest.class); } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.CategoryAnnotation; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.CategoryAnchor; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.AnnotationChangeListener; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.CategoryItemRendererState; import org.jfree.chart.ui.Layer; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.util.CloneUtils; import org.jfree.chart.util.ObjectUtils; import org.jfree.chart.util.PaintUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtils; import org.jfree.chart.util.ShadowGenerator; import org.jfree.chart.util.ShapeUtils; import org.jfree.chart.util.SortOrder; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; /** * A general plotting class that uses data from a {@link CategoryDataset} and * renders each data item using a {@link CategoryItemRenderer}. */ public class CategoryPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable, AnnotationChangeListener, RendererChangeListener, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3537691700434728188L; /** * The default visibility of the grid lines plotted against the domain * axis. */ public static final boolean DEFAULT_DOMAIN_GRIDLINES_VISIBLE = false; /** * The default visibility of the grid lines plotted against the range * axis. */ public static final boolean DEFAULT_RANGE_GRIDLINES_VISIBLE = true; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.LIGHT_GRAY; /** The default value label font. */ public static final Font DEFAULT_VALUE_LABEL_FONT = new Font("SansSerif", Font.PLAIN, 10); /** * The default crosshair visibility. * * @since 1.0.5 */ public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; /** * The default crosshair stroke. * * @since 1.0.5 */ public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; /** * The default crosshair paint. * * @since 1.0.5 */ public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.BLUE; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The plot orientation. */ private PlotOrientation orientation; /** The offset between the data area and the axes. */ private RectangleInsets axisOffset; /** Storage for the domain axes. */ private Map<Integer, CategoryAxis> domainAxes; /** Storage for the domain axis locations. */ private Map<Integer, AxisLocation> domainAxisLocations; /** * A flag that controls whether or not the shared domain axis is drawn * (only relevant when the plot is being used as a subplot). */ private boolean drawSharedDomainAxis; /** Storage for the range axes. */ private Map<Integer, ValueAxis> rangeAxes; /** Storage for the range axis locations. */ private Map<Integer, AxisLocation> rangeAxisLocations; /** Storage for the datasets. */ private Map<Integer, CategoryDataset> datasets; /** Storage for keys that map datasets to domain axes. */ private TreeMap<Integer, List<Integer>> datasetToDomainAxesMap; /** Storage for keys that map datasets to range axes. */ private TreeMap<Integer, List<Integer>> datasetToRangeAxesMap; /** Storage for the renderers. */ private Map<Integer, CategoryItemRenderer> renderers; /** The dataset rendering order. */ private DatasetRenderingOrder renderingOrder = DatasetRenderingOrder.REVERSE; /** * Controls the order in which the columns are traversed when rendering the * data items. */ private SortOrder columnRenderingOrder = SortOrder.ASCENDING; /** * Controls the order in which the rows are traversed when rendering the * data items. */ private SortOrder rowRenderingOrder = SortOrder.ASCENDING; /** * A flag that controls whether the grid-lines for the domain axis are * visible. */ private boolean domainGridlinesVisible; /** The position of the domain gridlines relative to the category. */ private CategoryAnchor domainGridlinePosition; /** The stroke used to draw the domain grid-lines. */ private transient Stroke domainGridlineStroke; /** The paint used to draw the domain grid-lines. */ private transient Paint domainGridlinePaint; /** * A flag that controls whether or not the zero baseline against the range * axis is visible. * * @since 1.0.13 */ private boolean rangeZeroBaselineVisible; /** * The stroke used for the zero baseline against the range axis. * * @since 1.0.13 */ private transient Stroke rangeZeroBaselineStroke; /** * The paint used for the zero baseline against the range axis. * * @since 1.0.13 */ private transient Paint rangeZeroBaselinePaint; /** * A flag that controls whether the grid-lines for the range axis are * visible. */ private boolean rangeGridlinesVisible; /** The stroke used to draw the range axis grid-lines. */ private transient Stroke rangeGridlineStroke; /** The paint used to draw the range axis grid-lines. */ private transient Paint rangeGridlinePaint; /** * A flag that controls whether or not gridlines are shown for the minor * tick values on the primary range axis. * * @since 1.0.13 */ private boolean rangeMinorGridlinesVisible; /** * The stroke used to draw the range minor grid-lines. * * @since 1.0.13 */ private transient Stroke rangeMinorGridlineStroke; /** * The paint used to draw the range minor grid-lines. * * @since 1.0.13 */ private transient Paint rangeMinorGridlinePaint; /** The anchor value. */ private double anchorValue; /** * The index for the dataset that the crosshairs are linked to (this * determines which axes the crosshairs are plotted against). * * @since 1.0.11 */ private int crosshairDatasetIndex; /** * A flag that controls the visibility of the domain crosshair. * * @since 1.0.11 */ private boolean domainCrosshairVisible; /** * The row key for the crosshair point. * * @since 1.0.11 */ private Comparable domainCrosshairRowKey; /** * The column key for the crosshair point. * * @since 1.0.11 */ private Comparable domainCrosshairColumnKey; /** * The stroke used to draw the domain crosshair if it is visible. * * @since 1.0.11 */ private transient Stroke domainCrosshairStroke; /** * The paint used to draw the domain crosshair if it is visible. * * @since 1.0.11 */ private transient Paint domainCrosshairPaint; /** A flag that controls whether or not a range crosshair is drawn. */ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean rangeCrosshairLockedOnData = true; /** A map containing lists of markers for the domain axes. */ private Map<Integer, Collection<Marker>> foregroundDomainMarkers; /** A map containing lists of markers for the domain axes. */ private Map<Integer, Collection<Marker>> backgroundDomainMarkers; /** A map containing lists of markers for the range axes. */ private Map<Integer, Collection<Marker>> foregroundRangeMarkers; /** A map containing lists of markers for the range axes. */ private Map<Integer, Collection<Marker>> backgroundRangeMarkers; /** * A (possibly empty) list of annotations for the plot. The list should * be initialised in the constructor and never allowed to be * <code>null</code>. */ private List<CategoryAnnotation> annotations; /** * The weight for the plot (only relevant when the plot is used as a subplot * within a combined plot). */ private int weight; /** The fixed space for the domain axis. */ private AxisSpace fixedDomainAxisSpace; /** The fixed space for the range axis. */ private AxisSpace fixedRangeAxisSpace; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private List<LegendItem> fixedLegendItems; /** * A flag that controls whether or not panning is enabled for the * range axis/axes. * * @since 1.0.13 */ private boolean rangePannable; /** * The shadow generator for the plot (<code>null</code> permitted). * * @since 1.0.14 */ private ShadowGenerator shadowGenerator; /** * Default constructor. */ public CategoryPlot() { this(null, null, null, null); } /** * Creates a new plot. * * @param dataset the dataset (<code>null</code> permitted). * @param domainAxis the domain axis (<code>null</code> permitted). * @param rangeAxis the range axis (<code>null</code> permitted). * @param renderer the item renderer (<code>null</code> permitted). * */ public CategoryPlot(CategoryDataset dataset, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryItemRenderer renderer) { super(); this.orientation = PlotOrientation.VERTICAL; // allocate storage for dataset, axes and renderers this.domainAxes = new HashMap<Integer, CategoryAxis>(); this.domainAxisLocations = new HashMap<Integer, AxisLocation>(); this.rangeAxes = new HashMap<Integer, ValueAxis>(); this.rangeAxisLocations = new HashMap<Integer, AxisLocation>(); this.datasetToDomainAxesMap = new TreeMap<Integer, List<Integer>>(); this.datasetToRangeAxesMap = new TreeMap<Integer, List<Integer>>(); this.renderers = new HashMap<Integer, CategoryItemRenderer>(); this.datasets = new HashMap<Integer, CategoryDataset>(); this.datasets.put(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.axisOffset = RectangleInsets.ZERO_INSETS; this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); this.rangeAxisLocations.put(0, AxisLocation.TOP_OR_LEFT); this.renderers.put(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.domainAxes.put(0, domainAxis); this.mapDatasetToDomainAxis(0, 0); if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.drawSharedDomainAxis = false; this.rangeAxes.put(0, rangeAxis); this.mapDatasetToRangeAxis(0, 0); if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); this.domainGridlinesVisible = DEFAULT_DOMAIN_GRIDLINES_VISIBLE; this.domainGridlinePosition = CategoryAnchor.MIDDLE; this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeZeroBaselineVisible = false; this.rangeZeroBaselinePaint = Color.BLACK; this.rangeZeroBaselineStroke = new BasicStroke(0.5f); this.rangeGridlinesVisible = DEFAULT_RANGE_GRIDLINES_VISIBLE; this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeMinorGridlinesVisible = false; this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeMinorGridlinePaint = Color.WHITE; this.foregroundDomainMarkers = new HashMap<Integer, Collection<Marker>>(); this.backgroundDomainMarkers = new HashMap<Integer, Collection<Marker>>(); this.foregroundRangeMarkers = new HashMap<Integer, Collection<Marker>>(); this.backgroundRangeMarkers = new HashMap<Integer, Collection<Marker>>(); this.anchorValue = 0.0; this.domainCrosshairVisible = false; this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.rangeCrosshairVisible = DEFAULT_CROSSHAIR_VISIBLE; this.rangeCrosshairValue = 0.0; this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.annotations = new java.util.ArrayList<CategoryAnnotation>(); this.rangePannable = false; this.shadowGenerator = null; } /** * Returns a string describing the type of plot. * * @return The type. */ @Override public String getPlotType() { return localizationResources.getString("Category_Plot"); } /** * Returns the orientation of the plot. * * @return The orientation of the plot (never <code>null</code>). * * @see #setOrientation(PlotOrientation) */ @Override public PlotOrientation getOrientation() { return this.orientation; } /** * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param orientation the orientation (<code>null</code> not permitted). * * @see #getOrientation() */ public void setOrientation(PlotOrientation orientation) { ParamChecks.nullNotPermitted(orientation, "orientation"); this.orientation = orientation; fireChangeEvent(); } /** * Returns the axis offset. * * @return The axis offset (never <code>null</code>). * * @see #setAxisOffset(RectangleInsets) */ public RectangleInsets getAxisOffset() { return this.axisOffset; } /** * Sets the axis offsets (gap between the data area and the axes) and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param offset the offset (<code>null</code> not permitted). * * @see #getAxisOffset() */ public void setAxisOffset(RectangleInsets offset) { ParamChecks.nullNotPermitted(offset, "offset"); this.axisOffset = offset; fireChangeEvent(); } /** * Returns the domain axis for the plot. If the domain axis for this plot * is <code>null</code>, then the method will return the parent plot's * domain axis (if there is a parent plot). * * @return The domain axis (<code>null</code> permitted). * * @see #setDomainAxis(CategoryAxis) */ public CategoryAxis getDomainAxis() { return getDomainAxis(0); } /** * Returns a domain axis. * * @param index the axis index. * * @return The axis (<code>null</code> possible). * * @see #setDomainAxis(int, CategoryAxis) */ public CategoryAxis getDomainAxis(int index) { CategoryAxis result = this.domainAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot cp = (CategoryPlot) parent; result = cp.getDomainAxis(index); } } return result; } /** * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis (<code>null</code> permitted). * * @see #getDomainAxis() */ public void setDomainAxis(CategoryAxis axis) { setDomainAxis(0, axis); } /** * Sets a domain axis and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * * @see #getDomainAxis(int) */ public void setDomainAxis(int index, CategoryAxis axis) { setDomainAxis(index, axis, true); } /** * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * @param notify notify listeners? */ public void setDomainAxis(int index, CategoryAxis axis, boolean notify) { CategoryAxis existing = this.domainAxes.get(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.domainAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the domain axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes (<code>null</code> not permitted). * * @see #setRangeAxes(ValueAxis[]) */ public void setDomainAxes(CategoryAxis[] axes) { for (int i = 0; i < axes.length; i++) { setDomainAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the index of the specified axis, or <code>-1</code> if the axis * is not assigned to the plot. * * @param axis the axis (<code>null</code> not permitted). * * @return The axis index. * * @see #getDomainAxis(int) * @see #getRangeAxisIndex(ValueAxis) * * @since 1.0.3 */ public int getDomainAxisIndex(CategoryAxis axis) { ParamChecks.nullNotPermitted(axis, "axis"); for (Map.Entry<Integer, CategoryAxis> entry : this.domainAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the domain axis location for the primary domain axis. * * @return The location (never <code>null</code>). * * @see #getRangeAxisLocation() */ public AxisLocation getDomainAxisLocation() { return getDomainAxisLocation(0); } /** * Returns the location for a domain axis. * * @param index the axis index. * * @return The location. * * @see #setDomainAxisLocation(int, AxisLocation) */ public AxisLocation getDomainAxisLocation(int index) { AxisLocation result = this.domainAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getDomainAxisLocation(0)); } return result; } /** * Sets the location of the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param location the axis location (<code>null</code> not permitted). * * @see #getDomainAxisLocation() * @see #setDomainAxisLocation(int, AxisLocation) */ public void setDomainAxisLocation(AxisLocation location) { // delegate... setDomainAxisLocation(0, location, true); } /** * Sets the location of the domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the axis location (<code>null</code> not permitted). * @param notify a flag that controls whether listeners are notified. */ public void setDomainAxisLocation(AxisLocation location, boolean notify) { // delegate... setDomainAxisLocation(0, location, notify); } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation) */ public void setDomainAxisLocation(int index, AxisLocation location) { // delegate... setDomainAxisLocation(index, location, true); } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * @param notify notify listeners? * * @since 1.0.5 * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setDomainAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.domainAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the domain axis edge. This is derived from the axis location * and the plot orientation. * * @return The edge (never <code>null</code>). */ public RectangleEdge getDomainAxisEdge() { return getDomainAxisEdge(0); } /** * Returns the edge for a domain axis. * * @param index the axis index. * * @return The edge (never <code>null</code>). */ public RectangleEdge getDomainAxisEdge(int index) { RectangleEdge result; AxisLocation location = getDomainAxisLocation(index); if (location != null) { result = Plot.resolveDomainAxisLocation(location, this.orientation); } else { result = RectangleEdge.opposite(getDomainAxisEdge(0)); } return result; } /** * Returns the number of domain axes. * * @return The axis count. */ public int getDomainAxisCount() { return this.domainAxes.size(); } /** * Clears the domain axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. */ public void clearDomainAxes() { for (CategoryAxis axis : this.domainAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.domainAxes.clear(); fireChangeEvent(); } /** * Configures the domain axes. */ public void configureDomainAxes() { for (CategoryAxis axis : this.domainAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the range axis for the plot. If the range axis for this plot is * null, then the method will return the parent plot's range axis (if there * is a parent plot). * * @return The range axis (possibly <code>null</code>). */ public ValueAxis getRangeAxis() { return getRangeAxis(0); } /** * Returns a range axis. * * @param index the axis index. * * @return The axis (<code>null</code> possible). */ public ValueAxis getRangeAxis(int index) { ValueAxis result = this.rangeAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot cp = (CategoryPlot) parent; result = cp.getRangeAxis(index); } } return result; } /** * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis (<code>null</code> permitted). */ public void setRangeAxis(ValueAxis axis) { setRangeAxis(0, axis); } /** * Sets a range axis and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param index the axis index. * @param axis the axis. */ public void setRangeAxis(int index, ValueAxis axis) { setRangeAxis(index, axis, true); } /** * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis. * @param notify notify listeners? */ public void setRangeAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = this.rangeAxes.get(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.rangeAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the range axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes (<code>null</code> not permitted). * * @see #setDomainAxes(CategoryAxis[]) */ public void setRangeAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setRangeAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the index of the specified axis, or <code>-1</code> if the axis * is not assigned to the plot. * * @param axis the axis (<code>null</code> not permitted). * * @return The axis index. * * @see #getRangeAxis(int) * @see #getDomainAxisIndex(CategoryAxis) * * @since 1.0.7 */ public int getRangeAxisIndex(ValueAxis axis) { ParamChecks.nullNotPermitted(axis, "axis"); int result = findRangeAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) parent; result = p.getRangeAxisIndex(axis); } } return result; } private int findRangeAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the range axis location. * * @return The location (never <code>null</code>). */ public AxisLocation getRangeAxisLocation() { return getRangeAxisLocation(0); } /** * Returns the location for a range axis. * * @param index the axis index. * * @return The location. * * @see #setRangeAxisLocation(int, AxisLocation) */ public AxisLocation getRangeAxisLocation(int index) { AxisLocation result = this.rangeAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getRangeAxisLocation(0)); } return result; } /** * Sets the location of the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param location the location (<code>null</code> not permitted). * * @see #setRangeAxisLocation(AxisLocation, boolean) * @see #setDomainAxisLocation(AxisLocation) */ public void setRangeAxisLocation(AxisLocation location) { // defer argument checking... setRangeAxisLocation(location, true); } /** * Sets the location of the range axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location (<code>null</code> not permitted). * @param notify notify listeners? * * @see #setDomainAxisLocation(AxisLocation, boolean) */ public void setRangeAxisLocation(AxisLocation location, boolean notify) { setRangeAxisLocation(0, location, notify); } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * * @see #getRangeAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location) { setRangeAxisLocation(index, location, true); } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * @param notify notify listeners? * * @see #getRangeAxisLocation(int) * @see #setDomainAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.rangeAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge where the primary range axis is located. * * @return The edge (never <code>null</code>). */ public RectangleEdge getRangeAxisEdge() { return getRangeAxisEdge(0); } /** * Returns the edge for a range axis. * * @param index the axis index. * * @return The edge. */ public RectangleEdge getRangeAxisEdge(int index) { AxisLocation location = getRangeAxisLocation(index); return Plot.resolveRangeAxisLocation(location, this.orientation); } /** * Returns the number of range axes. * * @return The axis count. */ public int getRangeAxisCount() { return this.rangeAxes.size(); } /** * Clears the range axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. */ public void clearRangeAxes() { for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.rangeAxes.clear(); fireChangeEvent(); } /** * Configures the range axes. */ public void configureRangeAxes() { for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly <code>null</code>). * * @see #setDataset(CategoryDataset) */ public CategoryDataset getDataset() { return getDataset(0); } /** * Returns the dataset with the given index, or {@code null} if there is * no dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The dataset (possibly {@code null}). * * @see #setDataset(int, CategoryDataset) */ public CategoryDataset getDataset(int index) { return this.datasets.get(index); } /** * Sets the dataset for the plot, replacing the existing dataset, if there * is one. This method also calls the * {@link #datasetChanged(DatasetChangeEvent)} method, which adjusts the * axis ranges if necessary and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(CategoryDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot and sends a change notification to all * registered listeners. * * @param index the dataset index (must be &gt;= 0). * @param dataset the dataset ({@code null} permitted). * * @see #getDataset(int) */ public void setDataset(int index, CategoryDataset dataset) { CategoryDataset existing = this.datasets.get(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.put(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. * * @since 1.0.2 */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or <code>-1</code> if the * dataset does not belong to the plot. * * @param dataset the dataset ({@code null} not permitted). * * @return The index. * * @since 1.0.11 */ public int findDatasetIndex(CategoryDataset dataset) { for (Map.Entry<Integer, CategoryDataset> entry: this.datasets.entrySet()) { if (dataset == entry.getValue()) { return entry.getKey(); } } return -1; } /** * Maps a dataset to a particular domain axis. * * @param index the dataset index (zero-based). * @param axisIndex the axis index (zero-based). * * @see #getDomainAxisForDataset(int) */ public void mapDatasetToDomainAxis(int index, int axisIndex) { List<Integer> axisIndices = new java.util.ArrayList<Integer>(1); axisIndices.add(axisIndex); mapDatasetToDomainAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices (<code>null</code> permitted). * * @since 1.0.12 */ public void mapDatasetToDomainAxes(int index, List<Integer> axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); this.datasetToDomainAxesMap.put(index, new ArrayList<Integer>( axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToDomainAxes() and * mapDatasetToRangeAxes(). * * @param indices the list of indices (<code>null</code> permitted). */ private void checkAxisIndices(List<Integer> indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } HashSet<Integer> set = new HashSet<Integer>(); for (Integer item : indices) { if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the domain axis for a dataset. You can change the axis for a * dataset using the {@link #mapDatasetToDomainAxis(int, int)} method. * * @param index the dataset index. * * @return The domain axis. * * @see #mapDatasetToDomainAxis(int, int) */ public CategoryAxis getDomainAxisForDataset(int index) { if (index < 0) { throw new IllegalArgumentException("Negative 'index'."); } CategoryAxis axis; List<Integer> axisIndices = this.datasetToDomainAxesMap.get( Integer.valueOf(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = axisIndices.get(0); axis = getDomainAxis(axisIndex); } else { axis = getDomainAxis(0); } return axis; } /** * Maps a dataset to a particular range axis. * * @param index the dataset index (zero-based). * @param axisIndex the axis index (zero-based). * * @see #getRangeAxisForDataset(int) */ public void mapDatasetToRangeAxis(int index, int axisIndex) { List<Integer> axisIndices = new java.util.ArrayList<Integer>(1); axisIndices.add(axisIndex); mapDatasetToRangeAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices (<code>null</code> permitted). * * @since 1.0.12 */ public void mapDatasetToRangeAxes(int index, List<Integer> axisIndices) { if (index < 0) { throw new IllegalArgumentException("Requires 'index' >= 0."); } checkAxisIndices(axisIndices); Integer key = index; this.datasetToRangeAxesMap.put(key, new ArrayList<Integer>(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * Returns the range axis for a dataset. You can change the axis for a * dataset using the {@link #mapDatasetToRangeAxis(int, int)} method. * * @param index the dataset index. * * @return The range axis. * * @see #mapDatasetToRangeAxis(int, int) */ public ValueAxis getRangeAxisForDataset(int index) { if (index < 0) { throw new IllegalArgumentException("Negative 'index'."); } ValueAxis axis; List<Integer> axisIndices = this.datasetToRangeAxesMap.get( Integer.valueOf(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = axisIndices.get(0); axis = getRangeAxis(axisIndex); } else { axis = getRangeAxis(0); } return axis; } /** * Returns the number of renderer slots for this plot. * * @return The number of renderer slots. * * @since 1.0.11 */ public int getRendererCount() { return this.renderers.size(); } /** * Returns a reference to the renderer for the plot. * * @return The renderer. * * @see #setRenderer(CategoryItemRenderer) */ public CategoryItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer at the given index. * * @param index the renderer index. * * @return The renderer (possibly {@code null}). * * @see #setRenderer(int, CategoryItemRenderer) */ public CategoryItemRenderer getRenderer(int index) { return this.renderers.get(index); } /** * Sets the renderer at index 0 (sometimes referred to as the "primary" * renderer) and sends a change event to all registered listeners. * * @param renderer the renderer (<code>null</code> permitted. * * @see #getRenderer() */ public void setRenderer(CategoryItemRenderer renderer) { setRenderer(0, renderer, true); } /** * Sets the renderer at index 0 (sometimes referred to as the "primary" * renderer) and, if requested, sends a change event to all registered * listeners. * <p> * You can set the renderer to <code>null</code>, but this is not * recommended because: * <ul> * <li>no data will be displayed;</li> * <li>the plot background will not be painted;</li> * </ul> * * @param renderer the renderer (<code>null</code> permitted). * @param notify notify listeners? * * @see #getRenderer() */ public void setRenderer(CategoryItemRenderer renderer, boolean notify) { setRenderer(0, renderer, notify); } /** * Sets the renderer to use for the dataset with the specified index and * sends a change event to all registered listeners. Note that each * dataset should have its own renderer, you should not use one renderer * for multiple datasets. * * @param index the index. * @param renderer the renderer (<code>null</code> permitted). * * @see #getRenderer(int) * @see #setRenderer(int, CategoryItemRenderer, boolean) */ public void setRenderer(int index, CategoryItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets the renderer to use for the dataset with the specified index and, * if requested, sends a change event to all registered listeners. Note * that each dataset should have its own renderer, you should not use one * renderer for multiple datasets. * * @param index the index. * @param renderer the renderer (<code>null</code> permitted). * @param notify notify listeners? * * @see #getRenderer(int) */ public void setRenderer(int index, CategoryItemRenderer renderer, boolean notify) { CategoryItemRenderer existing = this.renderers.get(index); if (existing != null) { existing.removeChangeListener(this); } this.renderers.put(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); if (notify) { fireChangeEvent(); } } /** * Sets the renderers for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param renderers the renderers. */ public void setRenderers(CategoryItemRenderer[] renderers) { for (int i = 0; i < renderers.length; i++) { setRenderer(i, renderers[i], false); } fireChangeEvent(); } /** * Returns the renderer for the specified dataset. If the dataset doesn't * belong to the plot, this method will return {@code null}. * * @param dataset the dataset ({@code null} permitted). * * @return The renderer (possibly {@code null}). */ public CategoryItemRenderer getRendererForDataset(CategoryDataset dataset) { int datasetIndex = findDatasetIndex(dataset); if (datasetIndex < 0) { return null; } CategoryItemRenderer renderer = this.renderers.get(datasetIndex); if (renderer == null) { return getRenderer(); } return renderer; } /** * Returns the index of the specified renderer, or <code>-1</code> if the * renderer is not assigned to this plot. * * @param renderer the renderer (<code>null</code> permitted). * * @return The renderer index. */ public int findRendererIndex(CategoryItemRenderer renderer) { for (Map.Entry<Integer, CategoryItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() == renderer) { return entry.getKey(); } } return -1; } /** * Returns the dataset rendering order. * * @return The order (never <code>null</code>). * * @see #setDatasetRenderingOrder(DatasetRenderingOrder) */ public DatasetRenderingOrder getDatasetRenderingOrder() { return this.renderingOrder; } /** * Sets the rendering order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary dataset * last (so that the primary dataset overlays the secondary datasets). You * can reverse this if you want to. * * @param order the rendering order (<code>null</code> not permitted). * * @see #getDatasetRenderingOrder() */ public void setDatasetRenderingOrder(DatasetRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.renderingOrder = order; fireChangeEvent(); } /** * Returns the order in which the columns are rendered. The default value * is <code>SortOrder.ASCENDING</code>. * * @return The column rendering order (never <code>null</code>). * * @see #setColumnRenderingOrder(SortOrder) */ public SortOrder getColumnRenderingOrder() { return this.columnRenderingOrder; } /** * Sets the column order in which the items in each dataset should be * rendered and sends a {@link PlotChangeEvent} to all registered * listeners. Note that this affects the order in which items are drawn, * NOT their position in the chart. * * @param order the order (<code>null</code> not permitted). * * @see #getColumnRenderingOrder() * @see #setRowRenderingOrder(SortOrder) */ public void setColumnRenderingOrder(SortOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.columnRenderingOrder = order; fireChangeEvent(); } /** * Returns the order in which the rows should be rendered. The default * value is <code>SortOrder.ASCENDING</code>. * * @return The order (never <code>null</code>). * * @see #setRowRenderingOrder(SortOrder) */ public SortOrder getRowRenderingOrder() { return this.rowRenderingOrder; } /** * Sets the row order in which the items in each dataset should be * rendered and sends a {@link PlotChangeEvent} to all registered * listeners. Note that this affects the order in which items are drawn, * NOT their position in the chart. * * @param order the order (<code>null</code> not permitted). * * @see #getRowRenderingOrder() * @see #setColumnRenderingOrder(SortOrder) */ public void setRowRenderingOrder(SortOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.rowRenderingOrder = order; fireChangeEvent(); } /** * Returns the flag that controls whether the domain grid-lines are visible. * * @return The <code>true</code> or <code>false</code>. * * @see #setDomainGridlinesVisible(boolean) */ public boolean isDomainGridlinesVisible() { return this.domainGridlinesVisible; } /** * Sets the flag that controls whether or not grid-lines are drawn against * the domain axis. * <p> * If the flag value changes, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainGridlinesVisible() */ public void setDomainGridlinesVisible(boolean visible) { if (this.domainGridlinesVisible != visible) { this.domainGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the position used for the domain gridlines. * * @return The gridline position (never <code>null</code>). * * @see #setDomainGridlinePosition(CategoryAnchor) */ public CategoryAnchor getDomainGridlinePosition() { return this.domainGridlinePosition; } /** * Sets the position used for the domain gridlines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param position the position (<code>null</code> not permitted). * * @see #getDomainGridlinePosition() */ public void setDomainGridlinePosition(CategoryAnchor position) { ParamChecks.nullNotPermitted(position, "position"); this.domainGridlinePosition = position; fireChangeEvent(); } /** * Returns the stroke used to draw grid-lines against the domain axis. * * @return The stroke (never <code>null</code>). * * @see #setDomainGridlineStroke(Stroke) */ public Stroke getDomainGridlineStroke() { return this.domainGridlineStroke; } /** * Sets the stroke used to draw grid-lines against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getDomainGridlineStroke() */ public void setDomainGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw grid-lines against the domain axis. * * @return The paint (never <code>null</code>). * * @see #setDomainGridlinePaint(Paint) */ public Paint getDomainGridlinePaint() { return this.domainGridlinePaint; } /** * Sets the paint used to draw the grid-lines (if any) against the domain * axis and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getDomainGridlinePaint() */ public void setDomainGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainGridlinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the range axis. * * @return A boolean. * * @see #setRangeZeroBaselineVisible(boolean) * * @since 1.0.13 */ public boolean isRangeZeroBaselineVisible() { return this.rangeZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the range axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @see #isRangeZeroBaselineVisible() * * @since 1.0.13 */ public void setRangeZeroBaselineVisible(boolean visible) { this.rangeZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeZeroBaselineStroke(Stroke) * * @since 1.0.13 */ public Stroke getRangeZeroBaselineStroke() { return this.rangeZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeZeroBaselineStroke() * * @since 1.0.13 */ public void setRangeZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeZeroBaselinePaint(Paint) * * @since 1.0.13 */ public Paint getRangeZeroBaselinePaint() { return this.rangeZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeZeroBaselinePaint() * * @since 1.0.13 */ public void setRangeZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether the range grid-lines are visible. * * @return The flag. * * @see #setRangeGridlinesVisible(boolean) */ public boolean isRangeGridlinesVisible() { return this.rangeGridlinesVisible; } /** * Sets the flag that controls whether or not grid-lines are drawn against * the range axis. If the flag changes value, a {@link PlotChangeEvent} is * sent to all registered listeners. * * @param visible the new value of the flag. * * @see #isRangeGridlinesVisible() */ public void setRangeGridlinesVisible(boolean visible) { if (this.rangeGridlinesVisible != visible) { this.rangeGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke used to draw the grid-lines against the range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeGridlineStroke(Stroke) */ public Stroke getRangeGridlineStroke() { return this.rangeGridlineStroke; } /** * Sets the stroke used to draw the grid-lines against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeGridlineStroke() */ public void setRangeGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw the grid-lines against the range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeGridlinePaint(Paint) */ public Paint getRangeGridlinePaint() { return this.rangeGridlinePaint; } /** * Sets the paint used to draw the grid lines against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeGridlinePaint() */ public void setRangeGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeGridlinePaint = paint; fireChangeEvent(); } /** * Returns <code>true</code> if the range axis minor grid is visible, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setRangeMinorGridlinesVisible(boolean) * * @since 1.0.13 */ public boolean isRangeMinorGridlinesVisible() { return this.rangeMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis minor grid * lines are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeMinorGridlinesVisible() * * @since 1.0.13 */ public void setRangeMinorGridlinesVisible(boolean visible) { if (this.rangeMinorGridlinesVisible != visible) { this.rangeMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the minor grid lines (if any) plotted against the * range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeMinorGridlineStroke(Stroke) * * @since 1.0.13 */ public Stroke getRangeMinorGridlineStroke() { return this.rangeMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeMinorGridlineStroke() * * @since 1.0.13 */ public void setRangeMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeMinorGridlinePaint(Paint) * * @since 1.0.13 */ public Paint getRangeMinorGridlinePaint() { return this.rangeMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the range axis * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeMinorGridlinePaint() * * @since 1.0.13 */ public void setRangeMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly <code>null</code>). * * @see #setFixedLegendItems(List<LegendItem>) */ public List<LegendItem> getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * <code>null</code> if you prefer the legend items to be created * automatically. * * @param items the legend items (<code>null</code> permitted). * * @see #getFixedLegendItems() */ public void setFixedLegendItems(List<LegendItem> items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Returns the legend items for the plot. By default, this method creates * a legend item for each series in each of the datasets. You can change * this behaviour by overriding this method. * * @return The legend items. */ @Override public List<LegendItem> getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } List<LegendItem> result = new ArrayList<LegendItem>(); // get the legend items for the datasets... for (CategoryDataset dataset: this.datasets.values()) { if (dataset == null) { continue; } int datasetIndex = findDatasetIndex(dataset); CategoryItemRenderer renderer = getRenderer(datasetIndex); if (renderer != null) { result.addAll(renderer.getLegendItems()); } } return result; } /** * Handles a 'click' on the plot by updating the anchor value. * * @param x x-coordinate of the click (in Java2D space). * @param y y-coordinate of the click (in Java2D space). * @param info information about the plot's dimensions. * */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { Rectangle2D dataArea = info.getDataArea(); if (dataArea.contains(x, y)) { // set the anchor value for the range axis... double java2D = 0.0; if (this.orientation == PlotOrientation.HORIZONTAL) { java2D = x; } else if (this.orientation == PlotOrientation.VERTICAL) { java2D = y; } RectangleEdge edge = Plot.resolveRangeAxisLocation( getRangeAxisLocation(), this.orientation); double value = getRangeAxis().java2DToValue( java2D, info.getDataArea(), edge); setAnchorValue(value); setRangeCrosshairValue(value); } } /** * Zooms (in or out) on the plot's value axis. * <p> * If the value 0.0 is passed in as the zoom percent, the auto-range * calculation for the axis is restored (which sets the range to include * the minimum and maximum data values, thus displaying all the data). * * @param percent the zoom amount. */ @Override public void zoom(double percent) { if (percent > 0.0) { double range = getRangeAxis().getRange().getLength(); double scaledRange = range * percent; getRangeAxis().setRange(this.anchorValue - scaledRange / 2.0, this.anchorValue + scaledRange / 2.0); } else { getRangeAxis().setAutoRange(true); } } /** * Receives notification of a change to an {@link Annotation} added to * this plot. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { if (getParent() != null) { getParent().annotationChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Receives notification of a change to the plot's dataset. * <P> * The range axis bounds will be recalculated if necessary. * * @param event information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { yAxis.configure(); } } if (getParent() != null) { getParent().datasetChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); e.setType(ChartChangeEventType.DATASET_UPDATED); notifyListeners(e); } } /** * Receives notification of a renderer change event. * * @param event the event. */ @Override public void rendererChanged(RendererChangeEvent event) { Plot parent = getParent(); if (parent != null) { if (parent instanceof RendererChangeListener) { RendererChangeListener rcl = (RendererChangeListener) parent; rcl.rendererChanged(event); } else { // this should never happen with the existing code, but throw // an exception in case future changes make it possible... throw new RuntimeException( "The renderer has changed and I don't know what to do!"); } } else { configureRangeAxes(); PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Adds a marker for display (in the foreground) against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. Typically a * marker will be drawn by the renderer as a line perpendicular to the * domain axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * * @see #removeDomainMarker(Marker) */ public void addDomainMarker(CategoryMarker marker) { addDomainMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for display against the domain axis and sends a * {@link PlotChangeEvent} to all registered listeners. Typically a marker * will be drawn by the renderer as a line perpendicular to the domain * axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background) (<code>null</code> * not permitted). * * @see #removeDomainMarker(Marker, Layer) */ public void addDomainMarker(CategoryMarker marker, Layer layer) { addDomainMarker(0, marker, layer); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a domain axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (<code>null</code> not permitted). * * @see #removeDomainMarker(int, Marker, Layer) */ public void addDomainMarker(int index, CategoryMarker marker, Layer layer) { addDomainMarker(index, marker, layer, true); } /** * Adds a marker for display by a particular renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a domain axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.10 * * @see #removeDomainMarker(int, Marker, Layer, boolean) */ public void addDomainMarker(int index, CategoryMarker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundDomainMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.foregroundDomainMarkers.put(index, markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = this.backgroundDomainMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.backgroundDomainMarkers.put(index, markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears all the domain markers for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #clearRangeMarkers() */ public void clearDomainMarkers() { if (this.backgroundDomainMarkers != null) { Set<Integer> keys = this.backgroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.backgroundDomainMarkers.clear(); } if (this.foregroundDomainMarkers != null) { Set<Integer> keys = this.foregroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.foregroundDomainMarkers.clear(); } fireChangeEvent(); } /** * Returns the list of domain markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of domain markers. */ public Collection<Marker> getDomainMarkers(Layer layer) { return getDomainMarkers(0, layer); } /** * Returns a collection of domain markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly <code>null</code>). */ public Collection<Marker> getDomainMarkers(int index, Layer layer) { Collection<Marker> result = null; if (layer == Layer.FOREGROUND) { result = this.foregroundDomainMarkers.get(index); } else if (layer == Layer.BACKGROUND) { result = this.backgroundDomainMarkers.get(index); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Clears all the domain markers for the specified renderer. * * @param index the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { if (this.backgroundDomainMarkers != null) { Collection<Marker> markers = this.backgroundDomainMarkers.get(index); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundDomainMarkers != null) { Collection<Marker> markers = this.foregroundDomainMarkers.get(index); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker) { return removeDomainMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker, Layer layer) { return removeDomainMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer) { return removeDomainMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) { Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundDomainMarkers.get(index); } else { markers = this.backgroundDomainMarkers.get(index); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds a marker for display (in the foreground) against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. Typically a * marker will be drawn by the renderer as a line perpendicular to the * range axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * * @see #removeRangeMarker(Marker) */ public void addRangeMarker(Marker marker) { addRangeMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for display against the range axis and sends a * {@link PlotChangeEvent} to all registered listeners. Typically a marker * will be drawn by the renderer as a line perpendicular to the range axis, * however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background) (<code>null</code> * not permitted). * * @see #removeRangeMarker(Marker, Layer) */ public void addRangeMarker(Marker marker, Layer layer) { addRangeMarker(0, marker, layer); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a range axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker. * @param layer the layer. * * @see #removeRangeMarker(int, Marker, Layer) */ public void addRangeMarker(int index, Marker marker, Layer layer) { addRangeMarker(index, marker, layer, true); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a range axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker. * @param layer the layer. * @param notify notify listeners? * * @since 1.0.10 * * @see #removeRangeMarker(int, Marker, Layer, boolean) */ public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify) { Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundRangeMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.foregroundRangeMarkers.put(index, markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = this.backgroundRangeMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.backgroundRangeMarkers.put(index, markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears all the range markers for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #clearDomainMarkers() */ public void clearRangeMarkers() { if (this.backgroundRangeMarkers != null) { Set<Integer> keys = this.backgroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.backgroundRangeMarkers.clear(); } if (this.foregroundRangeMarkers != null) { Set<Integer> keys = this.foregroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.foregroundRangeMarkers.clear(); } fireChangeEvent(); } /** * Returns the list of range markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of range markers. * * @see #getRangeMarkers(int, Layer) */ public Collection<Marker> getRangeMarkers(Layer layer) { return getRangeMarkers(0, layer); } /** * Returns a collection of range markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly <code>null</code>). */ public Collection<Marker> getRangeMarkers(int index, Layer layer) { Collection<Marker> result = null; Integer key = index; if (layer == Layer.FOREGROUND) { result = this.foregroundRangeMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = this.backgroundRangeMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Clears all the range markers for the specified renderer. * * @param index the renderer index. * * @see #clearDomainMarkers(int) */ public void clearRangeMarkers(int index) { Integer key = index; if (this.backgroundRangeMarkers != null) { Collection<Marker> markers = this.backgroundRangeMarkers.get(key); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection<Marker> markers = this.foregroundRangeMarkers.get(key); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(Marker) */ public boolean removeRangeMarker(Marker marker) { return removeRangeMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(Marker, Layer) */ public boolean removeRangeMarker(Marker marker, Layer layer) { return removeRangeMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(int, Marker, Layer) */ public boolean removeRangeMarker(int index, Marker marker, Layer layer) { return removeRangeMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 * * @see #addRangeMarker(int, Marker, Layer, boolean) */ public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundRangeMarkers.get(index); } else { markers = this.backgroundRangeMarkers.get(index); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Returns the flag that controls whether or not the domain crosshair is * displayed by the plot. * * @return A boolean. * * @since 1.0.11 * * @see #setDomainCrosshairVisible(boolean) */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag that controls whether or not the domain crosshair is * displayed by the plot, and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the new flag value. * * @since 1.0.11 * * @see #isDomainCrosshairVisible() * @see #setRangeCrosshairVisible(boolean) */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns the row key for the domain crosshair. * * @return The row key. * * @since 1.0.11 */ public Comparable getDomainCrosshairRowKey() { return this.domainCrosshairRowKey; } /** * Sets the row key for the domain crosshair and sends a * {PlotChangeEvent} to all registered listeners. * * @param key the key. * * @since 1.0.11 */ public void setDomainCrosshairRowKey(Comparable key) { setDomainCrosshairRowKey(key, true); } /** * Sets the row key for the domain crosshair and, if requested, sends a * {PlotChangeEvent} to all registered listeners. * * @param key the key. * @param notify notify listeners? * * @since 1.0.11 */ public void setDomainCrosshairRowKey(Comparable key, boolean notify) { this.domainCrosshairRowKey = key; if (notify) { fireChangeEvent(); } } /** * Returns the column key for the domain crosshair. * * @return The column key. * * @since 1.0.11 */ public Comparable getDomainCrosshairColumnKey() { return this.domainCrosshairColumnKey; } /** * Sets the column key for the domain crosshair and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param key the key. * * @since 1.0.11 */ public void setDomainCrosshairColumnKey(Comparable key) { setDomainCrosshairColumnKey(key, true); } /** * Sets the column key for the domain crosshair and, if requested, sends * a {@link PlotChangeEvent} to all registered listeners. * * @param key the key. * @param notify notify listeners? * * @since 1.0.11 */ public void setDomainCrosshairColumnKey(Comparable key, boolean notify) { this.domainCrosshairColumnKey = key; if (notify) { fireChangeEvent(); } } /** * Returns the dataset index for the crosshair. * * @return The dataset index. * * @since 1.0.11 */ public int getCrosshairDatasetIndex() { return this.crosshairDatasetIndex; } /** * Sets the dataset index for the crosshair and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. * * @since 1.0.11 */ public void setCrosshairDatasetIndex(int index) { setCrosshairDatasetIndex(index, true); } /** * Sets the dataset index for the crosshair and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. * @param notify notify listeners? * * @since 1.0.11 */ public void setCrosshairDatasetIndex(int index, boolean notify) { this.crosshairDatasetIndex = index; if (notify) { fireChangeEvent(); } } /** * Returns the paint used to draw the domain crosshair. * * @return The paint (never <code>null</code>). * * @since 1.0.11 * * @see #setDomainCrosshairPaint(Paint) * @see #getDomainCrosshairStroke() */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the paint used to draw the domain crosshair. * * @param paint the paint (<code>null</code> not permitted). * * @since 1.0.11 * * @see #getDomainCrosshairPaint() */ public void setDomainCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the domain crosshair. * * @return The stroke (never <code>null</code>). * * @since 1.0.11 * * @see #setDomainCrosshairStroke(Stroke) * @see #getDomainCrosshairPaint() */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the stroke used to draw the domain crosshair, and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @since 1.0.11 * * @see #getDomainCrosshairStroke() */ public void setDomainCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainCrosshairStroke = stroke; } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. * * @see #setRangeCrosshairVisible(boolean) */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * * @param flag the new value of the flag. * * @see #isRangeCrosshairVisible() */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setRangeCrosshairLockedOnData(boolean) */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values, and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param flag the flag. * * @see #isRangeCrosshairLockedOnData() */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. * * @see #setRangeCrosshairValue(double) */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the range crosshair value and, if the crosshair is visible, sends * a {@link PlotChangeEvent} to all registered listeners. * * @param value the new value. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners (but only if the * crosshair is visible). * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the pen-style (<code>Stroke</code>) used to draw the crosshair * (if visible). * * @return The crosshair stroke (never <code>null</code>). * * @see #setRangeCrosshairStroke(Stroke) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairPaint() */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the pen-style (<code>Stroke</code>) used to draw the range * crosshair (if visible), and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param stroke the new crosshair stroke (<code>null</code> not * permitted). * * @see #getRangeCrosshairStroke() */ public void setRangeCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw the range crosshair. * * @return The paint (never <code>null</code>). * * @see #setRangeCrosshairPaint(Paint) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairStroke() */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the paint used to draw the range crosshair (if visible) and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeCrosshairPaint() */ public void setRangeCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the list of annotations. * * @return The list of annotations (never <code>null</code>). * * @see #addAnnotation(CategoryAnnotation) * @see #clearAnnotations() */ public List<CategoryAnnotation> getAnnotations() { return this.annotations; } /** * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * * @see #removeAnnotation(CategoryAnnotation) */ public void addAnnotation(CategoryAnnotation annotation) { addAnnotation(annotation, true); } /** * Adds an annotation to the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.10 */ public void addAnnotation(CategoryAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); this.annotations.add(annotation); annotation.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * * @return A boolean (indicates whether or not the annotation was removed). * * @see #addAnnotation(CategoryAnnotation) */ public boolean removeAnnotation(CategoryAnnotation annotation) { return removeAnnotation(annotation, true); } /** * Removes an annotation from the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * @param notify notify listeners? * * @return A boolean (indicates whether or not the annotation was removed). * * @since 1.0.10 */ public boolean removeAnnotation(CategoryAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); boolean removed = this.annotations.remove(annotation); annotation.removeChangeListener(this); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Clears all the annotations and sends a {@link PlotChangeEvent} to all * registered listeners. */ public void clearAnnotations() { for (CategoryAnnotation annotation : this.annotations) { annotation.removeChangeListener(this); } this.annotations.clear(); fireChangeEvent(); } /** * Returns the shadow generator for the plot, if any. * * @return The shadow generator (possibly <code>null</code>). * * @since 1.0.14 */ public ShadowGenerator getShadowGenerator() { return this.shadowGenerator; } /** * Sets the shadow generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @since 1.0.14 */ public void setShadowGenerator(ShadowGenerator generator) { this.shadowGenerator = generator; fireChangeEvent(); } /** * Calculates the space required for the domain axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result (<code>null</code> permitted). * * @return The required space. */ protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the domain axis... if (this.fixedDomainAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(), RectangleEdge.RIGHT); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(), RectangleEdge.BOTTOM); } } else { // reserve space for the primary domain axis... RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( getDomainAxisLocation(), this.orientation); if (this.drawSharedDomainAxis) { space = getDomainAxis().reserveSpace(g2, this, plotArea, domainEdge, space); } // reserve space for any domain axes... for (CategoryAxis xAxis : this.domainAxes.values()) { if (xAxis != null) { int i = getDomainAxisIndex(xAxis); RectangleEdge edge = getDomainAxisEdge(i); space = xAxis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Calculates the space required for the range axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result (<code>null</code> permitted). * * @return The required space. */ protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the range axis... if (this.fixedRangeAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(), RectangleEdge.BOTTOM); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(), RectangleEdge.RIGHT); } } else { // reserve space for the range axes (if any)... for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { int i = findRangeAxisIndex(yAxis); RectangleEdge edge = getRangeAxisEdge(i); space = yAxis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Trims a rectangle to integer coordinates. * * @param rect the incoming rectangle. * * @return A rectangle with integer coordinates. */ private Rectangle integerise(Rectangle2D rect) { int x0 = (int) Math.ceil(rect.getMinX()); int y0 = (int) Math.ceil(rect.getMinY()); int x1 = (int) Math.floor(rect.getMaxX()); int y1 = (int) Math.floor(rect.getMaxY()); return new Rectangle(x0, y0, (x1 - x0), (y1 - y0)); } /** * Calculates the space required for the axes. * * @param g2 the graphics device. * @param plotArea the plot area. * * @return The space required for the axes. */ protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea) { AxisSpace space = new AxisSpace(); space = calculateRangeAxisSpace(g2, plotArea, space); space = calculateDomainAxisSpace(g2, plotArea, space); return space; } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * <P> * At your option, you may supply an instance of {@link PlotRenderingInfo}. * If you do, it will be populated with information about the drawing, * including various plot dimensions and tooltip info. * * @param g2 the graphics device. * @param area the area within which the plot (including axes) should * be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param state collects info as the chart is drawn (possibly * <code>null</code>). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo state) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (state == null) { // if the incoming state is null, no information will be passed // back to the caller - but we create a temporary state to record // the plot area, since that is used later by the axes state = new PlotRenderingInfo(null); } state.setPlotArea(area); // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); // calculate the data area... AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); dataArea = integerise(dataArea); if (dataArea.isEmpty()) { return; } state.setDataArea(dataArea); createAndAddEntity((Rectangle2D) dataArea.clone(), state, null, null); // if there is a renderer, it draws the background, otherwise use the // default background... if (getRenderer() != null) { getRenderer().drawBackground(g2, this, dataArea); } else { drawBackground(g2, dataArea); } Map<Axis, AxisState> axisStateMap = drawAxes(g2, area, dataArea, state); // the anchor point is typically the point where the mouse last // clicked - the crosshairs will be driven off this point... if (anchor != null && !dataArea.contains(anchor)) { anchor = ShapeUtils.getPointInRectangle(anchor.getX(), anchor.getY(), dataArea); } CategoryCrosshairState crosshairState = new CategoryCrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); // specify the anchor X and Y coordinates in Java2D space, for the // cases where these are not updated during rendering (i.e. no lock // on data) crosshairState.setAnchorX(Double.NaN); crosshairState.setAnchorY(Double.NaN); if (anchor != null) { ValueAxis rangeAxis = getRangeAxis(); if (rangeAxis != null) { double y; if (getOrientation() == PlotOrientation.VERTICAL) { y = rangeAxis.java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); } else { y = rangeAxis.java2DToValue(anchor.getX(), dataArea, getRangeAxisEdge()); } crosshairState.setAnchorY(y); } } crosshairState.setRowKey(getDomainCrosshairRowKey()); crosshairState.setColumnKey(getDomainCrosshairColumnKey()); crosshairState.setCrosshairY(getRangeCrosshairValue()); // don't let anyone draw outside the data area Shape savedClip = g2.getClip(); g2.clip(dataArea); drawDomainGridlines(g2, dataArea); AxisState rangeAxisState = axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = parentState.getSharedAxisStates() .get(getRangeAxis()); } } if (rangeAxisState != null) { drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } Graphics2D savedG2 = g2; BufferedImage dataImage = null; boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint( JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION)); if (this.shadowGenerator != null && !suppressShadow) { dataImage = new BufferedImage((int) dataArea.getWidth(), (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB); g2 = dataImage.createGraphics(); g2.translate(-dataArea.getX(), -dataArea.getY()); g2.setRenderingHints(savedG2.getRenderingHints()); } // draw the markers... for (CategoryItemRenderer renderer : this.renderers.values()) { int i = findRendererIndex(renderer); drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND); } for (CategoryItemRenderer renderer : this.renderers.values()) { int i = findRendererIndex(renderer); drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND); } // now render data items... boolean foundData = false; // set up the alpha-transparency... Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); DatasetRenderingOrder order = getDatasetRenderingOrder(); List<Integer> indices = this.getDatasetIndices(order); for (int i : indices) { foundData = render(g2, dataArea, i, state, crosshairState) || foundData; } // draw the foreground markers... List<Integer> rendererIndices = getRendererIndices(order); for (int i : rendererIndices) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i : rendererIndices) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } // draw the annotations (if any)... drawAnnotations(g2, dataArea); if (this.shadowGenerator != null && !suppressShadow) { BufferedImage shadowImage = this.shadowGenerator.createDropShadow( dataImage); g2 = savedG2; g2.drawImage(shadowImage, (int) dataArea.getX() + this.shadowGenerator.calculateOffsetX(), (int) dataArea.getY() + this.shadowGenerator.calculateOffsetY(), null); g2.drawImage(dataImage, (int) dataArea.getX(), (int) dataArea.getY(), null); } g2.setClip(savedClip); g2.setComposite(originalComposite); if (!foundData) { drawNoDataMessage(g2, dataArea); } int datasetIndex = crosshairState.getDatasetIndex(); setCrosshairDatasetIndex(datasetIndex, false); // draw domain crosshair if required... Comparable rowKey = crosshairState.getRowKey(); Comparable columnKey = crosshairState.getColumnKey(); setDomainCrosshairRowKey(rowKey, false); setDomainCrosshairColumnKey(columnKey, false); if (isDomainCrosshairVisible() && columnKey != null) { Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); drawDomainCrosshair(g2, dataArea, this.orientation, datasetIndex, rowKey, columnKey, stroke, paint); } // draw range crosshair if required... ValueAxis yAxis = getRangeAxisForDataset(datasetIndex); RectangleEdge yAxisEdge = getRangeAxisEdge(); if (!this.rangeCrosshairLockedOnData && anchor != null) { double yy; if (getOrientation() == PlotOrientation.VERTICAL) { yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge); } else { yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge); } crosshairState.setCrosshairY(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); drawRangeCrosshair(g2, dataArea, getOrientation(), y, yAxis, stroke, paint); } // draw the border around the chart drawOutline(g2, dataArea); } /** * Returns the indices of the non-null datasets in the specified order. * * @param order the order ({@code null} not permitted). * * @return The list of indices. */ private List<Integer> getDatasetIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Map.Entry<Integer, CategoryDataset> entry : this.datasets.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } /** * Returns the indices of the non-null renderers for the plot, in the * specified order. * * @param order the rendering order {@code null} not permitted). * * @return A list of indices. */ private List<Integer> getRendererIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Map.Entry<Integer, CategoryItemRenderer> entry: this.renderers.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } /** * Draws the plot background (the background color and/or image). * <P> * This method will be called during the chart drawing process and is * declared public so that it can be accessed by the renderers used by * certain subclasses. You shouldn't need to call this method directly. * * @param g2 the graphics device. * @param area the area within which the plot should be drawn. */ @Override public void drawBackground(Graphics2D g2, Rectangle2D area) { if (getBackgroundPainter() != null) { getBackgroundPainter().draw(g2, area); } drawBackgroundImage(g2, area); } /** * A utility method for drawing the plot's axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param dataArea the data area. * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return A map containing the axis states. */ protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) { AxisCollection axisCollection = new AxisCollection(); // add domain axes to lists... for (CategoryAxis xAxis : this.domainAxes.values()) { if (xAxis != null) { int index = getDomainAxisIndex(xAxis); axisCollection.add(xAxis, getDomainAxisEdge(index)); } } // add range axes to lists... for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { int index = findRangeAxisIndex(yAxis); axisCollection.add(yAxis, getRangeAxisEdge(index)); } } Map<Axis, AxisState> axisStateMap = new HashMap<Axis, AxisState>(); // draw the top axes double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset( dataArea.getHeight()); for (Axis axis : axisCollection.getAxesAtTop()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the bottom axes cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight()); for (Axis axis : axisCollection.getAxesAtBottom()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the left axes cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth()); for (Axis axis : axisCollection.getAxesAtLeft()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the right axes cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth()); for (Axis axis : axisCollection.getAxesAtRight()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } return axisStateMap; } /** * Draws a representation of a dataset within the dataArea region using the * appropriate renderer. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param index the dataset and renderer index. * @param info an optional object for collection dimension information. * @param crosshairState a state object for tracking crosshair info * (<code>null</code> permitted). * * @return A boolean that indicates whether or not real data was found. * * @since 1.0.11 */ public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CategoryCrosshairState crosshairState) { boolean foundData = false; CategoryDataset currentDataset = getDataset(index); CategoryItemRenderer renderer = getRenderer(index); CategoryAxis domainAxis = getDomainAxisForDataset(index); ValueAxis rangeAxis = getRangeAxisForDataset(index); boolean hasData = !DatasetUtilities.isEmptyOrNull(currentDataset); if (hasData && renderer != null) { foundData = true; CategoryItemRendererState state = renderer.initialise(g2, dataArea, this, index, info); state.setCrosshairState(crosshairState); int columnCount = currentDataset.getColumnCount(); int rowCount = currentDataset.getRowCount(); int passCount = renderer.getPassCount(); for (int pass = 0; pass < passCount; pass++) { if (this.columnRenderingOrder == SortOrder.ASCENDING) { for (int column = 0; column < columnCount; column++) { if (this.rowRenderingOrder == SortOrder.ASCENDING) { for (int row = 0; row < rowCount; row++) { renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } else { for (int row = rowCount - 1; row >= 0; row renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } } } else { for (int column = columnCount - 1; column >= 0; column if (this.rowRenderingOrder == SortOrder.ASCENDING) { for (int row = 0; row < rowCount; row++) { renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } else { for (int row = rowCount - 1; row >= 0; row renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } } } } } return foundData; } /** * Draws the domain gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List) */ protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea) { if (!isDomainGridlinesVisible()) { return; } CategoryAnchor anchor = getDomainGridlinePosition(); RectangleEdge domainAxisEdge = getDomainAxisEdge(); CategoryDataset dataset = getDataset(); if (dataset == null) { return; } CategoryAxis axis = getDomainAxis(); if (axis != null) { int columnCount = dataset.getColumnCount(); for (int c = 0; c < columnCount; c++) { double xx = axis.getCategoryJava2DCoordinate(anchor, c, columnCount, dataArea, domainAxisEdge); CategoryItemRenderer renderer1 = getRenderer(); if (renderer1 != null) { renderer1.drawDomainGridline(g2, this, dataArea, xx); } } } } /** * Draws the range gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param ticks the ticks. * * @see #drawDomainGridlines(Graphics2D, Rectangle2D) */ protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea, List<ValueTick> ticks) { // draw the range grid lines, if any... if (!isRangeGridlinesVisible() && !isRangeMinorGridlinesVisible()) { return; } // no axis, no gridlines... ValueAxis axis = getRangeAxis(); if (axis == null) { return; } // no renderer, no gridlines... CategoryItemRenderer r = getRenderer(); if (r == null) { return; } Stroke gridStroke = null; Paint gridPaint = null; boolean paintLine; for (ValueTick tick : ticks) { paintLine = false; if ((tick.getTickType() == TickType.MINOR) && isRangeMinorGridlinesVisible()) { gridStroke = getRangeMinorGridlineStroke(); gridPaint = getRangeMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isRangeGridlinesVisible()) { gridStroke = getRangeGridlineStroke(); gridPaint = getRangeGridlinePaint(); paintLine = true; } if (((tick.getValue() != 0.0) || !isRangeZeroBaselineVisible()) && paintLine) { // the method we want isn't in the CategoryItemRenderer // interface... if (r instanceof AbstractCategoryItemRenderer) { AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r; aci.drawRangeGridline(g2, this, axis, dataArea, tick.getValue(), gridPaint, gridStroke); } else { // we'll have to use the method in the interface, but // this doesn't have the paint and stroke settings... r.drawRangeGridline(g2, this, axis, dataArea, tick.getValue()); } } } } /** * Draws a base line across the chart at value zero on the range axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setRangeZeroBaselineVisible(boolean) * * @since 1.0.13 */ protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) { if (!isRangeZeroBaselineVisible()) { return; } CategoryItemRenderer r = getRenderer(); if (r instanceof AbstractCategoryItemRenderer) { AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r; aci.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0, this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke); } else { r.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0); } } /** * Draws the annotations. * * @param g2 the graphics device. * @param dataArea the data area. */ protected void drawAnnotations(Graphics2D g2, Rectangle2D dataArea) { if (getAnnotations() != null) { for (CategoryAnnotation annotation : getAnnotations()) { annotation.draw(g2, this, dataArea, getDomainAxis(), getRangeAxis()); } } } /** * Draws the domain markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). * * @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer) */ protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { CategoryItemRenderer r = getRenderer(index); if (r == null) { return; } Collection<Marker> markers = getDomainMarkers(index, layer); CategoryAxis axis = getDomainAxisForDataset(index); if (markers != null && axis != null) { for (Marker marker1 : markers) { CategoryMarker marker = (CategoryMarker) marker1; r.drawDomainMarker(g2, this, axis, marker, dataArea); } } } /** * Draws the range markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). * * @see #drawDomainMarkers(Graphics2D, Rectangle2D, int, Layer) */ protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { CategoryItemRenderer r = getRenderer(index); if (r == null) { return; } Collection<Marker> markers = getRangeMarkers(index, layer); ValueAxis axis = getRangeAxisForDataset(index); if (markers != null && axis != null) { for (Marker marker : markers) { r.drawRangeMarker(g2, this, axis, marker, dataArea); } } } /** * Utility method for drawing a line perpendicular to the range axis (used * for crosshairs). * * @param g2 the graphics device. * @param dataArea the area defined by the axes. * @param value the data value. * @param stroke the line stroke (<code>null</code> not permitted). * @param paint the line paint (<code>null</code> not permitted). */ protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { double java2D = getRangeAxis().valueToJava2D(value, dataArea, getRangeAxisEdge()); Line2D line = null; if (this.orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(java2D, dataArea.getMinY(), java2D, dataArea.getMaxY()); } else if (this.orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), java2D, dataArea.getMaxX(), java2D); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Draws a domain crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param datasetIndex the dataset index. * @param rowKey the row key. * @param columnKey the column key. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @see #drawRangeCrosshair(Graphics2D, Rectangle2D, PlotOrientation, * double, ValueAxis, Stroke, Paint) * * @since 1.0.11 */ protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, int datasetIndex, Comparable rowKey, Comparable columnKey, Stroke stroke, Paint paint) { CategoryDataset dataset = getDataset(datasetIndex); CategoryAxis axis = getDomainAxisForDataset(datasetIndex); CategoryItemRenderer renderer = getRenderer(datasetIndex); Line2D line; if (orientation == PlotOrientation.VERTICAL) { double xx = renderer.getItemMiddle(rowKey, columnKey, dataset, axis, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = renderer.getItemMiddle(rowKey, columnKey, dataset, axis, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Draws a range crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @see #drawDomainCrosshair(Graphics2D, Rectangle2D, PlotOrientation, int, * Comparable, Comparable, Stroke, Paint) * * @since 1.0.5 */ protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Returns the range of data values that will be plotted against the range * axis. If the dataset is <code>null</code>, this method returns * <code>null</code>. * * @param axis the axis. * * @return The data range. */ @Override public Range getDataRange(ValueAxis axis) { Range result = null; List<CategoryDataset> mappedDatasets = new ArrayList<CategoryDataset>(); int rangeIndex = this.findRangeAxisIndex(axis); if (rangeIndex >= 0) { mappedDatasets.addAll(datasetsMappedToRangeAxis(rangeIndex)); } else if (axis == getRangeAxis()) { mappedDatasets.addAll(datasetsMappedToRangeAxis(0)); } // iterate through the datasets that map to the axis and get the union // of the ranges. for (CategoryDataset d : mappedDatasets) { CategoryItemRenderer r = getRendererForDataset(d); if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } } return result; } /** * Returns a list of the datasets that are mapped to the axis with the * specified index. * * @param axisIndex the axis index. * * @return The list (possibly empty, but never <code>null</code>). * * @since 1.0.3 */ private List<CategoryDataset> datasetsMappedToDomainAxis(int axisIndex) { List<CategoryDataset> result = new ArrayList<CategoryDataset>(); for (CategoryDataset dataset : this.datasets.values()) { if (dataset == null) { continue; } int i = findDatasetIndex(dataset); List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(i); if (mappedAxes == null) { if (axisIndex == 0) { result.add(dataset); } } else { if (mappedAxes.contains(axisIndex)) { result.add(dataset); } } } return result; } /** * A utility method that returns a list of datasets that are mapped to a * given range axis. * * @param axisIndex the axis index. * * @return A list of datasets. */ private List<CategoryDataset> datasetsMappedToRangeAxis(int axisIndex) { List<CategoryDataset> result = new ArrayList<CategoryDataset>(); for (CategoryDataset dataset : this.datasets.values()) { int i = findDatasetIndex(dataset); List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(i); if (mappedAxes == null) { if (axisIndex == 0) { result.add(this.datasets.get(i)); } } else if (mappedAxes.contains(axisIndex)) { result.add(this.datasets.get(i)); } } return result; } /** * Returns the weight for this plot when it is used as a subplot within a * combined plot. * * @return The weight. * * @see #setWeight(int) */ public int getWeight() { return this.weight; } /** * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param weight the weight. * * @see #getWeight() */ public void setWeight(int weight) { this.weight = weight; fireChangeEvent(); } /** * Returns the fixed domain axis space. * * @return The fixed domain axis space (possibly <code>null</code>). * * @see #setFixedDomainAxisSpace(AxisSpace) */ public AxisSpace getFixedDomainAxisSpace() { return this.fixedDomainAxisSpace; } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * * @see #getFixedDomainAxisSpace() */ public void setFixedDomainAxisSpace(AxisSpace space) { setFixedDomainAxisSpace(space, true); } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * @param notify notify listeners? * * @see #getFixedDomainAxisSpace() * * @since 1.0.7 */ public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) { this.fixedDomainAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns the fixed range axis space. * * @return The fixed range axis space (possibly <code>null</code>). * * @see #setFixedRangeAxisSpace(AxisSpace) */ public AxisSpace getFixedRangeAxisSpace() { return this.fixedRangeAxisSpace; } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * * @see #getFixedRangeAxisSpace() */ public void setFixedRangeAxisSpace(AxisSpace space) { setFixedRangeAxisSpace(space, true); } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * @param notify notify listeners? * * @see #getFixedRangeAxisSpace() * * @since 1.0.7 */ public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) { this.fixedRangeAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns a list of the categories in the plot's primary dataset. * * @return A list of the categories in the plot's primary dataset. * * @see #getCategoriesForAxis(CategoryAxis) */ public List<Comparable> getCategories() { List<Comparable> result = null; if (getDataset() != null) { result = Collections.unmodifiableList(getDataset().getColumnKeys()); } return result; } /** * Returns a list of the categories that should be displayed for the * specified axis. * * @param axis the axis (<code>null</code> not permitted) * * @return The categories. * * @since 1.0.3 */ public List<Comparable> getCategoriesForAxis(CategoryAxis axis) { List<Comparable> result = new ArrayList<Comparable>(); int axisIndex = getDomainAxisIndex(axis); List<CategoryDataset> mappedDatasets = datasetsMappedToDomainAxis(axisIndex); for (CategoryDataset dataset : mappedDatasets) { // add the unique categories from this dataset for (int i = 0; i < dataset.getColumnCount(); i++) { Comparable category = dataset.getColumnKey(i); if (!result.contains(category)) { result.add(category); } } } return result; } /** * Returns the flag that controls whether or not the shared domain axis is * drawn for each subplot. * * @return A boolean. * * @see #setDrawSharedDomainAxis(boolean) */ public boolean getDrawSharedDomainAxis() { return this.drawSharedDomainAxis; } /** * Sets the flag that controls whether the shared domain axis is drawn when * this plot is being used as a subplot. * * @param draw a boolean. * * @see #getDrawSharedDomainAxis() */ public void setDrawSharedDomainAxis(boolean draw) { this.drawSharedDomainAxis = draw; fireChangeEvent(); } /** * Returns <code>false</code> always, because the plot cannot be panned * along the domain axis/axes. * * @return A boolean. * * @see #isRangePannable() * * @since 1.0.13 */ @Override public boolean isDomainPannable() { return false; } /** * Returns <code>true</code> if panning is enabled for the range axes, * and <code>false</code> otherwise. * * @return A boolean. * * @see #setRangePannable(boolean) * @see #isDomainPannable() * * @since 1.0.13 */ @Override public boolean isRangePannable() { return this.rangePannable; } /** * Sets the flag that enables or disables panning of the plot along * the range axes. * * @param pannable the new flag value. * * @see #isRangePannable() * * @since 1.0.13 */ public void setRangePannable(boolean pannable) { this.rangePannable = pannable; } /** * Pans the domain axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source) { // do nothing, because the plot is not pannable along the domain axes } /** * Pans the range axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isRangePannable()) { return; } for (ValueAxis axis : this.rangeAxes.values()) { if (axis == null) { continue; } double length = axis.getRange().getLength(); double adj = percent * length; if (axis.isInverted()) { adj = -adj; } axis.setRange(axis.getLowerBound() + adj, axis.getUpperBound() + adj); } } /** * Returns <code>false</code> to indicate that the domain axes are not * zoomable. * * @return A boolean. * * @see #isRangeZoomable() */ @Override public boolean isDomainZoomable() { return false; } /** * Returns <code>true</code> to indicate that the range axes are zoomable. * * @return A boolean. * * @see #isDomainZoomable() */ @Override public boolean isRangeZoomable() { return true; } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source) { // can't zoom domain axis } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { // can't zoom domain axis } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // can't zoom domain axis } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source) { // delegate to other method zoomRangeAxes(factor, state, source, false); } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * @param useAnchor a flag that controls whether or not the source point * is used for the zoom anchor. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each range axis for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceY = source.getY(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceY = source.getX(); } double anchorY = yAxis.java2DToValue(sourceY, info.getDataArea(), getRangeAxisEdge()); yAxis.resizeRange2(factor, anchorY); } else { yAxis.resizeRange(factor); } } } /** * Zooms in on the range axes. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { yAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Returns the anchor value. * * @return The anchor value. * * @see #setAnchorValue(double) */ public double getAnchorValue() { return this.anchorValue; } /** * Sets the anchor value and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param value the anchor value. * * @see #getAnchorValue() */ public void setAnchorValue(double value) { setAnchorValue(value, true); } /** * Sets the anchor value and, if requested, sends a {@link PlotChangeEvent} * to all registered listeners. * * @param value the value. * @param notify notify listeners? * * @see #getAnchorValue() */ public void setAnchorValue(double value, boolean notify) { this.anchorValue = value; if (notify) { fireChangeEvent(); } } /** * Tests the plot for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryPlot)) { return false; } CategoryPlot that = (CategoryPlot) obj; if (this.orientation != that.orientation) { return false; } if (!ObjectUtils.equal(this.axisOffset, that.axisOffset)) { return false; } if (!this.domainAxes.equals(that.domainAxes)) { return false; } if (!this.domainAxisLocations.equals(that.domainAxisLocations)) { return false; } if (this.drawSharedDomainAxis != that.drawSharedDomainAxis) { return false; } if (!this.rangeAxes.equals(that.rangeAxes)) { return false; } if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) { return false; } if (!ObjectUtils.equal(this.datasetToDomainAxesMap, that.datasetToDomainAxesMap)) { return false; } if (!ObjectUtils.equal(this.datasetToRangeAxesMap, that.datasetToRangeAxesMap)) { return false; } if (!ObjectUtils.equal(this.renderers, that.renderers)) { return false; } if (this.renderingOrder != that.renderingOrder) { return false; } if (this.columnRenderingOrder != that.columnRenderingOrder) { return false; } if (this.rowRenderingOrder != that.rowRenderingOrder) { return false; } if (this.domainGridlinesVisible != that.domainGridlinesVisible) { return false; } if (this.domainGridlinePosition != that.domainGridlinePosition) { return false; } if (!ObjectUtils.equal(this.domainGridlineStroke, that.domainGridlineStroke)) { return false; } if (!PaintUtils.equal(this.domainGridlinePaint, that.domainGridlinePaint)) { return false; } if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) { return false; } if (!ObjectUtils.equal(this.rangeGridlineStroke, that.rangeGridlineStroke)) { return false; } if (!PaintUtils.equal(this.rangeGridlinePaint, that.rangeGridlinePaint)) { return false; } if (this.anchorValue != that.anchorValue) { return false; } if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) { return false; } if (this.rangeCrosshairValue != that.rangeCrosshairValue) { return false; } if (!ObjectUtils.equal(this.rangeCrosshairStroke, that.rangeCrosshairStroke)) { return false; } if (!PaintUtils.equal(this.rangeCrosshairPaint, that.rangeCrosshairPaint)) { return false; } if (this.rangeCrosshairLockedOnData != that.rangeCrosshairLockedOnData) { return false; } if (!ObjectUtils.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtils.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtils.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtils.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtils.equal(this.annotations, that.annotations)) { return false; } if (this.weight != that.weight) { return false; } if (!ObjectUtils.equal(this.fixedDomainAxisSpace, that.fixedDomainAxisSpace)) { return false; } if (!ObjectUtils.equal(this.fixedRangeAxisSpace, that.fixedRangeAxisSpace)) { return false; } if (!ObjectUtils.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } if (this.domainCrosshairVisible != that.domainCrosshairVisible) { return false; } if (this.crosshairDatasetIndex != that.crosshairDatasetIndex) { return false; } if (!ObjectUtils.equal(this.domainCrosshairColumnKey, that.domainCrosshairColumnKey)) { return false; } if (!ObjectUtils.equal(this.domainCrosshairRowKey, that.domainCrosshairRowKey)) { return false; } if (!PaintUtils.equal(this.domainCrosshairPaint, that.domainCrosshairPaint)) { return false; } if (!ObjectUtils.equal(this.domainCrosshairStroke, that.domainCrosshairStroke)) { return false; } if (this.rangeMinorGridlinesVisible != that.rangeMinorGridlinesVisible) { return false; } if (!PaintUtils.equal(this.rangeMinorGridlinePaint, that.rangeMinorGridlinePaint)) { return false; } if (!ObjectUtils.equal(this.rangeMinorGridlineStroke, that.rangeMinorGridlineStroke)) { return false; } if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) { return false; } if (!PaintUtils.equal(this.rangeZeroBaselinePaint, that.rangeZeroBaselinePaint)) { return false; } if (!ObjectUtils.equal(this.rangeZeroBaselineStroke, that.rangeZeroBaselineStroke)) { return false; } if (!ObjectUtils.equal(this.shadowGenerator, that.shadowGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException if the cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { CategoryPlot clone = (CategoryPlot) super.clone(); clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes); for (CategoryAxis axis : clone.domainAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes); for (ValueAxis axis : clone.rangeAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } // AxisLocation is immutable, so we can just copy the maps clone.domainAxisLocations = new HashMap<Integer, AxisLocation>( this.domainAxisLocations); clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>( this.rangeAxisLocations); // we don't clone the datasets clone.datasets = new HashMap<Integer, CategoryDataset>(this.datasets); for (CategoryDataset dataset : clone.datasets.values()) { if (dataset != null) { dataset.addChangeListener(clone); } } clone.datasetToDomainAxesMap = new TreeMap<Integer, List<Integer>>(); clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap); clone.datasetToRangeAxesMap = new TreeMap<Integer, List<Integer>>(); clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap); clone.renderers = CloneUtils.cloneMapValues(this.renderers); for (CategoryItemRenderer renderer : clone.renderers.values()) { if (renderer != null) { renderer.setPlot(clone); renderer.addChangeListener(clone); } } if (this.fixedDomainAxisSpace != null) { clone.fixedDomainAxisSpace = ObjectUtils.clone( this.fixedDomainAxisSpace); } if (this.fixedRangeAxisSpace != null) { clone.fixedRangeAxisSpace = ObjectUtils.clone( this.fixedRangeAxisSpace); } clone.annotations = ObjectUtils.deepClone(this.annotations); clone.foregroundDomainMarkers = cloneMarkerMap( this.foregroundDomainMarkers); clone.backgroundDomainMarkers = cloneMarkerMap( this.backgroundDomainMarkers); clone.foregroundRangeMarkers = cloneMarkerMap( this.foregroundRangeMarkers); clone.backgroundRangeMarkers = cloneMarkerMap( this.backgroundRangeMarkers); if (this.fixedLegendItems != null) { clone.fixedLegendItems = ObjectUtils.deepClone(this.fixedLegendItems); } return clone; } /** * A utility method to clone the marker maps. * * @param map the map to clone. * * @return A clone of the map. * * @throws CloneNotSupportedException if there is some problem cloning the * map. */ private Map<Integer, Collection<Marker>> cloneMarkerMap(Map<Integer, Collection<Marker>> map) throws CloneNotSupportedException { Map<Integer, Collection<Marker>> clone = new HashMap<Integer, Collection<Marker>>(); Set<Integer> keys = map.keySet(); for (Integer key : keys) { Collection<Marker> entry = map.get(key); Collection<Marker> toAdd = ObjectUtils.<Marker, Collection<Marker>>deepClone(entry); clone.put(key, toAdd); } return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtils.writeStroke(this.domainGridlineStroke, stream); SerialUtils.writePaint(this.domainGridlinePaint, stream); SerialUtils.writeStroke(this.rangeGridlineStroke, stream); SerialUtils.writePaint(this.rangeGridlinePaint, stream); SerialUtils.writeStroke(this.rangeCrosshairStroke, stream); SerialUtils.writePaint(this.rangeCrosshairPaint, stream); SerialUtils.writeStroke(this.domainCrosshairStroke, stream); SerialUtils.writePaint(this.domainCrosshairPaint, stream); SerialUtils.writeStroke(this.rangeMinorGridlineStroke, stream); SerialUtils.writePaint(this.rangeMinorGridlinePaint, stream); SerialUtils.writeStroke(this.rangeZeroBaselineStroke, stream); SerialUtils.writePaint(this.rangeZeroBaselinePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.domainGridlineStroke = SerialUtils.readStroke(stream); this.domainGridlinePaint = SerialUtils.readPaint(stream); this.rangeGridlineStroke = SerialUtils.readStroke(stream); this.rangeGridlinePaint = SerialUtils.readPaint(stream); this.rangeCrosshairStroke = SerialUtils.readStroke(stream); this.rangeCrosshairPaint = SerialUtils.readPaint(stream); this.domainCrosshairStroke = SerialUtils.readStroke(stream); this.domainCrosshairPaint = SerialUtils.readPaint(stream); this.rangeMinorGridlineStroke = SerialUtils.readStroke(stream); this.rangeMinorGridlinePaint = SerialUtils.readPaint(stream); this.rangeZeroBaselineStroke = SerialUtils.readStroke(stream); this.rangeZeroBaselinePaint = SerialUtils.readPaint(stream); for (CategoryAxis xAxis: this.domainAxes.values()) { if (xAxis != null) { xAxis.setPlot(this); xAxis.addChangeListener(this); } } for (ValueAxis yAxis: this.rangeAxes.values()) { if (yAxis != null) { yAxis.setPlot(this); yAxis.addChangeListener(this); } } for (CategoryDataset dataset: this.datasets.values()) { if (dataset != null) { dataset.addChangeListener(this); } } for (CategoryItemRenderer renderer: this.renderers.values()) { if (renderer != null) { renderer.addChangeListener(this); } } } }
package joliex.db; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import jolie.net.CommMessage; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server * 2009 - Claudio Guidi: added support for SQLite */ @CanUseJars({ "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar", // Microsoft SQLServer "jdbc-sqlite.jar" // SQLite }) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private boolean mustCheckConnection = false; @Override protected void finalize() { if ( connection != null ) { try { connection.close(); } catch( SQLException e ) {} } } public CommMessage connect( CommMessage message ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) {} } mustCheckConnection = message.value().getFirstChild( "checkConnection" ).intValue() > 0; String driver = message.value().getChildren( "driver" ).first().strValue(); String host = message.value().getChildren( "host" ).first().strValue(); String port = message.value().getChildren( "port" ).first().strValue(); String databaseName = message.value().getChildren( "database" ).first().strValue(); username = message.value().getChildren( "username" ).first().strValue(); password = message.value().getChildren( "password" ).first().strValue(); String separator = "/"; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlite".equals( driver ) ) { Class.forName( "org.sqlite.JDBC" ); } else if ( "sqlserver".equals( driver ) ) { //Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } connectionString = "jdbc:"+ driver + "://" + host + ( port.equals( "" ) ? "" : ":" + port ) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } return CommMessage.createResponse( message, Value.create() ); } private void checkConnection() throws FaultException { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } if ( mustCheckConnection ) { try { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } catch( SQLException e ) { throw new FaultException( e ); } } } public CommMessage update( CommMessage request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); String query = request.value().strValue(); try { Statement stm = connection.createStatement(); resultValue.setValue( stm.executeUpdate( query ) ); } catch( SQLException e ) { throw new FaultException( e ); } return CommMessage.createResponse( request, resultValue ); } public CommMessage query( CommMessage request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); Value rowValue, fieldValue; String query = request.value().strValue(); try { Statement stm = connection.createStatement(); ResultSet result = stm.executeQuery( query ); ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = resultValue.getChildren( "row" ).get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getChildren( metadata.getColumnLabel( i ) ).first(); switch( metadata.getColumnType( i ) ) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: case java.sql.Types.NUMERIC: fieldValue.setValue( result.getInt( i ) ); break; case java.sql.Types.DOUBLE: fieldValue.setValue( result.getDouble( i ) ); break; case java.sql.Types.FLOAT: fieldValue.setValue( result.getFloat( i ) ); break; case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( i ); fieldValue.setValue( clob.getSubString( 0L, (int)clob.length() ) ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: fieldValue.setValue( result.getNString( i ) ); break; case java.sql.Types.VARCHAR: default: fieldValue.setValue( result.getString( i ) ); break; } } rowIndex++; } } catch( SQLException e ) { throw new FaultException( "SQLException", e ); } return CommMessage.createResponse( request, resultValue ); } }
package org.apache.jorphan.test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.Properties; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.reflect.ClassFinder; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; public final class AllTests { transient private static Logger log = LoggingManager.getLoggerForClass(); /** * Private constructor to prevent instantiation. */ private AllTests() { } /** * Starts a run through all unit tests found in the specified classpaths. * The first argument should be a list of paths to search. The second * argument is optional and specifies a properties file used to initialize * logging. The third argument is also optional, and specifies a class * that implements the UnitTestManager interface. This provides a means of * initializing your application with a configuration file prior to the * start of any unit tests. * * @param args the command line arguments */ public static void main(String[] args) { if (args.length < 1) { System.out.println( "You must specify a comma-delimited list of paths to search " + "for unit tests"); System.exit(0); } initializeLogging(args); initializeManager(args); // end : added - 11 July 2001 // GUI tests throw the error // testArgumentCreation(org.apache.jmeter.config.gui.ArgumentsPanel$Test)java.lang.NoClassDefFoundError // at java.lang.Class.forName0(Native Method) // at java.lang.Class.forName(Class.java:141) // at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62) // Try to find out why this is ... // String e = "java.awt.headless"; // String g="java.awt.graphicsenv"; // System.out.println("+++++++++++"); // System.out.println(e+"="+System.getProperty(e)); // String n=System.getProperty(g); // System.out.println(g+"="+n); // try {// // Class c = Class.forName(n); // System.out.println("Found class: "+n); //// c.newInstance(); //// System.out.println("Instantiated: "+n); // } catch (Exception e1) { // System.out.println("Error finding class "+n+" "+e1); // } catch (java.lang.InternalError e1){ // System.out.println("Error finding class "+n+" "+e1); // don't call isHeadless() here, as it has a side effect. TestSuite suite = suite(args[0]); // Jeremy Arnold: This method used to attempt to write results to // a file, but it had a bug and instead just wrote to System.out. // Since nobody has complained about this behavior, I'm changing // the code to not attempt to write to a file, so it will continue // behaving as it did before. It would be simple to make it write // to a file instead if that is the desired behavior. TestRunner.run(suite); // Recheck settings: // System.out.println("+++++++++++"); // System.out.println(e+"="+System.getProperty(e)); // System.out.println(g+"="+System.getProperty(g)); // System.out.println("Headless? "+java.awt.GraphicsEnvironment.isHeadless()); // try { // Class c = Class.forName(n); // System.out.println("Found class: "+n); // c.newInstance(); // System.out.println("Instantiated: "+n); // } catch (Exception e1) { // System.out.println("Error with class "+n+" "+e1); // } catch (java.lang.InternalError e1){ // System.out.println("Error with class "+n+" "+e1); System.exit(0); } /** * An overridable method that initializes the logging for the unit test * run, using the properties file passed in as the second argument. * @param args */ protected static void initializeLogging(String[] args) { if (args.length >= 2) { Properties props = new Properties(); try { System.out.println( "setting up logging props using file: " + args[1]); props.load(new FileInputStream(args[1])); LoggingManager.initializeLogging(props); } catch (FileNotFoundException e) { } catch (IOException e) { } } } /** * An overridable method that that instantiates a UnitTestManager (if one * was specified in the command-line arguments), and hands it the name of * the properties file to use to configure the system. * @param args */ protected static void initializeManager(String[] args) { if (args.length >= 3) { try { UnitTestManager um = (UnitTestManager) Class.forName(args[2]).newInstance(); um.initializeProperties(args[1]); } catch (Exception e) { System.out.println("Couldn't create: " + args[2]); e.printStackTrace(); } } } /** * A unit test suite for JUnit. * * @return The test suite */ private static TestSuite suite(String searchPaths) { TestSuite suite = new TestSuite(); try { Iterator classes = ClassFinder .findClassesThatExtend( JOrphanUtils.split(searchPaths, ","), new Class[] { TestCase.class }, true) .iterator(); while (classes.hasNext()) { String name = (String) classes.next(); try { suite.addTest(new TestSuite(Class.forName(name))); } catch (Exception ex) { log.error("error adding test :" + ex); } } } catch (IOException e) { log.error("", e); } catch (ClassNotFoundException e) { log.error("", e); } return suite; } }
package joliex.db; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.embedding.RequestResponse; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server * 2009 - Claudio Guidi: added support for SQLite */ @CanUseJars({ "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar", // Microsoft SQLServer "jdbc-sqlite.jar" // SQLite }) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private boolean mustCheckConnection = false; private final Object transactionMutex = new Object(); @Override protected void finalize() { if ( connection != null ) { try { connection.close(); } catch( SQLException e ) {} } } @RequestResponse public void connect( Value request ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) {} } mustCheckConnection = request.getFirstChild( "checkConnection" ).intValue() > 0; String driver = request.getChildren( "driver" ).first().strValue(); String host = request.getChildren( "host" ).first().strValue(); String port = request.getChildren( "port" ).first().strValue(); String databaseName = request.getChildren( "database" ).first().strValue(); username = request.getChildren( "username" ).first().strValue(); password = request.getChildren( "password" ).first().strValue(); String separator = "/"; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlite".equals( driver ) ) { Class.forName( "org.sqlite.JDBC" ); } else if ( "sqlserver".equals( driver ) ) { //Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } connectionString = "jdbc:"+ driver + "://" + host + ( port.equals( "" ) ? "" : ":" + port ) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } } private void checkConnection() throws FaultException { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } if ( mustCheckConnection ) { try { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } catch( SQLException e ) { throw new FaultException( e ); } } } public Value update( String query ) throws FaultException { checkConnection(); Value resultValue = Value.create(); try { synchronized( transactionMutex ) { Statement stm = connection.createStatement(); resultValue.setValue( stm.executeUpdate( query ) ); } } catch( SQLException e ) { throw new FaultException( e ); } return resultValue; } private static void resultSetToValueVector( ResultSet result, ValueVector vector ) throws SQLException { Value rowValue, fieldValue; ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getFirstChild( metadata.getColumnLabel( i ) ); switch( metadata.getColumnType( i ) ) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: fieldValue.setValue( result.getInt( i ) ); break; case java.sql.Types.BIGINT: // TODO: to be changed when getting support for Long in Jolie. fieldValue.setValue( result.getInt( i ) ); break; case java.sql.Types.DOUBLE: fieldValue.setValue( result.getDouble( i ) ); break; case java.sql.Types.FLOAT: fieldValue.setValue( result.getFloat( i ) ); break; case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( i ); fieldValue.setValue( clob.getSubString( 0L, (int)clob.length() ) ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: String s = result.getNString( i ); if ( s == null ) { s = ""; } fieldValue.setValue( s ); break; case java.sql.Types.NUMERIC: BigDecimal dec = result.getBigDecimal( i ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } break; case java.sql.Types.VARCHAR: default: String str = result.getString( i ); if ( str == null ) { str = ""; } fieldValue.setValue( str ); break; } } rowIndex++; } } public Value executeTransaction( Value request ) throws FaultException { checkConnection(); Value resultValue = Value.create(); ValueVector resultVector = resultValue.getChildren( "result" ); try { synchronized( transactionMutex ) { connection.setAutoCommit( false ); Value currResultValue; for( Value statementValue : request.getChildren( "statement" ) ) { currResultValue = Value.create(); Statement stm = connection.createStatement(); if ( stm.execute( statementValue.strValue() ) == true ) { resultSetToValueVector( stm.getResultSet(), currResultValue.getChildren( "row" ) ); } resultVector.add( currResultValue ); } connection.commit(); connection.setAutoCommit( true ); } } catch( SQLException e ) { throw new FaultException( e ); } return resultValue; } public Value query( String query ) throws FaultException { checkConnection(); Value resultValue = Value.create(); try { synchronized( transactionMutex ) { Statement stm = connection.createStatement(); ResultSet result = stm.executeQuery( query ); resultSetToValueVector( result, resultValue.getChildren( "row" ) ); } } catch( SQLException e ) { throw new FaultException( "SQLException", e ); } return resultValue; } }
package com.marklogic.client.datamovement.functionaltests; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.DatabaseClientFactory.Authentication; import com.marklogic.client.admin.ExtensionMetadata; import com.marklogic.client.admin.TransformExtensionsManager; import com.marklogic.client.datamovement.ApplyTransformListener; import com.marklogic.client.datamovement.ApplyTransformListener.ApplyResult; import com.marklogic.client.datamovement.DataMovementManager; import com.marklogic.client.datamovement.JobTicket; import com.marklogic.client.datamovement.QueryBatcher; import com.marklogic.client.datamovement.WriteBatcher; import com.marklogic.client.datamovement.functionaltests.util.DmsdkJavaClientREST; import com.marklogic.client.document.DocumentPage; import com.marklogic.client.document.DocumentRecord; import com.marklogic.client.document.ServerTransform; import com.marklogic.client.impl.DatabaseClientImpl; import com.marklogic.client.io.DOMHandle; import com.marklogic.client.io.DocumentMetadataHandle; import com.marklogic.client.io.FileHandle; import com.marklogic.client.io.Format; import com.marklogic.client.io.JacksonHandle; import com.marklogic.client.io.StringHandle; import com.marklogic.client.query.QueryManager; import com.marklogic.client.query.StringQueryDefinition; import com.marklogic.client.query.StructuredQueryBuilder; public class QueryBatcherJobReportTest extends DmsdkJavaClientREST { private static String dbName = "QueryBatcherJobReport"; private static DataMovementManager dmManager = null; private static final String TEST_DIR_PREFIX = "/WriteHostBatcher-testdata/"; private static DatabaseClient dbClient; private static String host = "localhost"; private static String user = "admin"; private static int port = 8000; private static String password = "admin"; private static String server = "App-Services"; private static JsonNode clusterInfo; private static StringHandle stringHandle; private static FileHandle fileHandle; private static DocumentMetadataHandle meta1; private static DocumentMetadataHandle meta2; private static String stringTriple; private static File fileJson; private static final String query1 = "fn:count(fn:doc())"; private static String[] hostNames ; private static JobTicket queryTicket; /** * @throws Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { dbClient = DatabaseClientFactory.newClient(host, port, user, password, Authentication.DIGEST); dmManager = dbClient.newDataMovementManager(); hostNames = getHosts(); createDB(dbName); Thread.currentThread().sleep(500L); int count = 1; for ( String forestHost : hostNames ) { createForestonHost(dbName+"-"+count,dbName,forestHost); count ++; Thread.currentThread().sleep(500L); } associateRESTServerWithDB(server,dbName); clusterInfo = ((DatabaseClientImpl) dbClient).getServices() .getResource(null, "internal/forestinfo", null, null, new JacksonHandle()) .get(); // FileHandle fileJson = FileUtils.toFile(WriteHostBatcherTest.class.getResource(TEST_DIR_PREFIX+"dir.json")); fileHandle = new FileHandle(fileJson); fileHandle.setFormat(Format.JSON); meta1 = new DocumentMetadataHandle().withCollections("JsonTransform"); //StringHandle stringTriple = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo>This is so foo</foo>"; stringHandle = new StringHandle(stringTriple); stringHandle.setFormat(Format.XML); meta2 = new DocumentMetadataHandle().withCollections("XmlTransform"); WriteBatcher ihb2 = dmManager.newWriteBatcher(); ihb2.withBatchSize(27).withThreadCount(10); ihb2.onBatchSuccess( batch -> { } ) .onBatchFailure( (batch, throwable) -> { throwable.printStackTrace(); }); dmManager.startJob(ihb2); for (int j =0 ;j < 2000; j++){ String uri ="/local/json-"+ j; ihb2.add(uri, meta1, fileHandle); } ihb2.flushAndWait(); Assert.assertTrue(dbClient.newServerEval().xquery(query1).eval().next().getNumber().intValue() == 2000); for (int j =0 ;j < 2000; j++){ String uri ="/local/string-"+ j; ihb2.add(uri, meta2, stringHandle); } ihb2.flushAndWait(); Assert.assertTrue(dbClient.newServerEval().xquery(query1).eval().next().getNumber().intValue() == 4000); //Xquery transformation TransformExtensionsManager transMgr = dbClient.newServerConfigManager().newTransformExtensionsManager(); ExtensionMetadata metadata = new ExtensionMetadata(); metadata.setTitle("Adding attribute xquery Transform"); metadata.setDescription("This plugin transforms an XML document by adding attribute to root node"); metadata.setProvider("MarkLogic"); metadata.setVersion("0.1"); // get the transform file File transformFile = FileUtils.toFile(WriteHostBatcherTest.class.getResource(TEST_DIR_PREFIX+"add-attr-xquery-transform.xqy")); FileHandle transformHandle = new FileHandle(transformFile); transMgr.writeXQueryTransform("add-attr-xquery-transform", transformHandle, metadata); //JS Transformation File transformFile1 = FileUtils.toFile(WriteHostBatcherTest.class.getResource(TEST_DIR_PREFIX+"javascript_transform.sjs")); FileHandle transformHandle1 = new FileHandle(transformFile1); transMgr.writeJavascriptTransform("jsTransform", transformHandle1); } @AfterClass public static void tearDownAfterClass() throws Exception { clearDB(port); associateRESTServerWithDB(server,"Documents"); for (int i =0 ; i < clusterInfo.size(); i++){ detachForest(dbName, dbName+"-"+(i+1)); deleteForest(dbName+"-"+(i+1)); } deleteDB(dbName); } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void jobReport() throws Exception{ AtomicInteger batchCount = new AtomicInteger(0); AtomicInteger successCount = new AtomicInteger(0); AtomicLong count1 = new AtomicLong(0); AtomicLong count2 = new AtomicLong(0); AtomicLong count3 = new AtomicLong(0); QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform")).withBatchSize(500).withThreadCount(20); batcher.onUrisReady(batch->{ System.out.println("Yes"); if(dmManager.getJobReport(queryTicket).getSuccessBatchesCount() == batchCount.incrementAndGet()){ count1.incrementAndGet(); } }); batcher.onQueryFailure(throwable -> throwable.printStackTrace()); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); dmManager.stopJob(queryTicket); batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform")).withBatchSize(500).withThreadCount(20); batcher.onUrisReady(batch->{ if(dmManager.getJobReport(queryTicket).getSuccessEventsCount() == successCount.addAndGet(batch.getItems().length)){ count2.incrementAndGet(); } }); batcher.onQueryFailure(throwable -> throwable.printStackTrace()); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); dmManager.stopJob(queryTicket); batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform")).withBatchSize(500).withThreadCount(20); batcher.onUrisReady(batch->{ if(Math.abs(dmManager.getJobReport(queryTicket).getReportTimestamp().getTime().getTime()-Calendar.getInstance().getTime().getTime()) < 10000){ count3.incrementAndGet(); } }); batcher.onQueryFailure(throwable -> throwable.printStackTrace()); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); dmManager.stopJob(queryTicket); Assert.assertEquals(0, dmManager.getJobReport(queryTicket).getFailureEventsCount()); Assert.assertEquals(dmManager.getJobReport(queryTicket).getSuccessBatchesCount(), batchCount.get()); Assert.assertEquals(dmManager.getJobReport(queryTicket).getSuccessEventsCount(), successCount.get()); Assert.assertEquals(dmManager.getJobReport(queryTicket).getSuccessBatchesCount() , count1.get()); Assert.assertEquals(dmManager.getJobReport(queryTicket).getSuccessBatchesCount() , count2.get()); Assert.assertEquals(dmManager.getJobReport(queryTicket).getSuccessBatchesCount() , count3.get()); } @Test public void testNullQdef() throws IOException, InterruptedException { JsonNode node = null; JacksonHandle jacksonHandle = null; WriteBatcher wbatcher = dmManager.newWriteBatcher().withBatchSize(32).withThreadCount(20); try{ wbatcher.addAs("/nulldoc",node); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(IllegalArgumentException e){ Assert.assertTrue(e.getMessage().equals("content must not be null")); } try{ wbatcher.add("/nulldoc",jacksonHandle); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(IllegalArgumentException e){ Assert.assertTrue(e.getMessage().equals("contentHandle must not be null")); } QueryManager queryMgr = dbClient.newQueryManager(); StringQueryDefinition querydef = queryMgr.newStringDefinition(); querydef = null; try{ QueryBatcher batcher = dmManager.newQueryBatcher(querydef).withBatchSize(32).withThreadCount(20); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(IllegalArgumentException e){ Assert.assertTrue(e.getMessage().equals("query must not be null")); } } @Test public void queryFailures() throws Exception{ Thread t1 = new Thread(new DisabledDBRunnable()); t1.setName("Status Check -1"); QueryManager queryMgr = dbClient.newQueryManager(); StringQueryDefinition querydef = queryMgr.newStringDefinition(); querydef.setCriteria("John AND Bob"); AtomicInteger batches = new AtomicInteger(0); String jsonDoc = "{" + "\"employees\": [" + "{ \"firstName\":\"John\" , \"lastName\":\"Doe\" }," + "{ \"firstName\":\"Ann\" , \"lastName\":\"Smith\" }," + "{ \"firstName\":\"Bob\" , \"lastName\":\"Foo\" }]" + "}"; WriteBatcher wbatcher = dmManager.newWriteBatcher(); wbatcher.withBatchSize(6000); wbatcher.onBatchFailure((batch, throwable)->throwable.printStackTrace()); StringHandle handle = new StringHandle(); handle.set(jsonDoc); String uri = null; // Insert 10 K documents for (int i = 0; i < 6000; i++) { uri = "/firstName" + i + ".json"; wbatcher.add(uri, handle); } wbatcher.flushAndWait(); QueryBatcher batcher = dmManager.newQueryBatcher(querydef).withBatchSize(10).withThreadCount(3); batcher.onUrisReady(batch->{ batches.incrementAndGet(); }); batcher.onQueryFailure((throwable)->{ System.out.println("queryFailures: "); try { Thread.currentThread().sleep(7000L); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } throwable.getBatcher().retry(throwable); String s = null; s.length(); }); queryTicket = dmManager.startJob(batcher); t1.start(); t1.join(); batcher.awaitCompletion(); Assert.assertEquals(6000, dmManager.getJobReport(queryTicket).getSuccessEventsCount()); Assert.assertEquals(batches.intValue(), dmManager.getJobReport(queryTicket).getSuccessBatchesCount()); Assert.assertEquals( hostNames.length, dmManager.getJobReport(queryTicket).getFailureEventsCount()); Assert.assertEquals( hostNames.length, dmManager.getJobReport(queryTicket).getFailureBatchesCount()); } class DisabledDBRunnable implements Runnable { Map<String,String> properties = new HashMap<>(); @Override public void run() { properties.put("enabled", "false"); boolean state = true; while (state){ System.out.println(dmManager.getJobReport(queryTicket).getSuccessEventsCount()); if(dmManager.getJobReport(queryTicket).getSuccessEventsCount() >= 0){ changeProperty(properties,"/manage/v2/databases/"+dbName+"/properties"); System.out.println("DB disabled"); state=false; } } try { Thread.currentThread().sleep(5000L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } properties.put("enabled", "true"); changeProperty(properties,"/manage/v2/databases/"+dbName+"/properties"); } } @Test public void jobReportStopJob() throws Exception{ QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform")).withBatchSize(20).withThreadCount(20); AtomicInteger batchCount = new AtomicInteger(0); Set<String> uris = Collections.synchronizedSet(new HashSet<String>()); batcher.onUrisReady(batch->{ uris.addAll(Arrays.asList(batch.getItems())); batchCount.incrementAndGet(); if(dmManager.getJobReport(queryTicket).getSuccessEventsCount() > 40){ dmManager.stopJob(queryTicket); } }); batcher.onQueryFailure(throwable -> throwable.printStackTrace()); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("Success event: "+dmManager.getJobReport(queryTicket).getSuccessEventsCount()); System.out.println("Success batch: "+dmManager.getJobReport(queryTicket).getSuccessBatchesCount()); System.out.println("Failure event: "+dmManager.getJobReport(queryTicket).getFailureEventsCount()); System.out.println("Failure batch: "+dmManager.getJobReport(queryTicket).getFailureBatchesCount()); Assert.assertTrue(dmManager.getJobReport(queryTicket).getSuccessEventsCount() > 40); Assert.assertTrue(dmManager.getJobReport(queryTicket).getSuccessEventsCount() < 1000); Assert.assertTrue(dmManager.getJobReport(queryTicket).getFailureEventsCount() == 0); Assert.assertTrue(dmManager.getJobReport(queryTicket).getFailureBatchesCount() == 0); Assert.assertTrue(batchCount.get() == dmManager.getJobReport(queryTicket).getSuccessBatchesCount()); } @Test public void jsMasstransformReplace() throws Exception{ ServerTransform transform = new ServerTransform("jsTransform"); transform.put("newValue", "new Value"); ApplyTransformListener listener = new ApplyTransformListener() .withTransform(transform) .withApplyResult(ApplyResult.REPLACE); QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("JsonTransform")).withBatchSize(20).withThreadCount(20); AtomicBoolean success = new AtomicBoolean(false); AtomicInteger batchCount = new AtomicInteger(0); AtomicInteger successCount = new AtomicInteger(0); AtomicInteger count = new AtomicInteger(0); batcher = batcher.onUrisReady((batch)->{ successCount.addAndGet(batch.getItems().length); batchCount.incrementAndGet(); if(dmManager.getJobReport(queryTicket).getSuccessEventsCount() ==successCount.get()) { success.set(true); count.incrementAndGet(); } }).onUrisReady(listener).onQueryFailure((throwable)-> throwable.printStackTrace()); queryTicket = dmManager.startJob( batcher ); batcher.awaitCompletion(Long.MAX_VALUE, TimeUnit.DAYS); dmManager.stopJob(queryTicket); String uris[] = new String[2000]; for(int i =0;i<2000;i++){ uris[i] = "/local/json-"+ i; } int doccount=0; DocumentPage page = dbClient.newDocumentManager().read(uris); JacksonHandle dh = new JacksonHandle(); while(page.hasNext()){ DocumentRecord rec = page.next(); rec.getContent(dh); assertEquals("Attribute value should be new Value","new Value",dh.get().get("c").asText()); doccount++; } assertEquals("document count", 2000,doccount); Assert.assertTrue(success.get()); Assert.assertEquals(batchCount.get(), dmManager.getJobReport(queryTicket).getSuccessBatchesCount()); Assert.assertEquals(batchCount.get(), count.get()); Assert.assertEquals(2000, dmManager.getJobReport(queryTicket).getSuccessEventsCount()); } //ISSUE # 106 @Test public void stopTransformJobTest() throws Exception{ ServerTransform transform = new ServerTransform("add-attr-xquery-transform"); transform.put("name", "Lang"); transform.put("value", "French"); List<String> skippedBatch = new ArrayList<>(); List<String> successBatch = new ArrayList<>(); List<String> failedBatch = new ArrayList<>(); ApplyTransformListener listener = new ApplyTransformListener() .withTransform(transform) .withApplyResult(ApplyResult.REPLACE) .onSuccess(batch -> { List<String> batchList = Arrays.asList(batch.getItems()); successBatch.addAll(batchList); System.out.println("stopTransformJobTest: Success: "+batch.getItems()[0]); System.out.println("stopTransformJobTest: Success: "+dbClient.newServerEval().xquery("fn:doc(\""+batch.getItems()[0]+"\")").eval().next().getString()); }) .onSkipped(batch -> { List<String> batchList = Arrays.asList(batch.getItems()); skippedBatch.addAll(batchList); System.out.println("stopTransformJobTest : Skipped: "+batch.getItems()[0]); }) .onBatchFailure((batch,throwable) -> { List<String> batchList = Arrays.asList(batch.getItems()); failedBatch.addAll(batchList); throwable.printStackTrace(); System.out.println("stopTransformJobTest: Failed: "+batch.getItems()[0]); }); QueryBatcher batcher = dmManager.newQueryBatcher(new StructuredQueryBuilder().collection("XmlTransform")) .withBatchSize(1) .withThreadCount(1); AtomicLong successCount = new AtomicLong(0L); batcher = batcher.onUrisReady((batch)->{ successCount.set(dmManager.getJobReport(queryTicket).getSuccessEventsCount()); }).onUrisReady(listener); queryTicket = dmManager.startJob( batcher ); Thread.currentThread().sleep(4000L); dmManager.stopJob(queryTicket); String uris[] = new String[2000]; for(int i =0;i<2000;i++){ uris[i] = "/local/string-"+ i; } int doccount=0; DocumentPage page = dbClient.newDocumentManager().read(uris); DOMHandle dh = new DOMHandle(); while(page.hasNext()){ DocumentRecord rec = page.next(); rec.getContent(dh); if(dh.get().getElementsByTagName("foo").item(0).getAttributes().item(0) == null){ doccount++; System.out.println("stopTransformJobTest: skipped in server"+rec.getUri()); } } System.out.println("stopTransformJobTest: Success: "+successBatch.size()); System.out.println("stopTransformJobTest: Skipped: "+skippedBatch.size()); System.out.println("stopTransformJobTest: Failed: "+failedBatch.size()); System.out.println("stopTransformJobTest : count "+doccount); Assert.assertEquals(2000-doccount,successBatch.size()); Assert.assertEquals(2000-doccount, successCount.get()); } }
package dk.statsbiblioteket.doms.updatetracker.improved.worklog; import dk.statsbiblioteket.doms.updatetracker.improved.fedora.FedoraFailedException; import dk.statsbiblioteket.doms.updatetracker.improved.database.UpdateTrackerPersistentStore; import dk.statsbiblioteket.doms.updatetracker.improved.database.UpdateTrackerStorageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimerTask; /** * This timertasks regularly polls the fedora worklog and calls the update tracker with the unit of work */ public class WorkLogPollTask extends TimerTask { private static Logger log = LoggerFactory.getLogger(WorkLogPollTask.class); private final WorkLogPollDAO workLogPollDAO; private final UpdateTrackerPersistentStore updateTrackerPersistentStore; private int limit; /** * @param workLogPollDAO * @param updateTrackerPersistentStore * @param limit the amount of work units to retrieve in each invocation */ public WorkLogPollTask(WorkLogPollDAO workLogPollDAO, UpdateTrackerPersistentStore updateTrackerPersistentStore, int limit) { this.workLogPollDAO = workLogPollDAO; this.updateTrackerPersistentStore = updateTrackerPersistentStore; this.limit = limit; } @Override public void run() { try { Long latestKey = updateTrackerPersistentStore.getLatestKey(); List<WorkLogUnit> events = getEvents(latestKey); for (WorkLogUnit event : events) { try { handleEvent(event, event.getKey()); } catch(UpdateTrackerStorageException e){ log.error("Failed to store events in update tracker. Failed on '" + event + "'", e); break; //If we fail, break the loop, as we DO NOT WANT to miss an event } catch(FedoraFailedException e){ log.error("Failed to communicate with fedora. Failed on '" + event + "'", e); break; //If we fail, break the loop, as we DO NOT WANT to miss an event } } if (!events.isEmpty()) { log.info("Finished working on event list"); } } catch (Exception e){ //Fault barrier to avoid that this method bombs out //If this method bombs out, the timer is stopped, and will not start until the webservice is reloaded // So, we catch and log all exceptions, including runtime exceptions. Throwable and Errors will take the thing down hard, as they should log.error("Failed to poll for worklog tasks",e); //Log this and keep going. Only Errors get through now } } private List<WorkLogUnit> getEvents(Long lastRegisteredKey) { List<WorkLogUnit> events = new ArrayList<WorkLogUnit>(); try { log.debug("Starting query for events since '{}'", lastRegisteredKey); events = workLogPollDAO.getFedoraEvents(lastRegisteredKey, limit); log.info("Looking for events since '{}'. Found '{}", lastRegisteredKey, events.size()); } catch (IOException e) { log.error("Failed to get Fedora events.", e); } return events; } private void handleEvent(WorkLogUnit event, long key) throws UpdateTrackerStorageException, FedoraFailedException { final String pid = event.getPid(); final Date date = event.getDate(); final String param = event.getParam(); final String method = event.getMethod(); log.debug("Registering the event '{}'", event); if (method.equals("ingest")) { updateTrackerPersistentStore.objectCreated(pid, date, key); } else if (method.equals("modifyObject")) { updateTrackerPersistentStore.objectStateChanged(pid, date, param, key); } else if (method.equals("purgeObject")) { updateTrackerPersistentStore.objectDeleted(pid, date, key); } else if (method.equals("addDatastream") || method.equals("modifyDatastreamByReference") || method.equals("modifyDatastreamByValue") || method.equals("purgeDatastream") || method.equals("setDatastreamState") || method.equals("setDatastreamVersionable")) { updateTrackerPersistentStore.datastreamChanged(pid, date, param, key); } else if (method.equals("addRelationship") || method.equals("purgeRelationship")) { updateTrackerPersistentStore.objectRelationsChanged(pid, date, key); } else if (method.equals("getObjectXML") || method.equals("export") || method.equals("getDatastream") || method.equals("getDatastreams") || method.equals("getDatastreamHistory") || method.equals("putTempStream") || method.equals("getTempStream") || method.equals("compareDatastreamChecksum") || method.equals("getNextPID") || method.equals("getRelationships") || method.equals("validate")) {// Nothing to do log.debug("Got nonchanging event '{}' from worklog", event); } else { log.warn("Got unknown event '{}' from worklog", event); } } }
package progen.output.outputers; import java.util.Map; import progen.context.ProGenContext; import progen.kernel.population.Individual; import progen.output.HistoricalData; import progen.output.datacollectors.DataCollector; import progen.output.plugins.Mean; import progen.output.plugins.Plugin; public class StandardFile extends FileOutput { private static final String SINGLE_BLANK_SPACE = " "; private static final String EXPERIMENT_INDIVIDUAL_DATA = "ExperimentIndividualData"; /** Separador central de la tabla que imprime por pantalla. */ private static final String CENTER_SEP = " | "; /** Separador izquierdo de la tabla que imprime por pantalla. */ private static final String LEFT_SEP = CENTER_SEP.substring(1, 3); /** Separador derecho de la tabla que imprime por pantalla. */ private static final String RIGHT_SEP = CENTER_SEP.substring(1); /** Ancho de cada columna de la tabla. */ private static final int WIDTH_COLUMN = 10; /** Ancho de la primera columna. */ private int firstColumnWidth; /** Ancho de la segunda columna. */ private int secondColumnWidth; private HistoricalData historical; /** Datos de un experimento concreto. */ private DataCollector experimentData; /** Separador horizontal de filas. */ private String hline; private int totalRPB; private int totalADF; /** * Constructor por defecto. */ public StandardFile() { super("standardOutput.txt", true); historical = HistoricalData.makeInstance(); experimentData = historical.getDataCollectorExperiment(EXPERIMENT_INDIVIDUAL_DATA); final int maxLineLength = getMaxLine().length(); final StringBuilder stb = new StringBuilder(SINGLE_BLANK_SPACE); for (int i = 2; i < maxLineLength - 1; i++) { stb.append("-"); } hline = String.format("%s%n", stb.toString()); totalRPB = Integer.parseInt(ProGenContext.getMandatoryProperty("progen.total.RPB")); totalADF = ProGenContext.getOptionalProperty("progen.total.ADF", 0); } /* * (non-Javadoc) * * @see progen.output.outputers.Outputer#print() */ public void print() { this.init(); final int currentGeneration = historical.getCurrentGeneration(); final int maxGenerations = ProGenContext.getOptionalProperty("progen.max-generation", Integer.MAX_VALUE); if (currentGeneration < maxGenerations) { printHeader(maxGenerations); printBody(); printTail(); } this.close(); } /** * Imprime la cabecera de la tabla de resultados. */ private void printHeader(int maxGenerations) { final String generation = String.format("%s%s",getLiterals().getString("generation"), Formatter.right(historical.getCurrentGeneration(), maxGenerations)); getWriter().printf("%n%n%s", hline); getWriter().printf("%s%s%s%n", LEFT_SEP, Formatter.center(generation, getMaxLine().length() - LEFT_SEP.length() - RIGHT_SEP.length()), RIGHT_SEP); getWriter().printf("%s", hline); } /** * Imprime el grueso de la tabla. */ private void printBody() { final Individual bestTotal = (Individual) (historical.getDataCollectorExperiment(EXPERIMENT_INDIVIDUAL_DATA).getPlugin("best").getValue()); final Individual bestGeneration = (Individual) (historical.getCurrentDataCollector(EXPERIMENT_INDIVIDUAL_DATA).getPlugin("best").getValue()); printIndividual(); printTime(); if (bestTotal.equals(bestGeneration)) { printBest(); } } /** * Imprime la tabla del mejor individuo. */ private void printBest() { printBestHeaderTable(); printBestSubHeaderTable(); printBestData(); printBestTail(); } /** * Imprime la cabecera de la tabla del mejor individuo. */ private void printBestHeaderTable() { final StringBuilder line = new StringBuilder(LEFT_SEP); int padding; line.append(String.format("%s%s", Formatter.left(getLiterals().getString("newBestIndividual"), firstColumnWidth + secondColumnWidth), CENTER_SEP)); padding = Formatter.center(getLiterals().getString("raw"), WIDTH_COLUMN).length(); padding += Formatter.center(getLiterals().getString("adjusted"), WIDTH_COLUMN).length() + 3; line.append(String.format("%s%s", Formatter.center(getLiterals().getString("fitness"), padding), CENTER_SEP)); padding = Formatter.center(getLiterals().getString("nodes"), WIDTH_COLUMN).length(); padding += Formatter.center(getLiterals().getString("depth"), WIDTH_COLUMN).length() + 3; for (int i = 0; i < totalRPB; i++) { line.append(String.format("%s%s", Formatter.center("RBP" + i, padding), CENTER_SEP)); } for (int i = 0; i < totalADF; i++) { line.append(String.format("%s%s", Formatter.center("ADF" + i, padding), CENTER_SEP)); } getWriter().printf("%s%n%s", line.toString(), hline); } /** * Imprime la cabecera de la tabla de mejor individuo. */ private void printBestSubHeaderTable() { printIndividualSubHeaderTable(); } /** * Imprime los datos del mejor individuo. */ private void printBestData() { StringBuilder line; String ceilData; Individual best = (Individual) (experimentData.getPlugin("best").getValue()); int padding = Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN).length(); line = new StringBuilder(LEFT_SEP); line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, padding + CENTER_SEP.length()))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("individual"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%.3f", best.getRawFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); ceilData = String.format("%.5f", best.getAdjustedFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); printDataRPB(line, best); printDataADF(line, best); getWriter().printf("%s%n%s", line.toString(), hline); } private void printDataADF(StringBuilder line, Individual individual) { for (int i = 0; i < totalADF; i++) { line.append(String.format("%s%s", Formatter.center(individual.getTrees().get("ADF" + i).getRoot().getTotalNodes() + "", WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(individual.getTrees().get("ADF" + i).getRoot().getMaximunDepth() + "", WIDTH_COLUMN), CENTER_SEP)); } } private void printDataRPB(StringBuilder line, Individual individual) { for (int i = 0; i < totalRPB; i++) { line.append(String.format("%s%s", Formatter.center(individual.getTrees().get("RPB" + i).getRoot().getTotalNodes() + "", WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(individual.getTrees().get("RPB" + i).getRoot().getMaximunDepth() + "", WIDTH_COLUMN), CENTER_SEP)); } } /** * Imprime los datos resumen del mejor individuo. */ private void printBestTail() { StringBuilder stb = new StringBuilder(); Individual best = (Individual) (experimentData.getPlugin("best").getValue()); for (int i = 0; i < best.getTotalRPB(); i++) { stb.append(String.format("RPB%d:%n", i)); stb.append(Formatter.tree(best.getTrees().get("RPB" + i))); stb.append(String.format("%n")); } for (int i = 0; i < best.getTotalADF(); i++) { stb.append(String.format("ADF%d:%n", i)); stb.append(Formatter.tree(best.getTrees().get("ADF" + i))); stb.append(String.format("%n")); } getWriter().println(stb.toString()); } /** * Imprime la tabla de tiempos. */ private void printTime() { printTimeHeaderTable(); printTimeData(); } /** * Imprime los datos de la tabla de tiempos. */ private void printTimeData() { printTimeBreeding(); printTimeEvaluation(); } private void printTimeEvaluation() { final StringBuilder line = new StringBuilder(LEFT_SEP); int padding = hline.length() - (firstColumnWidth + secondColumnWidth) - 2 * CENTER_SEP.length() - 3; padding = padding / 2; Plugin evaluation = historical.getCurrentDataCollector("PopulationTimeData").getPlugin("evaluation"); String ceilData; line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, firstColumnWidth))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("evaluation"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%s", evaluation.getPlugin("mean").getValue().toString()); line.append(String.format("%s%s", Formatter.center(ceilData, padding), CENTER_SEP)); ceilData = String.format("%s", evaluation.getPlugin("total").getValue().toString()); line.append(String.format("%s%s", Formatter.center(ceilData, padding), CENTER_SEP)); getWriter().printf("%s%n%s", line.toString(), hline); } private void printTimeBreeding() { StringBuilder line = new StringBuilder(LEFT_SEP); int padding = hline.length() - (firstColumnWidth + secondColumnWidth) - 2 * CENTER_SEP.length() - 3; padding = padding / 2; Plugin breeding = historical.getCurrentDataCollector("PopulationTimeData").getPlugin("breeding"); String ceilData; line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, firstColumnWidth))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("breeding"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%s", breeding.getPlugin("mean").getValue().toString()); line.append(String.format("%s%s", Formatter.center(ceilData, padding), CENTER_SEP)); ceilData = String.format("%s", breeding.getPlugin("total").getValue().toString()); line.append(String.format("%s%s", Formatter.center(ceilData, padding), CENTER_SEP)); getWriter().printf("%s%n", line.toString()); } /** * Imprime la cabecera de la tabla de tiempos. */ private void printTimeHeaderTable() { StringBuilder line = new StringBuilder(LEFT_SEP); int padding; line.append(String.format("%s%s", Formatter.left(getLiterals().getString("time"), firstColumnWidth + secondColumnWidth), CENTER_SEP)); padding = hline.length() - (firstColumnWidth + secondColumnWidth) - 2 * CENTER_SEP.length() - 3; padding = padding / 2; line.append(String.format("%s%s", Formatter.center(getLiterals().getString("populationMean"), padding), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("totalPopulation"), padding), CENTER_SEP)); getWriter().printf("%s%n%s", line.toString(), hline); } /** * Imprime un individuo. */ private void printIndividual() { printIndividualHeaderTable(); printIndividualSubHeaderTable(); printIndividualData(); } /** * Imprime los datos de un individuo. */ private void printIndividualData() { printIndividualBestRunData(); printIndividualGenerationMeanData(); printIndividualWorstData(); } @SuppressWarnings("unchecked") private void printIndividualGenerationMeanData() { StringBuilder line; String ceilData; DataCollector populationData = historical.getCurrentDataCollector("PopulationData"); Map<String, Mean> mean = (Map<String, Mean>) (populationData.getPlugin("individualMean").getValue()); int padding = Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN).length(); line = new StringBuilder(LEFT_SEP); line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, padding + CENTER_SEP.length()))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("generationMean"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%.3G", mean.get("raw").getValue()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); ceilData = String.format("%.5f", mean.get("adjusted").getValue()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); for (int i = 0; i < totalRPB; i++) { line.append(String.format("%s%s", Formatter.center(mean.get("RPB" + i + "-nodes").getValue().toString(), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(mean.get("RPB" + i + "-depth").getValue().toString(), WIDTH_COLUMN), CENTER_SEP)); } for (int i = 0; i < totalADF; i++) { line.append(String.format("%s%s", Formatter.center(mean.get("ADF" + i + "-nodes").getValue().toString(), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(mean.get("ADF" + i + "-depth").getValue().toString(), WIDTH_COLUMN), CENTER_SEP)); } getWriter().println(line.toString()); } private void printIndividualBestRunData() { StringBuilder line; String ceilData; Individual best = (Individual) (experimentData.getPlugin("best").getValue()); int padding = Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN).length(); line = new StringBuilder(LEFT_SEP); line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, padding + CENTER_SEP.length()))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("bestRun"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%.3f", best.getRawFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); ceilData = String.format("%.5f", best.getAdjustedFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); printDataRPB(line, best); printDataADF(line, best); getWriter().println(line.toString()); } /** * Imprime los datos del peor individuo. */ private void printIndividualWorstData() { StringBuilder line; String ceilData; Individual worst = (Individual) (historical.getCurrentDataCollector(EXPERIMENT_INDIVIDUAL_DATA).getPlugin("worst").getValue()); int padding = Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN).length(); line = new StringBuilder(LEFT_SEP); line.append(String.format("%s", Formatter.center(SINGLE_BLANK_SPACE, padding + CENTER_SEP.length()))); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("worstRun"), secondColumnWidth), CENTER_SEP)); ceilData = String.format("%.3G", worst.getRawFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); ceilData = String.format("%.5f", worst.getAdjustedFitness()); line.append(String.format("%s%s", Formatter.right(ceilData, WIDTH_COLUMN), CENTER_SEP)); printDataRPB(line, worst); printDataADF(line, worst); getWriter().printf("%s%n%s", line.toString(), hline); } /** * Imprime la cabecera de la subtabla de individuos. */ private void printIndividualSubHeaderTable() { // Print sub-head table StringBuilder line = new StringBuilder(LEFT_SEP); int padding = Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN).length(); line.append(String.format("%s %s", Formatter.center(SINGLE_BLANK_SPACE, padding + secondColumnWidth), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("raw"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("adjusted"), WIDTH_COLUMN), CENTER_SEP)); for (int i = 0; i < totalRPB; i++) { line.append(String.format("%s%s", Formatter.center(getLiterals().getString("nodes"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("depth"), WIDTH_COLUMN), CENTER_SEP)); } for (int i = 0; i < totalADF; i++) { line.append(String.format("%s%s", Formatter.center(getLiterals().getString("nodes"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("depth"), WIDTH_COLUMN), CENTER_SEP)); } getWriter().printf("%s%n", line.toString()); } /** * Imprime la cabecera de la tabla de individuos. */ private void printIndividualHeaderTable() { // Print head table StringBuilder line = new StringBuilder(LEFT_SEP); int padding; firstColumnWidth = WIDTH_COLUMN + CENTER_SEP.length(); secondColumnWidth = Math.max(WIDTH_COLUMN, getLiterals().getString("generationMean").length()); secondColumnWidth = Math.max(secondColumnWidth, getLiterals().getString("bestRun").length()); secondColumnWidth = Math.max(secondColumnWidth, getLiterals().getString("worstRun").length()); line.append(String.format("%s%s", Formatter.left(getLiterals().getString("individual"), firstColumnWidth + secondColumnWidth), CENTER_SEP)); padding = Formatter.center(getLiterals().getString("raw"), WIDTH_COLUMN).length(); padding += Formatter.center(getLiterals().getString("adjusted"), WIDTH_COLUMN).length() + 3; line.append(String.format("%s%s", Formatter.center(getLiterals().getString("fitness"), padding), CENTER_SEP)); padding = Formatter.center(getLiterals().getString("nodes"), WIDTH_COLUMN).length(); padding += Formatter.center(getLiterals().getString("depth"), WIDTH_COLUMN).length() + 3; for (int i = 0; i < totalRPB; i++) { line.append(String.format("%s%s", Formatter.center("RBP" + i, padding), CENTER_SEP)); } for (int i = 0; i < totalADF; i++) { line.append(String.format("%s%s", Formatter.center("ADF" + i, padding), CENTER_SEP)); } getWriter().printf("%s%n%s", line.toString(), hline); } /** * Imprime los resumenes de las tablas. */ private void printTail() { // do nothing } private String getMaxLine() { StringBuilder line = new StringBuilder(LEFT_SEP); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("individual"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("generationMean"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("raw"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("adjusted"), WIDTH_COLUMN), CENTER_SEP)); int totalTrees = 0; totalTrees += totalRPB; totalTrees += totalADF; for (int i = 0; i < totalTrees; i++) { line.append(String.format("%s%s", Formatter.center(getLiterals().getString("nodes"), WIDTH_COLUMN), CENTER_SEP)); line.append(String.format("%s%s", Formatter.center(getLiterals().getString("depth"), WIDTH_COLUMN), CENTER_SEP)); } return line.toString(); } }
package org.scijava.plugin; import org.scijava.AbstractContextual; import org.scijava.Contextual; import org.scijava.Prioritized; import org.scijava.Priority; import org.scijava.util.ClassUtils; /** * Abstract base class for {@link Contextual}, {@link Prioritized} plugins that * retain access to their associated {@link PluginInfo} metadata via the * {@link HasPluginInfo} interface. This class is intended as a convenient * extension point for plugin type implementations. * * @author Curtis Rueden */ public abstract class SortablePlugin extends AbstractContextual implements Prioritized, HasPluginInfo, SciJavaPlugin { /** The priority of the plugin. */ private double priority = Priority.NORMAL_PRIORITY; /** The metadata associated with the plugin. */ private PluginInfo<?> info; // -- Object methods -- @Override public String toString() { final PluginInfo<?> pi = getInfo(); return pi == null ? super.toString() : pi.getTitle(); } // -- Prioritized methods -- @Override public double getPriority() { return priority; } @Override public void setPriority(final double priority) { this.priority = priority; } // -- HasPluginInfo methods -- @Override public PluginInfo<?> getInfo() { return info; } @Override public void setInfo(final PluginInfo<?> info) { this.info = info; } // -- Comparable methods -- @Override public int compareTo(final Prioritized that) { if (that == null) return 1; // compare priorities final int priorityCompare = Priority.compare(this, that); if (priorityCompare != 0) return priorityCompare; // compare classes return ClassUtils.compare(getClass(), that.getClass()); } }
package com.xpn.xwiki.plugin.activitystream.impl; import java.util.List; import java.util.ArrayList; import java.io.StringWriter; import java.io.IOException; import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.lang.RandomStringUtils; import org.hibernate.Query; import org.hibernate.Session; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.XWikiLock; import com.xpn.xwiki.notify.DocChangeRule; import com.xpn.xwiki.notify.XWikiDocChangeNotificationInterface; import com.xpn.xwiki.notify.XWikiNotificationRule; import com.xpn.xwiki.plugin.activitystream.api.ActivityEvent; import com.xpn.xwiki.plugin.activitystream.api.ActivityEventPriority; import com.xpn.xwiki.plugin.activitystream.api.ActivityEventType; import com.xpn.xwiki.plugin.activitystream.api.ActivityStream; import com.xpn.xwiki.plugin.activitystream.api.ActivityStreamException; import com.xpn.xwiki.store.XWikiHibernateStore; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.SyndFeedOutput; import com.sun.syndication.io.FeedException; /** * @version $Id: $ */ public class ActivityStreamImpl implements ActivityStream, XWikiDocChangeNotificationInterface { public void initClasses(XWikiContext context) throws XWikiException { // listen to notifications context.getWiki().getNotificationManager().addGeneralRule(new DocChangeRule(this)); } protected void prepareEvent(ActivityEvent event, XWikiDocument doc, XWikiContext context) { if (doc == null) doc = context.getDoc(); if (event.getUser() == null) { event.setUser(context.getUser()); } if (event.getStream() == null) { String space = (doc == null) ? "" : doc.getSpace(); event.setStream(getStreamName(space, context)); } if (event.getWiki() == null) { event.setWiki(context.getDatabase()); } if (event.getSpace() == null) { event.setSpace((doc == null) ? "" : doc.getSpace()); } if (event.getPage() == null) { event.setPage((doc == null) ? "" : doc.getFullName()); } if (event.getUrl() == null) { event.setUrl((doc == null) ? "" : doc.getURL("view", context)); } if (event.getApplication() == null) { event.setApplication("xwiki"); } if (event.getDate() == null) { event.setDate(context.getWiki().getCurrentDate()); } if (event.getEventId() == null) { event.setEventId(generateEventId(event, context)); } if (event.getRequestId() == null) { event.setRequestId((String) context.get("activitystream_requestid")); } } public String getStreamName(String space, XWikiContext context) { return space; } protected String generateEventId(ActivityEvent event, XWikiContext context) { String key = event.getStream() + "-" + event.getApplication() + "-" + event.getWiki() + ":" + event.getPage() + "-" + event.getType(); long hash = key.hashCode(); if (hash < 0) hash = -hash; String id = "" + hash + "-" + event.getDate().getTime() + "-" + RandomStringUtils.randomAlphanumeric(8); if (context.get("activitystream_requestid") == null) { context.put("activitystream_requestid", id); } return id; } public void addActivityEvent(ActivityEvent event, XWikiContext context) throws ActivityStreamException { addActivityEvent(event, null, context); } public void addActivityEvent(ActivityEvent event, XWikiDocument doc, XWikiContext context) throws ActivityStreamException { prepareEvent(event, doc, context); // store event using hibernate XWikiHibernateStore hibstore = context.getWiki().getHibernateStore(); try { hibstore.beginTransaction(context); Session session = hibstore.getSession(context); session.save(event); hibstore.endTransaction(context, true); } catch (XWikiException e) { hibstore.endTransaction(context, false); } } public void addActivityEvent(String streamName, String type, String title, XWikiContext context) throws ActivityStreamException { addActivityEvent(streamName, type, title, null, context); } public void addActivityEvent(String streamName, String type, String title, List<String> params, XWikiContext context) throws ActivityStreamException { ActivityEvent event = newActivityEvent(); event.setStream(streamName); event.setType(type); event.setTitle(title); event.setBody(title); event.setParams(params); addActivityEvent(event, context); } public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, String title, XWikiContext context) throws ActivityStreamException { addDocumentActivityEvent(streamName, doc, type, ActivityEventPriority.NOTIFICATION, title, null, context); } public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, int priority, String title, XWikiContext context) throws ActivityStreamException { addDocumentActivityEvent(streamName, doc, type, priority, title, null, context); } public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, String title, List<String> params, XWikiContext context) throws ActivityStreamException { addDocumentActivityEvent(streamName, doc, type, ActivityEventPriority.NOTIFICATION, title, params, context); } public void addDocumentActivityEvent(String streamName, XWikiDocument doc, String type, int priority, String title, List<String> params, XWikiContext context) throws ActivityStreamException { ActivityEvent event = newActivityEvent(); event.setStream(streamName); event.setPage(doc.getFullName()); if (doc.getDatabase() != null) { event.setWiki(doc.getDatabase()); } event.setDate(doc.getDate()); event.setPriority(priority); event.setType(type); event.setTitle(title); event.setBody(title); event.setParams(params); addActivityEvent(event, doc, context); } private ActivityEventImpl loadActivityEvent(ActivityEvent ev, boolean bTransaction, XWikiContext context) throws ActivityStreamException { ActivityEventImpl act = null; String eventId = ev.getEventId(); XWikiHibernateStore hibstore = context.getWiki().getHibernateStore(); try { if (bTransaction) { hibstore.checkHibernate(context); bTransaction = hibstore.beginTransaction(false, context); } Session session = hibstore.getSession(context); Query query = session .createQuery("select act.eventId from ActivityEventImpl as act where act.eventId = :eventId"); query.setString("eventId", eventId); if (query.uniqueResult() != null) { act = new ActivityEventImpl(); session.load(act, eventId); } if (bTransaction) hibstore.endTransaction(context, false, false); } catch (Exception e) { throw new ActivityStreamException(); } finally { try { if (bTransaction) hibstore.endTransaction(context, false, false); } catch (Exception e) { } } return act; } public void deleteActivityEvent(ActivityEvent event, XWikiContext context) throws ActivityStreamException { boolean bTransaction = true; ActivityEventImpl evImpl = loadActivityEvent(event, true, context); XWikiHibernateStore hibstore = context.getWiki().getHibernateStore(); try { if (bTransaction) { hibstore.checkHibernate(context); bTransaction = hibstore.beginTransaction(context); } Session session = hibstore.getSession(context); session.delete(evImpl); if (bTransaction) { hibstore.endTransaction(context, true); } } catch (XWikiException e) { throw new ActivityStreamException(); } finally { try { if (bTransaction) { hibstore.endTransaction(context, false); } } catch (Exception e) { } } } public List<ActivityEvent> searchEvents(String hql, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { String searchHql; if (filter) { searchHql = "select act from ActivityEventImpl as act, ActivityEventImpl as act2 where act.eventId=act2.eventId and " + hql + " group by act.requestId having (act.priority)=max(act2.priority) order by act.date desc"; } else { searchHql = "select act from ActivityEventImpl as act where " + hql + " order by act.date desc"; } try { return context.getWiki().search(searchHql, nb, start, context); } catch (XWikiException e) { throw new ActivityStreamException(e); } } public List<ActivityEvent> getEvents(boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("1=1", filter, nb, start, context); } public List<ActivityEvent> getEventsForSpace(String space, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("act.space='" + space + "'", filter, nb, start, context); } public List<ActivityEvent> getEventsForUser(String user, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("act.user='" + user + "'", filter, nb, start, context); } public List<ActivityEvent> getEvents(String stream, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("act.stream='" + stream + "'", filter, nb, start, context); } public List<ActivityEvent> getEventsForSpace(String stream, String space, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("act.space='" + space + "' and act.stream='" + stream + "'", filter, nb, start, context); } public List<ActivityEvent> getEventsForUser(String stream, String user, boolean filter, int nb, int start, XWikiContext context) throws ActivityStreamException { return searchEvents("act.user='" + user + "' and act.stream='" + stream + "'", filter, nb, start, context); } protected ActivityEvent newActivityEvent() { return new ActivityEventImpl(); } public void notify(XWikiNotificationRule rule, XWikiDocument newdoc, XWikiDocument olddoc, int event, XWikiContext context) { ArrayList<String> params = new ArrayList<String>(); params.add(0, newdoc.getDisplayTitle(context)); String streamName = getStreamName(newdoc.getSpace(), context); if (streamName == null) return; try { switch (event) { case XWikiDocChangeNotificationInterface.EVENT_CHANGE: if (olddoc==null || olddoc.isNew()) addDocumentActivityEvent(streamName, newdoc, ActivityEventType.CREATE, "as_document_has_been_created", params, context); else if (newdoc==null || newdoc.isNew()) addDocumentActivityEvent(streamName, newdoc, ActivityEventType.DELETE, "as_document_has_been_deleted", params, context); else addDocumentActivityEvent(streamName, newdoc, ActivityEventType.UPDATE, "as_document_has_been_updated", params, context); break; case XWikiDocChangeNotificationInterface.EVENT_NEW: addDocumentActivityEvent(streamName, newdoc, ActivityEventType.CREATE, "as_document_has_been_created", params, context); break; case XWikiDocChangeNotificationInterface.EVENT_DELETE: addDocumentActivityEvent(streamName, newdoc, ActivityEventType.DELETE, "as_document_has_been_deleted", params, context); break; case XWikiDocChangeNotificationInterface.EVENT_UPDATE_CONTENT: addDocumentActivityEvent(streamName, newdoc, ActivityEventType.UPDATE, "as_document_has_been_updated", params, context); break; case XWikiDocChangeNotificationInterface.EVENT_UPDATE_OBJECT: addDocumentActivityEvent(streamName, newdoc, ActivityEventType.UPDATE, "as_document_has_been_updated", params, context); break; case XWikiDocChangeNotificationInterface.EVENT_UPDATE_CLASS: addDocumentActivityEvent(streamName, newdoc, ActivityEventType.UPDATE, "as_document_has_been_updated", params, context); break; } } catch (Throwable e) { // Error in activity stream notify should be ignored but logged in the log file e.printStackTrace(); } } public SyndEntry getFeedEntry(ActivityEvent event, XWikiContext context) { SyndEntry entry = new SyndEntryImpl(); String user = event.getUser(); String displayUser = context.getWiki().getUserName(user, null, false, context); entry.setAuthor(displayUser); entry.setTitle(event.getDisplayTitle(context)); // entry.setDescription(event.getDisplayBody(context)); String url; try { url = (new URL(context.getURL(), event.getUrl())).toString(); } catch (MalformedURLException e) { url = event.getUrl(); } entry.setLink(url); entry.setPublishedDate(event.getDate()); entry.setUpdatedDate(event.getDate()); return entry; } public SyndFeed getFeed(List<ActivityEvent> events, XWikiContext context) { SyndFeed feed = new SyndFeedImpl(); List<SyndEntry> entries = new ArrayList<SyndEntry>(); for (ActivityEvent event : events) { SyndEntry entry = getFeedEntry(event, context); entries.add(entry); } feed.setEntries(entries); return feed; } public SyndFeed getFeed(List<ActivityEvent> events, String author, String title, String description, String copyright, String encoding, String url, XWikiContext context) { SyndFeed feed = getFeed(events, context); feed.setAuthor(author); feed.setDescription(description); feed.setCopyright(copyright); feed.setEncoding(encoding); feed.setLink(url); feed.setTitle(title); return feed; } public String getFeedOutput(List<ActivityEvent> events, String author, String title, String description, String copyright, String encoding, String url, String type, XWikiContext context) { SyndFeed feed = getFeed(events, author, title, description, copyright, encoding, url, context); return getFeedOutput(feed, type); } public String getFeedOutput(SyndFeed feed, String type) { feed.setFeedType(type); StringWriter writer = new StringWriter(); SyndFeedOutput output = new SyndFeedOutput(); try { output.output(feed, writer); writer.close(); return writer.toString(); } catch (Exception e) { return ""; } } }
package org.scijava.service; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.scijava.AbstractContextual; import org.scijava.Context; import org.scijava.Optional; import org.scijava.event.EventService; import org.scijava.log.LogService; import org.scijava.log.StderrLogService; import org.scijava.plugin.Parameter; import org.scijava.plugin.PluginInfo; import org.scijava.service.event.ServicesLoadedEvent; import org.scijava.util.ClassUtils; /** * Helper class for discovering and instantiating available services. * * @author Curtis Rueden */ public class ServiceHelper extends AbstractContextual { /** * For logging. */ private LogService log; /** * Classes to scan when searching for dependencies. Data structure is a map * with keys being relevant classes, and values being associated priorities. */ private final Map<Class<? extends Service>, Double> classPoolMap; /** Classes to scan when searching for dependencies, sorted by priority. */ private final List<Class<? extends Service>> classPoolList; /** Classes to instantiate as services. */ private final List<Class<? extends Service>> serviceClasses; /** * Creates a new service helper for discovering and instantiating services. * * @param context The application context for which services should be * instantiated. */ public ServiceHelper(final Context context) { this(context, null); } /** * Creates a new service helper for discovering and instantiating services. * * @param context The application context to which services should be added. * @param serviceClasses The service classes to instantiate. */ public ServiceHelper(final Context context, final Collection<Class<? extends Service>> serviceClasses) { setContext(context); log = context.getService(LogService.class); if (log == null) log = new StderrLogService(); classPoolMap = new HashMap<Class<? extends Service>, Double>(); classPoolList = new ArrayList<Class<? extends Service>>(); findServiceClasses(classPoolMap, classPoolList); if (classPoolList.isEmpty()) { log.warn("Class pool is empty: forgot to call Thread#setClassLoader?"); } this.serviceClasses = new ArrayList<Class<? extends Service>>(); if (serviceClasses == null) { // load all discovered services this.serviceClasses.addAll(classPoolList); } else { // load only the services that were explicitly specified this.serviceClasses.addAll(serviceClasses); } } // -- ServiceHelper methods -- /** * Ensures all candidate service classes are registered in the index, locating * and instantiating compatible services as needed. */ public void loadServices() { for (final Class<? extends Service> serviceClass : serviceClasses) { loadService(serviceClass); if (serviceClass == LogService.class) { final LogService logService = getContext().getService(LogService.class); if (logService != null) log = logService; } } final EventService eventService = getContext().getService(EventService.class); if (eventService != null) eventService.publish(new ServicesLoadedEvent()); } public <S extends Service> S loadService(final Class<S> c) { // if a compatible service already exists, return it final S service = getContext().getServiceIndex().getService(c); if (service != null) return service; // scan the class pool for a suitable match for (final Class<? extends Service> serviceClass : classPoolList) { if (c.isAssignableFrom(serviceClass)) { // found a match; now instantiate it @SuppressWarnings("unchecked") final S result = (S) createExactService(serviceClass); return result; } } if (c.isInterface()) { throw new IllegalArgumentException("No class found that implements " + c); } return createExactService(c); } /** * Instantiates a service of the given class, registering it in the index. * * @return the newly created service, or null if the given class cannot be * instantiated */ public <S extends Service> S createExactService(final Class<S> c) { final String name = c.getName(); log.debug("Creating service: " + name, null); try { long start = 0, end = 0; boolean debug = log.isDebug(); if (debug) start = System.currentTimeMillis(); final S service = createService(c); getContext().getServiceIndex().add(service); if (debug) end = System.currentTimeMillis(); log.info("Created service: " + name); if (debug) { log.debug("\t[" + name + " created in " + (end - start) + " ms]"); } return service; } catch (final Throwable t) { if (log.isDebug()) { // when in debug mode, always give full stack trace of invalid services log.debug("Invalid service: " + name, t); } else if (!Optional.class.isAssignableFrom(c)) { // for required (i.e., non-optional) services, we also dump the stack log.warn("Invalid service: " + name, t); } else { // we emit only a short warning for failing optional services log.warn("Invalid service: " + name); } } return null; } // -- Helper methods -- /** Instantiates a service using the given constructor. */ private <S extends Service> S createService(final Class<S> c) throws InstantiationException, IllegalAccessException { final S service = c.newInstance(); service.setContext(getContext()); // propagate priority if known final Double priority = classPoolMap.get(c); if (priority != null) service.setPriority(priority); // populate service parameters final List<Field> fields = ClassUtils.getAnnotatedFields(c, Parameter.class); for (final Field f : fields) { f.setAccessible(true); // expose private fields final Class<?> type = f.getType(); if (!Service.class.isAssignableFrom(type)) { throw new IllegalArgumentException("Invalid parameter: " + f.getName()); } @SuppressWarnings("unchecked") final Class<Service> serviceType = (Class<Service>) type; Service s = getContext().getServiceIndex().getService(serviceType); if (s == null) { // recursively obtain needed service s = loadService(serviceType); } ClassUtils.setValue(f, service, s); } service.initialize(); service.registerEventHandlers(); return service; } /** Asks the plugin index for all available service implementations. */ private void findServiceClasses( final Map<Class<? extends Service>, Double> serviceMap, final List<Class<? extends Service>> serviceList) { // ask the plugin index for the (sorted) list of available services final List<PluginInfo<Service>> services = getContext().getPluginIndex().getPlugins(Service.class); for (final PluginInfo<Service> info : services) { try { final Class<? extends Service> c = info.loadClass(); final double priority = info.getPriority(); serviceMap.put(c, priority); serviceList.add(c); } catch (final Throwable e) { log.error("Invalid service: " + info, e); } } } }
package org.xwiki.url; import org.xwiki.component.annotation.Role; import org.xwiki.stability.Unstable; /** * Normalize a relative URL. Various implementations can exist, for example one implementation may normalize the passed * relative URL into a full absolute {@link java.net.URL} object. Another implementation may simply prefix the passed * relative URL with a Servlet Container's webapp name (aka application context name). Note that in general the * implementations will depends on the Container in which XWiki is executing (eg Servlet Container). * <p/> * It's also important that Normalizers should be independent of URL Scheme formats since they should be usable * for all URL Schemes. Note that Normalizers should not replace {@link org.xwiki.resource.ResourceReferenceSerializer} * implementations. * * @param <T> the type of object to return (eg {@link ExtendedURL}, {@link java.net.URL}) * @version $Id$ * @since 6.1M2 */ @Role @Unstable public interface URLNormalizer<T> { /** * @param partialURL the partial URL to normalize * @return the normalized URL, what is done depends on the implementation */ T normalize(ExtendedURL partialURL); }
package org.opendaylight.yangtools.yang.data.impl.schema.tree; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Verify.verify; import static java.util.Objects.requireNonNull; import com.google.common.base.MoreObjects; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.yangtools.concepts.Immutable; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild; import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode; import org.opendaylight.yangtools.yang.data.api.schema.LeafNode; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A validator for a single {@code unique} constraint. This class is further specialized for single- and * multiple-constraint implementations. * * <p> * The basic idea is that for each list entry there is a corresponding value vector of one or more values, each * corresponding to one component of the {@code unique} constraint. */ abstract class UniqueValidator<T> implements Immutable { private static final class One extends UniqueValidator<Object> { One(final List<NodeIdentifier> path) { super(encodePath(path)); } @Override Object extractValues(final Map<List<NodeIdentifier>, Object> valueCache, final DataContainerNode<?> data) { return extractValue(valueCache, data, decodePath(descendants)); } @Override Map<Descendant, @Nullable Object> indexValues(final Object values) { return Collections.singletonMap(decodeDescendant(descendants), values); } } private static final class Many extends UniqueValidator<Set<Object>> { Many(final List<List<NodeIdentifier>> descendantPaths) { super(descendantPaths.stream().map(UniqueValidator::encodePath).collect(ImmutableSet.toImmutableSet())); } @Override UniqueValues extractValues(final Map<List<NodeIdentifier>, Object> valueCache, final DataContainerNode<?> data) { return descendants.stream() .map(obj -> extractValue(valueCache, data, decodePath(obj))) .collect(UniqueValues.COLLECTOR); } @Override Map<Descendant, @Nullable Object> indexValues(final Object values) { final Map<Descendant, @Nullable Object> index = Maps.newHashMapWithExpectedSize(descendants.size()); final Iterator<?> it = ((UniqueValues) values).iterator(); for (Object obj : descendants) { verify(index.put(decodeDescendant(obj), it.next()) == null); } return index; } } private static final Logger LOG = LoggerFactory.getLogger(UniqueValidator.class); final @NonNull T descendants; UniqueValidator(final T descendants) { this.descendants = requireNonNull(descendants); } static UniqueValidator<?> of(final List<List<NodeIdentifier>> descendants) { return descendants.size() == 1 ? new One(descendants.get(0)) : new Many(descendants); } /** * Extract a value vector from a particular child. * * @param valueCache Cache of descendants already looked up * @param data Root data node * @return Value vector */ abstract @Nullable Object extractValues(Map<List<NodeIdentifier>, Object> valueCache, DataContainerNode<?> data); /** * Index a value vector by associating each value with its corresponding {@link Descendant}. * * @param values Value vector * @return Map of Descandant/value relations */ abstract Map<Descendant, @Nullable Object> indexValues(Object values); @Override public final String toString() { return MoreObjects.toStringHelper(this).add("paths", descendants).toString(); } /** * Encode a path for storage. Single-element paths are squashed to their only element. The inverse operation is * {@link #decodePath(Object)}. * * @param path Path to encode * @return Encoded path. */ @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "https://github.com/spotbugs/spotbugs/issues/811") private static Object encodePath(final List<NodeIdentifier> path) { return path.size() == 1 ? path.get(0) : ImmutableList.copyOf(path); } /** * Decode a path from storage. This is the inverse operation to {@link #encodePath(List)}. * * @param obj Encoded path * @return Decoded path */ private static @NonNull ImmutableList<NodeIdentifier> decodePath(final Object obj) { return obj instanceof NodeIdentifier ? ImmutableList.of((NodeIdentifier) obj) : (ImmutableList<NodeIdentifier>) obj; } @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "https://github.com/spotbugs/spotbugs/issues/811") private static @NonNull Descendant decodeDescendant(final Object obj) { return Descendant.of(Collections2.transform(decodePath(obj), NodeIdentifier::getNodeType)); } /** * Extract the value for a single descendant. * * @param valueCache Cache of descendants already looked up * @param data Root data node * @param path Descendant path * @return Value for the descendant */ @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD", justification = "https://github.com/spotbugs/spotbugs/issues/811") private static @Nullable Object extractValue(final Map<List<NodeIdentifier>, Object> valueCache, final DataContainerNode<?> data, final List<NodeIdentifier> path) { return valueCache.computeIfAbsent(path, key -> extractValue(data, key)); } /** * Extract the value for a single descendant. * * @param data Root data node * @param path Descendant path * @return Value for the descendant */ private static @Nullable Object extractValue(final DataContainerNode<?> data, final List<NodeIdentifier> path) { DataContainerNode<?> current = data; final Iterator<NodeIdentifier> it = path.iterator(); while (true) { final NodeIdentifier step = it.next(); final Optional<DataContainerChild<?, ?>> optNext = current.getChild(step); if (optNext.isEmpty()) { return null; } final DataContainerChild<?, ?> next = optNext.orElseThrow(); if (!it.hasNext()) { checkState(next instanceof LeafNode, "Unexpected node %s at %s", next, path); final Object value = next.getValue(); LOG.trace("Resolved {} to value {}", path, value); return value; } checkState(next instanceof DataContainerNode, "Unexpected node %s in %s", next, path); current = (DataContainerNode<?>) next; } } }
package org.voovan.tools.reflect; import org.voovan.tools.TDateTime; import org.voovan.tools.TObject; import org.voovan.tools.TString; import org.voovan.tools.json.JSON; import org.voovan.tools.json.annotation.NotJSON; import org.voovan.tools.reflect.annotation.NotSerialization; import java.lang.reflect.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Map.Entry; public class TReflect { private static Map<String, Field> fields = new HashMap<String ,Field>(); private static Map<String, Method> methods = new HashMap<String ,Method>(); private static Map<String, Field[]> fieldArrays = new HashMap<String ,Field[]>(); private static Map<String, Method[]> methodArrays = new HashMap<String ,Method[]>(); /** * Field * * @param clazz * @return Field */ public static Field[] getFields(Class<?> clazz) { String mark = clazz.getCanonicalName(); Field[] fields = null; if(fieldArrays.containsKey(mark)){ fields = fieldArrays.get(mark); }else { ArrayList<Field> fieldArray = new ArrayList<Field>(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { Field[] tmpFields = clazz.getDeclaredFields(); fieldArray.addAll(Arrays.asList(tmpFields)); } fields = fieldArray.toArray(new Field[]{}); fieldArrays.put(mark, fields); fieldArray.clear(); } return fields; } /** * Field * * @param clazz * @param fieldName field * @return field * @throws NoSuchFieldException Field * @throws SecurityException */ public static Field findField(Class<?> clazz, String fieldName) throws ReflectiveOperationException { String mark = clazz.getCanonicalName()+"#"+fieldName; try { if(fields.containsKey(mark)){ return fields.get(mark); }else { Field field = clazz.getDeclaredField(fieldName); fields.put(mark, field); return field; } }catch(NoSuchFieldException ex){ Class superClazz = clazz.getSuperclass(); if( superClazz != Object.class ) { return findField(clazz.getSuperclass(), fieldName); }else{ return null; } } } /** * Field * , * @param clazz * @param fieldName Field * @return Field * @throws ReflectiveOperationException */ public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName) throws ReflectiveOperationException{ String mark = clazz.getCanonicalName()+"#"+fieldName; if(fields.containsKey(mark)){ return fields.get(mark); }else { for (Field field : getFields(clazz)) { if (field.getName().equalsIgnoreCase(fieldName)) { fields.put(mark, field); return field; } } } return null; } /** * Field * @param field field * @return * @throws ClassNotFoundException */ public static Class[] getFieldGenericType(Field field) throws ClassNotFoundException { Class[] result = null; Type fieldType = field.getGenericType(); if(fieldType instanceof ParameterizedType){ ParameterizedType parameterizedFieldType = (ParameterizedType)fieldType; Type[] actualType = parameterizedFieldType.getActualTypeArguments(); result = new Class[actualType.length]; for(int i=0;i<actualType.length;i++){ String classStr = actualType[i].getTypeName(); classStr = classStr.replaceAll("<.*>",""); result[i] = Class.forName(classStr); } return result; } return null; } /** * Field * @param <T> * @param obj * @param fieldName Field * @return Field * @throws ReflectiveOperationException */ @SuppressWarnings("unchecked") static public <T> T getFieldValue(Object obj, String fieldName) throws ReflectiveOperationException { Field field = findField(obj.getClass(), fieldName); field.setAccessible(true); return (T) field.get(obj); } /** * Field * : private * * @param obj * @param fieldName field * @param fieldValue field * @throws ReflectiveOperationException */ public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws ReflectiveOperationException { Field field = findField(obj.getClass(), fieldName); field.setAccessible(true); field.set(obj, fieldValue); } /** * fieldMap (static) * * @param obj * @return field - Map * @throws ReflectiveOperationException */ public static Map<Field, Object> getFieldValues(Object obj) throws ReflectiveOperationException { HashMap<Field, Object> result = new HashMap<Field, Object>(); Field[] fields = getFields(obj.getClass()); for (Field field : fields) { if (!Modifier.isStatic(field.getModifiers()) && field.getAnnotation(NotJSON.class)==null && field.getAnnotation(NotSerialization.class)==null) { Object value = getFieldValue(obj, field.getName()); result.put(field, value); } } return result; } /** * * @param clazz * @param name * @param paramTypes * @return * @throws ReflectiveOperationException */ public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) throws ReflectiveOperationException { String mark = clazz.getCanonicalName()+"#"+name; for(Class<?> paramType : paramTypes){ mark = mark + "$" + paramType.getCanonicalName(); } if(methods.containsKey(mark)){ return methods.get(mark); }else { Method method = clazz.getDeclaredMethod(name, paramTypes); methods.put(mark, method); return method; } } /** * () * @param clazz * @param name * @param paramCount * @return * @throws ReflectiveOperationException */ public static Method[] findMethod(Class<?> clazz, String name, int paramCount) throws ReflectiveOperationException { Method[] methods = null; String mark = clazz.getCanonicalName()+"#"+name+"@"+paramCount; if(methodArrays.containsKey(mark)){ return methodArrays.get(mark); } else { ArrayList<Method> methodList = new ArrayList<Method>(); Method[] allMethods = getMethods(clazz, name); for (Method method : allMethods) { if (method.getParameters().length == paramCount) { methodList.add(method); } } methods = methodList.toArray(new Method[]{}); methodArrays.put(mark,methods); methodList.clear(); } return methods; } /** * * @param clazz * @return Method */ public static Method[] getMethods(Class<?> clazz) { Method[] methods = null; String mark = clazz.getCanonicalName(); if(methodArrays.containsKey(mark)){ return methodArrays.get(mark); } else { List<Method> methodList = new ArrayList<Method>(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { Method[] tmpMethods = clazz.getDeclaredMethods(); methodList.addAll(Arrays.asList(tmpMethods)); } methods = methodList.toArray(new Method[]{}); methodList.clear(); methodArrays.put(mark,methods); } return methods; } /** * * * @param clazz * @param name * @return Method */ public static Method[] getMethods(Class<?> clazz,String name) { Method[] methods = null; String mark = clazz.getCanonicalName()+"#"+name; if(methodArrays.containsKey(mark)){ return methodArrays.get(mark); } else { ArrayList<Method> methodList = new ArrayList<Method>(); Method[] allMethods = getMethods(clazz); for (Method method : allMethods) { if (method.getName().equals(name)) methodList.add(method); } methods = methodList.toArray(new Method[0]); methodList.clear(); methodArrays.put(mark,methods); } return methods; } /** * * @param method method * @param parameterIndex (0)[0,], (-1) * @return * @throws ClassNotFoundException */ public static Class[] getMethodParameterGenericType(Method method,int parameterIndex) throws ClassNotFoundException { Class[] result = null; Type parameterType; if(parameterIndex == -1){ parameterType = method.getGenericReturnType(); }else{ parameterType = method.getGenericParameterTypes()[parameterIndex]; } if(parameterType instanceof ParameterizedType){ ParameterizedType parameterizedFieldType = (ParameterizedType)parameterType; Type[] actualType = parameterizedFieldType.getActualTypeArguments(); result = new Class[actualType.length]; for(int i=0;i<actualType.length;i++){ String classStr = actualType[i].getTypeName(); classStr = classStr.replaceAll("<.*>",""); result[i] = Class.forName(classStr); } return result; } return null; } /** * * Method * @param obj * @param method * @param parameters * @return * @throws ReflectiveOperationException */ public static Object invokeMethod(Object obj, Method method, Object... parameters) throws ReflectiveOperationException { return method.invoke(obj, parameters); } /** * * , * * @param obj , Class * @param name * @param parameters * @return * @throws ReflectiveOperationException */ public static Object invokeMethod(Object obj, String name, Object... parameters) throws ReflectiveOperationException { Class<?>[] parameterTypes = getArrayClasses(parameters); Method method = null; Class objClass = (obj instanceof Class) ? (Class)obj : obj.getClass(); try { method = findMethod(objClass, name, parameterTypes); method.setAccessible(true); return method.invoke(obj, parameters); }catch(Exception e){ Exception lastExecption = e; Method[] methods = findMethod(objClass,name,parameterTypes.length); for(Method similarMethod : methods){ Parameter[] methodParams = similarMethod.getParameters(); if(methodParams.length == parameters.length){ Object[] convertedParams = new Object[parameters.length]; for(int i=0;i<methodParams.length;i++){ Parameter parameter = methodParams[i]; String value = ""; Class parameterClass = parameters[i].getClass(); // JSON, if(parameters[i] instanceof Collection || parameters[i] instanceof Map || parameterClass.isArray() || !parameterClass.getCanonicalName().startsWith("java.lang")){ value = JSON.toJSON(parameters[i]); }else{ value = parameters[i].toString(); } convertedParams[i] = TString.toObject(value, parameter.getType()); } method = similarMethod; try{ method.setAccessible(true); return method.invoke(obj, convertedParams); }catch(Exception ex){ lastExecption = (Exception) ex.getCause(); continue; } } } if ( !(lastExecption instanceof ReflectiveOperationException) ) { lastExecption = new ReflectiveOperationException(lastExecption); } throw (ReflectiveOperationException)lastExecption; } } /** * * parameters, * @param <T> * @param clazz * @param parameters * @return * @throws ReflectiveOperationException */ public static <T> T newInstance(Class<T> clazz, Object ...parameters) throws ReflectiveOperationException { Class<?>[] parameterTypes = getArrayClasses(parameters); Constructor<T> constructor = null; try { if (parameters.length == 0) { constructor = clazz.getConstructor(); } else { constructor = clazz.getConstructor(parameterTypes); } return constructor.newInstance(parameters); }catch(Exception e){ Constructor[] constructors = clazz.getConstructors(); for(Constructor similarConstructor : constructors){ Parameter[] methodParams = similarConstructor.getParameters(); if(methodParams.length == parameters.length){ Object[] convertedParams = new Object[parameters.length]; for(int i=0;i<methodParams.length;i++){ Parameter parameter = methodParams[i]; String value = ""; Class parameterClass = parameters[i].getClass(); // JSON, if(parameters[i] instanceof Collection || parameters[i] instanceof Map || parameterClass.isArray() || !parameterClass.getCanonicalName().startsWith("java.lang")){ value = JSON.toJSON(parameters[i]); }else{ value = parameters[i].toString(); } convertedParams[i] = TString.toObject(value, parameter.getType()); } constructor = similarConstructor; try{ return constructor.newInstance(convertedParams); }catch(Exception ex){ continue; } } } throw e; } } /** * * @param <T> * @param className * @param parameters * @return * @throws ReflectiveOperationException */ public static <T> T newInstance(String className, Object ...parameters) throws ReflectiveOperationException { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>) Class.forName(className); return newInstance(clazz,parameters); } /** * , * @param objs * @return */ public static Class<?>[] getArrayClasses(Object[] objs){ Class<?>[] parameterTypes= new Class<?>[objs.length]; for(int i=0;i<objs.length;i++){ parameterTypes[i] = objs[i].getClass(); } return parameterTypes; } /** * Map * * @param clazz * @param mapArg Map * @param ignoreCase * @return * @throws ReflectiveOperationException * @throws ParseException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object getObjectFromMap(Class<?> clazz, Map<String, ?> mapArg,boolean ignoreCase) throws ReflectiveOperationException, ParseException { Object obj = null; if(mapArg==null){ return obj; } Object singleValue = null; if(!mapArg.isEmpty()){ singleValue = mapArg.values().iterator().next(); } // java if (clazz.isPrimitive() || clazz == Object.class){ obj = singleValue; } //java else if(isExtendsByClass(clazz,Date.class)){ // Map.Values String value = singleValue==null?null:singleValue.toString(); SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE); obj = singleValue!=null?dateFormat.parse(value.toString()):null; } //Map else if(isImpByInterface(clazz,Map.class)){ if(Modifier.isAbstract(clazz.getModifiers()) && Modifier.isInterface(clazz.getModifiers())){ clazz = HashMap.class; } Map mapObject = TObject.cast(newInstance(clazz)); mapObject.putAll(mapArg); obj = mapObject; } //Collection else if(isImpByInterface(clazz,Collection.class)){ if(Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())){ clazz = ArrayList.class; } Collection listObject = TObject.cast(newInstance(clazz)); if(singleValue!=null){ listObject.addAll((Collection) TObject.cast(singleValue)); } obj = listObject; } //Array else if(clazz.isArray()){ Class arrayClass = clazz.getComponentType(); Object tempArrayObj = Array.newInstance(arrayClass, 0); return ((Collection)singleValue).toArray((Object[])tempArrayObj); } //java else if (clazz.getName().startsWith("java.lang")) { // Map.Values String value = singleValue==null?null:singleValue.toString(); obj = singleValue==null?null:newInstance(clazz, value); } else { obj = newInstance(clazz); for(Entry<String,?> argEntry : mapArg.entrySet()){ String key = argEntry.getKey(); Object value = argEntry.getValue(); Field field = null; if(ignoreCase) { field = findFieldIgnoreCase(clazz, key); }else{ field = findField(clazz, key); } if(field!=null) { String fieldName = field.getName(); Class fieldType = field.getType(); try { if(value != null) { // Map ,, if (isImpByInterface(fieldType, Map.class) && value instanceof Map) { Class[] mapGenericTypes = getFieldGenericType(field); if (mapGenericTypes != null) { if (fieldType == Map.class) { fieldType = HashMap.class; } Map result = (Map) TReflect.newInstance(fieldType); Map mapValue = (Map) value; Iterator iterator = mapValue.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = (Entry) iterator.next(); Map keyOfMap = null; Map valueOfMap = null; if (entry.getKey() instanceof Map) { keyOfMap = (Map) entry.getKey(); } else { keyOfMap = TObject.newMap("value", entry.getKey()); } if (entry.getValue() instanceof Map) { valueOfMap = (Map) entry.getValue(); } else { valueOfMap = TObject.newMap("value", entry.getValue()); } Object keyObj = getObjectFromMap(mapGenericTypes[0], keyOfMap, ignoreCase); Object valueObj = getObjectFromMap(mapGenericTypes[1], valueOfMap, ignoreCase); result.put(keyObj, valueObj); } value = result; } } // Collection ,, else if (isImpByInterface(fieldType, Collection.class) && value instanceof Collection) { Class[] listGenericTypes = getFieldGenericType(field); if (listGenericTypes != null) { if (fieldType == List.class) { fieldType = ArrayList.class; } List result = (List) TReflect.newInstance(fieldType); List listValue = (List) value; for (Object listItem : listValue) { Map valueOfMap = null; if (listItem instanceof Map) { valueOfMap = (Map) listItem; } else { valueOfMap = TObject.newMap("value", listItem); } Object item = getObjectFromMap(listGenericTypes[0], valueOfMap, ignoreCase); result.add(item); } value = result; } } else if (value instanceof Map) { value = getObjectFromMap(fieldType, (Map<String, ?>) value, ignoreCase); } else { value = getObjectFromMap(fieldType, TObject.newMap("value", value), ignoreCase); } } setFieldValue(obj, fieldName, value); }catch(Exception e){ throw new ReflectiveOperationException("Fill object " + obj.getClass().getCanonicalName() + "#"+fieldName+" failed",e); } } } } return obj; } /** * Map * key * value * @param obj * @return Map * @throws ReflectiveOperationException */ public static Map<String, Object> getMapfromObject(Object obj) throws ReflectiveOperationException{ Map<String, Object> mapResult = new HashMap<String, Object>(); Map<Field, Object> fieldValues = TReflect.getFieldValues(obj); // java if(obj.getClass().getName().startsWith("java.lang") || obj.getClass().isPrimitive()){ mapResult.put("value", obj); } // Collection else if(obj instanceof Collection){ Collection collection = (Collection) newInstance(obj.getClass()); for(Object collectionItem : (Collection)obj) { collection.add(getMapfromObject(collectionItem)); } mapResult.put("value", collection); } // Map else if(obj instanceof Map){ Map mapObject = (Map)obj; Map map = (Map)newInstance(obj.getClass()); for(Object key : mapObject.keySet()) { map.put(getMapfromObject(key),getMapfromObject(mapObject.get(key))); } mapResult.put("value", map); } else{ for(Entry<Field,Object> entry : fieldValues.entrySet()){ String key = entry.getKey().getName(); Object value = entry.getValue(); if(value == null){ mapResult.put(key, value); }else if(!key.contains("$")){ String valueClass = entry.getValue().getClass().getName(); if(valueClass.startsWith("java")){ mapResult.put(key, value); }else { Map resultMap = getMapfromObject(value); if(resultMap.size()==1 && resultMap.containsKey("value")){ mapResult.put(key, resultMap.values().iterator().next()); }else{ mapResult.put(key,resultMap); } } } } } return mapResult; } /** * * * @param type * @param interfaceClass * @return */ public static boolean isImpByInterface(Class<?> type,Class<?> interfaceClass){ if(type==interfaceClass){ return true; } Class<?>[] interfaces= type.getInterfaces(); for (Class<?> interfaceItem : interfaces) { if (interfaceItem.equals(interfaceClass)) { return true; } else{ return isImpByInterface(interfaceItem,interfaceClass); } } return false; } /** * * * @param type * @param extendsClass * @return */ public static boolean isExtendsByClass(Class<?> type,Class<?> extendsClass){ if(extendsClass == type){ return true; } Class<?> superClass = type; do{ if(superClass.equals(extendsClass)){ return true; } superClass = superClass.getSuperclass(); }while(superClass!=null && !superClass.equals(extendsClass) && !superClass.equals(Object.class)); return false; } /** * * @param type Class * @return */ public static Class[] getAllExtendAndInterfaceClass(Class<?> type){ if(type == null){ return null; } ArrayList<Class> classes = new ArrayList<Class>(); Class<?> superClass = type; do{ superClass = superClass.getSuperclass(); classes.addAll(Arrays.asList(superClass.getInterfaces())); classes.add(superClass); }while(!Object.class.equals(superClass)); return classes.toArray(new Class[]{}); } /** * json * @param clazz Class * @return json */ public static String getClazzJSONModel(Class clazz){ StringBuilder jsonStrBuilder = new StringBuilder(); if(clazz.getName().startsWith("java") || clazz.isPrimitive()){ jsonStrBuilder.append(clazz.getName()); } else if(clazz.getName().startsWith("[L")){ String clazzName = clazz.getName(); clazzName = clazzName.substring(clazzName.lastIndexOf(".")+1,clazzName.length()-2)+"[]"; jsonStrBuilder.append(clazzName); } else { jsonStrBuilder.append("{"); for (Field field : TReflect.getFields(clazz)) { jsonStrBuilder.append("\""); jsonStrBuilder.append(field.getName()); jsonStrBuilder.append("\":"); String filedValueModel = getClazzJSONModel(field.getType()); if(filedValueModel.startsWith("{") && filedValueModel.endsWith("}")) { jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append(","); } else if(filedValueModel.startsWith("[") && filedValueModel.endsWith("]")) { jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append(","); } else { jsonStrBuilder.append("\""); jsonStrBuilder.append(filedValueModel); jsonStrBuilder.append("\","); } } jsonStrBuilder.deleteCharAt(jsonStrBuilder.length()-1); jsonStrBuilder.append("}"); } return jsonStrBuilder.toString(); } }
package co.smartreceipts.android.fragments.preferences; import java.util.ArrayList; import java.util.List; import co.smartreceipts.android.model.Category; import co.smartreceipts.android.model.factory.CategoryBuilderFactory; import co.smartreceipts.android.persistence.database.controllers.TableEventsListener; import co.smartreceipts.android.persistence.database.controllers.impl.CategoriesTableController; import wb.android.dialog.BetterDialogBuilder; import android.app.AlertDialog; import android.content.DialogInterface; import android.database.SQLException; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import co.smartreceipts.android.R; import co.smartreceipts.android.fragments.WBFragment; public class CategoriesListFragment extends WBFragment implements View.OnClickListener, TableEventsListener<Category> { public static String TAG = "CategoriesListFragment"; private BaseAdapter mAdapter; private Toolbar mToolbar; private ListView mListView; private List<Category> mCategories; private CategoriesTableController mTableController; private Category mScrollToCategory; public static CategoriesListFragment newInstance() { return new CategoriesListFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTableController = getSmartReceiptsApplication().getTableControllerManager().getCategoriesTableController(); mAdapter = getAdapter(); mCategories = new ArrayList<>(); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.simple_list, container, false); mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar); mListView = (ListView) rootView.findViewById(android.R.id.list); mListView.setAdapter(mAdapter); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setSupportActionBar(mToolbar); } @Override public void onResume() { super.onResume(); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(R.string.menu_main_categories); actionBar.setSubtitle(null); } mTableController.subscribe(this); mTableController.get(); } @Override public void onPause() { mTableController.unsubscribe(this); super.onPause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_settings_categories, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_settings_add) { addCategory(); return true; } else if (item.getItemId() == android.R.id.home) { getActivity().onBackPressed(); return true; } else { return super.onOptionsItemSelected(item); } } protected BaseAdapter getAdapter() { return new CategoriesListAdapter(LayoutInflater.from(getActivity())); } protected int getListItemLayoutId() { return R.layout.settings_category_card_item; } @Override public void onClick(View view) { if (view.getId() == R.id.edit) { Integer index = (Integer) view.getTag(); editCategory(index); } else if (view.getId() == R.id.delete) { Integer index = (Integer) view.getTag(); deleteCategory(index); } } private void addCategory() { final BetterDialogBuilder innerBuilder = new BetterDialogBuilder(getActivity()); final LinearLayout layout = new LinearLayout(getActivity()); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.BOTTOM); layout.setPadding(6, 6, 6, 6); final TextView nameLabel = new TextView(getActivity()); nameLabel.setText(R.string.category_name); final EditText nameBox = new EditText(getActivity()); final TextView codeLabel = new TextView(getActivity()); codeLabel.setText(R.string.category_code); final EditText codeBox = new EditText(getActivity()); layout.addView(nameLabel); layout.addView(nameBox); layout.addView(codeLabel); layout.addView(codeBox); innerBuilder.setTitle(getString(R.string.dialog_category_add)) .setView(layout) .setCancelable(true) .setPositiveButton(R.string.add, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String name = nameBox.getText().toString(); final String code = codeBox.getText().toString(); mTableController.insert(new CategoryBuilderFactory().setName(name).setCode(code).build()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } private void editCategory(int position) { final Category editCategory = mCategories.get(position); final String oldName = editCategory.getName(); final String oldCode = editCategory.getCode(); final BetterDialogBuilder innerBuilder = new BetterDialogBuilder(getActivity()); final LinearLayout layout = new LinearLayout(getActivity()); layout.setOrientation(LinearLayout.VERTICAL); layout.setGravity(Gravity.BOTTOM); layout.setPadding(6, 6, 6, 6); final TextView nameLabel = new TextView(getActivity()); nameLabel.setText(R.string.item_name); final EditText nameBox = new EditText(getActivity()); nameBox.setText(oldName); final TextView codeLabel = new TextView(getActivity()); codeLabel.setText(R.string.item_code); final EditText codeBox = new EditText(getActivity()); codeBox.setText(oldCode); layout.addView(nameLabel); layout.addView(nameBox); layout.addView(codeLabel); layout.addView(codeBox); innerBuilder.setTitle(R.string.dialog_category_edit) .setView(layout) .setCancelable(true) .setPositiveButton(R.string.update, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String newName = nameBox.getText().toString(); final String newCode = codeBox.getText().toString(); final Category newCategory = new CategoryBuilderFactory().setName(newName).setCode(newCode).build(); mTableController.update(editCategory, newCategory); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } private void deleteCategory(int position) { final Category category = mCategories.get(position); final AlertDialog.Builder innerBuilder = new AlertDialog.Builder(getActivity()); innerBuilder.setTitle(getString(R.string.delete_item, category.getName())) .setCancelable(true) .setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mTableController.delete(category); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } @Override public void onGetSuccess(@NonNull List<Category> list) { mCategories = list; mAdapter.notifyDataSetChanged(); if (mScrollToCategory != null) { mListView.smoothScrollToPosition(mCategories.indexOf(mScrollToCategory)); mScrollToCategory = null; } } @Override public void onGetFailure(@Nullable Throwable e) { } @Override public void onInsertSuccess(@NonNull Category category) { mTableController.get(); mScrollToCategory = category; } @Override public void onInsertFailure(@NonNull Category category, @Nullable Throwable e) { if (e instanceof SQLException) { Toast.makeText(getActivity(), getString(R.string.toast_error_category_exists), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), getString(R.string.DB_ERROR), Toast.LENGTH_SHORT).show(); } } @Override public void onUpdateSuccess(@NonNull Category oldCategory, @NonNull Category newCategory) { mTableController.get(); mScrollToCategory = newCategory; } @Override public void onUpdateFailure(@NonNull Category oldT, @Nullable Throwable e) { if (e instanceof SQLException) { Toast.makeText(getActivity(), getString(R.string.toast_error_category_exists), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getActivity(), getString(R.string.DB_ERROR), Toast.LENGTH_SHORT).show(); } } @Override public void onDeleteSuccess(@NonNull Category category) { mTableController.get(); } @Override public void onDeleteFailure(@NonNull Category category, @Nullable Throwable e) { Toast.makeText(getActivity(), getString(R.string.DB_ERROR), Toast.LENGTH_SHORT).show(); } private static final class MyViewHolder { public TextView category; public TextView code; public View edit; public View delete; } private class CategoriesListAdapter extends BaseAdapter { private final LayoutInflater mInflater; public CategoriesListAdapter(LayoutInflater inflater) { mInflater = inflater; } @Override public int getCount() { return mCategories.size(); } @Override public Category getItem(int i) { return mCategories.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View convertView, ViewGroup parent) { MyViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(getListItemLayoutId(), parent, false); holder = new MyViewHolder(); holder.category = (TextView) convertView.findViewById(android.R.id.title); holder.code = (TextView) convertView.findViewById(android.R.id.summary); holder.edit = convertView.findViewById(R.id.edit); holder.delete = convertView.findViewById(R.id.delete); holder.edit.setOnClickListener(CategoriesListFragment.this); holder.delete.setOnClickListener(CategoriesListFragment.this); convertView.setTag(holder); } else { holder = (MyViewHolder) convertView.getTag(); } holder.category.setText(getItem(i).getName()); holder.code.setText(getItem(i).getCode()); holder.edit.setTag(i); holder.delete.setTag(i); return convertView; } } }
package org.xtx.ut4converter; import org.xtx.ut4converter.ui.MainSceneController; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.HashMap; import java.util.Map; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import javafx.scene.control.TableView; import javax.xml.bind.JAXBException; import org.xtx.ut4converter.UTGames.UTGame; import org.xtx.ut4converter.config.UserConfig; import org.xtx.ut4converter.config.UserGameConfig; import org.xtx.ut4converter.export.UCCExporter; import org.xtx.ut4converter.export.UTPackageExtractor; import org.xtx.ut4converter.t3d.T3DLevelConvertor; import org.xtx.ut4converter.t3d.T3DMatch; import org.xtx.ut4converter.t3d.T3DUtils; import org.xtx.ut4converter.tools.Installation; import org.xtx.ut4converter.ui.TableRowLog; import org.xtx.ut4converter.ucore.UPackage; import org.xtx.ut4converter.ucore.UPackageRessource; import org.xtx.ut4converter.ui.ConversionViewController; /** * * @author XtremeXp */ public class MapConverter { /** * UT Game the map will be converted from */ UTGame inputGame; /** * UT Game the map will be converted to */ UTGame outputGame; public static final String CONV_PATH = File.separator + "Converted"; /** * Input map. Can be either a map (.unr, ...) or unreal text map (.t3d) */ File inMap; /** * Final map name, might differ from original one. * E.G: AS-Mazon (UT99) -> AS-Mazon-Original (for UT4 for exemple) */ String outMapName; File inT3d, outT3d; /** * Where all converted stuff will be converted */ Path outPath; /** * Scale factor applied to converted level. */ Double scale; /** * Quick converter of actor name. * E.G: * "Mover" (U1/UT99) -> "InterpActor" (UT3) */ T3DMatch tm = new T3DMatch(); /** * Tells whether or not map is team based */ private Boolean isTeamGameType; /** * TODO move this to T3D Level converter */ SupU1UT99ToUT4Classes supportedActorClasses; /** * T3d level converter */ T3DLevelConvertor t3dLvlConvertor; /** * If <code>true</code> textures of the map * will be exported and converted. */ public boolean convertTextures; /** * If <code>true</code> sounds of the map * will be exported and converted */ public boolean convertSounds = true; /** * Allow to extract packages. * There should be always only one instanced */ public UTPackageExtractor packageExtractor; /** * Unreal packages used in map * Can be sounds, textures, ... */ public Map<String, UPackage> mapPackages = new HashMap<>(); /** * User configuration which allows to know * where UT games are installed for exemple */ UserConfig userConfig; /** * Reference to user interface */ ConversionViewController conversionViewController; /** * Global logger */ static final Logger logger = Logger.getLogger("MapConverter"); /** * Original UT game the map comes from * @return */ public UTGame getInputGame() { return inputGame; } /** * UT game the map will be converted to * @return */ public UTGame getOutputGame() { return outputGame; } /** * Input map that will be converted * (Unreal Map (.unr, .ut2) or Unreal Text Map file (.t3d) * @return */ public File getInMap() { return inMap; } /** * Scale factor applied when converting * @return */ public Double getScale() { return scale; } /** * * @param inputGame Input game the map originally comes from * @param outputGame Output game the map will be converted to * @param inpMap Map to be converted (either a t3d file or map) * @param scale Scale applied to level when converting( defaut = 1) */ public MapConverter(UTGame inputGame, UTGame outputGame, File inpMap, Double scale) { this.inputGame = inputGame; this.outputGame = outputGame; this.inMap = inpMap; this.scale = scale; init(); } /** * Indicates that gametype is team based * @return true is gametype is team based */ public Boolean isTeamGameType() { return isTeamGameType; } /** * * @param isTeamGameType */ public void setIsTeamGameType(Boolean isTeamGameType) { this.isTeamGameType = isTeamGameType; } /** * Tried to find property converted to some other game ... * @param name * @param withT3dClass * @param properties * @return */ public T3DMatch.Match getMatchFor(String name, boolean withT3dClass, Map<String, String> properties){ return tm.getMatchFor(name, inputGame, outputGame, withT3dClass, properties); } /** * * @return */ public HashMap<String, T3DMatch.Match> getActorClassMatch(){ return tm.getActorClassMatch(inputGame, outputGame); } private void init(){ try { //config = Configuration.getInstance(); if(inMap.getName().endsWith(".t3d")){ inT3d = inMap; } if(isTeamGameType == null){ isTeamGameType = UTGameTypes.isTeamBasedFromMapName(inT3d != null ? inT3d.getName() : inMap.getName()); } if(outMapName==null){ // TODO being able to set it manually (chosen by user) outMapName = inMap.getName().split("\\.")[0] + "-" + inputGame.shortName; // Remove bad chars from name (e.g: DM-Cybrosis][ -> DM-Cybrosis) // else ue4 editor won't be able to set sounds or textures to actors outMapName = T3DUtils.filterName(outMapName); } supportedActorClasses = new SupU1UT99ToUT4Classes(this); userConfig = UserConfig.load(); } catch (JAXBException ex) { Logger.getLogger(MapConverter.class.getName()).log(Level.SEVERE, null, ex); } } /** * All logs redirect to user interface thought table */ private void addLoggerHandlers(){ if(conversionViewController == null || conversionViewController.getConvLogTableView() == null){ return; } final TableView<TableRowLog> t = conversionViewController.getConvLogTableView(); t.getItems().clear(); logger.addHandler(new Handler() { @Override public void publish(LogRecord record) { t.getItems().add(new TableRowLog(record)); } @Override public void flush() { t.getItems().clear(); } @Override public void close() throws SecurityException { // nothing to do } }); } /** * Converts level * @param path Where all converted stuff is copied to * @throws Exception */ public void convertTo(String path) throws Exception { outPath = Paths.get(path); if(!outPath.toFile().exists()){ outPath.toFile().mkdirs(); } // Export unreal map to Unreal Text map if(inT3d == null){ inT3d = UCCExporter.exportLevelToT3d(this, inMap); } outT3d = new File(path + File.separator + outMapName + ".t3d"); // t3d ever exported or directly converting from t3d file, then skip export of it // and directly convert it t3dLvlConvertor = new T3DLevelConvertor(inT3d, outT3d, this); t3dLvlConvertor.convert(); cleanAndConvertRessources(); } /** * Delete unused files * and convert them to good format if needed. * (e.g: convert staticmeshes to .ase or .fbx format for import in UE4) * @throws IOException */ private void cleanAndConvertRessources() throws IOException { // remove unecessary exported files // convert them to some new file format if needed // and rename them to fit with "naming" standards for(UPackage unrealPackage : mapPackages.values()){ for(UPackageRessource ressource : unrealPackage.getRessources()){ File exportedFile = ressource.getExportedFile(); if(exportedFile != null){ if(!ressource.isUsedInMap()){ exportedFile.delete(); } // Renaming exported files (e.g: Stream2.wav -> AmbOutside_Looping_Stream2.wav) else { // Some sounds might need to be converted for correct import in UE4 if(ressource.needsConversion(this)){ exportedFile = ressource.convert(logger); System.out.println("Exists "+exportedFile.getAbsolutePath()+" -> "+exportedFile.exists()); } File newFile = new File(getMapConvertFolder().getAbsolutePath() + File.separator + ressource.getType().getName() + File.separator + ressource.getConvertedFileName()); newFile.mkdirs(); newFile.createNewFile(); Files.copy(exportedFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); exportedFile.delete(); exportedFile = newFile; logger.info("Converted "+newFile.getAbsolutePath()); } } } } // DELETE ALL IN TEMP FOLDER for(File f : getTempExportFolder().listFiles()){ f.delete(); f.deleteOnExit(); } getTempExportFolder().delete(); // Create a folder for this map in UE4Editor // and copy a simple existing .uasset file so we can see the folder created in UT4 editor ... if(toUT4()){ UserGameConfig userGameConfig = userConfig.getGameConfigByGame(UTGame.UT4); File restrictedAssetsFolder = new File(userGameConfig.getPath() + File.separator + "UnrealTournament" + File.separator + "Content" + File.separator + "RestrictedAssets"); File wipFolder = new File(restrictedAssetsFolder + File.separator + "Maps" + File.separator + "WIP"); File wipConvertedMapFolder = new File(wipFolder + File.separator + getOutMapName()); wipConvertedMapFolder.mkdirs(); // copy small .uasset file so the folder will appear in UT4 editor .... File uassetFile = new File(restrictedAssetsFolder + File.separator + "Blueprints" + File.separator + "Lift" + File.separator + "Curves" + File.separator + "EaseIn-Out.uasset"); File uassetCopy = new File(wipConvertedMapFolder + File.separator + "dummyfile.uasset"); Files.copy(uassetFile.toPath(), uassetCopy.toPath(), StandardCopyOption.REPLACE_EXISTING); } } /** * * @return */ public SupportedClasses getSupportedActorClasses() { return supportedActorClasses; } /** * * @return */ public T3DLevelConvertor getT3dLvlConvertor() { return t3dLvlConvertor; } /** * * @param t3dLvlConvertor */ public void setT3dLvlConvertor(T3DLevelConvertor t3dLvlConvertor) { this.t3dLvlConvertor = t3dLvlConvertor; } public String getOutMapName() { return outMapName; } /** * Current user configuration such as program path for UT99 and so on ... * @return */ public UserConfig getUserConfig() { return userConfig; } /** * * @return <code>true</code> if the output game is using unreal engine 4 */ public boolean toUnrealEngine4(){ return UTGames.isUnrealEngine4(this.getOutputGame()); } /** * * @return */ public UTGames.UnrealEngine getUnrealEngineTo(){ return this.getOutputGame().engine; } /** * Indicated if converting from UT using Unreal Engine 1 or Unreal Engine 2 * (basically Unreal1, UT99, Unreal 2, UT2003 and UT2004) * @return true if converting from Unreal Engine 1 or 2 UTx game */ public boolean fromUE1OrUE2(){ return UTGames.isUnrealEngine1(this.getInputGame()) || UTGames.isUnrealEngine2(this.getInputGame()); } /** * Indicated if converting to UT using Unreal Engine 1 or Unreal Engine 2 * (basically Unreal1, UT99, Unreal 2, UT2003 and UT2004) * @return true if converting to Unreal Engine 1 or 2 UTx game */ public boolean toUE1OrUE2(){ return UTGames.isUnrealEngine1(this.getOutputGame()) || UTGames.isUnrealEngine2(this.getOutputGame()); } /** * Indicates games being converted from some UT game in unreal engine 3 or 4 * @return */ public boolean fromUE1orUE2OrUE3(){ return UTGames.isUnrealEngine1(this.getInputGame()) || UTGames.isUnrealEngine2(this.getInputGame()) || UTGames.isUnrealEngine3(this.getInputGame()); } /** * Indicates games being converted from some UT game in unreal engine 3 or 4 * @return */ public boolean fromUE3OrUE4(){ return UTGames.isUnrealEngine3(this.getInputGame()) || UTGames.isUnrealEngine4(this.getInputGame()); } /** * Indicates games being converted to some UT game in unreal engine 3 or 4 * @return */ public boolean toUE3OrUE4(){ return UTGames.isUnrealEngine3(this.getOutputGame()) || UTGames.isUnrealEngine4(this.getOutputGame()); } /** * Indicated game being converted to Unreal Engine 3 game (basically only UT3) * @return */ public boolean toUE3(){ return UTGames.isUnrealEngine3(this.getOutputGame()); } /** * Tells if converting UT game using Unreal Engine 1 or 2 * is being converted to some other UT game using Unreal Engine 3 or 4. * * @return true if converting UT game using Unreal Engine 1 or 2 to UT game using Unreal Engine 3 or 4 */ public boolean isFromUE1UE2ToUE3UE4(){ return fromUE1OrUE2() && toUE3OrUE4(); } public boolean fromUE123ToUE4(){ return fromUE1orUE2OrUE3() && toUnrealEngine4(); } public boolean toUT4(){ return outputGame == UTGame.UT4; } /** * Tells if converting UT game using Unreal Engine 1 or 2 * is being converted to some other UT game using Unreal Engine 3 or 4. * * @return true if converting UT game using Unreal Engine 1 or 2 to UT game using Unreal Engine 3 or 4 */ public boolean isFromUE3UE4ToUE1UE2(){ return toUE1OrUE2() && fromUE3OrUE4(); } public File getOutT3d() { return outT3d; } public void setConversionViewController(ConversionViewController conversionViewController) { this.conversionViewController = conversionViewController; addLoggerHandlers(); } public Logger getLogger(){ return logger; } /** * <UT4ConverterFolder>/Converted * @return */ private static File getBaseConvertFolder(){ return new File(Installation.getProgramFolder().getAbsolutePath() + File.separator + CONV_PATH); } /** * <UT4ConverterFolder>/Converted/<MapName> * @return */ private File getMapConvertFolder(){ return new File(getBaseConvertFolder()+ File.separator + getInMap().getName().split("\\.")[0]); } /** * <UT4ConverterFolder>/Converted/<MapName>/Temp * @return */ public File getTempExportFolder(){ return new File(getMapConvertFolder() + File.separator + "Temp"); } }
package org.openhab.binding.rfxcom.handler; import static org.openhab.binding.rfxcom.RFXComBindingConstants.*; import java.util.List; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingStatusInfo; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.thing.binding.ThingHandler; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.rfxcom.RFXComValueSelector; import org.openhab.binding.rfxcom.internal.DeviceMessageListener; import org.openhab.binding.rfxcom.internal.config.RFXComDeviceConfiguration; import org.openhab.binding.rfxcom.internal.exceptions.RFXComException; import org.openhab.binding.rfxcom.internal.exceptions.RFXComMessageNotImplementedException; import org.openhab.binding.rfxcom.internal.messages.RFXComBaseMessage; import org.openhab.binding.rfxcom.internal.messages.RFXComBaseMessage.PacketType; import org.openhab.binding.rfxcom.internal.messages.RFXComMessage; import org.openhab.binding.rfxcom.internal.messages.RFXComMessageFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link RFXComHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Pauli Anttila - Initial contribution */ public class RFXComHandler extends BaseThingHandler implements DeviceMessageListener { private static final int LOW_BATTERY_LEVEL = 1; private final Logger logger = LoggerFactory.getLogger(RFXComHandler.class); private RFXComBridgeHandler bridgeHandler; private RFXComDeviceConfiguration config; public RFXComHandler(Thing thing) { super(thing); } @Override public void handleCommand(ChannelUID channelUID, Command command) { logger.debug("Received channel: {}, command: {}", channelUID, command); if (bridgeHandler != null) { if (command instanceof RefreshType) { logger.trace("Received unsupported Refresh command"); } else { try { PacketType packetType = RFXComMessageFactory .convertPacketType(channelUID.getThingUID().getThingTypeId().toUpperCase()); RFXComMessage msg = RFXComMessageFactory.createMessage(packetType); List<RFXComValueSelector> supportedValueSelectors = msg.getSupportedOutputValueSelectors(); RFXComValueSelector valSelector = RFXComValueSelector.getValueSelector(channelUID.getId()); if (supportedValueSelectors.contains(valSelector)) { msg.setConfig(config); msg.convertFromState(valSelector, command); bridgeHandler.sendMessage(msg); } else { logger.warn("RFXCOM doesn't support transmitting for channel '{}'", channelUID.getId()); } } catch (RFXComMessageNotImplementedException e) { logger.error("Message not supported", e); } catch (RFXComException e) { logger.error("Transmitting error", e); } } } } /** * {@inheritDoc} */ @Override public void initialize() { logger.debug("Initializing thing {}", getThing().getUID()); initializeBridge((getBridge() == null) ? null : getBridge().getHandler(), (getBridge() == null) ? null : getBridge().getStatus()); } @Override public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { logger.debug("bridgeStatusChanged {} for thing {}", bridgeStatusInfo, getThing().getUID()); initializeBridge((getBridge() == null) ? null : getBridge().getHandler(), bridgeStatusInfo.getStatus()); } private void initializeBridge(ThingHandler thingHandler, ThingStatus bridgeStatus) { logger.debug("initializeBridge {} for thing {}", bridgeStatus, getThing().getUID()); config = getConfigAs(RFXComDeviceConfiguration.class); if (config.deviceId == null || config.subType == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "RFXCOM device missing deviceId or subType"); } else if (thingHandler != null && bridgeStatus != null) { bridgeHandler = (RFXComBridgeHandler) thingHandler; bridgeHandler.registerDeviceStatusListener(this); if (bridgeStatus == ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE); } } else { updateStatus(ThingStatus.OFFLINE); } } /* * (non-Javadoc) * * @see org.eclipse.smarthome.core.thing.binding.BaseThingHandler#dispose() */ @Override public void dispose() { logger.debug("Thing {} disposed.", getThing().getUID()); if (bridgeHandler != null) { bridgeHandler.unregisterDeviceStatusListener(this); } bridgeHandler = null; super.dispose(); } @Override public void onDeviceMessageReceived(ThingUID bridge, RFXComMessage message) { try { String id = message.getDeviceId(); if (config.deviceId.equals(id)) { RFXComBaseMessage msg = (RFXComBaseMessage) message; String receivedId = PACKET_TYPE_THING_TYPE_UID_MAP.get(msg.packetType).getId(); logger.debug("Received message from bridge: {} message: {}", bridge, message); if (receivedId.equals(getThing().getThingTypeUID().getId())) { updateStatus(ThingStatus.ONLINE); List<RFXComValueSelector> supportedValueSelectors = msg.getSupportedInputValueSelectors(); if (supportedValueSelectors != null) { for (RFXComValueSelector valueSelector : supportedValueSelectors) { switch (valueSelector) { case BATTERY_LEVEL: updateState(CHANNEL_BATTERY_LEVEL, convertBatteryLevelToSystemWideLevel( message.convertToState(valueSelector))); break; case CHIME_SOUND: updateState(CHANNEL_CHIME_SOUND, message.convertToState(valueSelector)); break; case COMMAND: updateState(CHANNEL_COMMAND, message.convertToState(valueSelector)); break; case COMMAND_ID: updateState(CHANNEL_COMMAND_ID, message.convertToState(valueSelector)); break; case CONTACT: updateState(CHANNEL_CONTACT, message.convertToState(valueSelector)); break; case CONTACT_1: updateState(CHANNEL_CONTACT_1, message.convertToState(valueSelector)); break; case CONTACT_2: updateState(CHANNEL_CONTACT_2, message.convertToState(valueSelector)); break; case CONTACT_3: updateState(CHANNEL_CONTACT_3, message.convertToState(valueSelector)); break; case DIMMING_LEVEL: updateState(CHANNEL_DIMMING_LEVEL, message.convertToState(valueSelector)); break; case FORECAST: updateState(CHANNEL_FORECAST, message.convertToState(valueSelector)); break; case HUMIDITY: updateState(CHANNEL_HUMIDITY, message.convertToState(valueSelector)); break; case HUMIDITY_STATUS: updateState(CHANNEL_HUMIDITY_STATUS, message.convertToState(valueSelector)); break; case INSTANT_AMPS: updateState(CHANNEL_INSTANT_AMPS, message.convertToState(valueSelector)); break; case INSTANT_POWER: updateState(CHANNEL_INSTANT_POWER, message.convertToState(valueSelector)); break; case LOW_BATTERY: updateState(CHANNEL_BATTERY_LEVEL, isLowBattery(message.convertToState(valueSelector))); break; case MOOD: updateState(CHANNEL_MOOD, message.convertToState(valueSelector)); break; case MOTION: updateState(CHANNEL_MOTION, message.convertToState(valueSelector)); break; case PRESSURE: updateState(CHANNEL_PRESSURE, message.convertToState(valueSelector)); break; case RAIN_RATE: updateState(CHANNEL_RAIN_RATE, message.convertToState(valueSelector)); break; case RAIN_TOTAL: updateState(CHANNEL_RAIN_TOTAL, message.convertToState(valueSelector)); break; case RAW_MESSAGE: updateState(CHANNEL_RAW_MESSAGE, message.convertToState(valueSelector)); break; case RAW_PAYLOAD: updateState(CHANNEL_RAW_PAYLOAD, message.convertToState(valueSelector)); break; case SET_POINT: updateState(CHANNEL_SET_POINT, message.convertToState(valueSelector)); break; case SHUTTER: updateState(CHANNEL_SHUTTER, message.convertToState(valueSelector)); break; case SIGNAL_LEVEL: updateState(CHANNEL_SIGNAL_LEVEL, convertSignalLevelToSystemWideLevel(message.convertToState(valueSelector))); break; case STATUS: updateState(CHANNEL_STATUS, message.convertToState(valueSelector)); break; case TEMPERATURE: updateState(CHANNEL_TEMPERATURE, message.convertToState(valueSelector)); break; case CHILL_TEMPERATURE: updateState(CHANNEL_CHILL_TEMPERATURE, message.convertToState(valueSelector)); break; case TOTAL_AMP_HOUR: updateState(CHANNEL_TOTAL_AMP_HOUR, message.convertToState(valueSelector)); break; case TOTAL_USAGE: updateState(CHANNEL_TOTAL_USAGE, message.convertToState(valueSelector)); break; case UV: updateState(CHANNEL_UV, message.convertToState(valueSelector)); break; case VOLTAGE: updateState(CHANNEL_VOLTAGE, message.convertToState(valueSelector)); break; case WIND_DIRECTION: updateState(CHANNEL_WIND_DIRECTION, message.convertToState(valueSelector)); break; case AVG_WIND_SPEED: updateState(CHANNEL_AVG_WIND_SPEED, message.convertToState(valueSelector)); break; case WIND_SPEED: updateState(CHANNEL_WIND_SPEED, message.convertToState(valueSelector)); break; default: logger.debug("Unsupported value selector '{}'", valueSelector); break; } } } } } } catch (Exception e) { logger.error("Error occurred during message receiving", e); } } /** * Convert internal signal level (0-15) to system wide signal level (0-4). * * @param signalLevel Internal signal level * @return Signal level in system wide level */ private State convertSignalLevelToSystemWideLevel(State signalLevel) { int level = ((DecimalType) signalLevel).intValue(); int newLevel; /* * RFXCOM signal levels are always between 0-15. * * Use switch case to make level adaption easier in future if needed. * * BigDecimal level = * ((DecimalType)signalLevel).toBigDecimal().divide(new BigDecimal(4)); * return new DecimalType(level.setScale(0, RoundingMode.HALF_UP)); */ switch (level) { case 0: case 1: newLevel = 0; break; case 2: case 3: case 4: newLevel = 1; break; case 5: case 6: case 7: newLevel = 2; break; case 8: case 9: case 10: case 11: newLevel = 3; break; case 12: case 13: case 14: case 15: default: newLevel = 4; } return new DecimalType(newLevel); } /** * Convert internal battery level (0-9) to system wide battery level (0-100%). * * @param batteryLevel Internal battery level * @return Battery level in system wide level */ private State convertBatteryLevelToSystemWideLevel(State batteryLevel) { int level = ((DecimalType) batteryLevel).intValue(); level = (level + 1) * 10; return new DecimalType(level); } /** * Check if battery level is below low battery threshold level. * * @param batteryLevel Internal battery level * @return OnOffType */ private State isLowBattery(State batteryLevel) { int level = ((DecimalType) batteryLevel).intValue(); if (level <= LOW_BATTERY_LEVEL) { return OnOffType.ON; } else { return OnOffType.OFF; } } }
package org.xtx.ut4converter.t3d; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.vecmath.Vector3d; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.UTGames.UnrealEngine; import org.xtx.ut4converter.geom.Vertex; import org.xtx.ut4converter.tools.Geometry; import org.xtx.ut4converter.ucore.ue1.BrushPolyflag; /** * Generic Class for T3D brushes (includes movers as well) * * @author XtremeXp */ public class T3DBrush extends T3DSound { protected BrushClass brushClass = BrushClass.Brush; public static enum BrushClass { // UE1, UE2 Volume Brush, Mover, KillZVolume, UTPainVolume, UTWaterVolume, BlockingVolume, // UE3 and UE4 Volumes PostProcessVolume, TriggerVolume, UTSlimeVolume, UTLavaVolume, UTKillZVolume, CullDistanceVolume, /** * TODO for UE3 -> UE4 convert to PhysicsVolume + PainVolume */ PhysicsVolume, // Specific UE3 Volumes /** * Has been replaced by AudioVolume in UE4 */ ReverbVolume, DynamicTriggerVolume, // Specific UE4 Volume AudioVolume, PainCausingVolume, LightmassImportanceVolume, NavMeshBoundsVolume; public static BrushClass getBrushClass(String t3dBrushClass) { for (BrushClass bc : BrushClass.values()) { if (bc.name().equals(t3dBrushClass)) { return bc; } } return BrushClass.Brush; } } /** * UE1/2/3 */ private enum UE123_BrushType { CSG_Active, CSG_Add, CSG_Subtract, CSG_Intersect, CSG_Deintersect; } /** * UE4 */ private enum UE4_BrushType { Brush_Subtract, Brush_Add; } private String brushType; /** * Type of brush (regular, portal, semi-solid, ...) UE1/UE2 only */ List<BrushPolyflag> polyflags = new ArrayList<>(); /** * Used by Unreal Engine 1 */ Vector3d mainScale; /** * Used by Unreal Engine 1 */ Vector3d postScale; /** * Used by Unreal Engine 1 */ Vector3d tempScale; /** * Pre-Pivot used for brushes Changed the relative origin of brush */ Vector3d prePivot; /** * Polygons of the brush */ LinkedList<T3DPolygon> polyList = new LinkedList<>(); /** * E.G: "Begin Brush Name=TestLev_S787" */ String modelName; /** * Used for cull distances only */ private List<CullDistance> cullDistances; /** * * Used for cull distances volumes only * */ class CullDistance { private Double size; private Double distance; public void scale(Double scale) { if (size != null) { size *= scale; } if (distance != null) { distance *= scale; } } } public T3DBrush(MapConverter mapConverter, String t3dClass) { super(mapConverter, t3dClass); init(); } /** * * @param mapConverter * @param t3dClass * @param actor Used if creating brush from another type of actor (like zoneinfo for postprocessvolume, ...) */ public T3DBrush(MapConverter mapConverter, String t3dClass, T3DActor actor) { super(mapConverter, t3dClass, actor); init(); } private void init(){ brushClass = BrushClass.getBrushClass(t3dClass); if (mapConverter.fromUE1orUE2OrUE3()) { brushType = UE123_BrushType.CSG_Add.name(); } else { brushType = UE4_BrushType.Brush_Add.name(); } // just need one modelName = "Model_6"; } /** * If true reverse the order of vertices when writting converted t3d. This * is due to MainScale factor. Depending on it it. */ boolean reverseVertexOrder = false; /** * If true this brush might create bsp holes and should not be written */ boolean bspHoleCausing; @Override public boolean analyseT3DData(String line) { // CsgOper=CSG_Subtract // BrushType=Brush_Subtract if (line.contains("CsgOper")) { brushType = line.split("\\=")[1]; } // MainScale=(Scale=(Y=-1.000000),SheerAxis=SHEER_ZX) // MainScale=(SheerAxis=SHEER_ZX) else if (line.contains("MainScale=") && line.contains("(Scale=")) { mainScale = T3DUtils.getVector3d(line.split("\\(Scale")[1], 1D); reverseVertexOrder = mainScale.x * mainScale.y * mainScale.z < 0; // reverseVertexOrder = mainScale.x < 0; } // PostScale=(Scale=(X=1.058824,Y=1.250000,Z=0.920918),SheerAxis=SHEER_ZX) else if (line.contains("PostScale=") && line.contains("(Scale=")) { postScale = T3DUtils.getVector3d(line.split("\\(Scale")[1], 1D); } // TempScale=(Scale=(X=0.483090,Y=2.274808,Z=0.488054)) else if (line.contains("TempScale") && line.contains("(Scale=")) { tempScale = T3DUtils.getVector3d(line.split("\\(Scale")[1], 1D); } else if (line.contains("PrePivot")) { prePivot = T3DUtils.getVector3d(line, 0D); } else if (line.contains("PolyFlags=")) { polyflags = BrushPolyflag.parse(T3DUtils.getInteger(line)); } // Begin Polygon Item=Rise Texture=r-plates-g Link=0 else if (line.contains("Begin Polygon")) { polyList.add(new T3DPolygon(line, mapConverter)); } // Origin -00128.000000,-00128.000000,-00128.000000 else if (line.contains("Origin ")) { polyList.getLast().origin = T3DUtils.getPolyVector3d(line, "Origin"); } else if (line.contains("Normal ")) { polyList.getLast().normal = T3DUtils.getPolyVector3d(line, "Normal"); } else if (line.contains("TextureU ")) { polyList.getLast().texture_u = T3DUtils.getPolyVector3d(line, "TextureU"); } else if (line.contains("TextureV ")) { polyList.getLast().texture_v = T3DUtils.getPolyVector3d(line, "TextureV"); } else if (line.contains("Vertex ")) { Vector3d coordinates = T3DUtils.getPolyVector3d(line, "Vertex"); polyList.getLast().vertices.add(new Vertex(coordinates, polyList.getLast())); } // Pan U=381 V=-7 else if (line.contains(" Pan ")) { polyList.getLast().pan_u = Double.valueOf(line.split("U=")[1].split("\\ ")[0]); polyList.getLast().pan_v = Double.valueOf(line.split("V=")[1].split("\\ ")[0]); } // Hack, normally analysed in T3DActor but needed // for waterzone, lavazone to be converted ... else if (line.contains("Begin Actor")) { if (isU1ZoneVolume(t3dClass)) { forceToBox(90d); } // need force trigger function else name is null return super.analyseT3DData(line); } else if (line.startsWith("Begin Brush") && line.contains("Name=")) { // modelName = line.split("Name=")[1].replaceAll("\"", ""); } // CullDistances(1)=(Size=64.000000,CullDistance=3000.000000) else if (line.startsWith("CullDistances(")) { if (cullDistances == null) { cullDistances = new ArrayList<T3DBrush.CullDistance>(); } CullDistance cullDistance = new CullDistance(); if (line.contains("Size=")) { cullDistance.size = Double.valueOf(line.split("Size=")[1].split("\\)")[0].split("\\,")[0]); } if (line.contains("CullDistance=")) { cullDistance.distance = Double.valueOf(line.split("CullDistance=")[1].split("\\)")[0].split("\\,")[0]); } cullDistances.add(cullDistance); } else { return super.analyseT3DData(line); } return true; } /** * * @param t3dBrushClass * @return */ private boolean isU1ZoneVolume(String t3dBrushClass) { if (t3dBrushClass.equals(BrushClass.Brush.name())) { return false; } else if (t3dBrushClass.equals("LavaZone") || t3dBrushClass.equals("SlimeZone") || t3dBrushClass.equals("VaccuumZone") || t3dBrushClass.equals("NitrogenZone") || t3dBrushClass.equals("VaccuumZone") || t3dBrushClass.equals(BrushClass.UTSlimeVolume.name()) || t3dBrushClass.equals(BrushClass.UTLavaVolume.name())) { brushClass = BrushClass.UTPainVolume; forcedWrittenLines.add("DamagePerSec=10.000000"); return true; } else if (t3dBrushClass.equals("WaterZone")) { brushClass = BrushClass.UTWaterVolume; return true; } return false; } @Override public boolean isValidConverting() { boolean valid = true; if (mapConverter.fromUE123ToUE4()) { // do not convert invisible brushes such as portals and so on if (BrushPolyflag.hasInvisibleFlag(polyflags)) { logger.warning("Skipped invisible brush " + name); valid = false; } if (UE123_BrushType.valueOf(brushType) == UE123_BrushType.CSG_Active || UE123_BrushType.valueOf(brushType) == UE123_BrushType.CSG_Intersect || UE123_BrushType.valueOf(brushType) == UE123_BrushType.CSG_Deintersect) { logger.warning("Skipped unsupported CsgOper '" + brushType + "' in " + mapConverter.getUnrealEngineTo().name() + " for " + name); valid = false; } } return valid && super.isValidConverting(); } /** * * @return */ @Override public boolean isValidWriting() { boolean valid = true; // is first "red" brush in previous UE editors if ("Brush".equals(name)) { return false; } if (mapConverter.fromUE123ToUE4()) { if ("BlockAll".equals(t3dClass)) { return true; } // BUG UE4 DON'T LIKE SHEETS brushes or "Light Brushes" mainly // coming from UE1/UE2 ... // Else geometry building got holes so need to get rid of them ... // TODO add note? (some sheet brushes are movers ...) // TODO replace sheetbrush with sheet staticmesh // if 2 polygons and sheetbrush not a portal if (isUnsupportedUE4Brush()) { valid = false; // only notify if this brush could not be replaced by another // actor if (children.isEmpty()) { logger.warning("Skipped unsupported 'sheet brush' in " + mapConverter.getUnrealEngineTo().name() + " for " + name); } } /* * else if (willCauseBspHoles()) { bspHoleCausing = true; brushClass * = BrushClass.BlockingVolume; * logger.warning("Replaced potential bsphole with " + name + * " to blockingvolume"); } */ if (!valid) { return valid; } } return super.isValidWriting(); } /** * Tells if current brush is sheet brush: - one polygon - 4 vertices for * this polygon * * @return */ protected boolean isSheetBrush() { return polyList.size() == 1 && polyList.get(0).vertices.size() == 4; } /** * Detect if this current brush is not supported by Unreal Engine 4. This * kind of brush makes bsp holes on import. Generally is a "flat" brush used * in Unreal Engine 1 / 2 as a "Torch", "Water surface" and so on ... 1 poly * = sheet brush 2+ poly (generally torch) * * @return <code>true</code> If this brush is a sheet brush */ protected boolean isUnsupportedUE4Brush() { return polyList.size() <= 4; // FIXME all sheet brushes are well deleted but some (a very few) // normal brushes are detected as sheet ones (eg.: stairs / test // AS-HighSpeed) // so they are not being converted. // so the test is not reliable yet // for each vertices we check that it is linked to 3 polygons /* * for(T3DPolygon poly : polyList){ for(Vector3d v : poly.vertices){ * if(getPolyCountWithVertexCoordinate(v) < 3){ return true; } } } * return false; */ } /** * Compute if this brush will cause bsp holes: - only 4 or less polygon - OR * some vertex not bound with at least 3 polygons not enough accurate at * this stage * * @return <code>true</code> if this brush will cause bsp holes on import */ private boolean willCauseBspHoles() { // sheet brush (total nb polygons <= 4) if (polyList.size() <= 4) { return true; } for (T3DPolygon poly : polyList) { for (Vertex v : poly.vertices) { // vertex only linked with 2 or less other vertices // might be candidate for bsp hole // however need to do some extra checks if (getPolyCountWithVertexCoordinate(v) < 3) { // if this vertex is belonging to edge // of another polygon if (!Geometry.vertexInOtherPoly(polyList, poly, v)) { return true; } } } } return false; } final double VERY_TINY_NUM = 0.001d; /** * Return how many polygons are attached to this vertex. * * @param v * Brush vertex * @return Number of polygons attached to this vertex. */ private int getPolyCountWithVertexCoordinate(Vertex v) { int count = 0; for (T3DPolygon poly : polyList) { for (Vertex v2 : poly.vertices) { if (Math.abs(v.getX() - v2.getX()) < VERY_TINY_NUM && Math.abs(v.getY() - v2.getY()) < VERY_TINY_NUM && Math.abs(v.getZ() - v2.getZ()) < VERY_TINY_NUM) { count++; break; } } } return count; } public static DecimalFormat df = new DecimalFormat("+00000.000000;-00000.000000", new DecimalFormatSymbols(Locale.US)); /** * * @return */ @Override public String toString() { sbf.append(IDT).append("Begin Actor Class=").append(brushClass.name()).append(" Name=").append(name).append("\n"); // Location Data sbf.append(IDT).append("\tBegin Object Name=\"BrushComponent0\"\n"); writeLocRotAndScale(); sbf.append(IDT).append("\tEnd Object\n"); sbf.append(IDT).append("\tBrushType=").append(UE123_BrushType.valueOf(brushType) == UE123_BrushType.CSG_Add ? UE4_BrushType.Brush_Add : UE4_BrushType.Brush_Subtract).append("\n"); // UE3 only CullDistanceVolume if (brushClass == BrushClass.CullDistanceVolume && cullDistances != null) { int idx = 0; boolean hasCullDistProp = false; for (CullDistance cullDistance : cullDistances) { // CullDistances(1)=(Size=64.000000,CullDistance=3000.000000) sbf.append(IDT).append("\tCullDistances(").append(idx).append(")=("); if (cullDistance.size != null) { hasCullDistProp = true; sbf.append("Size=").append(cullDistance.size).append(","); } if (cullDistance.distance != null) { hasCullDistProp = true; sbf.append("CullDistance=").append(cullDistance.distance).append(","); } if (hasCullDistProp) { sbf.deleteCharAt(sbf.length() - 1); } sbf.append(")\n"); idx++; } } sbf.append(IDT).append("\tBegin Brush Name=").append(modelName).append("\n"); sbf.append(IDT).append("\t\tBegin PolyList\n"); int numPoly = 0; for (T3DPolygon t3dPolygon : polyList) { if (reverseVertexOrder) { t3dPolygon.reverseVertexOrder(); } t3dPolygon.toT3D(sbf, df, IDT, numPoly); numPoly++; } sbf.append(IDT).append("\t\tEnd PolyList\n"); sbf.append(IDT).append("\tEnd Brush\n"); sbf.append(IDT).append("\tBrush=Model'").append(modelName).append("'\n"); sbf.append(IDT).append("\tBrushComponent=BrushComponent0\n"); for (String line : forcedWrittenLines) { sbf.append(IDT).append(line).append("\n"); } // write specific properties of post process volume brush subclass if(this instanceof T3DPostProcessVolume){ T3DPostProcessVolume ppv = (T3DPostProcessVolume) this; ppv.writeProps(); } writeEndActor(); // UT3 has postprocess volumes // TODO merge/refactor/move to T3DPostProcessVolume class if ((mapConverter.getInputGame().engine.version < UnrealEngine.UE3.version) && (brushClass == BrushClass.UTWaterVolume || brushClass == BrushClass.UTSlimeVolume)) { // add post processvolume T3DBrush postProcessVolume = createBox(mapConverter, 95d, 95d, 95d); postProcessVolume.brushClass = BrushClass.PostProcessVolume; postProcessVolume.name = this.name + "PPVolume"; postProcessVolume.location = this.location; if (null != t3dClass) switch (t3dClass) { case "SlimeZone": // slimy ppv copied/pasted from DM-DeckTest (UT4) postProcessVolume.forcedWrittenLines .add("Settings=(bOverride_FilmWhitePoint=True,bOverride_AmbientCubemapIntensity=True,bOverride_DepthOfFieldMethod=True,FilmWhitePoint=(R=0.700000,G=1.000000,B=0.000000,A=1.000000),FilmShadowTint=(R=0.000000,G=1.000000,B=0.180251,A=1.000000),AmbientCubemapIntensity=0.000000,DepthOfFieldMethod=DOFM_Gaussian)"); break; case "UTSlimeVolume": // slimy ppv copied/pasted from DM-DeckTest (UT4) postProcessVolume.forcedWrittenLines .add("Settings=(bOverride_FilmWhitePoint=True,bOverride_AmbientCubemapIntensity=True,bOverride_DepthOfFieldMethod=True,FilmWhitePoint=(R=0.700000,G=1.000000,B=0.000000,A=1.000000),FilmShadowTint=(R=0.000000,G=1.000000,B=0.180251,A=1.000000),AmbientCubemapIntensity=0.000000,DepthOfFieldMethod=DOFM_Gaussian)"); break; case "WaterZone": postProcessVolume.forcedWrittenLines.add("Settings=(bOverride_FilmWhitePoint=True,bOverride_BloomIntensity=True,FilmWhitePoint=(R=0.189938,G=0.611443,B=1.000000,A=0.000000))"); break; } sbf.append(postProcessVolume.toString()); // TODO add sheet surface } return super.toString(); } /** * Creates a brush box. * * @param mc * Map Converter * @param width * @param length * @param height * @return */ public static T3DBrush createBox(MapConverter mc, Double width, Double length, Double height) { T3DBrush volume = new T3DBrush(mc, BrushClass.Brush.name()); volume.polyList = Geometry.createBox(width, length, height); return volume; } /** * Force brush to be a box * * @param size */ public void forceToBox(Double size) { polyList.clear(); polyList = Geometry.createBox(size, size, size); } /** * Creates a cylinder brush * * @param mc * Map Converter * @param radius * Radius of cylinder * @param height * Height * @param sides * Number of sides for cylinder * @return */ public static T3DBrush createCylinder(MapConverter mc, Double radius, Double height, int sides) { T3DBrush volume = new T3DBrush(mc, BrushClass.Brush.name()); volume.polyList.clear(); volume.polyList = Geometry.createCylinder(radius, height, sides); return volume; } @Override public void convert() { if ("BlockAll".equals(t3dClass)) { brushClass = BrushClass.BlockingVolume; if(collisionRadius == null){ collisionRadius = 10d; // default value in UE1/UE2 } if(collisionHeight == null){ collisionHeight = 10d; } polyList = Geometry.createCylinder(collisionRadius, collisionHeight, 8); super.convert(); } // UT3 if(brushClass == BrushClass.UTKillZVolume){ brushClass = BrushClass.KillZVolume; } // TODO handle other properties of volume like friction, ... // maybe add a super-class T3DVolume? // UTSlimeVolume does not exists in UT4 if (brushClass == BrushClass.UTSlimeVolume) { brushClass = BrushClass.UTPainVolume; forcedWrittenLines.add("\tDamagePerSec=10.000000"); } // UTSlimeVolume does not exists in UT4 if (brushClass == BrushClass.UTLavaVolume) { brushClass = BrushClass.UTPainVolume; forcedWrittenLines.add("\tDamagePerSec=60.000000"); } if (mapConverter.isFromUE1UE2ToUE3UE4()) { transformPermanently(); } // Update Location if prepivot set if (prePivot != null) { prePivot.negate(); // location = location - prepivot if (location == null) { location = prePivot; } else { location.add(prePivot); } prePivot = null; } // TODO check texture alignement after convert for (T3DPolygon p : polyList) { p.convert(); } // Replace Sheet Brush with Sheet StaticMesh if (isSheetBrush()) { T3DStaticMesh sheetStaticMesh = new T3DStaticMesh(mapConverter, this); children.add(sheetStaticMesh); } if (mapConverter.isTo(UnrealEngine.UE4)) { // ReverbVolume replaced with audio volume from ut3 to ut4 // TODO convert specific properties of these volume if (brushClass == BrushClass.ReverbVolume) { brushClass = BrushClass.AudioVolume; } if (brushClass == BrushClass.DynamicTriggerVolume) { brushClass = BrushClass.TriggerVolume; } } super.convert(); } /** * TransformPermanently a brush in UT/U1 Editor After that rotation, * mainscale and postscale are 'reset' Origin = (Origin * MainScale x * Rotate) * PostScale PrePivot = PrePivot * Rotation Normal = Normal * * Rotation MainScale * Vector -> Rotation * Vector -> PostScale * Vector */ private void transformPermanently() { if (prePivot != null) { Geometry.transformPermanently(prePivot, mainScale, rotation, postScale, false); } for (T3DPolygon polygon : polyList) { polygon.transformPermanently(mainScale, rotation, postScale); } rotation = null; mainScale = null; postScale = null; // TODO see purpose of TempScale // after tp in Unreal Engine, it is still set } /** * Rescale brush. Must be done always after convert */ @Override public void scale(Double newScale) { if (cullDistances != null) { for (CullDistance cullDistance : cullDistances) { cullDistance.scale(newScale); } } for (T3DPolygon polygon : polyList) { polygon.scale(newScale); } super.scale(newScale); } /** * Returns the max position of vertex belonging to this brush. * * @return Max position */ public Vector3d getMaxVertexPos() { Vector3d max = new Vector3d(0d, 0d, 0d); for (T3DPolygon p : polyList) { for (Vertex v : p.vertices) { Vector3d c = v.getCoordinates(); max.x = Math.max(max.x, c.x); max.y = Math.max(max.y, c.y); max.z = Math.max(max.z, c.z); } } if (location != null) { max.x = Math.max(max.x, location.x + max.x); max.y = Math.max(max.y, location.y + max.y); max.z = Math.max(max.z, location.z + max.z); } return max; } /** * Returns the min position of vertex belonging to this brush. * * @return Min position */ public Vector3d getMinVertexPos() { Vector3d min = new Vector3d(0d, 0d, 0d); for (T3DPolygon p : polyList) { for (Vertex v : p.vertices) { Vector3d c = v.getCoordinates(); min.x = Math.min(min.x, c.x); min.y = Math.min(min.y, c.y); min.z = Math.min(min.z, c.z); } } if (location != null) { min.x = Math.min(min.x, location.x + min.x); min.y = Math.min(min.y, location.y + min.y); min.z = Math.min(min.z, location.z + min.z); } return min; } /** * Sets polygons to this brush * * @param polyList */ public void setPolyList(LinkedList<T3DPolygon> polyList) { this.polyList = polyList; } public LinkedList<T3DPolygon> getPolyList() { return polyList; } private int curIdx = 0; /** * Give and index for each vertex having same coordinate */ public void calcVerticeIndices() { for (T3DPolygon polygon : polyList) { for (Vertex v : polygon.vertices) { if (v.getVertexPolyIdx() == null) { getVerticeWithCoordinate(v.getCoordinates(), SMALL_NUMBER); curIdx++; } } } } private final double SMALL_NUMBER = 0.001d; /** * Get the vertices with same coordinates * * @param coordinates * @param delta * @return List of vertices having same coordinates */ private List<Vertex> getVerticeWithCoordinate(Vector3d coordinates, double delta) { List<Vertex> vertices = new ArrayList<>(); for (T3DPolygon polygon : polyList) { for (Vertex v : polygon.vertices) { Double distance = Geometry.getDistance(v.getCoordinates(), coordinates); if (distance <= delta) { v.setVertexPolyIdx(curIdx); vertices.add(v); } } } return vertices; } }
package cpw.mods.fml.common; /** * Copied from ConsoleLogFormatter for shared use on the client * */ import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; final class FMLLogFormatter extends Formatter { private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public String format(LogRecord record) { StringBuilder msg = new StringBuilder(); msg.append(this.dateFormat.format(Long.valueOf(record.getMillis()))); Level lvl = record.getLevel(); if (lvl == Level.FINEST) { msg.append(" [FINEST] "); } else if (lvl == Level.FINER) { msg.append(" [FINER] "); } else if (lvl == Level.FINE) { msg.append(" [FINE] "); } else if (lvl == Level.INFO) { msg.append(" [INFO] "); } else if (lvl == Level.WARNING) { msg.append(" [WARNING] "); } else if (lvl == Level.SEVERE) { msg.append(" [SEVERE] "); } else if (lvl == Level.SEVERE) { msg.append(" [" + lvl.getLocalizedName() + "] "); } msg.append(record.getMessage()); msg.append(System.getProperty("line.separator")); Throwable thr = record.getThrown(); if (thr != null) { StringWriter thrDump = new StringWriter(); thr.printStackTrace(new PrintWriter(thrDump)); msg.append(thrDump.toString()); } return msg.toString(); } }
package edu.cmu.pocketsphinx; import static java.lang.String.format; import java.io.File; import java.util.Collection; import java.util.HashSet; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder.AudioSource; import android.os.*; import android.util.Log; import edu.cmu.pocketsphinx.Config; import edu.cmu.pocketsphinx.Decoder; import edu.cmu.pocketsphinx.Hypothesis; public class SpeechRecognizer { protected static final String TAG = SpeechRecognizer.class.getSimpleName(); private static final int MSG_START = 1; private static final int MSG_STOP = 2; private static final int MSG_CANCEL = 3; private static final int BUFFER_SIZE = 1024; private final Config config; private final Decoder decoder; private Thread recognizerThread; private final Handler mainHandler = new Handler(Looper.getMainLooper()); private final Collection<RecognitionListener> listeners = new HashSet<RecognitionListener>(); private final int sampleRate; protected SpeechRecognizer(Config config) { sampleRate = (int) config.getFloat("-samprate"); if (config.getFloat("-samprate") != sampleRate) throw new IllegalArgumentException("sampling rate must be integer"); this.config = config; decoder = new Decoder(config); } /** * Adds listener. */ public void addListener(RecognitionListener listener) { synchronized (listeners) { listeners.add(listener); } } /** * Removes listener. */ public void removeListener(RecognitionListener listener) { synchronized (listeners) { listeners.remove(listener); } } /** * Starts recognition. Does nothing if recognition is active. * * @return true if recognition was actually started */ public boolean startListening(String searchName) { if (null != recognizerThread) return false; Log.i(TAG, format("Start recognition \"%s\"", searchName)); decoder.setSearch(searchName); recognizerThread = new RecognizerThread(); recognizerThread.start(); return true; } private boolean stopRecognizerThread() { if (null == recognizerThread) return false; try { recognizerThread.interrupt(); recognizerThread.join(); } catch (InterruptedException e) { // Restore the interrupted status. Thread.currentThread().interrupt(); } recognizerThread = null; return true; } /** * Stops recognition. All listeners should receive final result if there is * any. Does nothing if recognition is not active. * * @return true if recognition was actually stopped */ public boolean stop() { boolean result = stopRecognizerThread(); if (result) Log.i(TAG, "Stop recognition"); return result; } /** * Cancels recogition. Listeners do not recevie final result. Does nothing * if recognition is not active. * * @return true if recognition was actually canceled */ public boolean cancel() { boolean result = stopRecognizerThread(); if (result) { Log.i(TAG, "Cancel recognition"); mainHandler.removeCallbacksAndMessages(null); } return result; } /** * Gets name of the currently active search. * * @return active search name or null if no search was started */ public String getSearchName() { return decoder.getSearch(); } public void addFsgSearch(String searchName, FsgModel fsgModel) { decoder.setFsg(searchName, fsgModel); } /** * Adds searches based on JSpeech grammar. * * @param name search name * @param file JSGF file */ public void addGrammarSearch(String name, File file) { Log.i(TAG, format("Load JSGF %s", file)); decoder.setJsgfFile(name, file.getPath()); } /** * Adds search based on N-gram language model. * * @param name search name * @param file N-gram model file */ public void addNgramSearch(String name, File file) { Log.i(TAG, format("Load N-gram model %s", file)); decoder.setLmFile(name, file.getPath()); } /** * Adds search based on a single phrase. * * @param name search name * @param phrase search phrase */ public void addKeywordSearch(String name, String phrase) { decoder.setKws(name, phrase); } private final class RecognizerThread extends Thread { @Override public void run() { AudioRecord recorder = new AudioRecord(AudioSource.VOICE_RECOGNITION, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, 8192); // TODO:calculate properly decoder.startUtt(null); recorder.startRecording(); short[] buffer = new short[BUFFER_SIZE]; boolean vadState = decoder.getVadState(); while (!interrupted()) { int nread = recorder.read(buffer, 0, buffer.length); if (-1 == nread) { throw new RuntimeException("error reading audio buffer"); } else if (nread > 0) { decoder.processRaw(buffer, nread, false, false); if (decoder.getVadState() != vadState) { vadState = decoder.getVadState(); mainHandler.post(new VadStateChangeEvent(vadState)); } final Hypothesis hypothesis = decoder.hyp(); if (null != hypothesis) mainHandler.post(new ResultEvent(hypothesis, false)); } } recorder.stop(); int nread = recorder.read(buffer, 0, buffer.length); recorder.release(); decoder.processRaw(buffer, nread, false, false); decoder.endUtt(); // Remove all pending notifications. mainHandler.removeCallbacksAndMessages(null); final Hypothesis hypothesis = decoder.hyp(); if (null != hypothesis) mainHandler.post(new ResultEvent(hypothesis, true)); } } private abstract class RecognitionEvent implements Runnable { public void run() { RecognitionListener[] emptyArray = new RecognitionListener[0]; for (RecognitionListener listener : listeners.toArray(emptyArray)) execute(listener); } protected abstract void execute(RecognitionListener listener); } private class VadStateChangeEvent extends RecognitionEvent { private final boolean state; VadStateChangeEvent(boolean state) { this.state = state; } @Override protected void execute(RecognitionListener listener) { if (state) listener.onBeginningOfSpeech(); else listener.onEndOfSpeech(); } } private class ResultEvent extends RecognitionEvent { protected final Hypothesis hypothesis; private final boolean finalResult; ResultEvent(Hypothesis hypothesis, boolean finalResult) { this.hypothesis = hypothesis; this.finalResult = finalResult; } @Override protected void execute(RecognitionListener listener) { if (finalResult) listener.onResult(hypothesis); else listener.onPartialResult(hypothesis); } } } /* vim: set ts=4 sw=4: */
package com.jfixby.r3.fokker.api.render; public enum RENDER_MACHINE_STATE { NEW, READY, FRAME, SHAPES, RASTER, SHADER; }
package edu.utdallas.robotchess.gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JToggleButton; import edu.utdallas.robotchess.game.Team; import edu.utdallas.robotchess.manager.ChessManager; import edu.utdallas.robotchess.manager.Manager; import edu.utdallas.robotchess.manager.NullManager; import edu.utdallas.robotchess.manager.RobotChessManager; import edu.utdallas.robotchess.manager.RobotDemoManager; public class MainFrame extends JFrame { public final static int SQUARE_SIZE = 100; public final static int CHESSBOT_INFO_PANEL_WIDTH = 300; public final static int CHESSBOT_INFO_PANEL_HEIGHT = 300; private static final long serialVersionUID = 0; Manager manager; BoardPanel boardPanel; ChessbotInfoPanel chessbotInfoPanel; JMenuBar menuBar; JMenu gameMenu; JMenu chessbotMenu; JMenu optionsMenu; JMenuItem newGameMenuItem; JMenuItem newChessDemoMenuItem; JRadioButton playWithChessbotsButton; JRadioButton playWithoutChessbotsButton; ButtonGroup chessbotButtonGroup; JToggleButton enableChessAIMenuItem; JToggleButton showConnectedChessbotButton; JButton connectToXbeeButton; JButton discoverChessbotsButton; MenuItemListener menuListener; public MainFrame() { manager = new NullManager(); boardPanel = new BoardPanel(manager); chessbotInfoPanel = new ChessbotInfoPanel(); setTitle("Robot Chess"); setSize(8 * SQUARE_SIZE, 8 * SQUARE_SIZE); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setupMenuBar(); add(boardPanel, BorderLayout.CENTER); add(chessbotInfoPanel, BorderLayout.EAST); chessbotInfoPanel.setVisible(false); setVisible(true); } private void setupMenuBar() { menuBar = new JMenuBar(); menuListener = new MenuItemListener(); gameMenu = new JMenu("Play Game"); chessbotMenu = new JMenu("Chessbots"); optionsMenu = new JMenu("Options"); newGameMenuItem = new JMenuItem("New Chessgame"); newChessDemoMenuItem = new JMenuItem("New Chessbot Demo"); showConnectedChessbotButton = new JToggleButton("Show Chessbot Info"); playWithChessbotsButton = new JRadioButton("Play with Chessbots"); playWithoutChessbotsButton = new JRadioButton("Play without Chessbots"); connectToXbeeButton = new JButton("Connect to Xbee"); enableChessAIMenuItem = new JToggleButton("Enable Chess AI"); discoverChessbotsButton = new JButton("Discover Chessbots"); // Figure out how to do keyboard shortcuts // gameMenu.setMnemonic(KeyEvent.VK_G); chessbotButtonGroup = new ButtonGroup(); chessbotButtonGroup.add(playWithChessbotsButton); chessbotButtonGroup.add(playWithoutChessbotsButton); gameMenu.add(newGameMenuItem); gameMenu.add(newChessDemoMenuItem); chessbotMenu.add(playWithChessbotsButton); chessbotMenu.add(playWithoutChessbotsButton); chessbotMenu.add(showConnectedChessbotButton); optionsMenu.add(enableChessAIMenuItem); optionsMenu.add(discoverChessbotsButton); gameMenu.setEnabled(false); showConnectedChessbotButton.setEnabled(false); connectToXbeeButton.setEnabled(false); enableChessAIMenuItem.setEnabled(false); discoverChessbotsButton.setEnabled(false); newGameMenuItem.addActionListener(menuListener); newChessDemoMenuItem.addActionListener(menuListener); showConnectedChessbotButton.addActionListener(menuListener); playWithChessbotsButton.addActionListener(menuListener); playWithoutChessbotsButton.addActionListener(menuListener); connectToXbeeButton.addActionListener(menuListener); enableChessAIMenuItem.addActionListener(menuListener); discoverChessbotsButton.addActionListener(menuListener); menuBar.add(gameMenu); menuBar.add(chessbotMenu); menuBar.add(optionsMenu); menuBar.add(connectToXbeeButton); setJMenuBar(menuBar); } private void switchManager(Manager manager) { manager.setComm(this.manager.getComm()); this.manager = manager; boardPanel.setManager(this.manager); toggleAI(false); boardPanel.updateDisplay(); } private void toggleChessbotInfo(boolean enabled) { if (enabled) { showConnectedChessbotButton.setText("Hide Chessbot Info"); setSize(getWidth() + CHESSBOT_INFO_PANEL_WIDTH, getHeight()); } else { showConnectedChessbotButton.setText("Show Chessbot Info"); if (chessbotInfoPanel.isShowing()) setSize(getWidth() - CHESSBOT_INFO_PANEL_WIDTH, getHeight()); } chessbotInfoPanel.setVisible(enabled); showConnectedChessbotButton.setSelected(enabled); } private void toggleAI(boolean enabled) { if (enabled) enableChessAIMenuItem.setText("Disable Chess AI"); else enableChessAIMenuItem.setText("Enable Chess AI"); //Will probably only need to see if instanceof ChessManager or //RobotChessManager, as they should both have the //setComputerControlsTeam() method //Add dialogue later for choosing team for AI as well as //choosing difficulty if (manager instanceof ChessManager) ((ChessManager) manager).setComputerControlsTeam(enabled, Team.GREEN); else if (manager instanceof RobotChessManager) { //TODO: Implement } enableChessAIMenuItem.setSelected(enabled); } private static void createAndShowGUI() { @SuppressWarnings("unused") MainFrame frame = new MainFrame(); } class MenuItemListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == playWithChessbotsButton) { gameMenu.setEnabled(true); connectToXbeeButton.setEnabled(true); enableChessAIMenuItem.setEnabled(false); showConnectedChessbotButton.setEnabled(true); newChessDemoMenuItem.setEnabled(true); discoverChessbotsButton.setEnabled(true); switchManager(new NullManager()); } if (e.getSource() == playWithoutChessbotsButton) { gameMenu.setEnabled(true); connectToXbeeButton.setEnabled(false); enableChessAIMenuItem.setEnabled(false); showConnectedChessbotButton.setEnabled(false); newChessDemoMenuItem.setEnabled(false); toggleChessbotInfo(false); discoverChessbotsButton.setEnabled(false); switchManager(new NullManager()); } if (e.getSource() == newGameMenuItem) { if (playWithChessbotsButton.isSelected()) { if(manager.checkIfAllChessbotsAreConnected()) { switchManager(new RobotChessManager()); enableChessAIMenuItem.setEnabled(true); } else JOptionPane.showMessageDialog(null, "All Chessbots need to " + "be connected in order to play a chessgame with them." + " To check how many are currently connected, go to " + "Options > Show Chessbot Info", "Not enough Chessbots connected", JOptionPane.WARNING_MESSAGE); } else { switchManager(new ChessManager()); enableChessAIMenuItem.setEnabled(true); } } if (e.getSource() == enableChessAIMenuItem) { boolean state = enableChessAIMenuItem.isSelected(); toggleAI(state); } if (e.getSource() == showConnectedChessbotButton) toggleChessbotInfo(showConnectedChessbotButton.isSelected()); if (e.getSource() == connectToXbeeButton) { boolean xbeeConnected = manager.isXbeeConnected(); if(manager.isXbeeConnected()) JOptionPane.showMessageDialog(null, "Xbee is connected"); else { xbeeConnected = manager.connectToXbee(); if(xbeeConnected) { chessbotInfoPanel.setChessbotInfoArrayHandler(manager.getChessbotInfo()); JOptionPane.showMessageDialog(null, "Successfully connected to Xbee"); } else JOptionPane.showMessageDialog(null, "Could not connect to Xbee. " + "Try again after unplugging and plugging in the Xbee. " + "If this does not work, restart the app.", "Cannot find Xbee", JOptionPane.WARNING_MESSAGE); } } if (e.getSource() == discoverChessbotsButton) { if (manager.isXbeeConnected()) { if(manager.isDiscoveringChessbots()) { JOptionPane.showMessageDialog(null, "Currently Discovering Chessbots", "Chessbot Discovery Underway", JOptionPane.WARNING_MESSAGE); } else manager.discoverChessbots(); } else JOptionPane.showMessageDialog(null, "Could not connect to Xbee. " + "Try again after unplugging and plugging in the Xbee. " + "If this does not work, restart the app.", "Cannot find Xbee", JOptionPane.WARNING_MESSAGE); } if (e.getSource() == newChessDemoMenuItem) { if (manager.isXbeeConnected() == false) { JOptionPane.showMessageDialog(null, "Xbee must be connected in order to " + "choose this game type.", "Xbee not Connected", JOptionPane.WARNING_MESSAGE); } else { ArrayList<String> robotsPresent = manager.getChessbotInfo().getRobotsPresent(); int boardRows = determineBoardRows(); int boardColumns = determineBoardColumns(); int[] userSelection = offerUserRobotSelection(robotsPresent, boardRows, boardColumns); int[] initialLocations = generateInitialLocations(userSelection); switchManager(new RobotDemoManager(initialLocations)); manager.setBoardRowCount(boardRows); manager.setBoardColumnCount(boardColumns); remove(boardPanel); boardPanel = new BoardPanel(manager); add(boardPanel); boardPanel.updateDisplay(); setSize(boardColumns * SQUARE_SIZE, boardRows * SQUARE_SIZE); } } } private int[] offerUserRobotSelection(ArrayList<String> robotsPresent, int boardRows, int boardColumns) { ArrayList<String> impossibleRobotStartingLocations = new ArrayList<String>(boardRows * boardColumns); for (int i = 0; i < 64; i++) if (i >= 8 * boardRows || (i % 8) >= boardColumns) impossibleRobotStartingLocations.add(Integer.toString(i)); for (int i = 0; i < robotsPresent.size(); i++) { int tempBotId = Integer.parseInt(robotsPresent.get(i)); if (tempBotId > 16) robotsPresent.set(i, Integer.toString(tempBotId + 32)); } robotsPresent.removeAll(impossibleRobotStartingLocations); for (int i = 0; i < robotsPresent.size(); i++) { int tempBotId = Integer.parseInt(robotsPresent.get(i)); if (tempBotId > 16) robotsPresent.set(i, Integer.toString(tempBotId - 32)); } JList<Object> list = new JList<Object>(robotsPresent.toArray()); JOptionPane.showMessageDialog(null, list, "Choose Available Chessbots", JOptionPane.PLAIN_MESSAGE); int[] selectedIndices = list.getSelectedIndices(); int[] userSelection = new int[selectedIndices.length]; int index = 0; for (int i : selectedIndices) userSelection[index++] = Integer.parseInt(robotsPresent.get(i)); return userSelection; } private int[] generateInitialLocations(int[] robotsPresent) { int[] locations = new int[32]; for (int i = 0; i < locations.length; i++) locations[i] = -1; for (int i = 0; i < robotsPresent.length; i++) { if (robotsPresent[i] > 15) locations[robotsPresent[i]] = robotsPresent[i] + 32; else locations[robotsPresent[i]] = robotsPresent[i]; } return locations; } private int determineBoardRows() { Object[] possibleDimensions = {"2", "3", "4", "5", "6", "7", "8"}; String boardRows = (String) JOptionPane.showInputDialog( (Component) null, "Please enter the number of board rows", "Board Rows", JOptionPane.PLAIN_MESSAGE, (Icon) null, possibleDimensions, "8"); int boardRowCount = Integer.parseInt(boardRows); return boardRowCount; } private int determineBoardColumns() { Object[] possibleDimensions = {"2", "3", "4", "5", "6", "7", "8"}; String boardColumns = (String) JOptionPane.showInputDialog( (Component) null, "Please enter the number of board columns", "Board Columns", JOptionPane.PLAIN_MESSAGE, (Icon) null, possibleDimensions, "8"); int boardColumnCount = Integer.parseInt(boardColumns); return boardColumnCount; } } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
package py.una.med.base.model; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Anotacion que define la internacionalizacion para un field, con el * {@link DisplayName#path()} se setea la ubicacion de donde se sacara el valor * para ser mostrado * * @author Arturo Volpe * @since 1.2 * @version 1.0 * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface DisplayName { /** * Clave por la cual se buscara en el archivo de idiomas en el formato<br/> * * <pre> * &quot;{CADENA}&quot; * </pre> * * Ejemplo * * <pre> * {@literal @}DisplayName(key="NACIONALIDAD_DESCRIPCION") * Nacionalidad nacionalidad; * </pre> * * @return Llave del archivo de idiomas */ String key(); String path() default ""; }