diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java b/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java index 164ef0b2..6608d9ec 100644 --- a/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java +++ b/bndtools.core/src/bndtools/internal/decorator/ExportedPackageDecoratorJob.java @@ -1,125 +1,121 @@ package bndtools.internal.decorator; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.osgi.framework.Version; import aQute.bnd.build.Project; import aQute.bnd.build.Workspace; import aQute.lib.osgi.Builder; import aQute.lib.osgi.Constants; import aQute.lib.osgi.Descriptors.PackageRef; import aQute.lib.osgi.Jar; import aQute.lib.osgi.Packages; import aQute.lib.osgi.Processor; import aQute.libg.header.Attrs; import bndtools.Central; import bndtools.Plugin; import bndtools.api.ILogger; import bndtools.utils.SWTConcurrencyUtil; public class ExportedPackageDecoratorJob extends Job implements ISchedulingRule { private static final ConcurrentMap<String,ExportedPackageDecoratorJob> instances = new ConcurrentHashMap<String,ExportedPackageDecoratorJob>(); private final IProject project; private final ILogger logger; public static void scheduleForProject(IProject project, ILogger logger) { ExportedPackageDecoratorJob job = new ExportedPackageDecoratorJob(project, logger); if (instances.putIfAbsent(project.getFullPath().toPortableString(), job) == null) { job.schedule(1000); } } ExportedPackageDecoratorJob(IProject project, ILogger logger) { super("Update exported packages: " + project.getName()); this.project = project; this.logger = logger; setRule(this); } @Override protected IStatus run(IProgressMonitor monitor) { instances.remove(project.getFullPath().toPortableString()); try { Project model = Workspace.getProject(project.getLocation().toFile()); Collection< ? extends Builder> builders = model.getSubBuilders(); Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>(); for (Builder builder : builders) { - Jar jar = null; try { builder.build(); Packages exports = builder.getExports(); if (exports != null) { for (Entry<PackageRef,Attrs> export : exports.entrySet()) { Version version; String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE); try { version = Version.parseVersion(versionStr); String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN()); SortedSet<Version> versions = allExports.get(pkgName); if (versions == null) { versions = new TreeSet<Version>(); allExports.put(pkgName, versions); } versions.add(version); } catch (IllegalArgumentException e) { // Seems to be an invalid export, ignore it... } } } } catch (Exception e) { Plugin.getDefault().getLogger().logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e); - } finally { - if (jar != null) - jar.close(); } } Central.setExportedPackageModel(project, allExports); Display display = PlatformUI.getWorkbench().getDisplay(); SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() { public void run() { PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.exportedPackageDecorator"); } }); } catch (Exception e) { logger.logWarning("Error persisting exported package model.", e); } return Status.OK_STATUS; } public boolean contains(ISchedulingRule rule) { return this == rule; } public boolean isConflicting(ISchedulingRule rule) { return rule instanceof ExportedPackageDecoratorJob; } }
false
true
protected IStatus run(IProgressMonitor monitor) { instances.remove(project.getFullPath().toPortableString()); try { Project model = Workspace.getProject(project.getLocation().toFile()); Collection< ? extends Builder> builders = model.getSubBuilders(); Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>(); for (Builder builder : builders) { Jar jar = null; try { builder.build(); Packages exports = builder.getExports(); if (exports != null) { for (Entry<PackageRef,Attrs> export : exports.entrySet()) { Version version; String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE); try { version = Version.parseVersion(versionStr); String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN()); SortedSet<Version> versions = allExports.get(pkgName); if (versions == null) { versions = new TreeSet<Version>(); allExports.put(pkgName, versions); } versions.add(version); } catch (IllegalArgumentException e) { // Seems to be an invalid export, ignore it... } } } } catch (Exception e) { Plugin.getDefault().getLogger().logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e); } finally { if (jar != null) jar.close(); } } Central.setExportedPackageModel(project, allExports); Display display = PlatformUI.getWorkbench().getDisplay(); SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() { public void run() { PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.exportedPackageDecorator"); } }); } catch (Exception e) { logger.logWarning("Error persisting exported package model.", e); } return Status.OK_STATUS; }
protected IStatus run(IProgressMonitor monitor) { instances.remove(project.getFullPath().toPortableString()); try { Project model = Workspace.getProject(project.getLocation().toFile()); Collection< ? extends Builder> builders = model.getSubBuilders(); Map<String,SortedSet<Version>> allExports = new HashMap<String,SortedSet<Version>>(); for (Builder builder : builders) { try { builder.build(); Packages exports = builder.getExports(); if (exports != null) { for (Entry<PackageRef,Attrs> export : exports.entrySet()) { Version version; String versionStr = export.getValue().get(Constants.VERSION_ATTRIBUTE); try { version = Version.parseVersion(versionStr); String pkgName = Processor.removeDuplicateMarker(export.getKey().getFQN()); SortedSet<Version> versions = allExports.get(pkgName); if (versions == null) { versions = new TreeSet<Version>(); allExports.put(pkgName, versions); } versions.add(version); } catch (IllegalArgumentException e) { // Seems to be an invalid export, ignore it... } } } } catch (Exception e) { Plugin.getDefault().getLogger().logWarning(MessageFormat.format("Unable to process exported packages for builder of {0}.", builder.getPropertiesFile()), e); } } Central.setExportedPackageModel(project, allExports); Display display = PlatformUI.getWorkbench().getDisplay(); SWTConcurrencyUtil.execForDisplay(display, true, new Runnable() { public void run() { PlatformUI.getWorkbench().getDecoratorManager().update("bndtools.exportedPackageDecorator"); } }); } catch (Exception e) { logger.logWarning("Error persisting exported package model.", e); } return Status.OK_STATUS; }
diff --git a/src/com/codisimus/plugins/lores/Lores.java b/src/com/codisimus/plugins/lores/Lores.java index d53a574..61baa6c 100644 --- a/src/com/codisimus/plugins/lores/Lores.java +++ b/src/com/codisimus/plugins/lores/Lores.java @@ -1,348 +1,348 @@ package com.codisimus.plugins.lores; import java.util.*; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; public class Lores extends JavaPlugin implements CommandExecutor { private static enum Action { NAME, OWNER, ADD, DELETE, SET, INSERT, CLEAR, UNDO } private static HashMap<String, LinkedList<ItemStack>> undo = new HashMap<String, LinkedList<ItemStack>>(); char[] colorCodes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'l', 'n', 'o', 'k', 'm', 'r' }; @Override public void onEnable () { //Register the lore command getCommand("lore").setExecutor(this); //Retrieve the version file Properties version = new Properties(); try { version.load(this.getResource("version.properties")); } catch (Exception ex) { } //Log the version and build numbers getLogger().info("Lores " + this.getDescription().getVersion() + " (Build " + version.getProperty("Build") + ") is enabled!"); } @Override public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { //This Command is only useful to Players if (!(sender instanceof Player)) { sendHelp(sender); return true; } Player player = (Player) sender; ItemStack item = player.getItemInHand(); //Retrieve the meta and make one if it doesn't exist ItemMeta meta = item.getItemMeta(); if (meta == null) { meta = Bukkit.getItemFactory().getItemMeta(item.getType()); if (meta == null) { player.sendMessage("§4The Item you are holding does not support Lore"); return true; } } //There must be at least one argument if (args.length < 1) { sendHelp(sender); return true; } //Retrieve the lore and make one if it doesn't exist List<String> lore = meta.getLore(); if (lore == null) { lore = new LinkedList<String>(); } //Discover the action to be executed Action action; try { action = Action.valueOf(args[0].toUpperCase()); } catch (IllegalArgumentException notEnum) { sendHelp(sender); return true; } //Generate the String id for the Player/Item String id = player.getName() + "'" + item.getTypeId(); if (action != Action.UNDO) { //Create an undo List for the Player if there isn't one if (!undo.containsKey(id)) { undo.put(id, new LinkedList<ItemStack>()); } //Add the meta state to the undo List LinkedList<ItemStack> list = undo.get(id); list.addFirst(item.clone()); //Don't allow the undo List to grow too large while (list.size() > 5) { list.removeLast(); } } switch (action) { case NAME: //Change the Name of the Item if (!sender.hasPermission("lores.name") || args.length < 2) { sendHelp(sender); return true; } String name = concatArgs(sender, args, 1); if (name.contains("|")) { int max = name.replaceAll("§[0-9a-klmnor]", "").length(); Iterator<String> itr = lore.iterator(); while (itr.hasNext()) { max = Math.max(max, itr.next().replaceAll("§[0-9a-klmnor]", "").length()); } int spaces = max - name.replaceAll("§[0-9a-klmnor]", "").length() - 1; String space = " "; for (int i = 1; i < spaces * 1.5; i++) { space += ' '; } name = name.replace("|", space); } meta.setDisplayName(name); break; case OWNER: //Change the Owner of the Skull if (!sender.hasPermission("lores.owner") || args.length < 2) { sendHelp(sender); return true; } if (!(meta instanceof SkullMeta)) { player.sendMessage("§4You may only set the Owner of a §6Skull"); return true; } ((SkullMeta) meta).setOwner(args[1]); break; case ADD: //Add a line to the end of the lore - if (!sender.hasPermission("lores.name") || args.length < 2) { + if (!sender.hasPermission("lores.lore") || args.length < 2) { sendHelp(sender); return true; } lore.add(concatArgs(sender, args, 1)); break; case DELETE: //Delete a line of the lore if (!sender.hasPermission("lores.lore")) { sendHelp(sender); return true; } switch (args.length) { case 1: //Delete the last line if (lore.size() < 1) { player.sendMessage("§4There is nothing to delete!"); return true; } lore.remove(lore.size() - 1); break; case 2: //Delete specified line //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.remove(index); break; default: return false; } break; case SET: //Change a line of the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.set(index, concatArgs(sender, args, 2)); break; case INSERT: //Insert a line into the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int i; try { i = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= i || i < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.add(i, concatArgs(sender, args, 2)); break; case CLEAR: if (!sender.hasPermission("lores.lore") || args.length != 1) { sendHelp(sender); return true; } lore.clear(); break; case UNDO: //Ensure that we are given the correct number of arguments if (args.length != 1) { return false; } //Retrieve the old ItemStack from the undo List LinkedList<ItemStack> list = undo.get(id); if (list == null) { player.sendMessage("§4You have not yet modified this Item!"); return true; } if (list.size() < 1) { player.sendMessage("§4You cannot continue to undo for this Item!"); return true; } ItemStack undoneItem = list.removeFirst(); if (!item.isSimilar(undoneItem) && item.getType() != Material.SKULL_ITEM) { player.sendMessage("§4You have not yet modified this Item!"); return true; } //Dupe fix int stackSize = item.getAmount(); if (undoneItem.getAmount() != stackSize) { undoneItem.setAmount(stackSize); } //Place the old Item in the Player's hand player.setItemInHand(undoneItem); player.sendMessage("§5The last modification you made on this item has been undone!"); return true; } //Set the new lore/meta meta.setLore(lore); item.setItemMeta(meta); player.sendMessage("§5Lore successfully modified!"); return true; } /** * Concats arguments together to create a sentence from words * This also replaces & with § to add color codes to * the String if the sender has the needed permissions * * @param sender the Player concating * @param args the arguments to concat * @param first Which argument should the sentence start with * @return The new String that was created */ private static String concatArgs(CommandSender sender, String[] args, int first) { StringBuilder sb = new StringBuilder(); if (first > args.length) { return ""; } for (int i = first; i <= args.length - 1; i++) { sb.append(" "); sb.append(ChatColor.translateAlternateColorCodes('&', args[i])); } String string = sb.substring(1); char[] charArray = string.toCharArray(); boolean modified = false; for (int i = 0; i < charArray.length; i++) { if (charArray[i] == '§') { if (!sender.hasPermission("lores.color." + charArray[i + 1])) { charArray[i] = '?'; modified = true; } } } return modified ? String.copyValueOf(charArray) : string; } /** * Displays the Lores Help Page to the given Player * * @param player The Player needing help */ private static void sendHelp(CommandSender sender) { sender.sendMessage("§e Lores Help Page:"); sender.sendMessage("§5Each command will modify the Item in your hand"); if (sender.hasPermission("lores.color") || sender.hasPermission("lores.format")) { sender.sendMessage("§5Use §6& §5to add color with any command"); } if (sender.hasPermission("lores.name")) { sender.sendMessage("§2/lore name <custom name> §bSet the new Name of the Item"); } if (sender.hasPermission("lores.owner")) { sender.sendMessage("§2/lore owner <player> §bChange the Owner of a Skull"); } if (sender.hasPermission("lores.lore")) { sender.sendMessage("§2/lore add <line of text> §bAdd a line to the lore"); sender.sendMessage("§2/lore set <line #> <line of text> §bChange a line of the lore"); sender.sendMessage("§2/lore insert <line #> <line of text> §bInsert a line into the lore"); sender.sendMessage("§2/lore delete [line #] §bDelete a line of the lore (last line by default)"); sender.sendMessage("§2/lore clear §bClear all lines of the lore"); } sender.sendMessage("§2/lore undo §bUndoes your last modification (up to 5 times)"); } }
true
true
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { //This Command is only useful to Players if (!(sender instanceof Player)) { sendHelp(sender); return true; } Player player = (Player) sender; ItemStack item = player.getItemInHand(); //Retrieve the meta and make one if it doesn't exist ItemMeta meta = item.getItemMeta(); if (meta == null) { meta = Bukkit.getItemFactory().getItemMeta(item.getType()); if (meta == null) { player.sendMessage("§4The Item you are holding does not support Lore"); return true; } } //There must be at least one argument if (args.length < 1) { sendHelp(sender); return true; } //Retrieve the lore and make one if it doesn't exist List<String> lore = meta.getLore(); if (lore == null) { lore = new LinkedList<String>(); } //Discover the action to be executed Action action; try { action = Action.valueOf(args[0].toUpperCase()); } catch (IllegalArgumentException notEnum) { sendHelp(sender); return true; } //Generate the String id for the Player/Item String id = player.getName() + "'" + item.getTypeId(); if (action != Action.UNDO) { //Create an undo List for the Player if there isn't one if (!undo.containsKey(id)) { undo.put(id, new LinkedList<ItemStack>()); } //Add the meta state to the undo List LinkedList<ItemStack> list = undo.get(id); list.addFirst(item.clone()); //Don't allow the undo List to grow too large while (list.size() > 5) { list.removeLast(); } } switch (action) { case NAME: //Change the Name of the Item if (!sender.hasPermission("lores.name") || args.length < 2) { sendHelp(sender); return true; } String name = concatArgs(sender, args, 1); if (name.contains("|")) { int max = name.replaceAll("§[0-9a-klmnor]", "").length(); Iterator<String> itr = lore.iterator(); while (itr.hasNext()) { max = Math.max(max, itr.next().replaceAll("§[0-9a-klmnor]", "").length()); } int spaces = max - name.replaceAll("§[0-9a-klmnor]", "").length() - 1; String space = " "; for (int i = 1; i < spaces * 1.5; i++) { space += ' '; } name = name.replace("|", space); } meta.setDisplayName(name); break; case OWNER: //Change the Owner of the Skull if (!sender.hasPermission("lores.owner") || args.length < 2) { sendHelp(sender); return true; } if (!(meta instanceof SkullMeta)) { player.sendMessage("§4You may only set the Owner of a §6Skull"); return true; } ((SkullMeta) meta).setOwner(args[1]); break; case ADD: //Add a line to the end of the lore if (!sender.hasPermission("lores.name") || args.length < 2) { sendHelp(sender); return true; } lore.add(concatArgs(sender, args, 1)); break; case DELETE: //Delete a line of the lore if (!sender.hasPermission("lores.lore")) { sendHelp(sender); return true; } switch (args.length) { case 1: //Delete the last line if (lore.size() < 1) { player.sendMessage("§4There is nothing to delete!"); return true; } lore.remove(lore.size() - 1); break; case 2: //Delete specified line //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.remove(index); break; default: return false; } break; case SET: //Change a line of the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.set(index, concatArgs(sender, args, 2)); break; case INSERT: //Insert a line into the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int i; try { i = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= i || i < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.add(i, concatArgs(sender, args, 2)); break; case CLEAR: if (!sender.hasPermission("lores.lore") || args.length != 1) { sendHelp(sender); return true; } lore.clear(); break; case UNDO: //Ensure that we are given the correct number of arguments if (args.length != 1) { return false; } //Retrieve the old ItemStack from the undo List LinkedList<ItemStack> list = undo.get(id); if (list == null) { player.sendMessage("§4You have not yet modified this Item!"); return true; } if (list.size() < 1) { player.sendMessage("§4You cannot continue to undo for this Item!"); return true; } ItemStack undoneItem = list.removeFirst(); if (!item.isSimilar(undoneItem) && item.getType() != Material.SKULL_ITEM) { player.sendMessage("§4You have not yet modified this Item!"); return true; } //Dupe fix int stackSize = item.getAmount(); if (undoneItem.getAmount() != stackSize) { undoneItem.setAmount(stackSize); } //Place the old Item in the Player's hand player.setItemInHand(undoneItem); player.sendMessage("§5The last modification you made on this item has been undone!"); return true; } //Set the new lore/meta meta.setLore(lore); item.setItemMeta(meta); player.sendMessage("§5Lore successfully modified!"); return true; }
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) { //This Command is only useful to Players if (!(sender instanceof Player)) { sendHelp(sender); return true; } Player player = (Player) sender; ItemStack item = player.getItemInHand(); //Retrieve the meta and make one if it doesn't exist ItemMeta meta = item.getItemMeta(); if (meta == null) { meta = Bukkit.getItemFactory().getItemMeta(item.getType()); if (meta == null) { player.sendMessage("§4The Item you are holding does not support Lore"); return true; } } //There must be at least one argument if (args.length < 1) { sendHelp(sender); return true; } //Retrieve the lore and make one if it doesn't exist List<String> lore = meta.getLore(); if (lore == null) { lore = new LinkedList<String>(); } //Discover the action to be executed Action action; try { action = Action.valueOf(args[0].toUpperCase()); } catch (IllegalArgumentException notEnum) { sendHelp(sender); return true; } //Generate the String id for the Player/Item String id = player.getName() + "'" + item.getTypeId(); if (action != Action.UNDO) { //Create an undo List for the Player if there isn't one if (!undo.containsKey(id)) { undo.put(id, new LinkedList<ItemStack>()); } //Add the meta state to the undo List LinkedList<ItemStack> list = undo.get(id); list.addFirst(item.clone()); //Don't allow the undo List to grow too large while (list.size() > 5) { list.removeLast(); } } switch (action) { case NAME: //Change the Name of the Item if (!sender.hasPermission("lores.name") || args.length < 2) { sendHelp(sender); return true; } String name = concatArgs(sender, args, 1); if (name.contains("|")) { int max = name.replaceAll("§[0-9a-klmnor]", "").length(); Iterator<String> itr = lore.iterator(); while (itr.hasNext()) { max = Math.max(max, itr.next().replaceAll("§[0-9a-klmnor]", "").length()); } int spaces = max - name.replaceAll("§[0-9a-klmnor]", "").length() - 1; String space = " "; for (int i = 1; i < spaces * 1.5; i++) { space += ' '; } name = name.replace("|", space); } meta.setDisplayName(name); break; case OWNER: //Change the Owner of the Skull if (!sender.hasPermission("lores.owner") || args.length < 2) { sendHelp(sender); return true; } if (!(meta instanceof SkullMeta)) { player.sendMessage("§4You may only set the Owner of a §6Skull"); return true; } ((SkullMeta) meta).setOwner(args[1]); break; case ADD: //Add a line to the end of the lore if (!sender.hasPermission("lores.lore") || args.length < 2) { sendHelp(sender); return true; } lore.add(concatArgs(sender, args, 1)); break; case DELETE: //Delete a line of the lore if (!sender.hasPermission("lores.lore")) { sendHelp(sender); return true; } switch (args.length) { case 1: //Delete the last line if (lore.size() < 1) { player.sendMessage("§4There is nothing to delete!"); return true; } lore.remove(lore.size() - 1); break; case 2: //Delete specified line //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.remove(index); break; default: return false; } break; case SET: //Change a line of the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int index; try { index = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= index || index < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.set(index, concatArgs(sender, args, 2)); break; case INSERT: //Insert a line into the lore if (!sender.hasPermission("lores.lore") || args.length < 3) { sendHelp(sender); return true; } //Ensure that the argument is an Integer int i; try { i = Integer.parseInt(args[1]) - 1; } catch (Exception e) { return false; } //Ensure that the lore is large enough if (lore.size() <= i || i < 0) { player.sendMessage("§4Invalid line number!"); return true; } lore.add(i, concatArgs(sender, args, 2)); break; case CLEAR: if (!sender.hasPermission("lores.lore") || args.length != 1) { sendHelp(sender); return true; } lore.clear(); break; case UNDO: //Ensure that we are given the correct number of arguments if (args.length != 1) { return false; } //Retrieve the old ItemStack from the undo List LinkedList<ItemStack> list = undo.get(id); if (list == null) { player.sendMessage("§4You have not yet modified this Item!"); return true; } if (list.size() < 1) { player.sendMessage("§4You cannot continue to undo for this Item!"); return true; } ItemStack undoneItem = list.removeFirst(); if (!item.isSimilar(undoneItem) && item.getType() != Material.SKULL_ITEM) { player.sendMessage("§4You have not yet modified this Item!"); return true; } //Dupe fix int stackSize = item.getAmount(); if (undoneItem.getAmount() != stackSize) { undoneItem.setAmount(stackSize); } //Place the old Item in the Player's hand player.setItemInHand(undoneItem); player.sendMessage("§5The last modification you made on this item has been undone!"); return true; } //Set the new lore/meta meta.setLore(lore); item.setItemMeta(meta); player.sendMessage("§5Lore successfully modified!"); return true; }
diff --git a/src/test/java/PredicateTests.java b/src/test/java/PredicateTests.java index 1f360f3..b61ff5b 100644 --- a/src/test/java/PredicateTests.java +++ b/src/test/java/PredicateTests.java @@ -1,123 +1,122 @@ import org.junit.Test; import java.util.Objects; import java.util.function.Predicate; import java.util.function.Predicates; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; public class PredicateTests { @Test public void youCanMakeYourOwnPredicates(){ Predicate<String> isFoo = (x)-> Objects.equals(x,"foo"); assertTrue(isFoo.test("foo")); assertFalse(isFoo.test("bar")); } @Test public void canChainPredicates(){ Predicate<Integer> gt6 = (x)-> x > 6; Predicate<Integer> lt9 = (x)-> x < 9; assertTrue(gt6.and(lt9).test(7)); assertFalse(gt6.and(lt9).test(5)); assertFalse(gt6.and(lt9).test(10)); } @Test public void canProduceANegatingPredicate(){ Predicate<String> isFoo = (x)-> Objects.equals(x,"foo"); assertFalse(isFoo.negate().test("foo")); assertTrue(isFoo.negate().test("bar")); } @Test public void canProduceOrPredicates(){ Predicate<Integer> is6 = (x)->x.equals(6); Predicate<Integer> is9 = (x)->x.equals(9); assertTrue(is6.or(is9).test(6)); assertTrue(is6.or(is9).test(9)); assertFalse(is6.or(is9).test(7)); } @Test public void canDoAXOr(){ - Predicate<Integer> gt6 = (x) -> x > 6; - Predicate<Integer> lt9 = (x) -> x < 9; - Predicate<Integer> even = (x) -> x % 2 == 0; + Predicate<String> containsF = (x) -> x.contains("F"); + Predicate<String> startsWithp = (x) -> x.startsWith("p"); - Predicate<Integer> all = gt6.xor(lt9).xor(even); + Predicate<String> xor = containsF.xor(startsWithp); - assertTrue(all.test(8)); - assertFalse(all.test(7)); - assertFalse(all.test(10)); - assertFalse(all.test(6)); + assertFalse(xor.test("pAndFoo")); + assertTrue(xor.test("patty")); + assertTrue(xor.test("Barney Fife")); + assertFalse(xor.test("Neither is true here")); } @Test public void findNulls(){ Predicate<String> p = Predicates.isNull(); assertFalse(p.test("foo")); assertTrue(p.test(null)); } @Test public void findNotNulls(){ Predicate<String> p = Predicates.nonNull(); assertFalse(p.test(null)); assertTrue(p.test("foo")); } @Test public void alwaysFalseIsAlwaysFalse(){ Predicate<String> p = Predicates.alwaysFalse(); assertFalse(p.test(null)); assertFalse(p.test("foo")); } @Test public void alwaysTrueIsAlwaysTrue(){ Predicate<String> p = Predicates.alwaysTrue(); assertTrue(p.test(null)); assertTrue(p.test("foo")); } @Test public void canTellIfItsAnInstanceOf(){ Predicate<Foo> p = Predicates.instanceOf(FooBar.class); assertFalse(p.test(new Foo())); assertTrue(p.test(new FooBar())); } static class FooBar extends Foo {} @Test public void cantellIfSame(){ Foo foo = new Foo(); Predicate<Foo> p = Predicates.isSame(foo); assertTrue(p.test(foo)); assertFalse(p.test(new Foo())); } @Test public void canTellIfEquals(){ Predicate<String> p = Predicates.isEqual("foo"); assertTrue(p.test("foo")); assertFalse(p.test("bar")); } }
false
true
public void canDoAXOr(){ Predicate<Integer> gt6 = (x) -> x > 6; Predicate<Integer> lt9 = (x) -> x < 9; Predicate<Integer> even = (x) -> x % 2 == 0; Predicate<Integer> all = gt6.xor(lt9).xor(even); assertTrue(all.test(8)); assertFalse(all.test(7)); assertFalse(all.test(10)); assertFalse(all.test(6)); }
public void canDoAXOr(){ Predicate<String> containsF = (x) -> x.contains("F"); Predicate<String> startsWithp = (x) -> x.startsWith("p"); Predicate<String> xor = containsF.xor(startsWithp); assertFalse(xor.test("pAndFoo")); assertTrue(xor.test("patty")); assertTrue(xor.test("Barney Fife")); assertFalse(xor.test("Neither is true here")); }
diff --git a/src/classes/win32/javax/media/j3d/NativeConfigTemplate3D.java b/src/classes/win32/javax/media/j3d/NativeConfigTemplate3D.java index f52223f..b37af27 100644 --- a/src/classes/win32/javax/media/j3d/NativeConfigTemplate3D.java +++ b/src/classes/win32/javax/media/j3d/NativeConfigTemplate3D.java @@ -1,215 +1,215 @@ /* * $RCSfile$ * * Copyright (c) 2004 Sun Microsystems, Inc. All rights reserved. * * Use is subject to license terms. * * $Revision$ * $Date$ * $State$ */ package javax.media.j3d; import java.awt.GraphicsDevice; import java.awt.GraphicsConfiguration; import sun.awt.Win32GraphicsDevice; import sun.awt.Win32GraphicsConfig; import java.awt.GraphicsConfigTemplate; class NativeConfigTemplate3D { private final static boolean debug = false; NativeConfigTemplate3D() { } // This definition should match those in solaris NativeConfigTemplate3D.java final static int RED_SIZE = 0; final static int GREEN_SIZE = 1; final static int BLUE_SIZE = 2; final static int ALPHA_SIZE = 3; final static int ACCUM_BUFFER = 4; final static int DEPTH_SIZE = 5; final static int DOUBLEBUFFER = 6; final static int STEREO = 7; final static int ANTIALIASING = 8; final static int NUM_ITEMS = 9; /** * selects the proper visual */ native int choosePixelFormat(long ctx, int screen, int[] attrList, long[] pFormatInfo); // Native method to free an PixelFormatInfo struct. This is static since it // may need to be called to clean up the Canvas3D fbConfigTable after the // NativeConfigTemplate3D has been disposed of. static native void freePixelFormatInfo(long pFormatInfo); // Native methods to return whether a particular attribute is available native boolean isStereoAvailable(long pFormatInfo, boolean offScreen); native boolean isDoubleBufferAvailable(long pFormatInfo, boolean offScreen); native boolean isSceneAntialiasingAccumAvailable(long pFormatInfo, boolean offScreen); native boolean isSceneAntialiasingMultisampleAvailable(long pFormatInfo, boolean offScreen, int screen); /** * Chooses the best PixelFormat for Java 3D apps. */ GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate3D template, GraphicsConfiguration[] gc) { Win32GraphicsDevice gd = (Win32GraphicsDevice)((Win32GraphicsConfig)gc[0]).getDevice(); /* Not ready to enforce ARB extension in J3D1.3.2, but will likely to do so in J3D 1.4. System.out.println("getBestConfiguration : Checking WGL ARB support\n"); if (!NativeScreenInfo.isWglARB()) { Thread.dumpStack(); System.out.println("getBestConfiguration : WGL ARB support fail\n"); return null; } */ // holds the list of attributes to be tramslated // for glxChooseVisual call int attrList[] = new int[NUM_ITEMS]; // assign template values to array attrList[RED_SIZE] = template.getRedSize(); attrList[GREEN_SIZE] = template.getGreenSize(); attrList[BLUE_SIZE] = template.getBlueSize(); attrList[DEPTH_SIZE] = template.getDepthSize(); attrList[DOUBLEBUFFER] = template.getDoubleBuffer(); attrList[STEREO] = template.getStereo(); attrList[ANTIALIASING] = template.getSceneAntialiasing(); NativeScreenInfo nativeScreenInfo = new NativeScreenInfo(gd); int screen = nativeScreenInfo.getScreen(); long[] pFormatInfo = new long[1]; /* Deliberately set this to -1. pFormatInfo is not use in D3D, so this value will be unchange in the case of D3D. In the case of OGL, the return value should be 0 or a positive valid address. */ pFormatInfo[0] = -1; int pixelFormat = choosePixelFormat(0, screen, attrList, pFormatInfo); if (debug) { System.out.println(" choosePixelFormat() returns " + pixelFormat); System.out.println(" pFormatInfo is " + pFormatInfo[0]); System.out.println(); } if (pixelFormat < 0) { // current mode don't support the minimum config return null; } - // Fix to issue 97 -- + // Fix to issue 104 -- // Pass in 0 for pixel format to the AWT. // ATI driver will lockup pixelFormat, if it is passed to AWT. GraphicsConfiguration gc1 = new J3dGraphicsConfig(gd, 0); // We need to cache the offScreen pixelformat that glXChoosePixelFormat() // returns, since this is not cached with J3dGraphicsConfig and there // are no public constructors to allow us to extend it. synchronized (Canvas3D.fbConfigTable) { if (Canvas3D.fbConfigTable.get(gc1) == null) Canvas3D.fbConfigTable.put(gc1, new Long(pFormatInfo[0])); else freePixelFormatInfo(pFormatInfo[0]); } return gc1; } /** * Determine if a given GraphicsConfiguration object can be used * by Java 3D. */ boolean isGraphicsConfigSupported(GraphicsConfigTemplate3D template, GraphicsConfiguration gc) { Win32GraphicsDevice gd = (Win32GraphicsDevice)((Win32GraphicsConfig) gc).getDevice(); /* Not ready to enforce ARB extension in J3D1.3.2, but will likely to do so in J3D 1.4. System.out.println("isGraphicsConfigSupported : Checking WGL ARB support\n"); if (!NativeScreenInfo.isWglARB()) { Thread.dumpStack(); System.out.println("isGraphicsConfigSupported : WGL ARB support fail\n"); return false; } */ // holds the list of attributes to be tramslated // for glxChooseVisual call int attrList[] = new int[NUM_ITEMS]; // assign template values to array attrList[RED_SIZE] = template.getRedSize(); attrList[GREEN_SIZE] = template.getGreenSize(); attrList[BLUE_SIZE] = template.getBlueSize(); attrList[DEPTH_SIZE] = template.getDepthSize(); attrList[DOUBLEBUFFER] = template.getDoubleBuffer(); attrList[STEREO] = template.getStereo(); attrList[ANTIALIASING] = template.getSceneAntialiasing(); NativeScreenInfo nativeScreenInfo = new NativeScreenInfo(gd); int screen = nativeScreenInfo.getScreen(); long[] pFormatInfo = new long[1]; int pixelFormat = choosePixelFormat(0, screen, attrList, pFormatInfo); if (debug) { System.out.println(" choosePixelFormat() returns " + pixelFormat); System.out.println(" pFormatInfo is " + pFormatInfo[0]); System.out.println(); } if (pixelFormat < 0) { // current mode don't support the minimum config return false; } else return true; } // Return whether stereo is available. boolean hasStereo(Canvas3D c3d) { return isStereoAvailable(c3d.fbConfig, c3d.offScreen); } // Return whether a double buffer is available. boolean hasDoubleBuffer(Canvas3D c3d) { return isDoubleBufferAvailable(c3d.fbConfig, c3d.offScreen); } // Return whether scene antialiasing is available. boolean hasSceneAntialiasingAccum(Canvas3D c3d) { return isSceneAntialiasingAccumAvailable(c3d.fbConfig, c3d.offScreen); } // Return whether scene antialiasing is available. boolean hasSceneAntialiasingMultisample(Canvas3D c3d) { GraphicsConfiguration gc = c3d.graphicsConfiguration; Win32GraphicsDevice gd = (Win32GraphicsDevice)((Win32GraphicsConfig)gc).getDevice(); NativeScreenInfo nativeScreenInfo = new NativeScreenInfo(gd); int screen = nativeScreenInfo.getScreen(); /* Fix to issue 77 */ return isSceneAntialiasingMultisampleAvailable(c3d.fbConfig, c3d.offScreen, screen); } // Ensure that the native libraries are loaded static { VirtualUniverse.loadLibraries(); } }
true
true
GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate3D template, GraphicsConfiguration[] gc) { Win32GraphicsDevice gd = (Win32GraphicsDevice)((Win32GraphicsConfig)gc[0]).getDevice(); /* Not ready to enforce ARB extension in J3D1.3.2, but will likely to do so in J3D 1.4. System.out.println("getBestConfiguration : Checking WGL ARB support\n"); if (!NativeScreenInfo.isWglARB()) { Thread.dumpStack(); System.out.println("getBestConfiguration : WGL ARB support fail\n"); return null; } */ // holds the list of attributes to be tramslated // for glxChooseVisual call int attrList[] = new int[NUM_ITEMS]; // assign template values to array attrList[RED_SIZE] = template.getRedSize(); attrList[GREEN_SIZE] = template.getGreenSize(); attrList[BLUE_SIZE] = template.getBlueSize(); attrList[DEPTH_SIZE] = template.getDepthSize(); attrList[DOUBLEBUFFER] = template.getDoubleBuffer(); attrList[STEREO] = template.getStereo(); attrList[ANTIALIASING] = template.getSceneAntialiasing(); NativeScreenInfo nativeScreenInfo = new NativeScreenInfo(gd); int screen = nativeScreenInfo.getScreen(); long[] pFormatInfo = new long[1]; /* Deliberately set this to -1. pFormatInfo is not use in D3D, so this value will be unchange in the case of D3D. In the case of OGL, the return value should be 0 or a positive valid address. */ pFormatInfo[0] = -1; int pixelFormat = choosePixelFormat(0, screen, attrList, pFormatInfo); if (debug) { System.out.println(" choosePixelFormat() returns " + pixelFormat); System.out.println(" pFormatInfo is " + pFormatInfo[0]); System.out.println(); } if (pixelFormat < 0) { // current mode don't support the minimum config return null; } // Fix to issue 97 -- // Pass in 0 for pixel format to the AWT. // ATI driver will lockup pixelFormat, if it is passed to AWT. GraphicsConfiguration gc1 = new J3dGraphicsConfig(gd, 0); // We need to cache the offScreen pixelformat that glXChoosePixelFormat() // returns, since this is not cached with J3dGraphicsConfig and there // are no public constructors to allow us to extend it. synchronized (Canvas3D.fbConfigTable) { if (Canvas3D.fbConfigTable.get(gc1) == null) Canvas3D.fbConfigTable.put(gc1, new Long(pFormatInfo[0])); else freePixelFormatInfo(pFormatInfo[0]); } return gc1; }
GraphicsConfiguration getBestConfiguration(GraphicsConfigTemplate3D template, GraphicsConfiguration[] gc) { Win32GraphicsDevice gd = (Win32GraphicsDevice)((Win32GraphicsConfig)gc[0]).getDevice(); /* Not ready to enforce ARB extension in J3D1.3.2, but will likely to do so in J3D 1.4. System.out.println("getBestConfiguration : Checking WGL ARB support\n"); if (!NativeScreenInfo.isWglARB()) { Thread.dumpStack(); System.out.println("getBestConfiguration : WGL ARB support fail\n"); return null; } */ // holds the list of attributes to be tramslated // for glxChooseVisual call int attrList[] = new int[NUM_ITEMS]; // assign template values to array attrList[RED_SIZE] = template.getRedSize(); attrList[GREEN_SIZE] = template.getGreenSize(); attrList[BLUE_SIZE] = template.getBlueSize(); attrList[DEPTH_SIZE] = template.getDepthSize(); attrList[DOUBLEBUFFER] = template.getDoubleBuffer(); attrList[STEREO] = template.getStereo(); attrList[ANTIALIASING] = template.getSceneAntialiasing(); NativeScreenInfo nativeScreenInfo = new NativeScreenInfo(gd); int screen = nativeScreenInfo.getScreen(); long[] pFormatInfo = new long[1]; /* Deliberately set this to -1. pFormatInfo is not use in D3D, so this value will be unchange in the case of D3D. In the case of OGL, the return value should be 0 or a positive valid address. */ pFormatInfo[0] = -1; int pixelFormat = choosePixelFormat(0, screen, attrList, pFormatInfo); if (debug) { System.out.println(" choosePixelFormat() returns " + pixelFormat); System.out.println(" pFormatInfo is " + pFormatInfo[0]); System.out.println(); } if (pixelFormat < 0) { // current mode don't support the minimum config return null; } // Fix to issue 104 -- // Pass in 0 for pixel format to the AWT. // ATI driver will lockup pixelFormat, if it is passed to AWT. GraphicsConfiguration gc1 = new J3dGraphicsConfig(gd, 0); // We need to cache the offScreen pixelformat that glXChoosePixelFormat() // returns, since this is not cached with J3dGraphicsConfig and there // are no public constructors to allow us to extend it. synchronized (Canvas3D.fbConfigTable) { if (Canvas3D.fbConfigTable.get(gc1) == null) Canvas3D.fbConfigTable.put(gc1, new Long(pFormatInfo[0])); else freePixelFormatInfo(pFormatInfo[0]); } return gc1; }
diff --git a/src/com/poguico/palmabici/network/synchronizer/NetworkStationAlarm.java b/src/com/poguico/palmabici/network/synchronizer/NetworkStationAlarm.java index c337504..41ef0fe 100644 --- a/src/com/poguico/palmabici/network/synchronizer/NetworkStationAlarm.java +++ b/src/com/poguico/palmabici/network/synchronizer/NetworkStationAlarm.java @@ -1,217 +1,220 @@ /* * Copyright 2014 Sergio Garcia Villalonga ([email protected]) * * This file is part of PalmaBici. * * PalmaBici is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * PalmaBici is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Affero GNU General Public License for more details * (https://www.gnu.org/licenses/agpl-3.0.html). * */ package com.poguico.palmabici.network.synchronizer; import java.util.ArrayList; import java.util.Calendar; import com.poguico.palmabici.DatabaseManager; import com.poguico.palmabici.MainActivity; import com.poguico.palmabici.R; import com.poguico.palmabici.SynchronizableElement; import com.poguico.palmabici.map.OpenStreetMapConstants; import com.poguico.palmabici.util.Formatter; import com.poguico.palmabici.util.NetworkInformation; import com.poguico.palmabici.util.Station; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.preference.PreferenceManager; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NotificationCompat; import android.util.Log; public class NetworkStationAlarm extends IntentService implements OpenStreetMapConstants, SynchronizableElement{ private static final String ONLY_ONE_ALARM = "only_one_alarm"; private static final long WAIT_TIME = 30000; private static final long TIMEOUT = 1200000; private static ArrayList<String> stationAlarmsId = null; private static boolean active = false; private static DatabaseManager dbManager; private static Context context = null; private SharedPreferences conf; public NetworkStationAlarm() { super("NetworkStationAlarm"); Log.i("NetworkStationAlarm", "Initializing class"); active = true; } public static synchronized void addAlarm(Context c, Station station) { if (stationAlarmsId == null) { Log.i("NetworkStationAlarm", "Initializing alarms list"); //networkInformation = NetworkInformation.getInstance(context); stationAlarmsId = new ArrayList<String>(); dbManager = DatabaseManager.getInstance(c); context = c; } Log.i("NetworkStationAlarm", "Adding alarm for station " + station.getNEstacio()); dbManager.setAlarm(station); stationAlarmsId.add(station.getNEstacio()); } public static synchronized void removeAlarm(Station station) { if (stationAlarmsId.contains(station.getNEstacio())) { dbManager.removeAlarm(station); stationAlarmsId.remove(station.getNEstacio()); Log.i("NetworkStationAlarm", "Alarm for station " + station.getNEstacio() + " removed"); } } public static synchronized void removeAlarms() { NetworkInformation networkInformation = NetworkInformation.getInstance(context); for (String id : stationAlarmsId) { dbManager.removeAlarm(networkInformation.get(id)); } stationAlarmsId.clear(); } @Override protected void onHandleIntent(Intent arg0) { Log.i("NetworkStationAlarm", "Starting thread"); long startTime = Calendar.getInstance().getTimeInMillis(); long now = startTime; NetworkSynchronizer networkSynchronizer = NetworkSynchronizer.getInstance(context); conf=PreferenceManager .getDefaultSharedPreferences(context); networkSynchronizer.addSynchronizableElement(this); while (!NetworkStationAlarm.stationAlarmsId.isEmpty() && !(conf.getBoolean("alarm_timeout", false) && now - startTime > TIMEOUT)) { Log.i("NetworkStationAlarm", "Getting network info..."); networkSynchronizer.sync(true); try { Thread.sleep(WAIT_TIME); now = Calendar.getInstance().getTimeInMillis(); } catch (InterruptedException e) { e.printStackTrace(); } } networkSynchronizer.detachSynchronizableElement(this); if (!NetworkStationAlarm.stationAlarmsId.isEmpty()) { NetworkStationAlarm.removeAlarms(); } Log.i("NetworkStationAlarm", "Finishing thread"); } @SuppressWarnings("unchecked") @Override public void onSuccessfulNetworkSynchronization() { Log.i("NetworkStationAlarm", "Network synchronized"); Station station; ArrayList<String> ids = (ArrayList<String>)NetworkStationAlarm.stationAlarmsId.clone(); NetworkInformation networkInformation = NetworkInformation.getInstance(context); for (String nEstacio : ids) { station = networkInformation.get(nEstacio); Log.i("NetworkStationAlarm", "Station " + station.getNEstacio() + " has " + station.getBusySlots() + " bikes available"); if (station.getBusySlots() > 0) { showNotification(station); if (conf.getBoolean(ONLY_ONE_ALARM, true)) { NetworkStationAlarm.removeAlarms(); } else { NetworkStationAlarm.removeAlarm(station); } } } } @Override public void onUnsuccessfulNetworkSynchronization() {} @Override public void onDestroy() { Log.i("NetworkStationAlarm", "Destroying class"); active = false; super.onDestroy(); } public void showNotification(Station station) { SharedPreferences mPrefs; SharedPreferences.Editor edit; String message = Formatter.formatBikesAvailableMessage(context, station); Bitmap bigIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.palmabici_bw); Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); - PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, - new Intent(context, MainActivity.class), - 0); + PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, + new Intent(context, MainActivity.class) + .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | + Intent.FLAG_ACTIVITY_SINGLE_TOP | + Intent.FLAG_ACTIVITY_NEW_TASK), + PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.bike) .setLargeIcon(bigIcon) .setContentTitle("PalmaBici") .setContentText(message) .setLights(0x0000ff00, 1000, 1000) .setTicker(message) .setSound(uri) .setAutoCancel(true); NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); mBuilder.setContentIntent(pendingIntent); mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); edit = mPrefs.edit(); edit.putString(PREFS_SHOWN_STATION, station.getNEstacio()); edit.commit(); - mgr.notify(1234, mBuilder.build()); + mgr.notify(0, mBuilder.build()); } public static boolean isActive() { return active; } public static boolean hasAlarm(String id) { return stationAlarmsId != null && stationAlarmsId.contains(id); } @Override public void onLocationSynchronization() { // TODO Auto-generated method stub } @Override public FragmentActivity getSynchronizableActivity() { // TODO Auto-generated method stub return null; } }
false
true
public void showNotification(Station station) { SharedPreferences mPrefs; SharedPreferences.Editor edit; String message = Formatter.formatBikesAvailableMessage(context, station); Bitmap bigIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.palmabici_bw); Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, new Intent(context, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.bike) .setLargeIcon(bigIcon) .setContentTitle("PalmaBici") .setContentText(message) .setLights(0x0000ff00, 1000, 1000) .setTicker(message) .setSound(uri) .setAutoCancel(true); NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); mBuilder.setContentIntent(pendingIntent); mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); edit = mPrefs.edit(); edit.putString(PREFS_SHOWN_STATION, station.getNEstacio()); edit.commit(); mgr.notify(1234, mBuilder.build()); }
public void showNotification(Station station) { SharedPreferences mPrefs; SharedPreferences.Editor edit; String message = Formatter.formatBikesAvailableMessage(context, station); Bitmap bigIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.palmabici_bw); Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); PendingIntent pendingIntent=PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.bike) .setLargeIcon(bigIcon) .setContentTitle("PalmaBici") .setContentText(message) .setLights(0x0000ff00, 1000, 1000) .setTicker(message) .setSound(uri) .setAutoCancel(true); NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); mBuilder.setContentIntent(pendingIntent); mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); edit = mPrefs.edit(); edit.putString(PREFS_SHOWN_STATION, station.getNEstacio()); edit.commit(); mgr.notify(0, mBuilder.build()); }
diff --git a/smart-maven-plugin/src/main/java/org/smart/plugin/SmartDeployMojo.java b/smart-maven-plugin/src/main/java/org/smart/plugin/SmartDeployMojo.java index aea2d37..f0b699d 100644 --- a/smart-maven-plugin/src/main/java/org/smart/plugin/SmartDeployMojo.java +++ b/smart-maven-plugin/src/main/java/org/smart/plugin/SmartDeployMojo.java @@ -1,76 +1,79 @@ package org.smart.plugin; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import java.io.File; import java.io.FileWriter; import java.io.IOException; @Mojo( name = "deploy" ) @Execute( phase = LifecyclePhase.PACKAGE ) public class SmartDeployMojo extends AbstractMojo { /** * Location of the file. */ @Parameter( defaultValue = "${project.build.directory}/${project.build.finalName}.jar", property = "maven.smart.jarFile", required = true ) private File jarFile; @Parameter( property = "maven.smart.port", defaultValue = "9081", required = true ) private int port; @Parameter( property = "maven.smart.server", defaultValue = "localhost", required = true ) private String server; @Parameter( property = "maven.smart.user", defaultValue = "smartadmin", required = true ) private String user; @Parameter( property = "maven.smart.password", defaultValue = "smartadmin", required = true ) private String password; @Parameter( property = "maven.smart.flowsoa", required = true ) private String flowsoa; public void execute() throws MojoExecutionException { File f = jarFile; SecureSmartClient clnt = null; try { clnt = new SecureSmartClient(port, server, "", "", flowsoa); clnt.authenticateAdmin(user, password); - clnt.deployJar(jarFile.getAbsolutePath(), flowsoa); + String str = jarFile.getAbsolutePath(); + str = str.replaceAll("\\\\", "\\/"); + System.out.println("File Name is: " + str); + clnt.deployJar(str, flowsoa); } catch ( Exception e ) { throw new MojoExecutionException( "Error deploying file " + jarFile, e ); } } }
true
true
public void execute() throws MojoExecutionException { File f = jarFile; SecureSmartClient clnt = null; try { clnt = new SecureSmartClient(port, server, "", "", flowsoa); clnt.authenticateAdmin(user, password); clnt.deployJar(jarFile.getAbsolutePath(), flowsoa); } catch ( Exception e ) { throw new MojoExecutionException( "Error deploying file " + jarFile, e ); } }
public void execute() throws MojoExecutionException { File f = jarFile; SecureSmartClient clnt = null; try { clnt = new SecureSmartClient(port, server, "", "", flowsoa); clnt.authenticateAdmin(user, password); String str = jarFile.getAbsolutePath(); str = str.replaceAll("\\\\", "\\/"); System.out.println("File Name is: " + str); clnt.deployJar(str, flowsoa); } catch ( Exception e ) { throw new MojoExecutionException( "Error deploying file " + jarFile, e ); } }
diff --git a/oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/query/QueryFulltextTest.java b/oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/query/QueryFulltextTest.java index d0403222e5..bd7125e91c 100644 --- a/oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/query/QueryFulltextTest.java +++ b/oak-jcr/src/test/java/org/apache/jackrabbit/oak/jcr/query/QueryFulltextTest.java @@ -1,144 +1,148 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.jackrabbit.oak.jcr.query; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.query.Query; import javax.jcr.query.QueryManager; import javax.jcr.query.QueryResult; import javax.jcr.query.Row; import javax.jcr.query.RowIterator; import org.apache.jackrabbit.oak.jcr.AbstractRepositoryTest; import org.apache.jackrabbit.oak.jcr.NodeStoreFixture; import org.junit.Test; /** * Tests the fulltext index. */ public class QueryFulltextTest extends AbstractRepositoryTest { public QueryFulltextTest(NodeStoreFixture fixture) { super(fixture); } @Test public void excerpt() throws Exception { Session session = getAdminSession(); QueryManager qm = session.getWorkspace().getQueryManager(); Node testRootNode = session.getRootNode().addNode("testroot"); Node n1 = testRootNode.addNode("node1"); n1.setProperty("text", "hello world"); n1.setProperty("desc", "description"); Node n2 = testRootNode.addNode("node2"); n2.setProperty("text", "Hello World"); n2.setProperty("desc", "Description"); session.save(); Query q; RowIterator it; Row row; String s; - String xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by jcr:path descending"; + String xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by @jcr:path"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); + String path = row.getPath(); s = row.getValue("rep:excerpt(.)").getString(); - assertTrue(s, s.indexOf("<strong>hello</strong> world") >= 0); - assertTrue(s, s.indexOf("description") >= 0); + assertTrue(path + ":" + s + " (1)", s.indexOf("<strong>hello</strong> world") >= 0); + assertTrue(path + ":" + s + " (2)", s.indexOf("description") >= 0); row = it.nextRow(); + path = row.getPath(); s = row.getValue("rep:excerpt(.)").getString(); // TODO is this expected? - assertTrue(s, s.indexOf("Hello World") >= 0); - assertTrue(s, s.indexOf("Description") >= 0); + assertTrue(path + ":" + s + " (3)", s.indexOf("Hello World") >= 0); + assertTrue(path + ":" + s + " (4)", s.indexOf("Description") >= 0); - xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by jcr:path descending"; + xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by @jcr:path"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); + path = row.getPath(); s = row.getValue("rep:excerpt(text)").getString(); - assertTrue(s, s.indexOf("<strong>hello</strong> world") >= 0); - assertTrue(s, s.indexOf("description") < 0); + assertTrue(path + ":" + s + " (5)", s.indexOf("<strong>hello</strong> world") >= 0); + assertTrue(path + ":" + s + " (6)", s.indexOf("description") < 0); row = it.nextRow(); + path = row.getPath(); s = row.getValue("rep:excerpt(text)").getString(); // TODO is this expected? - assertTrue(s, s.indexOf("Hello World") >= 0); - assertTrue(s, s.indexOf("Description") < 0); + assertTrue(path + ":" + s + " (7)", s.indexOf("Hello World") >= 0); + assertTrue(path + ":" + s + " (8)", s.indexOf("Description") < 0); } @Test public void fulltextOrWithinText() throws Exception { Session session = getAdminSession(); QueryManager qm = session.getWorkspace().getQueryManager(); Node testRootNode = session.getRootNode().addNode("testroot"); Node n1 = testRootNode.addNode("node1"); n1.setProperty("text", "hello"); Node n2 = testRootNode.addNode("node2"); n2.setProperty("text", "hallo"); Node n3 = testRootNode.addNode("node3"); n3.setProperty("text", "hello hallo"); session.save(); String sql2 = "select [jcr:path] as [path] from [nt:base] " + "where contains([text], 'hello OR hallo') order by [jcr:path]"; Query q; q = qm.createQuery("explain " + sql2, Query.JCR_SQL2); assertEquals("[nt:base] as [nt:base] /* traverse \"*\" " + "where contains([nt:base].[text], cast('hello OR hallo' as string)) */", getResult(q.execute(), "plan")); // verify the result // uppercase "OR" mean logical "or" q = qm.createQuery(sql2, Query.JCR_SQL2); assertEquals("/testroot/node1, /testroot/node2, /testroot/node3", getResult(q.execute(), "path")); // lowercase "or" mean search for the term "or" sql2 = "select [jcr:path] as [path] from [nt:base] " + "where contains([text], 'hello or hallo') order by [jcr:path]"; q = qm.createQuery(sql2, Query.JCR_SQL2); assertEquals("", getResult(q.execute(), "path")); } static String getResult(QueryResult result, String propertyName) throws RepositoryException { StringBuilder buff = new StringBuilder(); RowIterator it = result.getRows(); while (it.hasNext()) { if (buff.length() > 0) { buff.append(", "); } buff.append(it.nextRow().getValue(propertyName).getString()); } return buff.toString(); } }
false
true
public void excerpt() throws Exception { Session session = getAdminSession(); QueryManager qm = session.getWorkspace().getQueryManager(); Node testRootNode = session.getRootNode().addNode("testroot"); Node n1 = testRootNode.addNode("node1"); n1.setProperty("text", "hello world"); n1.setProperty("desc", "description"); Node n2 = testRootNode.addNode("node2"); n2.setProperty("text", "Hello World"); n2.setProperty("desc", "Description"); session.save(); Query q; RowIterator it; Row row; String s; String xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by jcr:path descending"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); s = row.getValue("rep:excerpt(.)").getString(); assertTrue(s, s.indexOf("<strong>hello</strong> world") >= 0); assertTrue(s, s.indexOf("description") >= 0); row = it.nextRow(); s = row.getValue("rep:excerpt(.)").getString(); // TODO is this expected? assertTrue(s, s.indexOf("Hello World") >= 0); assertTrue(s, s.indexOf("Description") >= 0); xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by jcr:path descending"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); s = row.getValue("rep:excerpt(text)").getString(); assertTrue(s, s.indexOf("<strong>hello</strong> world") >= 0); assertTrue(s, s.indexOf("description") < 0); row = it.nextRow(); s = row.getValue("rep:excerpt(text)").getString(); // TODO is this expected? assertTrue(s, s.indexOf("Hello World") >= 0); assertTrue(s, s.indexOf("Description") < 0); }
public void excerpt() throws Exception { Session session = getAdminSession(); QueryManager qm = session.getWorkspace().getQueryManager(); Node testRootNode = session.getRootNode().addNode("testroot"); Node n1 = testRootNode.addNode("node1"); n1.setProperty("text", "hello world"); n1.setProperty("desc", "description"); Node n2 = testRootNode.addNode("node2"); n2.setProperty("text", "Hello World"); n2.setProperty("desc", "Description"); session.save(); Query q; RowIterator it; Row row; String s; String xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by @jcr:path"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); String path = row.getPath(); s = row.getValue("rep:excerpt(.)").getString(); assertTrue(path + ":" + s + " (1)", s.indexOf("<strong>hello</strong> world") >= 0); assertTrue(path + ":" + s + " (2)", s.indexOf("description") >= 0); row = it.nextRow(); path = row.getPath(); s = row.getValue("rep:excerpt(.)").getString(); // TODO is this expected? assertTrue(path + ":" + s + " (3)", s.indexOf("Hello World") >= 0); assertTrue(path + ":" + s + " (4)", s.indexOf("Description") >= 0); xpath = "//*[jcr:contains(., 'hello')]/rep:excerpt(.) order by @jcr:path"; q = qm.createQuery(xpath, "xpath"); it = q.execute().getRows(); row = it.nextRow(); path = row.getPath(); s = row.getValue("rep:excerpt(text)").getString(); assertTrue(path + ":" + s + " (5)", s.indexOf("<strong>hello</strong> world") >= 0); assertTrue(path + ":" + s + " (6)", s.indexOf("description") < 0); row = it.nextRow(); path = row.getPath(); s = row.getValue("rep:excerpt(text)").getString(); // TODO is this expected? assertTrue(path + ":" + s + " (7)", s.indexOf("Hello World") >= 0); assertTrue(path + ":" + s + " (8)", s.indexOf("Description") < 0); }
diff --git a/src/main/java/io/datamine/DataMineClient/DataWrappers/LogEvent.java b/src/main/java/io/datamine/DataMineClient/DataWrappers/LogEvent.java index c29c75d..9d75065 100644 --- a/src/main/java/io/datamine/DataMineClient/DataWrappers/LogEvent.java +++ b/src/main/java/io/datamine/DataMineClient/DataWrappers/LogEvent.java @@ -1,41 +1,42 @@ package io.datamine.DataMineClient.DataWrappers; import java.util.HashMap; public class LogEvent { public Chunk chunk; public World world; public String type; public HashMap<String, Object> additional; public Boolean stackable = false; public LogEvent(World w, Chunk c, String type, Boolean stackable, HashMap<String, Object> additional) { this.world = w; this.chunk = c; this.type = type; this.additional = additional; this.stackable = stackable; } public LogEvent(World w, Chunk c, String type, Boolean stackable) { this(w, c, type, stackable, new HashMap<String, Object>()); } public LogEvent(World w, Chunk c, String type) { this(w, c, type, false, new HashMap<String, Object>()); } public HashMap<String, Object> toHashMap() { HashMap<String, Object> ret = new HashMap<String, Object>(); - ret.put("chunk", this.chunk.toHashMap()); + if(chunk != null) + ret.put("chunk", this.chunk.toHashMap()); ret.put("type", this.type); ret.put("additional", this.additional); return ret; } }
true
true
public HashMap<String, Object> toHashMap() { HashMap<String, Object> ret = new HashMap<String, Object>(); ret.put("chunk", this.chunk.toHashMap()); ret.put("type", this.type); ret.put("additional", this.additional); return ret; }
public HashMap<String, Object> toHashMap() { HashMap<String, Object> ret = new HashMap<String, Object>(); if(chunk != null) ret.put("chunk", this.chunk.toHashMap()); ret.put("type", this.type); ret.put("additional", this.additional); return ret; }
diff --git a/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/KarafContainerRegistration.java b/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/KarafContainerRegistration.java index c611b5a3f..ccaf0dee7 100644 --- a/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/KarafContainerRegistration.java +++ b/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/KarafContainerRegistration.java @@ -1,358 +1,358 @@ /** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.zookeeper.internal; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import javax.management.MBeanServer; import javax.management.MBeanServerNotification; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.data.Stat; import org.fusesource.fabric.utils.HostUtils; import org.fusesource.fabric.zookeeper.ZkDefs; import org.fusesource.fabric.zookeeper.ZkPath; import org.linkedin.zookeeper.client.IZKClient; import org.linkedin.zookeeper.client.LifecycleListener; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceException; import org.osgi.framework.ServiceReference; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.fusesource.fabric.zookeeper.ZkPath.CONFIG_CONTAINER; import static org.fusesource.fabric.zookeeper.ZkPath.CONFIG_VERSIONS_CONTAINER; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_ADDRESS; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_ALIVE; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_DOMAIN; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_DOMAINS; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_IP; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_JMX; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_LOCAL_HOSTNAME; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_LOCAL_IP; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_PUBLIC_IP; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_RESOLVER; import static org.fusesource.fabric.zookeeper.ZkPath.CONTAINER_SSH; public class KarafContainerRegistration implements LifecycleListener, NotificationListener { private transient Logger logger = LoggerFactory.getLogger(KarafContainerRegistration.class); private ConfigurationAdmin configurationAdmin; private IZKClient zooKeeper; private BundleContext bundleContext; private final Set<String> domains = new CopyOnWriteArraySet<String>(); private String name = System.getProperty("karaf.name"); private volatile MBeanServer mbeanServer; private ReentrantLock lock = new ReentrantLock(); public IZKClient getZooKeeper() { return zooKeeper; } public void setZooKeeper(IZKClient zooKeeper) { this.zooKeeper = zooKeeper; } public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { this.configurationAdmin = configurationAdmin; } public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } public void onConnected() { logger.trace("onConnected"); try { lock.tryLock(10,TimeUnit.SECONDS); String nodeAlive = CONTAINER_ALIVE.getPath(name); Stat stat = zooKeeper.exists(nodeAlive); if (stat != null) { if (stat.getEphemeralOwner() != zooKeeper.getSessionId()) { zooKeeper.delete(nodeAlive); zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } } else { zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } String domainsNode = CONTAINER_DOMAINS.getPath(name); stat = zooKeeper.exists(domainsNode); if (stat != null) { zooKeeper.deleteWithChildren(domainsNode); } String jmxUrl = getJmxUrl(); if (jmxUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_JMX.getPath(name), getJmxUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } String sshUrl = getSshUrl(); if (sshUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_SSH.getPath(name), getSshUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(CONTAINER_RESOLVER.getPath(name)) == null) { zooKeeper.createOrSetWithParents(CONTAINER_RESOLVER.getPath(name), getGlobalResolutionPolicy(zooKeeper), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_HOSTNAME.getPath(name), HostUtils.getLocalHostName(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_IP.getPath(name), HostUtils.getLocalIp(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_IP.getPath(name), getContainerPointer(zooKeeper,name), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //Check if there are addresses specified as system properties and use them if there is not an existing value in the registry. //Mostly usable for adding values when creating containers without an existing ensemble. for (String resolver : ZkDefs.VALID_RESOLVERS) { String address = System.getProperty(resolver); if (address != null && !address.isEmpty()) { if (zooKeeper.exists(CONTAINER_ADDRESS.getPath(name, resolver)) == null) { - zooKeeper.createOrSetWithParents(CONTAINER_ADDRESS.getPath(name, resolver), getContainerPointer(zooKeeper, name), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + zooKeeper.createOrSetWithParents(CONTAINER_ADDRESS.getPath(name, resolver), address, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } } String version = System.getProperty("fabric.version", ZkDefs.DEFAULT_VERSION); String profiles = System.getProperty("fabric.profiles"); if (profiles != null) { String versionNode = CONFIG_CONTAINER.getPath(name); String profileNode = CONFIG_VERSIONS_CONTAINER.getPath(version, name); if (zooKeeper.exists(versionNode) == null) { zooKeeper.createOrSetWithParents(versionNode, version, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(profileNode) == null) { zooKeeper.createOrSetWithParents(profileNode, profiles, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } registerDomains(); } catch (Exception e) { logger.warn("Error updating Fabric Container information. This exception will be ignored.", e); } finally { lock.unlock(); } } private String getJmxUrl() throws IOException { Configuration config = configurationAdmin.getConfiguration("org.apache.karaf.management"); if (config.getProperties() != null) { String jmx = (String) config.getProperties().get("serviceUrl"); jmx = jmx.replace("service:jmx:rmi://localhost:", "service:jmx:rmi://${zk:" + name + "/ip}:"); jmx = jmx.replace("jndi/rmi://localhost","jndi/rmi://${zk:" + name + "/ip}"); return jmx; } else { return null; } } private String getSshUrl() throws IOException { Configuration config = configurationAdmin.getConfiguration("org.apache.karaf.shell"); if (config != null && config.getProperties() != null) { String port = (String) config.getProperties().get("sshPort"); return "${zk:" + name + "/ip}:" + port; } else { return null; } } /** * Returns the global resolution policy. * @param zookeeper * @return * @throws InterruptedException * @throws KeeperException */ private static String getGlobalResolutionPolicy(IZKClient zookeeper) throws InterruptedException, KeeperException { String policy = ZkDefs.LOCAL_HOSTNAME; List<String> validResoverList = Arrays.asList(ZkDefs.VALID_RESOLVERS); if (zookeeper.exists(ZkPath.POLICIES.getPath(ZkDefs.RESOLVER)) != null) { policy = zookeeper.getStringData(ZkPath.POLICIES.getPath(ZkDefs.RESOLVER)); } else if (System.getProperty(ZkDefs.GLOBAL_RESOLVER_PROPERTY) != null && validResoverList.contains(System.getProperty(ZkDefs.GLOBAL_RESOLVER_PROPERTY))){ policy = System.getProperty(ZkDefs.GLOBAL_RESOLVER_PROPERTY); zookeeper.createOrSetWithParents(ZkPath.POLICIES.getPath("resolver"),policy, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } return policy; } /** * Returns the container specific resolution policy. * @param zookeeper * @return * @throws InterruptedException * @throws KeeperException */ private static String getContainerResolutionPolicy(IZKClient zookeeper, String container) throws InterruptedException, KeeperException { String policy = ZkDefs.LOCAL_HOSTNAME; if (zookeeper.exists(ZkPath.POLICIES.getPath(ZkDefs.RESOLVER)) != null) { policy = zookeeper.getStringData(ZkPath.CONTAINER_RESOLVER.getPath(container)); } return policy; } /** * Returns a pointer to the container IP based on the global IP policy. * @param zookeeper The zookeeper client to use to read global policy. * @param container The name of the container. * @return * @throws InterruptedException * @throws KeeperException */ private static String getContainerPointer(IZKClient zookeeper, String container) throws InterruptedException, KeeperException { String pointer = "${zk:%s/%s}"; String policy = getContainerResolutionPolicy(zookeeper, container); return String.format(pointer,container,policy); } private static String getExternalAddresses(String host, String port) throws UnknownHostException, SocketException { InetAddress ip = InetAddress.getByName(host); if (ip.isAnyLocalAddress()) { return HostUtils.getLocalHostName() + ":" + port; } else if (!ip.isLoopbackAddress()) { return ip.getHostName() + ":" + port; } return null; } public void destroy() { logger.trace("destroy"); try { unregisterDomains(); } catch (ServiceException e) { logger.trace("ZooKeeper is no longer available", e); } catch (Exception e) { logger.warn("An error occurred during disconnecting to zookeeper. This exception will be ignored.", e); } } public void onDisconnected() { logger.trace("onDisconnected"); // noop } public void registerMBeanServer(ServiceReference ref) { try { lock.lock(); String name = System.getProperty("karaf.name"); mbeanServer = (MBeanServer) bundleContext.getService(ref); if (mbeanServer != null) { mbeanServer.addNotificationListener(new ObjectName("JMImplementation:type=MBeanServerDelegate"), this, null, name); registerDomains(); } } catch (Exception e) { logger.warn("An error occurred during mbean server registration. This exception will be ignored.", e); } finally { lock.unlock(); } } public void unregisterMBeanServer(ServiceReference ref) { if (mbeanServer != null) { try { lock.lock(); mbeanServer.removeNotificationListener(new ObjectName("JMImplementation:type=MBeanServerDelegate"), this); unregisterDomains(); } catch (Exception e) { logger.warn("An error occurred during mbean server unregistration. This exception will be ignored.", e); } finally { lock.unlock(); } } mbeanServer = null; bundleContext.ungetService(ref); } protected void registerDomains() throws InterruptedException, KeeperException { if (isConnected() && mbeanServer != null) { String name = System.getProperty("karaf.name"); domains.addAll(Arrays.asList(mbeanServer.getDomains())); for (String domain : mbeanServer.getDomains()) { zooKeeper.createOrSetWithParents(CONTAINER_DOMAIN.getPath(name, domain), null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } } protected void unregisterDomains() throws InterruptedException, KeeperException { if (isConnected()) { String name = System.getProperty("karaf.name"); String domainsPath = CONTAINER_DOMAINS.getPath(name); if (zooKeeper.exists(domainsPath) != null) { for (String child : zooKeeper.getChildren(domainsPath)) { zooKeeper.delete(domainsPath + "/" + child); } } } } @Override public void handleNotification(Notification notif, Object o) { logger.trace("handleNotification[{}]", notif); // we may get notifications when zookeeper client is not really connected // handle mbeans registration and de-registration events if (isConnected() && mbeanServer != null && notif instanceof MBeanServerNotification) { MBeanServerNotification notification = (MBeanServerNotification) notif; String domain = notification.getMBeanName().getDomain(); String path = CONTAINER_DOMAIN.getPath((String) o, domain); try { lock.lock(); if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(notification.getType())) { if (domains.add(domain) && zooKeeper.exists(path) == null) { zooKeeper.createOrSetWithParents(path, "", ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } else if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(notification.getType())) { domains.clear(); domains.addAll(Arrays.asList(mbeanServer.getDomains())); if (!domains.contains(domain)) { // domain is no present any more zooKeeper.delete(path); } } // } catch (KeeperException.SessionExpiredException e) { // logger.debug("Session expiry detected. Handling notification once again", e); // handleNotification(notif, o); } catch (Exception e) { logger.warn("Exception while jmx domain synchronization from event: " + notif + ". This exception will be ignored.", e); } finally { lock.unlock(); } } } private boolean isConnected() { // we are only considered connected if we have a client and its connected return zooKeeper != null && zooKeeper.isConnected(); } }
true
true
public void onConnected() { logger.trace("onConnected"); try { lock.tryLock(10,TimeUnit.SECONDS); String nodeAlive = CONTAINER_ALIVE.getPath(name); Stat stat = zooKeeper.exists(nodeAlive); if (stat != null) { if (stat.getEphemeralOwner() != zooKeeper.getSessionId()) { zooKeeper.delete(nodeAlive); zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } } else { zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } String domainsNode = CONTAINER_DOMAINS.getPath(name); stat = zooKeeper.exists(domainsNode); if (stat != null) { zooKeeper.deleteWithChildren(domainsNode); } String jmxUrl = getJmxUrl(); if (jmxUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_JMX.getPath(name), getJmxUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } String sshUrl = getSshUrl(); if (sshUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_SSH.getPath(name), getSshUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(CONTAINER_RESOLVER.getPath(name)) == null) { zooKeeper.createOrSetWithParents(CONTAINER_RESOLVER.getPath(name), getGlobalResolutionPolicy(zooKeeper), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_HOSTNAME.getPath(name), HostUtils.getLocalHostName(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_IP.getPath(name), HostUtils.getLocalIp(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_IP.getPath(name), getContainerPointer(zooKeeper,name), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //Check if there are addresses specified as system properties and use them if there is not an existing value in the registry. //Mostly usable for adding values when creating containers without an existing ensemble. for (String resolver : ZkDefs.VALID_RESOLVERS) { String address = System.getProperty(resolver); if (address != null && !address.isEmpty()) { if (zooKeeper.exists(CONTAINER_ADDRESS.getPath(name, resolver)) == null) { zooKeeper.createOrSetWithParents(CONTAINER_ADDRESS.getPath(name, resolver), getContainerPointer(zooKeeper, name), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } } String version = System.getProperty("fabric.version", ZkDefs.DEFAULT_VERSION); String profiles = System.getProperty("fabric.profiles"); if (profiles != null) { String versionNode = CONFIG_CONTAINER.getPath(name); String profileNode = CONFIG_VERSIONS_CONTAINER.getPath(version, name); if (zooKeeper.exists(versionNode) == null) { zooKeeper.createOrSetWithParents(versionNode, version, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(profileNode) == null) { zooKeeper.createOrSetWithParents(profileNode, profiles, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } registerDomains(); } catch (Exception e) { logger.warn("Error updating Fabric Container information. This exception will be ignored.", e); } finally { lock.unlock(); } }
public void onConnected() { logger.trace("onConnected"); try { lock.tryLock(10,TimeUnit.SECONDS); String nodeAlive = CONTAINER_ALIVE.getPath(name); Stat stat = zooKeeper.exists(nodeAlive); if (stat != null) { if (stat.getEphemeralOwner() != zooKeeper.getSessionId()) { zooKeeper.delete(nodeAlive); zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } } else { zooKeeper.createWithParents(nodeAlive, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } String domainsNode = CONTAINER_DOMAINS.getPath(name); stat = zooKeeper.exists(domainsNode); if (stat != null) { zooKeeper.deleteWithChildren(domainsNode); } String jmxUrl = getJmxUrl(); if (jmxUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_JMX.getPath(name), getJmxUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } String sshUrl = getSshUrl(); if (sshUrl != null) { zooKeeper.createOrSetWithParents(CONTAINER_SSH.getPath(name), getSshUrl(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(CONTAINER_RESOLVER.getPath(name)) == null) { zooKeeper.createOrSetWithParents(CONTAINER_RESOLVER.getPath(name), getGlobalResolutionPolicy(zooKeeper), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_HOSTNAME.getPath(name), HostUtils.getLocalHostName(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_LOCAL_IP.getPath(name), HostUtils.getLocalIp(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zooKeeper.createOrSetWithParents(CONTAINER_IP.getPath(name), getContainerPointer(zooKeeper,name), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //Check if there are addresses specified as system properties and use them if there is not an existing value in the registry. //Mostly usable for adding values when creating containers without an existing ensemble. for (String resolver : ZkDefs.VALID_RESOLVERS) { String address = System.getProperty(resolver); if (address != null && !address.isEmpty()) { if (zooKeeper.exists(CONTAINER_ADDRESS.getPath(name, resolver)) == null) { zooKeeper.createOrSetWithParents(CONTAINER_ADDRESS.getPath(name, resolver), address, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } } String version = System.getProperty("fabric.version", ZkDefs.DEFAULT_VERSION); String profiles = System.getProperty("fabric.profiles"); if (profiles != null) { String versionNode = CONFIG_CONTAINER.getPath(name); String profileNode = CONFIG_VERSIONS_CONTAINER.getPath(version, name); if (zooKeeper.exists(versionNode) == null) { zooKeeper.createOrSetWithParents(versionNode, version, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (zooKeeper.exists(profileNode) == null) { zooKeeper.createOrSetWithParents(profileNode, profiles, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } registerDomains(); } catch (Exception e) { logger.warn("Error updating Fabric Container information. This exception will be ignored.", e); } finally { lock.unlock(); } }
diff --git a/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java b/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java index 728aa7e..e7df4d1 100644 --- a/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java +++ b/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java @@ -1,94 +1,100 @@ package org.disco.easyb.core.delegates; import groovy.lang.Closure; import org.disco.easyb.core.exception.VerificationException; /** * * @author aglover * */ public class EnsuringDelegate { /** * * @param clzz * the class of the exception type expected * @param closure * closure containing code to be run that should throw an * exception * @throws Exception */ - public void ensureThrows(final Class<?> clzz, final Closure closure) - throws Exception { + public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { + boolean expectedExceptionCaught = false; try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } + expectedExceptionCaught = true; + } + if (!expectedExceptionCaught) { + // Can't throw this immediately after the invokation of the closure because this exception + // would get inadvertantly caught by the catch which contains it. Thus the flag approach. + throw new VerificationException("expected exception of type " + clzz + " was not thrown"); } } /** * * @param expression * to be evaluated and should resolve to a boolean result * @throws Exception */ public void ensure(final boolean expression) throws Exception { if (!expression) { throw new VerificationException("the expression evaluated to false"); } } /** * * @param value * @param closure * @throws Exception */ public void ensure(final Object value, final Closure closure) throws Exception { RichlyEnsurable delegate = this.getDelegate(value); closure.setDelegate(delegate); closure.call(); } /** * * @param value * @return FlexibleDelegate instance * @throws Exception */ private RichlyEnsurable getDelegate(final Object value) throws Exception { RichlyEnsurable delegate = EnsurableFactory.manufacture(); delegate.setVerified(value); return delegate; } /** * * @param message */ public void fail(String message) { throw new VerificationException(message); } /** * * @param message * @param e */ public void fail(String message, Exception e) { throw new VerificationException(message, e); } /** * * @param message * @param expected * @param actual */ public void fail(String message, Object expected, Object actual) { throw new VerificationException(message, expected, actual); } }
false
true
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } } }
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { boolean expectedExceptionCaught = false; try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } expectedExceptionCaught = true; } if (!expectedExceptionCaught) { // Can't throw this immediately after the invokation of the closure because this exception // would get inadvertantly caught by the catch which contains it. Thus the flag approach. throw new VerificationException("expected exception of type " + clzz + " was not thrown"); } }
diff --git a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java index 10c221590..8c4738397 100644 --- a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java +++ b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java @@ -1,2649 +1,2651 @@ /** * Copyright (C) 2000 - 2009 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.kmelia.servlets; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.fileupload.FileItem; import org.xml.sax.SAXException; import com.silverpeas.form.DataRecord; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.PagesContext; import com.silverpeas.form.RecordSet; import com.silverpeas.kmelia.KmeliaConstants; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelper; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelperContext; import com.silverpeas.publicationTemplate.PublicationTemplate; import com.silverpeas.publicationTemplate.PublicationTemplateException; import com.silverpeas.publicationTemplate.PublicationTemplateImpl; import com.silverpeas.publicationTemplate.PublicationTemplateManager; import com.silverpeas.thumbnail.ThumbnailRuntimeException; import com.silverpeas.thumbnail.control.ThumbnailController; import com.silverpeas.thumbnail.model.ThumbnailDetail; import com.silverpeas.util.FileUtil; import com.silverpeas.util.ForeignPK; import com.silverpeas.util.MimeTypes; import com.silverpeas.util.StringUtil; import com.silverpeas.util.ZipManager; import com.silverpeas.util.i18n.I18NHelper; import com.silverpeas.util.web.servlet.FileUploadUtil; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.ComponentSessionController; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.versioning.model.Document; import com.stratelia.silverpeas.versioning.model.DocumentVersion; import com.stratelia.silverpeas.versioning.util.VersioningUtil; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.ProfileInst; import com.stratelia.webactiv.kmelia.KmeliaSecurity; import com.stratelia.webactiv.kmelia.control.KmeliaSessionController; import com.stratelia.webactiv.kmelia.control.ejb.KmeliaHelper; import com.stratelia.webactiv.kmelia.model.FileFolder; import com.stratelia.webactiv.kmelia.model.TopicDetail; import com.stratelia.webactiv.kmelia.model.UserCompletePublication; import com.stratelia.webactiv.kmelia.model.UserPublication; import com.stratelia.webactiv.kmelia.model.updatechain.FieldUpdateChainDescriptor; import com.stratelia.webactiv.kmelia.model.updatechain.Fields; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.WAAttributeValuePair; import com.stratelia.webactiv.util.fileFolder.FileFolderManager; import com.stratelia.webactiv.util.node.model.NodeDetail; import com.stratelia.webactiv.util.node.model.NodePK; import com.stratelia.webactiv.util.publication.info.model.InfoDetail; import com.stratelia.webactiv.util.publication.info.model.InfoImageDetail; import com.stratelia.webactiv.util.publication.info.model.InfoTextDetail; import com.stratelia.webactiv.util.publication.info.model.ModelDetail; import com.stratelia.webactiv.util.publication.model.Alias; import com.stratelia.webactiv.util.publication.model.CompletePublication; import com.stratelia.webactiv.util.publication.model.PublicationDetail; public class KmeliaRequestRouter extends ComponentRequestRouter { private static final long serialVersionUID = 1L; /** * This method creates a KmeliaSessionController instance * @param mainSessionCtrl The MainSessionController instance * @param context Context of current component instance * @return a KmeliaSessionController instance */ @Override public ComponentSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { ComponentSessionController component = (ComponentSessionController) new KmeliaSessionController( mainSessionCtrl, context); return component; } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" */ @Override public String getSessionControlBeanName() { return "kmelia"; } /** * This method has to be implemented by the component request rooter it has to compute a * destination page * @param function The entering request function ( : "Main.jsp") * @param componentSC The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if(type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if(type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>(kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if(request.getParameter("errorThumbnail") != null){ destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } - String checkPath = request.getParameter("CheckPath"); - if (checkPath != null && "1".equals(checkPath)) { + boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); + if (checkPath) { processPath(kmelia, id); + } else { + processPath(kmelia, null); } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication(request.getContextPath())); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; } private String getDocumentNotFoundDestination(KmeliaSessionController kmelia, HttpServletRequest request) { request.setAttribute("ComponentId", kmelia.getComponentId()); return "/admin/jsp/documentNotFound.jsp"; } private PublicationDetail getPublicationDetail(List<FileItem> parameters, KmeliaSessionController kmelia) throws Exception { String id = FileUploadUtil.getParameter(parameters, "PubId"); String status = FileUploadUtil.getParameter(parameters, "Status"); String name = FileUploadUtil.getParameter(parameters, "Name"); String description = FileUploadUtil.getParameter(parameters, "Description"); String keywords = FileUploadUtil.getParameter(parameters, "Keywords"); String beginDate = FileUploadUtil.getParameter(parameters, "BeginDate"); String endDate = FileUploadUtil.getParameter(parameters, "EndDate"); String version = FileUploadUtil.getParameter(parameters, "Version"); String importance = FileUploadUtil.getParameter(parameters, "Importance"); String beginHour = FileUploadUtil.getParameter(parameters, "BeginHour"); String endHour = FileUploadUtil.getParameter(parameters, "EndHour"); String author = FileUploadUtil.getParameter(parameters, "Author"); String targetValidatorId = FileUploadUtil.getParameter(parameters, "ValideurId"); String tempId = FileUploadUtil.getParameter(parameters, "TempId"); String infoId = FileUploadUtil.getParameter(parameters, "InfoId"); String draftOutDate = FileUploadUtil.getParameter(parameters, "DraftOutDate"); Date jBeginDate = null; Date jEndDate = null; Date jDraftOutDate = null; if (beginDate != null && !beginDate.trim().equals("")) { jBeginDate = DateUtil.stringToDate(beginDate, kmelia.getLanguage()); } if (endDate != null && !endDate.trim().equals("")) { jEndDate = DateUtil.stringToDate(endDate, kmelia.getLanguage()); } if (StringUtil.isDefined(draftOutDate)) { jDraftOutDate = DateUtil.stringToDate(draftOutDate, kmelia.getLanguage()); } String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, importance, version, keywords, "", status, "", author); pubDetail.setBeginHour(beginHour); pubDetail.setEndHour(endHour); pubDetail.setStatus(status); pubDetail.setDraftOutDate(jDraftOutDate); if (StringUtil.isDefined(targetValidatorId)) { pubDetail.setTargetValidatorId(targetValidatorId); } pubDetail.setCloneId(tempId); if (StringUtil.isDefined(infoId)) { pubDetail.setInfoId(infoId); } I18NHelper.setI18NInfo(pubDetail, parameters); return pubDetail; } /* * private PublicationDetail getPubDetail(List parameters, KmeliaSessionController kmelia) throws * Exception { String id = getParameterValue(parameters, "PubId"); String name = * getParameterValue(parameters, "Name"); String description = getParameterValue(parameters, * "Description"); Date jBeginDate = null; Date jEndDate = null; String pubId = "X"; if * (StringUtil.isDefined(id)) pubId = id; PublicationDetail pubDetail = new * PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, "0", "", "", "", * null, ""); pubDetail.setStatus("Valid"); I18NHelper.setI18NInfo(pubDetail, parameters); return * pubDetail; } */ private static boolean isInteger(String id) { try { Integer.parseInt(id); return true; } catch (NumberFormatException e) { return false; } } private void processVignette(List<FileItem> parameters, KmeliaSessionController kmelia, String instanceId, int pubId) throws Exception { FileItem file = FileUploadUtil.getFile(parameters, "WAIMGVAR0"); String physicalName = null; String mimeType = null; if (file != null) { String logicalName = file.getName(); String type = null; File dir = null; if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = FileRepositoryManager.getFileExtension(logicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { physicalName = new Long(new Date().getTime()).toString() + "." + type; dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + kmelia.getPublicationSettings().getString("imagesSubDirectory") + File.separator + physicalName); mimeType = file.getContentType(); file.write(dir); } } } if (physicalName == null) { // on a pas d'image, regarder s'il y a une provenant de la galerie String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery"); { if (StringUtil.isDefined(nameImageFromGallery)) { physicalName = nameImageFromGallery; mimeType = "image/jpeg"; } } } if (physicalName != null) { ThumbnailDetail detail = new ThumbnailDetail(instanceId, pubId, ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); detail.setOriginalFileName(physicalName); detail.setMimeType(mimeType); try { int[] thumbnailSize = kmelia.getThumbnailWidthAndHeight(); ThumbnailController.updateThumbnail(detail, thumbnailSize[0], thumbnailSize[1]); } catch (ThumbnailRuntimeException e) { SilverTrace.error("Thumbnail", "ThumbnailRequestRouter.addThumbnail", "root.MSG_GEN_PARAM_VALUE", e); // need remove the file on disk try { ThumbnailController.deleteThumbnail(detail); } catch (Exception exp) { SilverTrace.info("Thumbnail", "ThumbnailRequestRouter.addThumbnail - remove after error", "root.MSG_GEN_PARAM_VALUE", exp); } } } } /** * Process Form Upload for publications import * @param kmeliaScc * @param request * @param routDestination * @return destination */ private String processFormUpload(KmeliaSessionController kmeliaScc, HttpServletRequest request, String routeDestination, boolean isMassiveMode) { String destination = ""; String topicId = ""; String importMode = KmeliaSessionController.UNITARY_IMPORT_MODE; boolean draftMode = false; String logicalName = ""; String message = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; long processStart = new Date().getTime(); ResourceLocator attachmentResourceLocator = new ResourceLocator( "com.stratelia.webactiv.util.attachment.multilang.attachment", kmeliaScc.getLanguage()); FileItem fileItem = null; int versionType = DocumentVersion.TYPE_DEFAULT_VERSION; try { List<FileItem> items = FileUploadUtil.parseRequest(request); topicId = FileUploadUtil.getParameter(items, "topicId"); importMode = FileUploadUtil.getParameter(items, "opt_importmode"); String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype"); if (StringUtil.isDefined(sVersionType)) { versionType = Integer.parseInt(sVersionType); } String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft"); if (StringUtil.isDefined(sDraftMode)) { draftMode = StringUtil.getBooleanValue(sDraftMode); } fileItem = FileUploadUtil.getFile(items, "file_name"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { boolean runOnUnix = !FileUtil.isWindows(); if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.processFormUpload", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = new Long(new Date().getTime()).toString() + "_" + kmeliaScc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); // Zip contentType not detected under Firefox ! if (request.getHeader("User-Agent") != null && request.getHeader("User-Agent").indexOf("MSIE") == -1) { fileType = MimeTypes.ARCHIVE_MIME_TYPE; } fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getGeneralResourceLocator().getString( "RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath( kmeliaScc.getComponentId(), GeneralPropertiesManager.getGeneralResourceLocator(). getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getGeneralResourceLocator().getString( "RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType + " importMode=" + importMode + " draftMode=" + draftMode); int nbFiles = 1; // Compute nbFiles only in unitary Import mode if (!importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE) && fileUploaded.getName().toLowerCase().endsWith(".zip")) { nbFiles = ZipManager.getNbFiles(fileUploaded); } // Import !! List<PublicationDetail> publicationDetails = kmeliaScc.importFile(fileUploaded, fileType, topicId, importMode, draftMode, versionType); long processDuration = new Date().getTime() - processStart; // Title for popup report String importModeTitle = ""; if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre"); } else { importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre"); } SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "nbFiles = " + nbFiles + " publicationDetails=" + publicationDetails + " ProcessDuration=" + processDuration + " ImportMode=" + importMode + " Draftmode=" + draftMode + " Title=" + importModeTitle); request.setAttribute("PublicationsDetails", publicationDetails); request.setAttribute("NbFiles", new Integer(nbFiles)); request.setAttribute("ProcessDuration", FileRepositoryManager.formatFileUploadTime( processDuration)); request.setAttribute("ImportMode", importMode); request.setAttribute("DraftMode", Boolean.valueOf(draftMode)); request.setAttribute("Title", importModeTitle); destination = routeDestination + "reportImportFiles.jsp"; } else { // File access failed message = attachmentResourceLocator.getString("liaisonInaccessible"); request.setAttribute("Message", message); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } FileFolderManager.deleteFolder(tempFolderPath); } else { // the field did not contain a file request.setAttribute("Message", attachmentResourceLocator.getString("liaisonInaccessible")); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } } } /* * catch (IOException e) { //File size exceeds Maximum file size message = * attachmentResourceLocator.getString("fichierTropGrand")+ " (" + * FileRepositoryManager.formatFileSize(maxFileSize) + "&nbsp;" + * attachmentResourceLocator.getString("maximum") +") !!"; * request.setAttribute("Message",message); request.setAttribute("TopicId",topicId); * destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) destination = * routeDestination + "importMultiFiles.jsp"; } */ catch (Exception e) { // Other exception request.setAttribute("Message", e.getMessage()); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } SilverTrace.warn("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return destination; } private void processPath(KmeliaSessionController kmeliaSC, String id) throws RemoteException { TopicDetail currentTopic = null; if (!StringUtil.isDefined(id)) { currentTopic = kmeliaSC.getSessionTopic(); } else { currentTopic = kmeliaSC.getPublicationTopic(id); // Calcul du chemin de la } // publication Collection<NodeDetail> pathColl = currentTopic.getPath(); String linkedPathString = kmeliaSC.displayPath(pathColl, true, 3); String pathString = kmeliaSC.displayPath(pathColl, false, 3); kmeliaSC.setSessionPath(linkedPathString); kmeliaSC.setSessionPathString(pathString); } private void putXMLDisplayerIntoRequest(PublicationDetail pubDetail, KmeliaSessionController kmelia, HttpServletRequest request) throws PublicationTemplateException, FormException { String infoId = pubDetail.getInfoId(); String pubId = pubDetail.getPK().getId(); if (!isInteger(infoId)) { PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate(pubDetail. getPK().getInstanceId() + ":" + infoId); // RecordTemplate recordTemplate = pubTemplate.getRecordTemplate(); Form formView = pubTemplate.getViewForm(); // get displayed language String language = checkLanguage(kmelia, pubDetail); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("XMLForm", formView); request.setAttribute("XMLData", data); } } private String processWizard(String function, KmeliaSessionController kmeliaSC, HttpServletRequest request, String rootDestination) throws RemoteException, PublicationTemplateException, FormException { String destination = ""; if (function.equals("WizardStart")) { // récupération de l'id du thème dans lequel on veux mettre la // publication // si on ne viens pas d'un theme-tracker String topicId = request.getParameter("TopicId"); if (StringUtil.isDefined(topicId)) { TopicDetail topic = kmeliaSC.getTopic(topicId); kmeliaSC.setSessionTopic(topic); } // recherche du dernier onglet String wizardLast = "1"; List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if ((kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf( KmeliaSessionController.TAB_PDC) == -1) || kmeliaSC.isKmaxMode) { wizardLast = "4"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { wizardLast = "3"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { wizardLast = "2"; } kmeliaSC.setWizardLast(wizardLast); request.setAttribute("WizardLast", wizardLast); kmeliaSC.setWizard("progress"); request.setAttribute("Action", "Wizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardHeader")) { // passage des paramètres String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } request.setAttribute("WizardRow", kmeliaSC.getWizardRow()); request.setAttribute("WizardLast", kmeliaSC.getWizardLast()); request.setAttribute("Action", "UpdateWizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); request.setAttribute("PubId", id); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardNext")) { // redirige vers l'onglet suivant de l'assistant de publication String position = request.getParameter("Position"); if (!StringUtil.isDefined(position)) { position = (String) request.getAttribute("Position"); } String next = "End"; String wizardRow = kmeliaSC.getWizardRow(); request.setAttribute("WizardRow", wizardRow); int numRow = 0; if (StringUtil.isDefined(wizardRow)) { numRow = Integer.parseInt(wizardRow); } List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (position.equals("View")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { // on passe à la page du contenu next = "Content"; if (numRow <= 2) { wizardRow = "2"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Content")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Attachment")) { if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { next = "KmaxClassification"; } else { next = "End"; } if (!next.equals("End")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } } else if (position.equals("Pdc") || position.equals("KmaxClassification")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "End"; } // mise à jour du rang en cours kmeliaSC.setWizardRow(wizardRow); // passage des paramètres setWizardParams(request, kmeliaSC); if (next.equals("View")) { destination = getDestination("WizardStart", kmeliaSC, request); } else if (next.equals("Content")) { destination = getDestination("ToPubliContent", kmeliaSC, request); } else if (next.equals("Attachment")) { destination = getDestination("ViewAttachments", kmeliaSC, request); } else if (next.equals("Pdc")) { destination = getDestination("ViewPdcPositions", kmeliaSC, request); } else if (next.equals("KmaxClassification")) { destination = getDestination("KmaxViewCombination", kmeliaSC, request); } else if (next.equals("End")) { // terminer la publication : la sortir du mode brouillon kmeliaSC.setWizard("finish"); kmeliaSC.draftOutPublication(); destination = getDestination("ViewPublication", kmeliaSC, request); } } return destination; } private void setWizardParams(HttpServletRequest request, KmeliaSessionController kmelia) { // Paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("WizardRow", kmelia.getWizardRow()); request.setAttribute("WizardLast", kmelia.getWizardLast()); } private void resetWizard(KmeliaSessionController kmelia) { kmelia.setWizard("none"); kmelia.setWizardLast("0"); kmelia.setWizardRow("0"); } private void setXMLForm(HttpServletRequest request, KmeliaSessionController kmelia, String xmlFormName) throws PublicationTemplateException, FormException { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String pubId = pubDetail.getPK().getId(); String xmlFormShortName = null; if (!StringUtil.isDefined(xmlFormName)) { xmlFormShortName = pubDetail.getInfoId(); xmlFormName = null; } else { xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); SilverTrace.info("kmelia", "KmeliaRequestRouter.setXMLForm()", "root.MSG_GEN_PARAM_VALUE", "xmlFormShortName = " + xmlFormShortName); // register xmlForm to publication getPublicationTemplateManager().addDynamicPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName, xmlFormName); } PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate(kmelia. getComponentId() + ":" + xmlFormShortName, xmlFormName); Form formUpdate = pubTemplate.getUpdateForm(); RecordSet recordSet = pubTemplate.getRecordSet(); // get displayed language String language = checkLanguage(kmelia, pubDetail); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("Form", formUpdate); request.setAttribute("Data", data); request.setAttribute("XMLFormName", xmlFormName); } private void setLanguage(HttpServletRequest request, KmeliaSessionController kmelia) { String language = request.getParameter("SwitchLanguage"); if (StringUtil.isDefined(language)) { kmelia.setCurrentLanguage(language); } request.setAttribute("Language", kmelia.getCurrentLanguage()); } private String checkLanguage(KmeliaSessionController kmelia) { return checkLanguage(kmelia, kmelia.getSessionPublication().getPublication(). getPublicationDetail()); } private String checkLanguage(KmeliaSessionController kmelia, PublicationDetail pubDetail) { return pubDetail.getLanguageToDisplay(kmelia.getCurrentLanguage()); } private void checkAlias(KmeliaSessionController kmelia, UserCompletePublication publication) { if (!kmelia.getComponentId().equals( publication.getPublication().getPublicationDetail().getPK().getInstanceId())) { publication.setAlias(true); } } private void updatePubliDuringUpdateChain(String id, HttpServletRequest request, KmeliaSessionController kmelia) throws RemoteException { // enregistrement des modifications de la publi String name = request.getParameter("Name"); String description = request.getParameter("Description"); String keywords = request.getParameter("Keywords"); String tree = request.getParameter("Tree"); String[] topics = request.getParameterValues("topicChoice"); // sauvegarde des données Fields fields = kmelia.getFieldUpdateChain(); FieldUpdateChainDescriptor field = kmelia.getFieldUpdateChain().getName(); field.setName("Name"); field.setValue(name); fields.setName(field); field = kmelia.getFieldUpdateChain().getDescription(); field.setName("Description"); field.setValue(description); fields.setDescription(field); field = kmelia.getFieldUpdateChain().getKeywords(); field.setName("Keywords"); field.setValue(keywords); fields.setKeywords(field); field = kmelia.getFieldUpdateChain().getTree(); if (field != null) { field.setName("Topics"); field.setValue(tree); fields.setTree(field); } fields.setTopics(topics); kmelia.setFieldUpdateChain(fields); Date jBeginDate = null; Date jEndDate = null; String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, "0", "", keywords, "", "", "", ""); pubDetail.setStatus("Valid"); I18NHelper.setI18NInfo(pubDetail, request); try { // Execute helper String helperClassName = kmelia.getFieldUpdateChain().getHelper(); UpdateChainHelper helper; helper = (UpdateChainHelper) Class.forName(helperClassName).newInstance(); UpdateChainHelperContext uchc = new UpdateChainHelperContext(pubDetail, kmelia); uchc.setAllTopics(kmelia.getAllTopics()); helper.execute(uchc); pubDetail = uchc.getPubDetail(); // mettre à jour les emplacements si necessaire String[] calculedTopics = uchc.getTopics(); if (calculedTopics != null) { topics = calculedTopics; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } kmelia.updatePublication(pubDetail); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } kmelia.setAliases(pubDetail.getPK(), aliases); } private String processUpdateChainOperation(String rootDestination, String function, KmeliaSessionController kmelia, HttpServletRequest request) throws IOException, ClassNotFoundException, SAXException, ParserConfigurationException { if (function.equals("UpdateChainInit")) { // récupération du descripteur kmelia.initUpdateChainDescriptor(); // Modification par chaine de toutes les publications du thème : // positionnement sur la première publi String pubId = kmelia.getFirst(); request.setAttribute("PubId", pubId); // initialiser le topic en cours kmelia.initUpdateChainTopicChoice(pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainPublications")) { String id = (String) request.getAttribute("PubId"); request.setAttribute("Action", "UpdateChain"); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("PubId", id); request.setAttribute("SaveFields", kmelia.getFieldUpdateChain()); if (StringUtil.isDefined(id)) { request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } // request.setAttribute("PathList",kmelia.getPublicationFathers(id)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getUpdateChainTopics()); // mise à jour de la publication en session pour récupérer les alias UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); // url du fichier joint request.setAttribute("FileUrl", kmelia.getFirstAttachmentURLOfCurrentPublication(request. getContextPath())); return rootDestination + "updateByChain.jsp"; } } else if (function.equals("UpdateChainNextUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // récupération de la publication suivante String nextPubId = kmelia.getNext(); request.setAttribute("PubId", nextPubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainLastUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainSkipUpdate")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainEndUpdate")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainUpdateAll")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); // enregistrement des modifications sur toutes les publications restantes // publication courante String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // passer à la suivante si elle existe int rang = kmelia.getRang(); int nbPublis = kmelia.getSessionPublicationsList().size(); while (rang < nbPublis - 1) { String pubId = kmelia.getNext(); updatePubliDuringUpdateChain(pubId, request, kmelia); rang = kmelia.getRang(); } // retour au thème return getDestination("GoToTopic", kmelia, request); } return ""; } /** * Gets an instance of PublicationTemplateManager. * @return an instance of PublicationTemplateManager. */ public PublicationTemplateManager getPublicationTemplateManager() { return PublicationTemplateManager.getInstance(); } }
false
true
public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if(type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if(type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>(kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if(request.getParameter("errorThumbnail") != null){ destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } String checkPath = request.getParameter("CheckPath"); if (checkPath != null && "1".equals(checkPath)) { processPath(kmelia, id); } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication(request.getContextPath())); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if(type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if(type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>(kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if(request.getParameter("errorThumbnail") != null){ destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia .isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath) { processPath(kmelia, id); } else { processPath(kmelia, null); } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication(request.getContextPath())); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia. getAttachmentURL(request.getContextPath(), documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
diff --git a/teeda/teeda-extension/src/main/java/org/seasar/teeda/extension/util/ConditionUtil.java b/teeda/teeda-extension/src/main/java/org/seasar/teeda/extension/util/ConditionUtil.java index a3f5a9aa3..a22c8af28 100644 --- a/teeda/teeda-extension/src/main/java/org/seasar/teeda/extension/util/ConditionUtil.java +++ b/teeda/teeda-extension/src/main/java/org/seasar/teeda/extension/util/ConditionUtil.java @@ -1,200 +1,200 @@ /* * Copyright 2004-2008 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.teeda.extension.util; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.faces.component.UIComponent; import javax.faces.component.UIForm; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.internal.scope.PageScope; import org.seasar.teeda.core.JsfConstants; import org.seasar.teeda.core.render.Base64EncodeConverter; import org.seasar.teeda.extension.ExtensionConstants; import org.seasar.teeda.extension.component.UIBody; import org.seasar.teeda.extension.render.RendererListener; import org.seasar.teeda.extension.render.TBodyRenderer; /** * @author koichik */ public class ConditionUtil { public static final String KEY = "org.seasar.teeda.extension.Condition"; public static Boolean getCondition(final FacesContext context, final String clientId) { final Map conditions = getConditions(context); if (conditions == null) { return null; } return (Boolean) conditions.get(clientId); } public static void addCondition(final FacesContext context, final String clientId, final boolean value) { final Map conditions = getOrCreateConditions(context); conditions.put(clientId, Boolean.valueOf(value)); } public static Boolean removeCondition(final FacesContext context, final String clientId) { final Map conditions = getConditions(context); if (conditions == null) { return null; } return (Boolean) conditions.remove(clientId); } public static Map getConditions(final FacesContext context) { final Map map = PageScope.getContext(context); if (map == null) { return null; } return (Map) map.get(KEY); } public static Map getOrCreateConditions(final FacesContext context) { final Map map = PageScope.getOrCreateContext(context); Map conditions = (Map) map.get(KEY); if (conditions == null) { conditions = new LinkedHashMap(128); map.put(KEY, conditions); } return conditions; } public static void setConditions(final FacesContext context, final Map conditions) { final Map map = PageScope.getOrCreateContext(context); map.put(KEY, conditions); } public static void removeConditions(final FacesContext context) { final Map map = PageScope.getContext(context); if (map != null) { map.remove(KEY); } } public static List getForms(final FacesContext context) { final Map map = context.getExternalContext().getRequestMap(); final List forms = (List) map.get(KEY); return forms; } public static void addForm(final FacesContext context, final UIForm form) { final Map map = context.getExternalContext().getRequestMap(); List forms = (List) map.get(KEY); if (forms == null) { forms = new ArrayList(); map.put(KEY, forms); registerRendererListener(form.getParent()); } forms.add(form.getId()); } protected static void registerRendererListener(UIComponent component) { while (component != null) { if (component instanceof UIBody) { TBodyRenderer.addRendererListener(((UIBody) component), new ConditionRendererListener()); break; } component = component.getParent(); } } public static class ConditionRendererListener implements RendererListener { public void renderBeforeBodyEnd(final FacesContext context) throws IOException { final Map conditions = getConditions(context); if (conditions == null || conditions.isEmpty()) { return; } final List forms = getForms(context); if (forms == null || forms.isEmpty()) { return; } renderJavascript(context.getResponseWriter(), conditions, forms); } protected static void renderJavascript(final ResponseWriter writer, final Map conditions, final List forms) throws IOException { writer.write(JsfConstants.LINE_SP); writer.startElement(JsfConstants.SCRIPT_ELEM, null); writer.writeAttribute(JsfConstants.LANGUAGE_ATTR, JsfConstants.JAVASCRIPT_VALUE, null); writer.writeAttribute(JsfConstants.TYPE_ATTR, JsfConstants.TEXT_JAVASCRIPT_VALUE, null); writer.write(JsfConstants.LINE_SP); writer.write("<!--"); writer.write(JsfConstants.LINE_SP); writer.write("var forms = ["); for (int i = 0; i < forms.size(); ++i) { final String form = (String) forms.get(i); writer.write("'"); writer.write(form); writer.write("'"); if (i < forms.size() - 1) { writer.write(", "); } } writer.write("];"); writer.write(JsfConstants.LINE_SP); - writer.write("for (var i = 0; i < forms.length; ++i) {"); + writer.write("for (var i = 0, len = forms.length; i < len; ++i) {"); writer.write(JsfConstants.LINE_SP); writer.write(" var hidden = document.createElement('input');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('type', 'hidden');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('name', '"); writer.write(ExtensionConstants.CONDITIONS_PARAMETER); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('value', '"); final Base64EncodeConverter converter = new Base64EncodeConverter(); final String value = converter.getAsEncodeString(conditions); writer.write(value); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" var form = document.getElementById(forms[i]);"); writer.write(JsfConstants.LINE_SP); writer.write(" form.appendChild(hidden);"); writer.write(JsfConstants.LINE_SP); writer.write("}"); writer.write(JsfConstants.LINE_SP); writer.write(JsfConstants.LINE_SP); writer.write("//-->"); writer.write(JsfConstants.LINE_SP); writer.endElement(JsfConstants.SCRIPT_ELEM); } } }
true
true
protected static void renderJavascript(final ResponseWriter writer, final Map conditions, final List forms) throws IOException { writer.write(JsfConstants.LINE_SP); writer.startElement(JsfConstants.SCRIPT_ELEM, null); writer.writeAttribute(JsfConstants.LANGUAGE_ATTR, JsfConstants.JAVASCRIPT_VALUE, null); writer.writeAttribute(JsfConstants.TYPE_ATTR, JsfConstants.TEXT_JAVASCRIPT_VALUE, null); writer.write(JsfConstants.LINE_SP); writer.write("<!--"); writer.write(JsfConstants.LINE_SP); writer.write("var forms = ["); for (int i = 0; i < forms.size(); ++i) { final String form = (String) forms.get(i); writer.write("'"); writer.write(form); writer.write("'"); if (i < forms.size() - 1) { writer.write(", "); } } writer.write("];"); writer.write(JsfConstants.LINE_SP); writer.write("for (var i = 0; i < forms.length; ++i) {"); writer.write(JsfConstants.LINE_SP); writer.write(" var hidden = document.createElement('input');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('type', 'hidden');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('name', '"); writer.write(ExtensionConstants.CONDITIONS_PARAMETER); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('value', '"); final Base64EncodeConverter converter = new Base64EncodeConverter(); final String value = converter.getAsEncodeString(conditions); writer.write(value); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" var form = document.getElementById(forms[i]);"); writer.write(JsfConstants.LINE_SP); writer.write(" form.appendChild(hidden);"); writer.write(JsfConstants.LINE_SP); writer.write("}"); writer.write(JsfConstants.LINE_SP); writer.write(JsfConstants.LINE_SP); writer.write("//-->"); writer.write(JsfConstants.LINE_SP); writer.endElement(JsfConstants.SCRIPT_ELEM); }
protected static void renderJavascript(final ResponseWriter writer, final Map conditions, final List forms) throws IOException { writer.write(JsfConstants.LINE_SP); writer.startElement(JsfConstants.SCRIPT_ELEM, null); writer.writeAttribute(JsfConstants.LANGUAGE_ATTR, JsfConstants.JAVASCRIPT_VALUE, null); writer.writeAttribute(JsfConstants.TYPE_ATTR, JsfConstants.TEXT_JAVASCRIPT_VALUE, null); writer.write(JsfConstants.LINE_SP); writer.write("<!--"); writer.write(JsfConstants.LINE_SP); writer.write("var forms = ["); for (int i = 0; i < forms.size(); ++i) { final String form = (String) forms.get(i); writer.write("'"); writer.write(form); writer.write("'"); if (i < forms.size() - 1) { writer.write(", "); } } writer.write("];"); writer.write(JsfConstants.LINE_SP); writer.write("for (var i = 0, len = forms.length; i < len; ++i) {"); writer.write(JsfConstants.LINE_SP); writer.write(" var hidden = document.createElement('input');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('type', 'hidden');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('name', '"); writer.write(ExtensionConstants.CONDITIONS_PARAMETER); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" hidden.setAttribute('value', '"); final Base64EncodeConverter converter = new Base64EncodeConverter(); final String value = converter.getAsEncodeString(conditions); writer.write(value); writer.write("');"); writer.write(JsfConstants.LINE_SP); writer.write(" var form = document.getElementById(forms[i]);"); writer.write(JsfConstants.LINE_SP); writer.write(" form.appendChild(hidden);"); writer.write(JsfConstants.LINE_SP); writer.write("}"); writer.write(JsfConstants.LINE_SP); writer.write(JsfConstants.LINE_SP); writer.write("//-->"); writer.write(JsfConstants.LINE_SP); writer.endElement(JsfConstants.SCRIPT_ELEM); }
diff --git a/project/src/de/topobyte/livecg/ui/geometryeditor/object/action/ToRingsAction.java b/project/src/de/topobyte/livecg/ui/geometryeditor/object/action/ToRingsAction.java index 68250ac..907140f 100644 --- a/project/src/de/topobyte/livecg/ui/geometryeditor/object/action/ToRingsAction.java +++ b/project/src/de/topobyte/livecg/ui/geometryeditor/object/action/ToRingsAction.java @@ -1,58 +1,60 @@ /* This file is part of LiveCG. * * Copyright (C) 2013 Sebastian Kuerten * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.topobyte.livecg.ui.geometryeditor.object.action; import java.awt.event.ActionEvent; import de.topobyte.livecg.core.geometry.geom.Chain; import de.topobyte.livecg.core.geometry.geom.Polygon; import de.topobyte.livecg.ui.action.BasicAction; import de.topobyte.livecg.ui.geometryeditor.Content; import de.topobyte.livecg.ui.geometryeditor.GeometryEditPane; public class ToRingsAction extends BasicAction { private static final long serialVersionUID = -7826180655312955433L; private GeometryEditPane editPane; private Polygon polygon; public ToRingsAction(GeometryEditPane editPane, Polygon polygon) { super("to rings", "Convert to polygonal chains", "res/images/24x24/closedway.png"); this.editPane = editPane; this.polygon = polygon; } @Override public void actionPerformed(ActionEvent e) { Chain shell = polygon.getShell(); + shell.removePolygon(polygon); Content content = editPane.getContent(); content.removePolygon(polygon); editPane.removeCurrentPolygon(polygon); content.addChain(shell); for (Chain hole : polygon.getHoles()) { content.addChain(hole); + hole.removePolygon(polygon); } content.fireContentChanged(); } }
false
true
public void actionPerformed(ActionEvent e) { Chain shell = polygon.getShell(); Content content = editPane.getContent(); content.removePolygon(polygon); editPane.removeCurrentPolygon(polygon); content.addChain(shell); for (Chain hole : polygon.getHoles()) { content.addChain(hole); } content.fireContentChanged(); }
public void actionPerformed(ActionEvent e) { Chain shell = polygon.getShell(); shell.removePolygon(polygon); Content content = editPane.getContent(); content.removePolygon(polygon); editPane.removeCurrentPolygon(polygon); content.addChain(shell); for (Chain hole : polygon.getHoles()) { content.addChain(hole); hole.removePolygon(polygon); } content.fireContentChanged(); }
diff --git a/microsoft-azure-api/src/test/java/com/microsoft/azure/services/serviceBus/IntegrationTestBase.java b/microsoft-azure-api/src/test/java/com/microsoft/azure/services/serviceBus/IntegrationTestBase.java index cce7a5080d..e1904519bc 100644 --- a/microsoft-azure-api/src/test/java/com/microsoft/azure/services/serviceBus/IntegrationTestBase.java +++ b/microsoft-azure-api/src/test/java/com/microsoft/azure/services/serviceBus/IntegrationTestBase.java @@ -1,48 +1,48 @@ package com.microsoft.azure.services.serviceBus; import org.junit.Before; import com.microsoft.azure.configuration.Configuration; public abstract class IntegrationTestBase { protected Configuration createConfiguration() { Configuration config = new Configuration(); config.setProperty("serviceBus.uri", "https://lodejard.servicebus.windows.net"); config.setProperty("serviceBus.wrap.uri", "https://lodejard-sb.accesscontrol.windows.net/WRAPv0.9"); config.setProperty("serviceBus.wrap.name", "owner"); config.setProperty("serviceBus.wrap.password", "Zo3QCZ5jLlJofibEiifZyz7B3x6a5Suv2YoS1JAWopA="); config.setProperty("serviceBus.wrap.scope", "http://lodejard.servicebus.windows.net/"); // when mock running //config.setProperty("serviceBus.uri", "http://localhost:8086"); //config.setProperty("wrapClient.uri", "http://localhost:8081/WRAPv0.9"); return config; } @Before public void initialize() throws Exception { System.setProperty("http.proxyHost", "157.54.119.101"); System.setProperty("http.proxyPort", "80"); System.setProperty("http.keepAlive", "false"); boolean testAlphaExists = false; ServiceBusClient client = createConfiguration().create(ServiceBusClient.class); for(Queue queue : client.listQueues()){ if (queue.getPath().startsWith("Test") || queue.getPath().startsWith("test")) { - if (queue.getPath() == "testalpha") { + if (queue.getPath().equalsIgnoreCase("TestAlpha")) { testAlphaExists = true; long count = queue.getMessageCount(); for(long i = 0; i != count; ++i) { queue.receiveMessage(2000); } } else { queue.delete(); } } } if (!testAlphaExists) { client.getQueue("TestAlpha").save(); } } }
true
true
public void initialize() throws Exception { System.setProperty("http.proxyHost", "157.54.119.101"); System.setProperty("http.proxyPort", "80"); System.setProperty("http.keepAlive", "false"); boolean testAlphaExists = false; ServiceBusClient client = createConfiguration().create(ServiceBusClient.class); for(Queue queue : client.listQueues()){ if (queue.getPath().startsWith("Test") || queue.getPath().startsWith("test")) { if (queue.getPath() == "testalpha") { testAlphaExists = true; long count = queue.getMessageCount(); for(long i = 0; i != count; ++i) { queue.receiveMessage(2000); } } else { queue.delete(); } } } if (!testAlphaExists) { client.getQueue("TestAlpha").save(); } }
public void initialize() throws Exception { System.setProperty("http.proxyHost", "157.54.119.101"); System.setProperty("http.proxyPort", "80"); System.setProperty("http.keepAlive", "false"); boolean testAlphaExists = false; ServiceBusClient client = createConfiguration().create(ServiceBusClient.class); for(Queue queue : client.listQueues()){ if (queue.getPath().startsWith("Test") || queue.getPath().startsWith("test")) { if (queue.getPath().equalsIgnoreCase("TestAlpha")) { testAlphaExists = true; long count = queue.getMessageCount(); for(long i = 0; i != count; ++i) { queue.receiveMessage(2000); } } else { queue.delete(); } } } if (!testAlphaExists) { client.getQueue("TestAlpha").save(); } }
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/JavaEditingMonitor.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/JavaEditingMonitor.java index f04102b2d..928a0c276 100644 --- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/JavaEditingMonitor.java +++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/internal/java/ui/JavaEditingMonitor.java @@ -1,161 +1,165 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.java.ui; import java.util.Iterator; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylyn.internal.java.ui.search.JavaImplementorsProvider; import org.eclipse.mylyn.internal.java.ui.search.JavaReferencesProvider; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.monitor.ui.AbstractUserInteractionMonitor; import org.eclipse.ui.IWorkbenchPart; /** * @author Mik Kersten */ public class JavaEditingMonitor extends AbstractUserInteractionMonitor { protected IJavaElement lastSelectedElement = null; protected IJavaElement lastResolvedElement = null; protected JavaEditor currentEditor; protected StructuredSelection currentSelection = null; public JavaEditingMonitor() { super(); } /** * Only public for testing */ @Override public void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { try { IJavaElement selectedElement = null; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; if (structuredSelection.equals(currentSelection)) { return; } currentSelection = structuredSelection; // Object selectedObject = structuredSelection.getFirstElement(); for (Iterator<?> iterator = structuredSelection.iterator(); iterator.hasNext();) { Object selectedObject = iterator.next(); if (selectedObject instanceof IJavaElement) { IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary((IJavaElement) selectedObject); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } if (selectedElement != null) { super.handleElementSelection(part, selectedElement, contributeToContext); } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { currentEditor = (JavaEditor) part; TextSelection textSelection = (TextSelection) selection; selectedElement = SelectionConverter.resolveEnclosingElement(currentEditor, textSelection); if (selectedElement instanceof IPackageDeclaration) { - return; // HACK: ignoring these selections + // HACK: ignoring these selections + return; } IJavaElement[] resolved = SelectionConverter.codeResolve(currentEditor); if (resolved != null && resolved.length == 1 && !resolved[0].equals(selectedElement)) { lastResolvedElement = resolved[0]; } boolean selectionResolved = false; if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { + // navigation between two elements if (lastResolvedElement != null && lastSelectedElement != null && lastResolvedElement.equals(selectedElement) && !lastSelectedElement.equals(lastResolvedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } else if (lastSelectedElement != null && lastSelectedElement.equals(lastResolvedElement) && !lastSelectedElement.equals(selectedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } } else if (selectedElement != null && lastSelectedElement != null && !lastSelectedElement.equals(selectedElement)) { if (lastSelectedElement.getElementName().equals(selectedElement.getElementName())) { + // navigation between two elements if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } else if (selectedElement instanceof IType && lastSelectedElement instanceof IType) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } } } if (selectedElement != null) { + // selection of an element if (!selectionResolved && selectedElement.equals(lastSelectedElement)) { super.handleElementEdit(part, selectedElement, contributeToContext); } else if (!selectedElement.equals(lastSelectedElement)) { super.handleElementSelection(part, selectedElement, contributeToContext); } } IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary(selectedElement); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } } if (selectedElement != null) { lastSelectedElement = selectedElement; } } catch (JavaModelException e) { // ignore, fine to fail to resolve an element if the model is not up-to-date } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.PLUGIN_ID, "Failed to update model based on selection", t)); } } /** * @return null for elements that aren't modeled */ protected IJavaElement checkIfAcceptedAndPromoteIfNecessary(IJavaElement element) { // if (element instanceof IPackageDeclaration) return null; if (element instanceof IImportContainer) { return element.getParent(); } else if (element instanceof IImportDeclaration) { return element.getParent().getParent(); } else { return element; } } }
false
true
public void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { try { IJavaElement selectedElement = null; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; if (structuredSelection.equals(currentSelection)) { return; } currentSelection = structuredSelection; // Object selectedObject = structuredSelection.getFirstElement(); for (Iterator<?> iterator = structuredSelection.iterator(); iterator.hasNext();) { Object selectedObject = iterator.next(); if (selectedObject instanceof IJavaElement) { IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary((IJavaElement) selectedObject); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } if (selectedElement != null) { super.handleElementSelection(part, selectedElement, contributeToContext); } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { currentEditor = (JavaEditor) part; TextSelection textSelection = (TextSelection) selection; selectedElement = SelectionConverter.resolveEnclosingElement(currentEditor, textSelection); if (selectedElement instanceof IPackageDeclaration) { return; // HACK: ignoring these selections } IJavaElement[] resolved = SelectionConverter.codeResolve(currentEditor); if (resolved != null && resolved.length == 1 && !resolved[0].equals(selectedElement)) { lastResolvedElement = resolved[0]; } boolean selectionResolved = false; if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { if (lastResolvedElement != null && lastSelectedElement != null && lastResolvedElement.equals(selectedElement) && !lastSelectedElement.equals(lastResolvedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } else if (lastSelectedElement != null && lastSelectedElement.equals(lastResolvedElement) && !lastSelectedElement.equals(selectedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } } else if (selectedElement != null && lastSelectedElement != null && !lastSelectedElement.equals(selectedElement)) { if (lastSelectedElement.getElementName().equals(selectedElement.getElementName())) { if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } else if (selectedElement instanceof IType && lastSelectedElement instanceof IType) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } } } if (selectedElement != null) { if (!selectionResolved && selectedElement.equals(lastSelectedElement)) { super.handleElementEdit(part, selectedElement, contributeToContext); } else if (!selectedElement.equals(lastSelectedElement)) { super.handleElementSelection(part, selectedElement, contributeToContext); } } IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary(selectedElement); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } } if (selectedElement != null) { lastSelectedElement = selectedElement; } } catch (JavaModelException e) { // ignore, fine to fail to resolve an element if the model is not up-to-date } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.PLUGIN_ID, "Failed to update model based on selection", t)); } }
public void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection, boolean contributeToContext) { try { IJavaElement selectedElement = null; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection) selection; if (structuredSelection.equals(currentSelection)) { return; } currentSelection = structuredSelection; // Object selectedObject = structuredSelection.getFirstElement(); for (Iterator<?> iterator = structuredSelection.iterator(); iterator.hasNext();) { Object selectedObject = iterator.next(); if (selectedObject instanceof IJavaElement) { IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary((IJavaElement) selectedObject); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } if (selectedElement != null) { super.handleElementSelection(part, selectedElement, contributeToContext); } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { currentEditor = (JavaEditor) part; TextSelection textSelection = (TextSelection) selection; selectedElement = SelectionConverter.resolveEnclosingElement(currentEditor, textSelection); if (selectedElement instanceof IPackageDeclaration) { // HACK: ignoring these selections return; } IJavaElement[] resolved = SelectionConverter.codeResolve(currentEditor); if (resolved != null && resolved.length == 1 && !resolved[0].equals(selectedElement)) { lastResolvedElement = resolved[0]; } boolean selectionResolved = false; if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { // navigation between two elements if (lastResolvedElement != null && lastSelectedElement != null && lastResolvedElement.equals(selectedElement) && !lastSelectedElement.equals(lastResolvedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } else if (lastSelectedElement != null && lastSelectedElement.equals(lastResolvedElement) && !lastSelectedElement.equals(selectedElement)) { super.handleNavigation(part, selectedElement, JavaReferencesProvider.ID, contributeToContext); selectionResolved = true; } } else if (selectedElement != null && lastSelectedElement != null && !lastSelectedElement.equals(selectedElement)) { if (lastSelectedElement.getElementName().equals(selectedElement.getElementName())) { // navigation between two elements if (selectedElement instanceof IMethod && lastSelectedElement instanceof IMethod) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } else if (selectedElement instanceof IType && lastSelectedElement instanceof IType) { super.handleNavigation(part, selectedElement, JavaImplementorsProvider.ID, contributeToContext); selectionResolved = true; } } } if (selectedElement != null) { // selection of an element if (!selectionResolved && selectedElement.equals(lastSelectedElement)) { super.handleElementEdit(part, selectedElement, contributeToContext); } else if (!selectedElement.equals(lastSelectedElement)) { super.handleElementSelection(part, selectedElement, contributeToContext); } } IJavaElement checkedElement = checkIfAcceptedAndPromoteIfNecessary(selectedElement); if (checkedElement == null) { return; } else { selectedElement = checkedElement; } } } if (selectedElement != null) { lastSelectedElement = selectedElement; } } catch (JavaModelException e) { // ignore, fine to fail to resolve an element if the model is not up-to-date } catch (Throwable t) { StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.PLUGIN_ID, "Failed to update model based on selection", t)); } }
diff --git a/public/mbwapi/src/main/java/com/mrd/mbwapi/api/ExchangeRate.java b/public/mbwapi/src/main/java/com/mrd/mbwapi/api/ExchangeRate.java index 6b85de83..3fd62253 100644 --- a/public/mbwapi/src/main/java/com/mrd/mbwapi/api/ExchangeRate.java +++ b/public/mbwapi/src/main/java/com/mrd/mbwapi/api/ExchangeRate.java @@ -1,122 +1,122 @@ /* * Copyright 2013 Megion Research and Development GmbH * * Licensed under the Microsoft Reference Source License (MS-RSL) * * This license governs use of the accompanying software. If you use the software, you accept this license. * If you do not accept the license, do not use the software. * * 1. Definitions * The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law. * "You" means the licensee of the software. * "Your company" means the company you worked for when you downloaded the software. * "Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes * of debugging your products, maintaining your products, or enhancing the interoperability of your products with the * software, and specifically excludes the right to distribute the software outside of your company. * "Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor * under this license. * * 2. Grant of Rights * (A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, * worldwide, royalty-free copyright license to reproduce the software for reference use. * (B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, * worldwide, royalty-free patent license under licensed patents for reference use. * * 3. Limitations * (A) No Trademark License- This license does not grant you any rights to use the Licensor’s name, logo, or trademarks. * (B) If you begin patent litigation against the Licensor over patents that you think may apply to the software * (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically. * (C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, * guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot * change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, * fitness for a particular purpose and non-infringement. */ package com.mrd.mbwapi.api; import java.util.Date; import com.mrd.bitlib.util.ByteReader; import com.mrd.bitlib.util.ByteReader.InsufficientBytesException; import com.mrd.bitlib.util.ByteWriter; public class ExchangeRate extends ApiObject { public final String name; public final long time; public final String currency; public final Double price; // null if price is not available public ExchangeRate(String name, long time, String currency, Double price) { this.name = name; this.time = time; this.currency = currency; this.price = price; } public ExchangeRate(ExchangeRate o) { this(o.name, o.time, o.currency, o.price); } protected ExchangeRate(ByteReader reader) throws InsufficientBytesException { name = reader.getString(); time = reader.getLongLE(); currency = reader.getString(); String priceString = reader.getString(); - if (priceString.isEmpty()) { + if (priceString.length() == 0) { price = null; } else { Double p; try { p = Double.valueOf(priceString); } catch (NumberFormatException e) { p = null; } price = p; } // Payload may contain more, but we ignore it for forwards // compatibility } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ").append(name); sb.append(" time: ").append(new Date(time)); sb.append(" currency: ").append(currency); sb.append(" price: ").append(price == null ? "<Not available>" : price); return sb.toString(); } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ExchangeRate)) { return false; } ExchangeRate other = (ExchangeRate) obj; return other.time == time && other.name.equals(name) && other.currency.equals(currency); } @Override protected ByteWriter toByteWriter(ByteWriter writer) { writer.putString(name.toString()); writer.putLongLE(time); writer.putString(currency); writer.putString(price == null ? "" : price.toString()); return writer; } @Override public byte getType() { return ApiObject.EXCHANGE_RATE_TYPE; } }
true
true
protected ExchangeRate(ByteReader reader) throws InsufficientBytesException { name = reader.getString(); time = reader.getLongLE(); currency = reader.getString(); String priceString = reader.getString(); if (priceString.isEmpty()) { price = null; } else { Double p; try { p = Double.valueOf(priceString); } catch (NumberFormatException e) { p = null; } price = p; } // Payload may contain more, but we ignore it for forwards // compatibility }
protected ExchangeRate(ByteReader reader) throws InsufficientBytesException { name = reader.getString(); time = reader.getLongLE(); currency = reader.getString(); String priceString = reader.getString(); if (priceString.length() == 0) { price = null; } else { Double p; try { p = Double.valueOf(priceString); } catch (NumberFormatException e) { p = null; } price = p; } // Payload may contain more, but we ignore it for forwards // compatibility }
diff --git a/src/wowebookcom/cz/vity/freerapid/plugins/services/wowebookcom/WowEbookComFileRunner.java b/src/wowebookcom/cz/vity/freerapid/plugins/services/wowebookcom/WowEbookComFileRunner.java index c839d410..032c12c3 100644 --- a/src/wowebookcom/cz/vity/freerapid/plugins/services/wowebookcom/WowEbookComFileRunner.java +++ b/src/wowebookcom/cz/vity/freerapid/plugins/services/wowebookcom/WowEbookComFileRunner.java @@ -1,60 +1,65 @@ package cz.vity.freerapid.plugins.services.wowebookcom; import cz.vity.freerapid.plugins.exceptions.ErrorDuringDownloadingException; import cz.vity.freerapid.plugins.exceptions.ServiceConnectionProblemException; import cz.vity.freerapid.plugins.exceptions.URLNotAvailableAnymoreException; import cz.vity.freerapid.plugins.webclient.AbstractRunner; import cz.vity.freerapid.plugins.webclient.DownloadState; import cz.vity.freerapid.plugins.webclient.utils.PlugUtils; import org.apache.commons.httpclient.methods.GetMethod; import java.net.URL; import java.util.logging.Logger; /** * Class which contains main code * * @author CrazyCoder, Abinash Bishoyi */ class WowEbookComFileRunner extends AbstractRunner { private final static Logger logger = Logger.getLogger(WowEbookComFileRunner.class.getName()); @Override public void runCheck() throws Exception { super.runCheck(); final GetMethod getMethod = getGetMethod(fileURL); if (makeRedirectedRequest(getMethod)) { checkProblems(); } else { checkProblems(); throw new ServiceConnectionProblemException(); } } @Override public void run() throws Exception { super.run(); logger.info("Starting download in TASK " + fileURL); final GetMethod method = getGetMethod(fileURL); if (makeRedirectedRequest(method)) { checkProblems(); - String directURL = PlugUtils.getStringBetween(getContentAsString(), "] <a target=\"_blank\" href=\"", "\""); + final String start = "] <a target=\"_blank\" href=\""; + final String end = "\""; + String directURL = PlugUtils.getStringBetween(getContentAsString(), start, end); + if (!directURL.contains("prefiles")) { + directURL = PlugUtils.getStringBetween(getContentAsString(), start, end, 2); + } directURL = directURL.replaceFirst("http://adf.ly/\\d+/", ""); logger.info("Download Service URL: " + directURL); httpFile.setNewURL(new URL(directURL)); httpFile.setPluginID(""); httpFile.setState(DownloadState.QUEUED); } else { checkProblems(); throw new ServiceConnectionProblemException(); } } private void checkProblems() throws ErrorDuringDownloadingException { final String contentAsString = getContentAsString(); if (contentAsString.contains("File Not Found")) { throw new URLNotAvailableAnymoreException("File not found"); } } }
true
true
public void run() throws Exception { super.run(); logger.info("Starting download in TASK " + fileURL); final GetMethod method = getGetMethod(fileURL); if (makeRedirectedRequest(method)) { checkProblems(); String directURL = PlugUtils.getStringBetween(getContentAsString(), "] <a target=\"_blank\" href=\"", "\""); directURL = directURL.replaceFirst("http://adf.ly/\\d+/", ""); logger.info("Download Service URL: " + directURL); httpFile.setNewURL(new URL(directURL)); httpFile.setPluginID(""); httpFile.setState(DownloadState.QUEUED); } else { checkProblems(); throw new ServiceConnectionProblemException(); } }
public void run() throws Exception { super.run(); logger.info("Starting download in TASK " + fileURL); final GetMethod method = getGetMethod(fileURL); if (makeRedirectedRequest(method)) { checkProblems(); final String start = "] <a target=\"_blank\" href=\""; final String end = "\""; String directURL = PlugUtils.getStringBetween(getContentAsString(), start, end); if (!directURL.contains("prefiles")) { directURL = PlugUtils.getStringBetween(getContentAsString(), start, end, 2); } directURL = directURL.replaceFirst("http://adf.ly/\\d+/", ""); logger.info("Download Service URL: " + directURL); httpFile.setNewURL(new URL(directURL)); httpFile.setPluginID(""); httpFile.setState(DownloadState.QUEUED); } else { checkProblems(); throw new ServiceConnectionProblemException(); } }
diff --git a/DataDroid/src/com/foxykeep/datadroid/factory/RssFactory.java b/DataDroid/src/com/foxykeep/datadroid/factory/RssFactory.java index b6eb960..bf2ad6f 100644 --- a/DataDroid/src/com/foxykeep/datadroid/factory/RssFactory.java +++ b/DataDroid/src/com/foxykeep/datadroid/factory/RssFactory.java @@ -1,254 +1,254 @@ /** * 2011 Foxykeep (http://datadroid.foxykeep.com) * <p> * Licensed under the Beerware License : <br /> * As long as you retain this notice you can do whatever you want with this stuff. If we meet some * day, and you think this stuff is worth it, you can buy me a beer in return */ package com.foxykeep.datadroid.factory; import android.text.TextUtils; import com.foxykeep.datadroid.exception.DataException; import com.foxykeep.datadroid.model.RssFeed; import com.foxykeep.datadroid.model.RssItem; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import java.io.IOException; import java.io.StringReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; /** * Factory used to parse the RSS feed. * * @author Foxykeep */ public final class RssFactory { private RssFactory() { // No public constructor } public static RssFeed parseResult(String wsResponse) throws DataException { RssHandler parser = new RssHandler(); try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(parser); StringReader sr = new StringReader(wsResponse); InputSource is = new InputSource(sr); xr.parse(is); } catch (ParserConfigurationException e) { throw new DataException(e); } catch (SAXException e) { throw new DataException(e); } catch (IOException e) { throw new DataException(e); } return parser.mRssFeed; } private static class RssHandler extends DefaultHandler { private static final String DATE_FORMAT_1 = "ccc',' dd MMM yyyy HH:mm:ss Z"; private static final String DATE_FORMAT_2 = "ccc',' dd MMM yyyy"; private static final SimpleDateFormat SIMPLE_DATE_FORMAT_1 = new SimpleDateFormat(DATE_FORMAT_1, Locale.US); private static final SimpleDateFormat SIMPLE_DATE_FORMAT_2 = new SimpleDateFormat(DATE_FORMAT_2, Locale.US); private StringBuilder mSb = new StringBuilder(); public RssFeed mRssFeed = new RssFeed(); private RssItem mCurrentRssItem = null; private boolean mIsInItem = false; private boolean mIsInImage = false; private ArrayList<String> mSkipDayList = new ArrayList<String>(); private ArrayList<String> mSkipHourList = new ArrayList<String>(); @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { mSb.setLength(0); if (TextUtils.isEmpty(namespaceURI)) { if (localName.equals("item")) { mIsInItem = true; mCurrentRssItem = new RssItem(); } else if (localName.equals("image")) { mIsInImage = true; mRssFeed.imageWidth = 31; // Default value from W3Schools mRssFeed.imageHeight = 88; // Default value from W3Schools } else if (localName.equals("guid")) { String isPermaLink = atts.getValue("isPermaLink"); mCurrentRssItem.isGuidPermaLink = isPermaLink != null && isPermaLink.equals("true"); } else if (localName.equals("source")) { mCurrentRssItem.sourceLink = atts.getValue("url"); } else if (localName.equals("enclosure")) { mCurrentRssItem.enclosureLink = atts.getValue("url"); mCurrentRssItem.enclosureSize = Integer.parseInt(atts.getValue("length")); mCurrentRssItem.enclosureMimeType = atts.getValue("type"); } } } @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (TextUtils.isEmpty(namespaceURI)) { if (localName.equals("item")) { mRssFeed.rssItemList.add(mCurrentRssItem); mIsInItem = false; } else if (localName.equals("image")) { mIsInImage = false; } else if (localName.equals("title")) { if (mIsInImage) { mRssFeed.imageTitle = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.title = mSb.toString(); } else { mRssFeed.title = mSb.toString(); } } else if (localName.equals("link")) { if (mIsInImage) { mRssFeed.imageWebsiteLink = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.link = mSb.toString(); } else { mRssFeed.link = mSb.toString(); } } else if (localName.equals("description")) { if (mIsInImage) { mRssFeed.imageDescription = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.description = mSb.toString(); } else { mRssFeed.description = mSb.toString(); } } else if (localName.equals("category")) { if (mIsInItem) { mCurrentRssItem.categoryList.add(mSb.toString()); } else { mRssFeed.categoryList.add(mSb.toString()); } } else if (localName.equals("pubDate")) { if (mIsInItem) { mCurrentRssItem.pubDate = getMillisFromDate(mSb.toString()); } else { mRssFeed.pubDate = getMillisFromDate(mSb.toString()); } } else if (localName.equals("lastBuildDate")) { getMillisFromDate(mSb.toString()); } else if (localName.equals("language")) { mRssFeed.language = mSb.toString(); } else if (localName.equals("copyright")) { mRssFeed.copyright = mSb.toString(); } else if (localName.equals("generator")) { mRssFeed.generator = mSb.toString(); } else if (localName.equals("url")) { mRssFeed.imageUrl = mSb.toString(); } else if (localName.equals("width")) { mRssFeed.imageWidth = Integer.parseInt(mSb.toString()); } else if (localName.equals("height")) { mRssFeed.imageHeight = Integer.parseInt(mSb.toString()); } else if (localName.equals("managingEditor")) { mRssFeed.managingEditor = mSb.toString(); } else if (localName.equals("webMaster")) { mRssFeed.webmaster = mSb.toString(); } else if (localName.equals("author")) { mCurrentRssItem.author = mSb.toString(); } else if (localName.equals("guid")) { mCurrentRssItem.guid = mSb.toString(); } else if (localName.equals("encodedText")) { mCurrentRssItem.encodedContext = mSb.toString(); } else if (localName.equals("source")) { mCurrentRssItem.sourceText = mSb.toString(); } else if (localName.equals("day")) { - mSkipDayList.add(mSb.toString().toLowerCase()); + mSkipDayList.add(mSb.toString().toLowerCase(Locale.US)); } else if (localName.equals("skipDays")) { int skipDayListSize = mSkipDayList.size(); mRssFeed.skipDayArray = new int[skipDayListSize]; for (int i = 0; i < skipDayListSize; i++) { final String day = mSkipDayList.get(i); if (day.equals("monday")) { mRssFeed.skipDayArray[i] = 0; } else if (day.equals("tuesday")) { mRssFeed.skipDayArray[i] = 1; } else if (day.equals("wednesday")) { mRssFeed.skipDayArray[i] = 2; } else if (day.equals("thrusday")) { mRssFeed.skipDayArray[i] = 3; } else if (day.equals("friday")) { mRssFeed.skipDayArray[i] = 4; } else if (day.equals("saturday")) { mRssFeed.skipDayArray[i] = 5; } else if (day.equals("sunday")) { mRssFeed.skipDayArray[i] = 6; } } } else if (localName.equals("hour")) { - mSkipHourList.add(mSb.toString().toLowerCase()); + mSkipHourList.add(mSb.toString().toLowerCase(Locale.US)); } else if (localName.equals("skipHours")) { int skipHourListSize = mSkipHourList.size(); mRssFeed.skipHourArray = new int[skipHourListSize]; for (int i = 0; i < skipHourListSize; i++) { mRssFeed.skipHourArray[i] = Integer.parseInt(mSkipHourList.get(i)); } } else if (localName.equals("ttl")) { mRssFeed.ttl = Integer.parseInt(mSb.toString()); } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); mSb.append(ch, start, length); } /** * Method used to get the milliseconds corresponding to the 2 common formats for the date. * * @param date The given date. * @return The timestamp corresponding to the given date. * @throws SAXException Exception thrown if the given date doesn't follow one of the 2 * common formats. */ private long getMillisFromDate(String date) throws SAXException { long millis = -1; try { millis = SIMPLE_DATE_FORMAT_1.parse(date).getTime(); } catch (ParseException e) { // fall through } if (millis != -1) { return millis; } try { return SIMPLE_DATE_FORMAT_2.parse(date).getTime(); } catch (ParseException e) { throw new SAXException(e); } } } }
false
true
public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (TextUtils.isEmpty(namespaceURI)) { if (localName.equals("item")) { mRssFeed.rssItemList.add(mCurrentRssItem); mIsInItem = false; } else if (localName.equals("image")) { mIsInImage = false; } else if (localName.equals("title")) { if (mIsInImage) { mRssFeed.imageTitle = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.title = mSb.toString(); } else { mRssFeed.title = mSb.toString(); } } else if (localName.equals("link")) { if (mIsInImage) { mRssFeed.imageWebsiteLink = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.link = mSb.toString(); } else { mRssFeed.link = mSb.toString(); } } else if (localName.equals("description")) { if (mIsInImage) { mRssFeed.imageDescription = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.description = mSb.toString(); } else { mRssFeed.description = mSb.toString(); } } else if (localName.equals("category")) { if (mIsInItem) { mCurrentRssItem.categoryList.add(mSb.toString()); } else { mRssFeed.categoryList.add(mSb.toString()); } } else if (localName.equals("pubDate")) { if (mIsInItem) { mCurrentRssItem.pubDate = getMillisFromDate(mSb.toString()); } else { mRssFeed.pubDate = getMillisFromDate(mSb.toString()); } } else if (localName.equals("lastBuildDate")) { getMillisFromDate(mSb.toString()); } else if (localName.equals("language")) { mRssFeed.language = mSb.toString(); } else if (localName.equals("copyright")) { mRssFeed.copyright = mSb.toString(); } else if (localName.equals("generator")) { mRssFeed.generator = mSb.toString(); } else if (localName.equals("url")) { mRssFeed.imageUrl = mSb.toString(); } else if (localName.equals("width")) { mRssFeed.imageWidth = Integer.parseInt(mSb.toString()); } else if (localName.equals("height")) { mRssFeed.imageHeight = Integer.parseInt(mSb.toString()); } else if (localName.equals("managingEditor")) { mRssFeed.managingEditor = mSb.toString(); } else if (localName.equals("webMaster")) { mRssFeed.webmaster = mSb.toString(); } else if (localName.equals("author")) { mCurrentRssItem.author = mSb.toString(); } else if (localName.equals("guid")) { mCurrentRssItem.guid = mSb.toString(); } else if (localName.equals("encodedText")) { mCurrentRssItem.encodedContext = mSb.toString(); } else if (localName.equals("source")) { mCurrentRssItem.sourceText = mSb.toString(); } else if (localName.equals("day")) { mSkipDayList.add(mSb.toString().toLowerCase()); } else if (localName.equals("skipDays")) { int skipDayListSize = mSkipDayList.size(); mRssFeed.skipDayArray = new int[skipDayListSize]; for (int i = 0; i < skipDayListSize; i++) { final String day = mSkipDayList.get(i); if (day.equals("monday")) { mRssFeed.skipDayArray[i] = 0; } else if (day.equals("tuesday")) { mRssFeed.skipDayArray[i] = 1; } else if (day.equals("wednesday")) { mRssFeed.skipDayArray[i] = 2; } else if (day.equals("thrusday")) { mRssFeed.skipDayArray[i] = 3; } else if (day.equals("friday")) { mRssFeed.skipDayArray[i] = 4; } else if (day.equals("saturday")) { mRssFeed.skipDayArray[i] = 5; } else if (day.equals("sunday")) { mRssFeed.skipDayArray[i] = 6; } } } else if (localName.equals("hour")) { mSkipHourList.add(mSb.toString().toLowerCase()); } else if (localName.equals("skipHours")) { int skipHourListSize = mSkipHourList.size(); mRssFeed.skipHourArray = new int[skipHourListSize]; for (int i = 0; i < skipHourListSize; i++) { mRssFeed.skipHourArray[i] = Integer.parseInt(mSkipHourList.get(i)); } } else if (localName.equals("ttl")) { mRssFeed.ttl = Integer.parseInt(mSb.toString()); } } }
public void endElement(String namespaceURI, String localName, String qName) throws SAXException { if (TextUtils.isEmpty(namespaceURI)) { if (localName.equals("item")) { mRssFeed.rssItemList.add(mCurrentRssItem); mIsInItem = false; } else if (localName.equals("image")) { mIsInImage = false; } else if (localName.equals("title")) { if (mIsInImage) { mRssFeed.imageTitle = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.title = mSb.toString(); } else { mRssFeed.title = mSb.toString(); } } else if (localName.equals("link")) { if (mIsInImage) { mRssFeed.imageWebsiteLink = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.link = mSb.toString(); } else { mRssFeed.link = mSb.toString(); } } else if (localName.equals("description")) { if (mIsInImage) { mRssFeed.imageDescription = mSb.toString(); } else if (mIsInItem) { mCurrentRssItem.description = mSb.toString(); } else { mRssFeed.description = mSb.toString(); } } else if (localName.equals("category")) { if (mIsInItem) { mCurrentRssItem.categoryList.add(mSb.toString()); } else { mRssFeed.categoryList.add(mSb.toString()); } } else if (localName.equals("pubDate")) { if (mIsInItem) { mCurrentRssItem.pubDate = getMillisFromDate(mSb.toString()); } else { mRssFeed.pubDate = getMillisFromDate(mSb.toString()); } } else if (localName.equals("lastBuildDate")) { getMillisFromDate(mSb.toString()); } else if (localName.equals("language")) { mRssFeed.language = mSb.toString(); } else if (localName.equals("copyright")) { mRssFeed.copyright = mSb.toString(); } else if (localName.equals("generator")) { mRssFeed.generator = mSb.toString(); } else if (localName.equals("url")) { mRssFeed.imageUrl = mSb.toString(); } else if (localName.equals("width")) { mRssFeed.imageWidth = Integer.parseInt(mSb.toString()); } else if (localName.equals("height")) { mRssFeed.imageHeight = Integer.parseInt(mSb.toString()); } else if (localName.equals("managingEditor")) { mRssFeed.managingEditor = mSb.toString(); } else if (localName.equals("webMaster")) { mRssFeed.webmaster = mSb.toString(); } else if (localName.equals("author")) { mCurrentRssItem.author = mSb.toString(); } else if (localName.equals("guid")) { mCurrentRssItem.guid = mSb.toString(); } else if (localName.equals("encodedText")) { mCurrentRssItem.encodedContext = mSb.toString(); } else if (localName.equals("source")) { mCurrentRssItem.sourceText = mSb.toString(); } else if (localName.equals("day")) { mSkipDayList.add(mSb.toString().toLowerCase(Locale.US)); } else if (localName.equals("skipDays")) { int skipDayListSize = mSkipDayList.size(); mRssFeed.skipDayArray = new int[skipDayListSize]; for (int i = 0; i < skipDayListSize; i++) { final String day = mSkipDayList.get(i); if (day.equals("monday")) { mRssFeed.skipDayArray[i] = 0; } else if (day.equals("tuesday")) { mRssFeed.skipDayArray[i] = 1; } else if (day.equals("wednesday")) { mRssFeed.skipDayArray[i] = 2; } else if (day.equals("thrusday")) { mRssFeed.skipDayArray[i] = 3; } else if (day.equals("friday")) { mRssFeed.skipDayArray[i] = 4; } else if (day.equals("saturday")) { mRssFeed.skipDayArray[i] = 5; } else if (day.equals("sunday")) { mRssFeed.skipDayArray[i] = 6; } } } else if (localName.equals("hour")) { mSkipHourList.add(mSb.toString().toLowerCase(Locale.US)); } else if (localName.equals("skipHours")) { int skipHourListSize = mSkipHourList.size(); mRssFeed.skipHourArray = new int[skipHourListSize]; for (int i = 0; i < skipHourListSize; i++) { mRssFeed.skipHourArray[i] = Integer.parseInt(mSkipHourList.get(i)); } } else if (localName.equals("ttl")) { mRssFeed.ttl = Integer.parseInt(mSb.toString()); } } }
diff --git a/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/FindServiceImpl.java b/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/FindServiceImpl.java index d485a6ae6..d7a768aa3 100644 --- a/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/FindServiceImpl.java +++ b/juddi-console/uddi-portlets/src/main/java/org/apache/juddi/portlets/server/service/FindServiceImpl.java @@ -1,108 +1,110 @@ /* * Copyright 2001-2009 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.juddi.portlets.server.service; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.juddi.portlets.client.model.Business; import org.apache.juddi.portlets.client.model.Service; import org.apache.juddi.portlets.client.service.FindResponse; import org.apache.juddi.portlets.client.service.FindService; import org.apache.juddi.v3.client.config.WebHelper; import org.apache.juddi.v3.client.i18n.EntityForLang; import org.apache.juddi.v3.client.transport.Transport; import org.apache.log4j.Logger; import org.uddi.api_v3.BusinessInfo; import org.uddi.api_v3.BusinessList; import org.uddi.api_v3.FindBusiness; import org.uddi.api_v3.FindQualifiers; import org.uddi.api_v3.Name; import org.uddi.api_v3.ServiceInfo; import org.uddi.v3_service.UDDIInquiryPortType; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /** * * @author <a href="mailto:[email protected]">Kurt T Stam</a> * */ public class FindServiceImpl extends RemoteServiceServlet implements FindService { private static final long serialVersionUID = 1939609260067702168L; private Logger logger = Logger.getLogger(this.getClass()); public FindResponse getBusinesses(String nameStr, String[] findQualifyers) { HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); String lang = request.getLocale().getLanguage(); FindResponse response = new FindResponse(); try { FindBusiness findBusiness = new FindBusiness(); FindQualifiers findQualifiers = new FindQualifiers(); for (String string : findQualifyers) { findQualifiers.getFindQualifier().add(string); } findBusiness.setFindQualifiers(findQualifiers); Name name = new Name(); name.setValue(nameStr); findBusiness.getName().add(name); logger.debug("FindBusiness " + findBusiness + " sending findBusinesses request.."); List<Business> businesses = new ArrayList<Business>(); Transport transport = WebHelper.getTransport(session.getServletContext()); UDDIInquiryPortType inquiryService = transport.getUDDIInquiryService(); BusinessList businessList = inquiryService.findBusiness(findBusiness); for (BusinessInfo businessInfo : businessList.getBusinessInfos().getBusinessInfo()) { Business business = new Business( businessInfo.getBusinessKey(), EntityForLang.getName(businessInfo.getName(),lang).getValue(), EntityForLang.getDescription(businessInfo.getDescription(),lang).getValue()); List<Service> services = new ArrayList<Service>(); - for (ServiceInfo serviceInfo : businessInfo.getServiceInfos().getServiceInfo()) { - Service service = new Service( - serviceInfo.getServiceKey(), - EntityForLang.getName(serviceInfo.getName(), lang).getValue()); - services.add(service); + if (businessInfo.getServiceInfos()!=null) { + for (ServiceInfo serviceInfo : businessInfo.getServiceInfos().getServiceInfo()) { + Service service = new Service( + serviceInfo.getServiceKey(), + EntityForLang.getName(serviceInfo.getName(), lang).getValue()); + services.add(service); + } } business.setServices(services); businesses.add(business); } response.setSuccess(true); response.setBusinesses(businesses); } catch (Exception e) { logger.error("Could not obtain token. " + e.getMessage(), e); response.setSuccess(false); response.setMessage(e.getMessage()); response.setErrorCode("102"); } catch (Throwable t) { logger.error("Could not obtain token. " + t.getMessage(), t); response.setSuccess(false); response.setMessage(t.getMessage()); response.setErrorCode("102"); } return response; } }
true
true
public FindResponse getBusinesses(String nameStr, String[] findQualifyers) { HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); String lang = request.getLocale().getLanguage(); FindResponse response = new FindResponse(); try { FindBusiness findBusiness = new FindBusiness(); FindQualifiers findQualifiers = new FindQualifiers(); for (String string : findQualifyers) { findQualifiers.getFindQualifier().add(string); } findBusiness.setFindQualifiers(findQualifiers); Name name = new Name(); name.setValue(nameStr); findBusiness.getName().add(name); logger.debug("FindBusiness " + findBusiness + " sending findBusinesses request.."); List<Business> businesses = new ArrayList<Business>(); Transport transport = WebHelper.getTransport(session.getServletContext()); UDDIInquiryPortType inquiryService = transport.getUDDIInquiryService(); BusinessList businessList = inquiryService.findBusiness(findBusiness); for (BusinessInfo businessInfo : businessList.getBusinessInfos().getBusinessInfo()) { Business business = new Business( businessInfo.getBusinessKey(), EntityForLang.getName(businessInfo.getName(),lang).getValue(), EntityForLang.getDescription(businessInfo.getDescription(),lang).getValue()); List<Service> services = new ArrayList<Service>(); for (ServiceInfo serviceInfo : businessInfo.getServiceInfos().getServiceInfo()) { Service service = new Service( serviceInfo.getServiceKey(), EntityForLang.getName(serviceInfo.getName(), lang).getValue()); services.add(service); } business.setServices(services); businesses.add(business); } response.setSuccess(true); response.setBusinesses(businesses); } catch (Exception e) { logger.error("Could not obtain token. " + e.getMessage(), e); response.setSuccess(false); response.setMessage(e.getMessage()); response.setErrorCode("102"); } catch (Throwable t) { logger.error("Could not obtain token. " + t.getMessage(), t); response.setSuccess(false); response.setMessage(t.getMessage()); response.setErrorCode("102"); } return response; }
public FindResponse getBusinesses(String nameStr, String[] findQualifyers) { HttpServletRequest request = this.getThreadLocalRequest(); HttpSession session = request.getSession(); String lang = request.getLocale().getLanguage(); FindResponse response = new FindResponse(); try { FindBusiness findBusiness = new FindBusiness(); FindQualifiers findQualifiers = new FindQualifiers(); for (String string : findQualifyers) { findQualifiers.getFindQualifier().add(string); } findBusiness.setFindQualifiers(findQualifiers); Name name = new Name(); name.setValue(nameStr); findBusiness.getName().add(name); logger.debug("FindBusiness " + findBusiness + " sending findBusinesses request.."); List<Business> businesses = new ArrayList<Business>(); Transport transport = WebHelper.getTransport(session.getServletContext()); UDDIInquiryPortType inquiryService = transport.getUDDIInquiryService(); BusinessList businessList = inquiryService.findBusiness(findBusiness); for (BusinessInfo businessInfo : businessList.getBusinessInfos().getBusinessInfo()) { Business business = new Business( businessInfo.getBusinessKey(), EntityForLang.getName(businessInfo.getName(),lang).getValue(), EntityForLang.getDescription(businessInfo.getDescription(),lang).getValue()); List<Service> services = new ArrayList<Service>(); if (businessInfo.getServiceInfos()!=null) { for (ServiceInfo serviceInfo : businessInfo.getServiceInfos().getServiceInfo()) { Service service = new Service( serviceInfo.getServiceKey(), EntityForLang.getName(serviceInfo.getName(), lang).getValue()); services.add(service); } } business.setServices(services); businesses.add(business); } response.setSuccess(true); response.setBusinesses(businesses); } catch (Exception e) { logger.error("Could not obtain token. " + e.getMessage(), e); response.setSuccess(false); response.setMessage(e.getMessage()); response.setErrorCode("102"); } catch (Throwable t) { logger.error("Could not obtain token. " + t.getMessage(), t); response.setSuccess(false); response.setMessage(t.getMessage()); response.setErrorCode("102"); } return response; }
diff --git a/catalog/src/main/java/com/ning/billing/catalog/PriceList.java b/catalog/src/main/java/com/ning/billing/catalog/PriceList.java index 0c9940d3c..70a23d93c 100644 --- a/catalog/src/main/java/com/ning/billing/catalog/PriceList.java +++ b/catalog/src/main/java/com/ning/billing/catalog/PriceList.java @@ -1,105 +1,105 @@ /* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.catalog; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import com.ning.billing.catalog.api.BillingPeriod; import com.ning.billing.catalog.api.IPriceList; import com.ning.billing.catalog.api.IProduct; import com.ning.billing.util.config.ValidatingConfig; import com.ning.billing.util.config.ValidationError; import com.ning.billing.util.config.ValidationErrors; @XmlAccessorType(XmlAccessType.NONE) public class PriceList extends ValidatingConfig<Catalog> implements IPriceList { @XmlAttribute(required=true) @XmlID private String name; @XmlElementWrapper(name="plans", required=true) @XmlElement(name="plan", required=true) @XmlIDREF private Plan[] plans; public PriceList(){} public PriceList(Plan[] plans, String name) { this.plans = plans; this.name = name; } protected Plan[] getPlans() { return plans; } /* (non-Javadoc) * @see com.ning.billing.catalog.IPriceList#getName() */ @Override public String getName() { return name; } /* (non-Javadoc) * @see com.ning.billing.catalog.IPriceList#findPlan(com.ning.billing.catalog.api.IProduct, com.ning.billing.catalog.api.BillingPeriod) */ @Override public Plan findPlan(IProduct product, BillingPeriod period) { for (Plan cur : getPlans()) { if (cur.getProduct().equals(product) && (cur.getBillingPeriod() == null || cur.getBillingPeriod().equals(period))) { return cur; } } return null; } @Override public ValidationErrors validate(Catalog catalog, ValidationErrors errors) { for (Plan cur : getPlans()) { int numPlans = findNumberOfPlans(cur.getProduct(), cur.getBillingPeriod()); if ( numPlans > 1 ) { errors.add(new ValidationError( String.format("There are %d plans in pricelist %s and have the same product/billingPeriod (%s, %s)", - numPlans, getName(), cur.getProduct(), cur.getBillingPeriod()), catalog.getCatalogURI(), + numPlans, getName(), cur.getProduct().getName(), cur.getBillingPeriod()), catalog.getCatalogURI(), PriceListSet.class, getName())); } } return errors; } private int findNumberOfPlans(IProduct product, BillingPeriod period) { int count = 0; for (Plan cur : getPlans()) { if (cur.getProduct().equals(product) && (cur.getBillingPeriod() == null || cur.getBillingPeriod().equals(period))) { count++; } } return count; } }
true
true
public ValidationErrors validate(Catalog catalog, ValidationErrors errors) { for (Plan cur : getPlans()) { int numPlans = findNumberOfPlans(cur.getProduct(), cur.getBillingPeriod()); if ( numPlans > 1 ) { errors.add(new ValidationError( String.format("There are %d plans in pricelist %s and have the same product/billingPeriod (%s, %s)", numPlans, getName(), cur.getProduct(), cur.getBillingPeriod()), catalog.getCatalogURI(), PriceListSet.class, getName())); } } return errors; }
public ValidationErrors validate(Catalog catalog, ValidationErrors errors) { for (Plan cur : getPlans()) { int numPlans = findNumberOfPlans(cur.getProduct(), cur.getBillingPeriod()); if ( numPlans > 1 ) { errors.add(new ValidationError( String.format("There are %d plans in pricelist %s and have the same product/billingPeriod (%s, %s)", numPlans, getName(), cur.getProduct().getName(), cur.getBillingPeriod()), catalog.getCatalogURI(), PriceListSet.class, getName())); } } return errors; }
diff --git a/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/service/impl/SiteEmailNotificationRWiki.java b/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/service/impl/SiteEmailNotificationRWiki.java index 8d8c56a6..67aefeae 100644 --- a/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/service/impl/SiteEmailNotificationRWiki.java +++ b/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/service/impl/SiteEmailNotificationRWiki.java @@ -1,371 +1,371 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package uk.ac.cam.caret.sakai.rwiki.component.service.impl; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.authz.api.SecurityService; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.email.api.DigestService; import org.sakaiproject.entity.api.EntityManager; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.Notification; import org.sakaiproject.event.api.NotificationAction; import org.sakaiproject.event.api.NotificationService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.thread_local.api.ThreadLocalManager; import org.sakaiproject.time.api.TimeService; import org.sakaiproject.user.api.User; import org.sakaiproject.util.SiteEmailNotification; import uk.ac.cam.caret.sakai.rwiki.component.Messages; import uk.ac.cam.caret.sakai.rwiki.service.api.RWikiObjectService; import uk.ac.cam.caret.sakai.rwiki.service.api.RenderService; import uk.ac.cam.caret.sakai.rwiki.service.api.model.RWikiEntity; import uk.ac.cam.caret.sakai.rwiki.service.api.model.RWikiObject; import uk.ac.cam.caret.sakai.rwiki.service.message.api.PreferenceService; import uk.ac.cam.caret.sakai.rwiki.utils.DigestHtml; import uk.ac.cam.caret.sakai.rwiki.utils.NameHelper; /** * <p> * SiteEmailNotificationRWiki fills the notification message and headers with details from the content change that triggered the notification event. * </p> * * @author Sakai Software Development Team * @author ieb */ public class SiteEmailNotificationRWiki extends SiteEmailNotification { private static Log log = LogFactory.getLog(SiteEmailNotificationRWiki.class); private RenderService renderService = null; private RWikiObjectService rwikiObjectService = null; private PreferenceService preferenceService = null; private SiteService siteService; private SecurityService securityService; private EntityManager entityManager; private ThreadLocalManager threadLocalManager; private TimeService timeService; private DigestService digestService; protected Thread senderThread = null; protected Vector sendList = new Vector(); /** * Construct. */ public SiteEmailNotificationRWiki(RWikiObjectService rwikiObjectService, RenderService renderService, PreferenceService preferenceService, SiteService siteService, SecurityService securityService, EntityManager entityManager, ThreadLocalManager threadLocalManager, TimeService timeService, DigestService digestService) { this.renderService = renderService; this.rwikiObjectService = rwikiObjectService; this.preferenceService = preferenceService; this.siteService = siteService; this.securityService = securityService; this.entityManager = entityManager; this.threadLocalManager = threadLocalManager; this.timeService = timeService; this.digestService = digestService; } /** * Construct. */ public SiteEmailNotificationRWiki(RWikiObjectService rwikiObjectService, RenderService renderService, PreferenceService preferenceService, SiteService siteService, SecurityService securityService, EntityManager entityManager, ThreadLocalManager threadLocalManager, TimeService timeService, DigestService digestService, String siteId) { super(siteId); this.renderService = renderService; this.rwikiObjectService = rwikiObjectService; this.preferenceService = preferenceService; this.siteService = siteService; this.securityService = securityService; this.entityManager = entityManager; this.threadLocalManager = threadLocalManager; this.timeService = timeService; this.digestService = digestService; } /** * @inheritDoc */ public NotificationAction getClone() { SiteEmailNotificationRWiki clone = new SiteEmailNotificationRWiki(rwikiObjectService, renderService, preferenceService, siteService, securityService, entityManager, threadLocalManager, timeService, digestService); clone.set(this); return clone; } protected String getSiteId(String context) { if (context.startsWith("/site/")) //$NON-NLS-1$ { context = context.substring("/site/".length()); //$NON-NLS-1$ } int il = context.indexOf("/"); //$NON-NLS-1$ if (il != -1) { context = context.substring(0, il); } return context; } /** * @inheritDoc */ protected String getMessage(Event event) { // get the content & properties Reference ref = entityManager.newReference(event.getResource()); ResourceProperties props = ref.getProperties(); // get the function // String function = event.getEvent(); // use either the configured site, or if not configured, the site // (context) of the resource String siteId = (getSite() != null) ? getSite() : getSiteId(ref.getContext()); // get a site title String title; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (IdUnusedException e) { title = siteId; } // get the URL and resource name. // StringBuffer buf = new StringBuffer(); String url = ref.getUrl() + "html"; //$NON-NLS-1$ String pageName = props.getProperty(RWikiEntity.RP_NAME); String realm = props.getProperty(RWikiEntity.RP_REALM); String localName = NameHelper.localizeName(pageName, realm); String user = props.getProperty(RWikiEntity.RP_USER); String moddate = new Date(Long.parseLong(props.getProperty(RWikiEntity.RP_VERSION))).toString(); String content = ""; //$NON-NLS-1$ try { RWikiEntity rwe = (RWikiEntity) rwikiObjectService.getEntity(ref); RWikiObject rwikiObject = rwe.getRWikiObject(); String pageSpace = NameHelper.localizeSpace(pageName, realm); ComponentPageLinkRenderImpl cplr = new ComponentPageLinkRenderImpl(pageSpace,true); content = renderService.renderPage(rwikiObject, pageSpace, cplr); content = DigestHtml.digest(content); if (content.length() > 1000) { content = content.substring(0, 1000); } } catch (Exception ex) { } String message = Messages.getString("SiteEmailNotificationRWiki.5") + title + Messages.getString("SiteEmailNotificationRWiki.6") //$NON-NLS-1$ //$NON-NLS-2$ + ServerConfigurationService.getString("ui.service", "Sakai") + " (" + ServerConfigurationService.getPortalUrl() //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ") " + " \n" + " \n" + Messages.getString("SiteEmailNotificationRWiki.13") + title + "\" > Wiki > " + localName + "\n" + Messages.getString("SiteEmailNotificationRWiki.16") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + moddate + "\n" + Messages.getString("SiteEmailNotificationRWiki.18") + user + "\n" + " \n" + " Page: " + localName + " " + url + " \n" + " \n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + Messages.getString("SiteEmailNotificationRWiki.4") + content + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ - log.error("Message is "+message); + log.debug("Message is "+message); return message; } protected String plainTextContent() { return getMessage(this.event); } /** * @inheritDoc */ protected List getHeaders(Event e) { List rv = super.getHeaders(e); Reference ref = entityManager.newReference(e.getResource()); ResourceProperties props = ref.getProperties(); String pageName = props.getProperty(RWikiEntity.RP_NAME); String realm = props.getProperty(RWikiEntity.RP_REALM); String localName = NameHelper.localizeName(pageName, realm); String subjectHeader = Messages.getString("SiteEmailNotificationRWiki.27") + localName + Messages.getString("SiteEmailNotificationRWiki.28"); //$NON-NLS-1$ //$NON-NLS-2$ // the Subject rv.add(subjectHeader); // from rv.add(getFrom(e)); // to rv.add(getTo(e)); return rv; } /** * @inheritDoc */ protected String getTag(String newline, String title) { // tag the message String rv = "----------------------\n" + Messages.getString("SiteEmailNotificationRWiki.30") //$NON-NLS-1$ //$NON-NLS-2$ + ServerConfigurationService.getString("ui.service", "Sakai") + " (" + ServerConfigurationService.getPortalUrl() //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + Messages.getString("SiteEmailNotificationRWiki.3") + title + Messages.getString("SiteEmailNotificationRWiki.35") //$NON-NLS-1$ //$NON-NLS-2$ + Messages.getString("SiteEmailNotificationRWiki.36"); //$NON-NLS-1$ /* * String rv = newline + "------" + newline + rb.getString("this") + " " + ServerConfigurationService.getString("ui.service", "Sakai") + " (" + ServerConfigurationService.getPortalUrl() + ") " + rb.getString("forthe") + " " + title + " " + * rb.getString("site") + newline + rb.getString("youcan") + newline; */ return rv; } protected int getOption(User user, Notification notification, Event event) { // FIXME I don't think this should be here, but it certainly shouldn't // be in preferenceService // We really want a entity reference to page name, without going via the // db! String resourceReference = event.getResource(); if (resourceReference == null || !resourceReference .startsWith(RWikiObjectService.REFERENCE_ROOT) || resourceReference.length() == RWikiObjectService.REFERENCE_ROOT .length()) { return NotificationService.PREF_IGNORE; } resourceReference = resourceReference.substring( RWikiObjectService.REFERENCE_ROOT.length(), resourceReference .lastIndexOf('.')); String preference = preferenceService.findPreferenceAt(user.getId(), resourceReference, PreferenceService.MAIL_NOTIFCIATION); if (preference == null || "".equals(preference)) //$NON-NLS-1$ { return NotificationService.PREF_IGNORE; } if (PreferenceService.NONE_PREFERENCE.equals(preference)) { return NotificationService.PREF_IGNORE; } if (PreferenceService.DIGEST_PREFERENCE.equals(preference)) { return NotificationService.PREF_DIGEST; } if (PreferenceService.SEPARATE_PREFERENCE.equals(preference)) { return NotificationService.PREF_IMMEDIATE; } return NotificationService.PREF_IGNORE; } /** * @inheritDoc */ protected List getRecipients(Event event) { // get the resource reference Reference ref = entityManager.newReference(event.getResource()); // use either the configured site, or if not configured, the site (context) of the resource String siteId = getSite(); if (siteId == null) { siteId = getSiteId(ref.getContext()); } // if the site is published, use the list of users who can SITE_VISIT the site, // else use the list of users who can SITE_VISIT_UNP the site. try { Site site = siteService.getSite(siteId); String ability = SiteService.SITE_VISIT; if (!site.isPublished()) { ability = SiteService.SITE_VISIT_UNPUBLISHED; } // get the list of users who can do the right kind of visit List users = securityService.unlockUsers(ability, ref.getReference()); // get the list of users who have the appropriate access to the resource if (getResourceAbility() != null) { List users2 = securityService.unlockUsers(getResourceAbility(), ref.getReference()); // find intersection of users and user2 users.retainAll(users2); } // add any other users addSpecialRecipients(users, ref); return users; } catch (Exception any) { log.error("Exception in getRecipients()", any); //$NON-NLS-1$ return new Vector(); } } }
true
true
protected String getMessage(Event event) { // get the content & properties Reference ref = entityManager.newReference(event.getResource()); ResourceProperties props = ref.getProperties(); // get the function // String function = event.getEvent(); // use either the configured site, or if not configured, the site // (context) of the resource String siteId = (getSite() != null) ? getSite() : getSiteId(ref.getContext()); // get a site title String title; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (IdUnusedException e) { title = siteId; } // get the URL and resource name. // StringBuffer buf = new StringBuffer(); String url = ref.getUrl() + "html"; //$NON-NLS-1$ String pageName = props.getProperty(RWikiEntity.RP_NAME); String realm = props.getProperty(RWikiEntity.RP_REALM); String localName = NameHelper.localizeName(pageName, realm); String user = props.getProperty(RWikiEntity.RP_USER); String moddate = new Date(Long.parseLong(props.getProperty(RWikiEntity.RP_VERSION))).toString(); String content = ""; //$NON-NLS-1$ try { RWikiEntity rwe = (RWikiEntity) rwikiObjectService.getEntity(ref); RWikiObject rwikiObject = rwe.getRWikiObject(); String pageSpace = NameHelper.localizeSpace(pageName, realm); ComponentPageLinkRenderImpl cplr = new ComponentPageLinkRenderImpl(pageSpace,true); content = renderService.renderPage(rwikiObject, pageSpace, cplr); content = DigestHtml.digest(content); if (content.length() > 1000) { content = content.substring(0, 1000); } } catch (Exception ex) { } String message = Messages.getString("SiteEmailNotificationRWiki.5") + title + Messages.getString("SiteEmailNotificationRWiki.6") //$NON-NLS-1$ //$NON-NLS-2$ + ServerConfigurationService.getString("ui.service", "Sakai") + " (" + ServerConfigurationService.getPortalUrl() //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ") " + " \n" + " \n" + Messages.getString("SiteEmailNotificationRWiki.13") + title + "\" > Wiki > " + localName + "\n" + Messages.getString("SiteEmailNotificationRWiki.16") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + moddate + "\n" + Messages.getString("SiteEmailNotificationRWiki.18") + user + "\n" + " \n" + " Page: " + localName + " " + url + " \n" + " \n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + Messages.getString("SiteEmailNotificationRWiki.4") + content + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ log.error("Message is "+message); return message; }
protected String getMessage(Event event) { // get the content & properties Reference ref = entityManager.newReference(event.getResource()); ResourceProperties props = ref.getProperties(); // get the function // String function = event.getEvent(); // use either the configured site, or if not configured, the site // (context) of the resource String siteId = (getSite() != null) ? getSite() : getSiteId(ref.getContext()); // get a site title String title; try { Site site = siteService.getSite(siteId); title = site.getTitle(); } catch (IdUnusedException e) { title = siteId; } // get the URL and resource name. // StringBuffer buf = new StringBuffer(); String url = ref.getUrl() + "html"; //$NON-NLS-1$ String pageName = props.getProperty(RWikiEntity.RP_NAME); String realm = props.getProperty(RWikiEntity.RP_REALM); String localName = NameHelper.localizeName(pageName, realm); String user = props.getProperty(RWikiEntity.RP_USER); String moddate = new Date(Long.parseLong(props.getProperty(RWikiEntity.RP_VERSION))).toString(); String content = ""; //$NON-NLS-1$ try { RWikiEntity rwe = (RWikiEntity) rwikiObjectService.getEntity(ref); RWikiObject rwikiObject = rwe.getRWikiObject(); String pageSpace = NameHelper.localizeSpace(pageName, realm); ComponentPageLinkRenderImpl cplr = new ComponentPageLinkRenderImpl(pageSpace,true); content = renderService.renderPage(rwikiObject, pageSpace, cplr); content = DigestHtml.digest(content); if (content.length() > 1000) { content = content.substring(0, 1000); } } catch (Exception ex) { } String message = Messages.getString("SiteEmailNotificationRWiki.5") + title + Messages.getString("SiteEmailNotificationRWiki.6") //$NON-NLS-1$ //$NON-NLS-2$ + ServerConfigurationService.getString("ui.service", "Sakai") + " (" + ServerConfigurationService.getPortalUrl() //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + ") " + " \n" + " \n" + Messages.getString("SiteEmailNotificationRWiki.13") + title + "\" > Wiki > " + localName + "\n" + Messages.getString("SiteEmailNotificationRWiki.16") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + moddate + "\n" + Messages.getString("SiteEmailNotificationRWiki.18") + user + "\n" + " \n" + " Page: " + localName + " " + url + " \n" + " \n" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + Messages.getString("SiteEmailNotificationRWiki.4") + content + "\n"; //$NON-NLS-1$ //$NON-NLS-2$ log.debug("Message is "+message); return message; }
diff --git a/cuke4duke/src/main/java/cuke4duke/internal/java/SpringFactory.java b/cuke4duke/src/main/java/cuke4duke/internal/java/SpringFactory.java index 579de9f0..8978a0a5 100644 --- a/cuke4duke/src/main/java/cuke4duke/internal/java/SpringFactory.java +++ b/cuke4duke/src/main/java/cuke4duke/internal/java/SpringFactory.java @@ -1,36 +1,36 @@ package cuke4duke.internal.java; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.ArrayList; import java.util.List; public class SpringFactory implements ObjectFactory { private final AbstractApplicationContext appContext; public SpringFactory() { String springXml = System.getProperty("cuke4duke.springXml", "cucumber.xml"); appContext = new ClassPathXmlApplicationContext(springXml); } public void dispose() { } @SuppressWarnings("unchecked") public Object getComponent(Class<?> type) { List beans = new ArrayList(appContext.getBeansOfType(type).values()); if(beans.size() == 1) { return beans.get(0); } else { - throw new RuntimeException("Found " + beans.size() + "Beans for class " + type + ". Expected exactly 1."); + throw new RuntimeException("Found " + beans.size() + " Beans for class " + type + ". Expected exactly 1."); } } public void addClass(Class<?> clazz) { } public void newWorld() { appContext.refresh(); } }
true
true
public Object getComponent(Class<?> type) { List beans = new ArrayList(appContext.getBeansOfType(type).values()); if(beans.size() == 1) { return beans.get(0); } else { throw new RuntimeException("Found " + beans.size() + "Beans for class " + type + ". Expected exactly 1."); } }
public Object getComponent(Class<?> type) { List beans = new ArrayList(appContext.getBeansOfType(type).values()); if(beans.size() == 1) { return beans.get(0); } else { throw new RuntimeException("Found " + beans.size() + " Beans for class " + type + ". Expected exactly 1."); } }
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/RoundedComposite.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/RoundedComposite.java index 4153da73e..e6e1bf099 100644 --- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/RoundedComposite.java +++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/RoundedComposite.java @@ -1,165 +1,165 @@ package de.fu_berlin.inf.dpp.ui.widgets; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import de.fu_berlin.inf.dpp.ui.util.PaintUtils; import de.fu_berlin.inf.dpp.util.ColorUtils; /** * Instances of this class are controls which are capable of containing other * controls. * <p> * The composite's content is surrounded by a rounded rectangle if a background * is set. * <p> * <img src="doc-files/RoundedComposite-1.png"/> * * <dl> * <dt><b>Styles:</b></dt> * <dd>SEPARATOR, BORDER, NO_BACKGROUND and those supported by Composite</dd> * <dt><b>Events:</b></dt> * <dd>(none)</dd> * </dl> * * <p> * Note: If you use SEPARATOR the content gets right aligned and the generated * space filled with a small horizontal line. * </p> * * <p> * This class may be subclassed by custom control implementors who are building * controls that are constructed from aggregates of other controls. * </p> * * @see Composite * @author bkahlert * */ public class RoundedComposite extends Composite { /** * style constants not passed to parent constructor */ protected static final int STYLES = SWT.SEPARATOR | SWT.BORDER | SWT.NO_BACKGROUND; protected int style; /** * Scale by which the background color's lightness should be modified for * use as the border color. */ private static final float BORDER_LIGHTNESS_SCALE = 0.85f; protected Color backgroundColor; protected Color borderColor; public RoundedComposite(Composite parent, final int style) { super(parent, style & ~STYLES); this.style = style & STYLES; /* * Checks whether to display a border */ this.style = style & ~SWT.BORDER; /* * Make sure child widgets respect transparency */ this.setBackgroundMode(SWT.INHERIT_DEFAULT); /* * Updates the rounded rectangle background. */ this.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (RoundedComposite.this.backgroundColor == null) return; Rectangle bounds = RoundedComposite.this.getBounds(); Rectangle clientArea = RoundedComposite.this.getClientArea(); /* * Draws the rounded background */ if ((style & SWT.NO_BACKGROUND) == 0) { PaintUtils.drawRoundedRectangle(e.gc, clientArea, RoundedComposite.this.backgroundColor); } /* * Draws the border */ if ((style & SWT.BORDER) != 0) { if (borderColor == null || borderColor.isDisposed()) borderColor = getDisplay().getSystemColor( SWT.COLOR_BLACK); - PaintUtils.drawRoundedBorder(e.gc, bounds, borderColor); + PaintUtils.drawRoundedBorder(e.gc, clientArea, borderColor); } /* * If the control shall be displayed as a separator, we draw a * horizontal line */ if ((style & SWT.SEPARATOR) != 0) { e.gc.setLineWidth(PaintUtils.LINE_WEIGHT); e.gc.setForeground(RoundedComposite.this.backgroundColor); int top = (bounds.height - PaintUtils.LINE_WEIGHT) / 2; e.gc.drawLine(PaintUtils.ARC / 2, top, bounds.width - PaintUtils.ARC / 2, top); } } }); /* * Set default layout */ this.setLayout(new FillLayout()); } @Override public Rectangle getClientArea() { Rectangle clientArea = super.getClientArea(); /* * If rendered as a separator compute the minimal width need width to * display the contents */ if ((style & SWT.SEPARATOR) != 0) { int neededWidth = this.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; int reduceBy = clientArea.width - neededWidth; clientArea.x += reduceBy; clientArea.width -= reduceBy; } return clientArea; } @Override public void setBackground(Color color) { this.backgroundColor = color; if (this.borderColor != null && !this.borderColor.isDisposed()) this.borderColor.dispose(); this.borderColor = ColorUtils.scaleColorBy(color, BORDER_LIGHTNESS_SCALE); this.redraw(); } @Override public Color getBackground() { return this.backgroundColor; } @Override public void dispose() { super.dispose(); if (this.borderColor != null && !this.borderColor.isDisposed()) { this.borderColor.dispose(); } } }
true
true
public RoundedComposite(Composite parent, final int style) { super(parent, style & ~STYLES); this.style = style & STYLES; /* * Checks whether to display a border */ this.style = style & ~SWT.BORDER; /* * Make sure child widgets respect transparency */ this.setBackgroundMode(SWT.INHERIT_DEFAULT); /* * Updates the rounded rectangle background. */ this.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (RoundedComposite.this.backgroundColor == null) return; Rectangle bounds = RoundedComposite.this.getBounds(); Rectangle clientArea = RoundedComposite.this.getClientArea(); /* * Draws the rounded background */ if ((style & SWT.NO_BACKGROUND) == 0) { PaintUtils.drawRoundedRectangle(e.gc, clientArea, RoundedComposite.this.backgroundColor); } /* * Draws the border */ if ((style & SWT.BORDER) != 0) { if (borderColor == null || borderColor.isDisposed()) borderColor = getDisplay().getSystemColor( SWT.COLOR_BLACK); PaintUtils.drawRoundedBorder(e.gc, bounds, borderColor); } /* * If the control shall be displayed as a separator, we draw a * horizontal line */ if ((style & SWT.SEPARATOR) != 0) { e.gc.setLineWidth(PaintUtils.LINE_WEIGHT); e.gc.setForeground(RoundedComposite.this.backgroundColor); int top = (bounds.height - PaintUtils.LINE_WEIGHT) / 2; e.gc.drawLine(PaintUtils.ARC / 2, top, bounds.width - PaintUtils.ARC / 2, top); } } }); /* * Set default layout */ this.setLayout(new FillLayout()); }
public RoundedComposite(Composite parent, final int style) { super(parent, style & ~STYLES); this.style = style & STYLES; /* * Checks whether to display a border */ this.style = style & ~SWT.BORDER; /* * Make sure child widgets respect transparency */ this.setBackgroundMode(SWT.INHERIT_DEFAULT); /* * Updates the rounded rectangle background. */ this.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (RoundedComposite.this.backgroundColor == null) return; Rectangle bounds = RoundedComposite.this.getBounds(); Rectangle clientArea = RoundedComposite.this.getClientArea(); /* * Draws the rounded background */ if ((style & SWT.NO_BACKGROUND) == 0) { PaintUtils.drawRoundedRectangle(e.gc, clientArea, RoundedComposite.this.backgroundColor); } /* * Draws the border */ if ((style & SWT.BORDER) != 0) { if (borderColor == null || borderColor.isDisposed()) borderColor = getDisplay().getSystemColor( SWT.COLOR_BLACK); PaintUtils.drawRoundedBorder(e.gc, clientArea, borderColor); } /* * If the control shall be displayed as a separator, we draw a * horizontal line */ if ((style & SWT.SEPARATOR) != 0) { e.gc.setLineWidth(PaintUtils.LINE_WEIGHT); e.gc.setForeground(RoundedComposite.this.backgroundColor); int top = (bounds.height - PaintUtils.LINE_WEIGHT) / 2; e.gc.drawLine(PaintUtils.ARC / 2, top, bounds.width - PaintUtils.ARC / 2, top); } } }); /* * Set default layout */ this.setLayout(new FillLayout()); }
diff --git a/filters/net.sf.okapi.filters.properties/src/net/sf/okapi/filters/properties/PropertiesFilter.java b/filters/net.sf.okapi.filters.properties/src/net/sf/okapi/filters/properties/PropertiesFilter.java index edab8d9cd..907d3e6ce 100644 --- a/filters/net.sf.okapi.filters.properties/src/net/sf/okapi/filters/properties/PropertiesFilter.java +++ b/filters/net.sf.okapi.filters.properties/src/net/sf/okapi/filters/properties/PropertiesFilter.java @@ -1,530 +1,533 @@ /*=========================================================================== Copyright (C) 2008-2009 by the Okapi Framework contributors ----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html ===========================================================================*/ package net.sf.okapi.filters.properties; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.URI; import java.util.LinkedList; import java.util.logging.Level; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.okapi.common.BOMAwareInputStream; import net.sf.okapi.common.Event; import net.sf.okapi.common.EventType; import net.sf.okapi.common.IParameters; import net.sf.okapi.common.Util; import net.sf.okapi.common.filters.IFilter; import net.sf.okapi.common.filters.IFilterWriter; import net.sf.okapi.common.resource.Ending; import net.sf.okapi.common.resource.Property; import net.sf.okapi.common.resource.StartDocument; import net.sf.okapi.common.resource.TextUnit; import net.sf.okapi.common.skeleton.GenericSkeleton; import net.sf.okapi.common.skeleton.GenericSkeletonWriter; import net.sf.okapi.common.skeleton.ISkeletonWriter; import net.sf.okapi.common.writer.GenericFilterWriter; /** * Implements the IFilter interface for properties files. */ public class PropertiesFilter implements IFilter { private static final int RESULT_END = 0; private static final int RESULT_ITEM = 1; private static final int RESULT_DATA = 2; private final Logger logger = LoggerFactory.getLogger("net.sf.okapi.logging"); private Parameters params; private BufferedReader reader; private boolean canceled; private String encoding; private TextUnit tuRes; private LinkedList<Event> queue; private String textLine; private int lineNumber; private int lineSince; private long position; private int tuId; private int otherId; private Pattern keyConditionPattern; private String lineBreak; private int parseState = 0; private GenericSkeleton skel; private String docName; private String srcLang; private boolean hasUTF8BOM; public PropertiesFilter () { params = new Parameters(); } public void cancel () { canceled = true; } public void close () { try { if ( reader != null ) { reader.close(); reader = null; docName = null; } parseState = 0; } catch ( IOException e) { throw new RuntimeException(e); } } public String getName () { return "okf_properties"; } public String getMimeType () { return "text/x-properties"; //TODO: check } public IParameters getParameters () { return params; } public boolean hasNext () { return (parseState > 0); } public Event next () { // Cancel if requested if ( canceled ) { parseState = 0; queue.clear(); queue.add(new Event(EventType.CANCELED)); } // Process queue if it's not empty yet if ( queue.size() > 0 ) { return queue.poll(); } // Continue the parsing int n; boolean resetBuffer = true; do { switch ( n = readItem(resetBuffer) ) { case RESULT_DATA: // Don't send the skeleton chunk now, wait for the complete one resetBuffer = false; break; case RESULT_ITEM: // It's a text-unit, the skeleton is already set return new Event(EventType.TEXT_UNIT, tuRes); default: resetBuffer = true; break; } } while ( n > RESULT_END ); // Set the ending call Ending ending = new Ending(String.valueOf(++otherId)); ending.setSkeleton(skel); parseState = 0; return new Event(EventType.END_DOCUMENT, ending); } public void open (InputStream input) { try { close(); parseState = 1; canceled = false; // Open the input reader from the provided stream BOMAwareInputStream bis = new BOMAwareInputStream(input, encoding); // Correct the encoding if we have detected a different one encoding = bis.detectEncoding(); hasUTF8BOM = bis.hasUTF8BOM(); commonOpen(new InputStreamReader(bis, encoding)); } catch ( IOException e ) { throw new RuntimeException(e); } } public void open (URI inputURI) { try { docName = inputURI.getPath(); open(inputURI.toURL().openStream()); } catch ( IOException e ) { throw new RuntimeException(e); } } public void open (CharSequence inputText) { encoding = "UTF-16"; hasUTF8BOM = false; commonOpen(new StringReader(inputText.toString())); } public void setOptions (String sourceLanguage, String targetLanguage, String defaultEncoding, boolean generateSkeleton) { //TODO: Implement boolean generateSkeleton encoding = defaultEncoding; srcLang = sourceLanguage; } public void setOptions (String sourceLanguage, String defaultEncoding, boolean generateSkeleton) { setOptions(sourceLanguage, null, defaultEncoding, generateSkeleton); } public void setParameters (IParameters params) { this.params = (Parameters)params; } public ISkeletonWriter createSkeletonWriter() { return new GenericSkeletonWriter(); } public IFilterWriter createFilterWriter () { return new GenericFilterWriter(createSkeletonWriter()); } private void commonOpen (Reader inputReader) { close(); parseState = 1; canceled = false; // Open the input reader from the provided reader reader = new BufferedReader(inputReader); // Initializes the variables tuId = 0; otherId = 0; lineBreak = System.getProperty("line.separator"); //TODO: Auto-detection of line-break type lineNumber = 0; lineSince = 0; position = 0; // Compile conditions if ( params.useKeyCondition ) { keyConditionPattern = Pattern.compile(params.keyCondition); } else { keyConditionPattern = null; } // Compile code finder rules if ( params.useCodeFinder ) { params.codeFinder.compile(); } // Set the start event queue = new LinkedList<Event>(); queue.add(new Event(EventType.START)); StartDocument startDoc = new StartDocument(String.valueOf(++otherId)); startDoc.setName(docName); startDoc.setEncoding(encoding, hasUTF8BOM); startDoc.setLanguage(srcLang); startDoc.setFilterParameters(params); startDoc.setLineBreak(lineBreak); startDoc.setType("text/x-properties"); startDoc.setMimeType("text/x-properties"); queue.add(new Event(EventType.START_DOCUMENT, startDoc)); } private int readItem (boolean resetBuffer) { try { if ( resetBuffer ) { skel = new GenericSkeleton(); } StringBuilder keyBuffer = new StringBuilder(); StringBuilder textBuffer = new StringBuilder(); String value = ""; String key = ""; boolean isMultiline = false; int startText = 0; long lS = -1; while ( true ) { if ( !getNextLine() ) { return RESULT_END; } // Else: process the line // Remove any leading white-spaces String tmp = Util.trimStart(textLine, "\t\r\n \f"); if ( isMultiline ) { value += tmp; } else { // Empty lines if ( tmp.length() == 0 ) { skel.append(textLine); skel.append(lineBreak); continue; } // Comments boolean isComment = (( tmp.charAt(0) == '#' ) || ( tmp.charAt(0) == '!' )); if ( params.extraComments && !isComment ) { if ( tmp.charAt(0) == ';' ) isComment = true; // .NET-style else if ( tmp.startsWith("//") ) isComment = true; // C++/Java-style, } if ( isComment ) { params.locDir.process(tmp); skel.append(textLine); skel.append(lineBreak); continue; } // Get the key boolean bEscape = false; int n = 0; for ( int i=0; i<tmp.length(); i++ ) { if ( bEscape ) bEscape = false; else { if ( tmp.charAt(i) == '\\' ) { bEscape = true; continue; } if (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ) || ( Character.isWhitespace(tmp.charAt(i)) )) { // That the first white-space after the key n = i; break; } } } // Get the key if ( n == 0 ) { // Line empty after the key n = tmp.length(); } key = tmp.substring(0, n); // Gets the value boolean bEmpty = true; boolean bCheckEqual = true; for ( int i=n; i<tmp.length(); i++ ) { if ( bCheckEqual && (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ))) { bCheckEqual = false; continue; } if ( !Character.isWhitespace(tmp.charAt(i)) ) { // That the first white-space after the key n = i; bEmpty = false; break; } } if ( bEmpty ) n = tmp.length(); value = tmp.substring(n); // Real text start point (adjusted for trimmed characters) startText = n + (textLine.length() - tmp.length()); // Use m_nLineSince-1 to not count the current one lS = (position-(textLine.length()+(lineSince-1))) + startText; lineSince = 0; // Reset the line counter for next time } // Is it a multi-lines entry? if ( value.endsWith("\\") ) { // Make sure we have an odd number of ending '\' int n = 0; for ( int i=value.length()-1; (( i > -1 ) && ( value.charAt(i) == '\\' )); i-- ) n++; if ( (n % 2) != 0 ) { // Continue onto the next line value = value.substring(0, value.length()-1); isMultiline = true; // Preserve parsed text in case we do not extract if ( keyBuffer.length() == 0 ) { keyBuffer.append(textLine.substring(0, startText)); startText = 0; // Next time we get the whole line } textBuffer.append(textLine.substring(startText)); continue; // Read next line } } // Check for key condition // Directives overwrite the key condition boolean extract = true; if ( params.locDir.isWithinScope() ) { extract = params.locDir.isLocalizable(true); } else { // Check for key condition if ( keyConditionPattern != null ) { if ( params.extractOnlyMatchingKey ) { if ( !keyConditionPattern.matcher(key).matches() ) extract = false; } else { // Extract all but items with matching keys if ( keyConditionPattern.matcher(key).matches() ) extract = false; } } + else { // Outside directive scope: check if we extract text outside + extract = params.locDir.localizeOutside(); + } } if ( extract ) { tuRes = new TextUnit(String.valueOf(++tuId), unescape(value)); tuRes.setName(key); tuRes.setMimeType("text/x-properties"); tuRes.setPreserveWhitespaces(true); } if ( extract ) { // Parts before the text if ( keyBuffer.length() == 0 ) { // Single-line case keyBuffer.append(textLine.substring(0, startText)); } skel.append(keyBuffer.toString()); skel.addContentPlaceholder(tuRes, null); // Line-break skel.append(lineBreak); } else { skel.append(keyBuffer.toString()); skel.append(textBuffer.toString()); skel.append(textLine); skel.append(lineBreak); return RESULT_DATA; } if ( params.useCodeFinder ) params.codeFinder.process(tuRes.getSourceContent()); tuRes.setSkeleton(skel); tuRes.setSourceProperty(new Property("start", String.valueOf(lS), true)); return RESULT_ITEM; } } catch ( IOException e ) { throw new RuntimeException(e); } } /** * Gets the next line of the string or file input. * @return True if there was a line to read, * false if this is the end of the input. */ private boolean getNextLine () throws IOException { while ( true ) { textLine = reader.readLine(); if ( textLine != null ) { lineNumber++; lineSince++; // We count char instead of byte, while the BaseStream.Length is in byte // Not perfect, but better than nothing. position += textLine.length() + lineBreak.length(); // +n For the line-break } return (textLine != null); } } /** * Un-escapes slash-u+HHHH characters in a string. * @param text The string to convert. * @return The converted string. */ //TODO: Deal with escape ctrl, etc. \n should be converted private String unescape (String text) { if ( text.indexOf('\\') == -1 ) return text; StringBuilder tmpText = new StringBuilder(); for ( int i=0; i<text.length(); i++ ) { if ( text.charAt(i) == '\\' ) { switch ( text.charAt(i+1) ) { case 'u': if ( i+5 < text.length() ) { try { int nTmp = Integer.parseInt(text.substring(i+2, i+6), 16); tmpText.append((char)nTmp); } catch ( Exception e ) { logMessage(Level.WARNING, String.format(Res.getString("INVALID_UESCAPE"), text.substring(i+2, i+6))); } i += 5; continue; } else { logMessage(Level.WARNING, String.format(Res.getString("INVALID_UESCAPE"), text.substring(i+2))); } break; case '\\': tmpText.append("\\\\"); i++; continue; case 'n': tmpText.append("\n"); i++; continue; case 't': tmpText.append("\t"); i++; continue; } } else tmpText.append(text.charAt(i)); } return tmpText.toString(); } private void logMessage (Level level, String text) { if ( level == Level.WARNING ) { logger.warn(String.format(Res.getString("LINE_LOCATION"), lineNumber) + text); } else if ( level == Level.SEVERE ) { logger.error(String.format(Res.getString("LINE_LOCATION"), lineNumber) + text); } else { logger.info(String.format(Res.getString("LINE_LOCATION"), lineNumber) + text); } } }
true
true
private int readItem (boolean resetBuffer) { try { if ( resetBuffer ) { skel = new GenericSkeleton(); } StringBuilder keyBuffer = new StringBuilder(); StringBuilder textBuffer = new StringBuilder(); String value = ""; String key = ""; boolean isMultiline = false; int startText = 0; long lS = -1; while ( true ) { if ( !getNextLine() ) { return RESULT_END; } // Else: process the line // Remove any leading white-spaces String tmp = Util.trimStart(textLine, "\t\r\n \f"); if ( isMultiline ) { value += tmp; } else { // Empty lines if ( tmp.length() == 0 ) { skel.append(textLine); skel.append(lineBreak); continue; } // Comments boolean isComment = (( tmp.charAt(0) == '#' ) || ( tmp.charAt(0) == '!' )); if ( params.extraComments && !isComment ) { if ( tmp.charAt(0) == ';' ) isComment = true; // .NET-style else if ( tmp.startsWith("//") ) isComment = true; // C++/Java-style, } if ( isComment ) { params.locDir.process(tmp); skel.append(textLine); skel.append(lineBreak); continue; } // Get the key boolean bEscape = false; int n = 0; for ( int i=0; i<tmp.length(); i++ ) { if ( bEscape ) bEscape = false; else { if ( tmp.charAt(i) == '\\' ) { bEscape = true; continue; } if (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ) || ( Character.isWhitespace(tmp.charAt(i)) )) { // That the first white-space after the key n = i; break; } } } // Get the key if ( n == 0 ) { // Line empty after the key n = tmp.length(); } key = tmp.substring(0, n); // Gets the value boolean bEmpty = true; boolean bCheckEqual = true; for ( int i=n; i<tmp.length(); i++ ) { if ( bCheckEqual && (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ))) { bCheckEqual = false; continue; } if ( !Character.isWhitespace(tmp.charAt(i)) ) { // That the first white-space after the key n = i; bEmpty = false; break; } } if ( bEmpty ) n = tmp.length(); value = tmp.substring(n); // Real text start point (adjusted for trimmed characters) startText = n + (textLine.length() - tmp.length()); // Use m_nLineSince-1 to not count the current one lS = (position-(textLine.length()+(lineSince-1))) + startText; lineSince = 0; // Reset the line counter for next time } // Is it a multi-lines entry? if ( value.endsWith("\\") ) { // Make sure we have an odd number of ending '\' int n = 0; for ( int i=value.length()-1; (( i > -1 ) && ( value.charAt(i) == '\\' )); i-- ) n++; if ( (n % 2) != 0 ) { // Continue onto the next line value = value.substring(0, value.length()-1); isMultiline = true; // Preserve parsed text in case we do not extract if ( keyBuffer.length() == 0 ) { keyBuffer.append(textLine.substring(0, startText)); startText = 0; // Next time we get the whole line } textBuffer.append(textLine.substring(startText)); continue; // Read next line } } // Check for key condition // Directives overwrite the key condition boolean extract = true; if ( params.locDir.isWithinScope() ) { extract = params.locDir.isLocalizable(true); } else { // Check for key condition if ( keyConditionPattern != null ) { if ( params.extractOnlyMatchingKey ) { if ( !keyConditionPattern.matcher(key).matches() ) extract = false; } else { // Extract all but items with matching keys if ( keyConditionPattern.matcher(key).matches() ) extract = false; } } } if ( extract ) { tuRes = new TextUnit(String.valueOf(++tuId), unescape(value)); tuRes.setName(key); tuRes.setMimeType("text/x-properties"); tuRes.setPreserveWhitespaces(true); } if ( extract ) { // Parts before the text if ( keyBuffer.length() == 0 ) { // Single-line case keyBuffer.append(textLine.substring(0, startText)); } skel.append(keyBuffer.toString()); skel.addContentPlaceholder(tuRes, null); // Line-break skel.append(lineBreak); } else { skel.append(keyBuffer.toString()); skel.append(textBuffer.toString()); skel.append(textLine); skel.append(lineBreak); return RESULT_DATA; } if ( params.useCodeFinder ) params.codeFinder.process(tuRes.getSourceContent()); tuRes.setSkeleton(skel); tuRes.setSourceProperty(new Property("start", String.valueOf(lS), true)); return RESULT_ITEM; } } catch ( IOException e ) { throw new RuntimeException(e); } }
private int readItem (boolean resetBuffer) { try { if ( resetBuffer ) { skel = new GenericSkeleton(); } StringBuilder keyBuffer = new StringBuilder(); StringBuilder textBuffer = new StringBuilder(); String value = ""; String key = ""; boolean isMultiline = false; int startText = 0; long lS = -1; while ( true ) { if ( !getNextLine() ) { return RESULT_END; } // Else: process the line // Remove any leading white-spaces String tmp = Util.trimStart(textLine, "\t\r\n \f"); if ( isMultiline ) { value += tmp; } else { // Empty lines if ( tmp.length() == 0 ) { skel.append(textLine); skel.append(lineBreak); continue; } // Comments boolean isComment = (( tmp.charAt(0) == '#' ) || ( tmp.charAt(0) == '!' )); if ( params.extraComments && !isComment ) { if ( tmp.charAt(0) == ';' ) isComment = true; // .NET-style else if ( tmp.startsWith("//") ) isComment = true; // C++/Java-style, } if ( isComment ) { params.locDir.process(tmp); skel.append(textLine); skel.append(lineBreak); continue; } // Get the key boolean bEscape = false; int n = 0; for ( int i=0; i<tmp.length(); i++ ) { if ( bEscape ) bEscape = false; else { if ( tmp.charAt(i) == '\\' ) { bEscape = true; continue; } if (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ) || ( Character.isWhitespace(tmp.charAt(i)) )) { // That the first white-space after the key n = i; break; } } } // Get the key if ( n == 0 ) { // Line empty after the key n = tmp.length(); } key = tmp.substring(0, n); // Gets the value boolean bEmpty = true; boolean bCheckEqual = true; for ( int i=n; i<tmp.length(); i++ ) { if ( bCheckEqual && (( tmp.charAt(i) == ':' ) || ( tmp.charAt(i) == '=' ))) { bCheckEqual = false; continue; } if ( !Character.isWhitespace(tmp.charAt(i)) ) { // That the first white-space after the key n = i; bEmpty = false; break; } } if ( bEmpty ) n = tmp.length(); value = tmp.substring(n); // Real text start point (adjusted for trimmed characters) startText = n + (textLine.length() - tmp.length()); // Use m_nLineSince-1 to not count the current one lS = (position-(textLine.length()+(lineSince-1))) + startText; lineSince = 0; // Reset the line counter for next time } // Is it a multi-lines entry? if ( value.endsWith("\\") ) { // Make sure we have an odd number of ending '\' int n = 0; for ( int i=value.length()-1; (( i > -1 ) && ( value.charAt(i) == '\\' )); i-- ) n++; if ( (n % 2) != 0 ) { // Continue onto the next line value = value.substring(0, value.length()-1); isMultiline = true; // Preserve parsed text in case we do not extract if ( keyBuffer.length() == 0 ) { keyBuffer.append(textLine.substring(0, startText)); startText = 0; // Next time we get the whole line } textBuffer.append(textLine.substring(startText)); continue; // Read next line } } // Check for key condition // Directives overwrite the key condition boolean extract = true; if ( params.locDir.isWithinScope() ) { extract = params.locDir.isLocalizable(true); } else { // Check for key condition if ( keyConditionPattern != null ) { if ( params.extractOnlyMatchingKey ) { if ( !keyConditionPattern.matcher(key).matches() ) extract = false; } else { // Extract all but items with matching keys if ( keyConditionPattern.matcher(key).matches() ) extract = false; } } else { // Outside directive scope: check if we extract text outside extract = params.locDir.localizeOutside(); } } if ( extract ) { tuRes = new TextUnit(String.valueOf(++tuId), unescape(value)); tuRes.setName(key); tuRes.setMimeType("text/x-properties"); tuRes.setPreserveWhitespaces(true); } if ( extract ) { // Parts before the text if ( keyBuffer.length() == 0 ) { // Single-line case keyBuffer.append(textLine.substring(0, startText)); } skel.append(keyBuffer.toString()); skel.addContentPlaceholder(tuRes, null); // Line-break skel.append(lineBreak); } else { skel.append(keyBuffer.toString()); skel.append(textBuffer.toString()); skel.append(textLine); skel.append(lineBreak); return RESULT_DATA; } if ( params.useCodeFinder ) params.codeFinder.process(tuRes.getSourceContent()); tuRes.setSkeleton(skel); tuRes.setSourceProperty(new Property("start", String.valueOf(lS), true)); return RESULT_ITEM; } } catch ( IOException e ) { throw new RuntimeException(e); } }
diff --git a/src/java/org/apache/hadoop/util/RunJar.java b/src/java/org/apache/hadoop/util/RunJar.java index 0f509c075..4e8adc910 100644 --- a/src/java/org/apache/hadoop/util/RunJar.java +++ b/src/java/org/apache/hadoop/util/RunJar.java @@ -1,157 +1,161 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.util; import java.util.jar.*; import java.lang.reflect.*; import java.net.URL; import java.net.URLClassLoader; import java.io.*; import java.util.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileUtil; /** Run a Hadoop job jar. */ public class RunJar { /** Unpack a jar file into a directory. */ public static void unJar(File jarFile, File toDir) throws IOException { JarFile jar = new JarFile(jarFile); try { Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); if (!entry.isDirectory()) { InputStream in = jar.getInputStream(entry); try { File file = new File(toDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { jar.close(); } } /** Run a Hadoop job jar. If the main class is not in the jar's manifest, * then it must be provided on the command line. */ public static void main(String[] args) throws Throwable { String usage = "RunJar jarFile [mainClass] args..."; if (args.length < 1) { System.err.println(usage); System.exit(-1); } int firstArg = 0; String fileName = args[firstArg++]; File file = new File(fileName); String mainClassName = null; JarFile jarFile; try { jarFile = new JarFile(fileName); } catch(IOException io) { throw new IOException("Error opening job jar: " + fileName) .initCause(io); } Manifest manifest = jarFile.getManifest(); if (manifest != null) { mainClassName = manifest.getMainAttributes().getValue("Main-Class"); } jarFile.close(); if (mainClassName == null) { if (args.length < 2) { System.err.println(usage); System.exit(-1); } mainClassName = args[firstArg++]; } mainClassName = mainClassName.replaceAll("/", "."); - final File workDir = File.createTempFile("hadoop-unjar","", - new File( new Configuration().get("hadoop.tmp.dir")) ); + File tmpDir = new File(new Configuration().get("hadoop.tmp.dir")); + tmpDir.mkdirs(); + if (!tmpDir.isDirectory()) { + System.err.println("Mkdirs failed to create " + tmpDir); + System.exit(-1); + } + final File workDir = File.createTempFile("hadoop-unjar", "", tmpDir ); workDir.delete(); - if (!workDir.mkdirs()) { - if (!workDir.isDirectory()) { - System.err.println("Mkdirs failed to create " + workDir.toString()); - System.exit(-1); - } + workDir.mkdirs(); + if (!workDir.isDirectory()) { + System.err.println("Mkdirs failed to create " + workDir); + System.exit(-1); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { FileUtil.fullyDelete(workDir); } catch (IOException e) { } } }); unJar(file, workDir); ArrayList classPath = new ArrayList(); classPath.add(new File(workDir+"/").toURL()); classPath.add(file.toURL()); classPath.add(new File(workDir, "classes/").toURL()); File[] libs = new File(workDir, "lib").listFiles(); if (libs != null) { for (int i = 0; i < libs.length; i++) { classPath.add(libs[i].toURL()); } } ClassLoader loader = new URLClassLoader((URL[])classPath.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(loader); Class mainClass = Class.forName(mainClassName, true, loader); Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() }); String[] newArgs = (String[])Arrays.asList(args) .subList(firstArg, args.length).toArray(new String[0]); try { main.invoke(null, new Object[] { newArgs }); } catch (InvocationTargetException e) { throw e.getTargetException(); } } }
false
true
public static void main(String[] args) throws Throwable { String usage = "RunJar jarFile [mainClass] args..."; if (args.length < 1) { System.err.println(usage); System.exit(-1); } int firstArg = 0; String fileName = args[firstArg++]; File file = new File(fileName); String mainClassName = null; JarFile jarFile; try { jarFile = new JarFile(fileName); } catch(IOException io) { throw new IOException("Error opening job jar: " + fileName) .initCause(io); } Manifest manifest = jarFile.getManifest(); if (manifest != null) { mainClassName = manifest.getMainAttributes().getValue("Main-Class"); } jarFile.close(); if (mainClassName == null) { if (args.length < 2) { System.err.println(usage); System.exit(-1); } mainClassName = args[firstArg++]; } mainClassName = mainClassName.replaceAll("/", "."); final File workDir = File.createTempFile("hadoop-unjar","", new File( new Configuration().get("hadoop.tmp.dir")) ); workDir.delete(); if (!workDir.mkdirs()) { if (!workDir.isDirectory()) { System.err.println("Mkdirs failed to create " + workDir.toString()); System.exit(-1); } } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { FileUtil.fullyDelete(workDir); } catch (IOException e) { } } }); unJar(file, workDir); ArrayList classPath = new ArrayList(); classPath.add(new File(workDir+"/").toURL()); classPath.add(file.toURL()); classPath.add(new File(workDir, "classes/").toURL()); File[] libs = new File(workDir, "lib").listFiles(); if (libs != null) { for (int i = 0; i < libs.length; i++) { classPath.add(libs[i].toURL()); } } ClassLoader loader = new URLClassLoader((URL[])classPath.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(loader); Class mainClass = Class.forName(mainClassName, true, loader); Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() }); String[] newArgs = (String[])Arrays.asList(args) .subList(firstArg, args.length).toArray(new String[0]); try { main.invoke(null, new Object[] { newArgs }); } catch (InvocationTargetException e) { throw e.getTargetException(); } }
public static void main(String[] args) throws Throwable { String usage = "RunJar jarFile [mainClass] args..."; if (args.length < 1) { System.err.println(usage); System.exit(-1); } int firstArg = 0; String fileName = args[firstArg++]; File file = new File(fileName); String mainClassName = null; JarFile jarFile; try { jarFile = new JarFile(fileName); } catch(IOException io) { throw new IOException("Error opening job jar: " + fileName) .initCause(io); } Manifest manifest = jarFile.getManifest(); if (manifest != null) { mainClassName = manifest.getMainAttributes().getValue("Main-Class"); } jarFile.close(); if (mainClassName == null) { if (args.length < 2) { System.err.println(usage); System.exit(-1); } mainClassName = args[firstArg++]; } mainClassName = mainClassName.replaceAll("/", "."); File tmpDir = new File(new Configuration().get("hadoop.tmp.dir")); tmpDir.mkdirs(); if (!tmpDir.isDirectory()) { System.err.println("Mkdirs failed to create " + tmpDir); System.exit(-1); } final File workDir = File.createTempFile("hadoop-unjar", "", tmpDir ); workDir.delete(); workDir.mkdirs(); if (!workDir.isDirectory()) { System.err.println("Mkdirs failed to create " + workDir); System.exit(-1); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { FileUtil.fullyDelete(workDir); } catch (IOException e) { } } }); unJar(file, workDir); ArrayList classPath = new ArrayList(); classPath.add(new File(workDir+"/").toURL()); classPath.add(file.toURL()); classPath.add(new File(workDir, "classes/").toURL()); File[] libs = new File(workDir, "lib").listFiles(); if (libs != null) { for (int i = 0; i < libs.length; i++) { classPath.add(libs[i].toURL()); } } ClassLoader loader = new URLClassLoader((URL[])classPath.toArray(new URL[0])); Thread.currentThread().setContextClassLoader(loader); Class mainClass = Class.forName(mainClassName, true, loader); Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() }); String[] newArgs = (String[])Arrays.asList(args) .subList(firstArg, args.length).toArray(new String[0]); try { main.invoke(null, new Object[] { newArgs }); } catch (InvocationTargetException e) { throw e.getTargetException(); } }
diff --git a/test/unit/org/apache/cassandra/db/compaction/LeveledCompactionStrategyTest.java b/test/unit/org/apache/cassandra/db/compaction/LeveledCompactionStrategyTest.java index 56f12deab..9392195ed 100644 --- a/test/unit/org/apache/cassandra/db/compaction/LeveledCompactionStrategyTest.java +++ b/test/unit/org/apache/cassandra/db/compaction/LeveledCompactionStrategyTest.java @@ -1,87 +1,87 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.compaction; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.Future; import org.junit.Test; import static org.junit.Assert.*; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.service.AntiEntropyService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; public class LeveledCompactionStrategyTest extends SchemaLoader { /* * This excercise in particular the code of #4142 */ @Test public void testValidationMultipleSSTablePerLevel() throws Exception { String ksname = "Keyspace1"; String cfname = "StandardLeveled"; Table table = Table.open(ksname); ColumnFamilyStore store = table.getColumnFamilyStore(cfname); ByteBuffer value = ByteBuffer.wrap(new byte[100 * 1024]); // 100 KB value, make it easy to have multiple files // Enough data to have a level 1 and 2 int rows = 20; int columns = 10; // Adds enough data to trigger multiple sstable per level for (int r = 0; r < rows; r++) { DecoratedKey key = Util.dk(String.valueOf(r)); RowMutation rm = new RowMutation(ksname, key.key); for (int c = 0; c < columns; c++) { rm.add(new QueryPath(cfname, null, ByteBufferUtil.bytes("column" + c)), value, 0); } rm.apply(); store.forceFlush(); } LeveledCompactionStrategy strat = (LeveledCompactionStrategy)store.getCompactionStrategy(); - while (strat.getLevelSize(0) > 0) + while (strat.getLevelSize(0) > 1) { store.forceMajorCompaction(); Thread.sleep(200); } // Checking we're not completely bad at math assert strat.getLevelSize(1) > 0; assert strat.getLevelSize(2) > 0; AntiEntropyService.CFPair p = new AntiEntropyService.CFPair(ksname, cfname); Range<Token> range = new Range<Token>(Util.token(""), Util.token("")); AntiEntropyService.TreeRequest req = new AntiEntropyService.TreeRequest("1", FBUtilities.getLocalAddress(), range, p); AntiEntropyService.Validator validator = new AntiEntropyService.Validator(req); CompactionManager.instance.submitValidation(store, validator).get(); } }
true
true
public void testValidationMultipleSSTablePerLevel() throws Exception { String ksname = "Keyspace1"; String cfname = "StandardLeveled"; Table table = Table.open(ksname); ColumnFamilyStore store = table.getColumnFamilyStore(cfname); ByteBuffer value = ByteBuffer.wrap(new byte[100 * 1024]); // 100 KB value, make it easy to have multiple files // Enough data to have a level 1 and 2 int rows = 20; int columns = 10; // Adds enough data to trigger multiple sstable per level for (int r = 0; r < rows; r++) { DecoratedKey key = Util.dk(String.valueOf(r)); RowMutation rm = new RowMutation(ksname, key.key); for (int c = 0; c < columns; c++) { rm.add(new QueryPath(cfname, null, ByteBufferUtil.bytes("column" + c)), value, 0); } rm.apply(); store.forceFlush(); } LeveledCompactionStrategy strat = (LeveledCompactionStrategy)store.getCompactionStrategy(); while (strat.getLevelSize(0) > 0) { store.forceMajorCompaction(); Thread.sleep(200); } // Checking we're not completely bad at math assert strat.getLevelSize(1) > 0; assert strat.getLevelSize(2) > 0; AntiEntropyService.CFPair p = new AntiEntropyService.CFPair(ksname, cfname); Range<Token> range = new Range<Token>(Util.token(""), Util.token("")); AntiEntropyService.TreeRequest req = new AntiEntropyService.TreeRequest("1", FBUtilities.getLocalAddress(), range, p); AntiEntropyService.Validator validator = new AntiEntropyService.Validator(req); CompactionManager.instance.submitValidation(store, validator).get(); }
public void testValidationMultipleSSTablePerLevel() throws Exception { String ksname = "Keyspace1"; String cfname = "StandardLeveled"; Table table = Table.open(ksname); ColumnFamilyStore store = table.getColumnFamilyStore(cfname); ByteBuffer value = ByteBuffer.wrap(new byte[100 * 1024]); // 100 KB value, make it easy to have multiple files // Enough data to have a level 1 and 2 int rows = 20; int columns = 10; // Adds enough data to trigger multiple sstable per level for (int r = 0; r < rows; r++) { DecoratedKey key = Util.dk(String.valueOf(r)); RowMutation rm = new RowMutation(ksname, key.key); for (int c = 0; c < columns; c++) { rm.add(new QueryPath(cfname, null, ByteBufferUtil.bytes("column" + c)), value, 0); } rm.apply(); store.forceFlush(); } LeveledCompactionStrategy strat = (LeveledCompactionStrategy)store.getCompactionStrategy(); while (strat.getLevelSize(0) > 1) { store.forceMajorCompaction(); Thread.sleep(200); } // Checking we're not completely bad at math assert strat.getLevelSize(1) > 0; assert strat.getLevelSize(2) > 0; AntiEntropyService.CFPair p = new AntiEntropyService.CFPair(ksname, cfname); Range<Token> range = new Range<Token>(Util.token(""), Util.token("")); AntiEntropyService.TreeRequest req = new AntiEntropyService.TreeRequest("1", FBUtilities.getLocalAddress(), range, p); AntiEntropyService.Validator validator = new AntiEntropyService.Validator(req); CompactionManager.instance.submitValidation(store, validator).get(); }
diff --git a/src/org/jimple/Jimple.java b/src/org/jimple/Jimple.java index 2636c46..17d9ff7 100644 --- a/src/org/jimple/Jimple.java +++ b/src/org/jimple/Jimple.java @@ -1,158 +1,158 @@ package org.jimple; /* * This file is part of Jimple. * * Copyright (c) 2013 Kuzmin Leonid * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.util.HashMap; /** * Jimple main class. * * @author Leonid Kuzmin */ public class Jimple extends HashMap<String, Object> { /** * Jimple Item */ public interface Item { public Object create(Jimple c); } /** * Jimple Item extender */ public interface Extender { public Object extend(Object object); } private class SimpleItem { private final Item item; private final Jimple c; private SimpleItem(Item item, Jimple c) { this.item = item; this.c = c; } protected Object create() { return this.item.create(this.c); } private Item getItem() { return item; } } private class SharedItem extends SimpleItem { private Object instance; private SharedItem(Item item, Jimple c) { super(item, c); } @Override protected Object create() { if (this.instance == null) { this.instance = super.create(); } return instance; } } private class ExtendedItem extends SimpleItem { private Extender extender; private ExtendedItem(Item item, Jimple c, Extender extender) { super(item, c); this.extender = extender; } @Override protected Object create() { return this.extender.extend(super.create()); } } /** * Returns a SharedItem that stores the result of the given Item for * uniqueness in the scope of this instance of Jimple. * * @param item A Item to wrap for uniqueness * @return The wrapped Item */ public SharedItem share(Item item) { return new SharedItem(item, this); } /** * Extends and Item definition * Useful when you want to extend an existing Item definition, * without necessarily loading that object. * * @param key The unique identifier for the Item * @param extender A Extender for the original * @return The wrapped Item * @throws IllegalArgumentException if the identifier is not defined */ public ExtendedItem extend(String key, Extender extender) { if (!super.containsKey(key)) { throw new IllegalArgumentException("Identifier " + key + " is not defined."); } Object item = super.get(key); if (item instanceof SimpleItem) { - return new ExtendedItem((Item) super.get(key), this, extender); + return new ExtendedItem((Item) this.raw(key), this, extender); } throw new IllegalArgumentException("Identifier " + key + " does not contain an object definition."); } @Override public Object get(Object key) { Object item = super.get(key); if (item instanceof SimpleItem) { item = ((SimpleItem) item).create(); } return item; } @Override public Object put(String key, Object value) { if (value instanceof Item) { value = new SimpleItem((Item) value, this); } return super.put(key, value); } /** * Gets a parameter or the Item defining an object. * * @param key The unique identifier for the parameter or object * @return The value of the parameter or the Item defining an object */ public Object raw(String key) { Object value = super.get(key); if (value instanceof SimpleItem) { value = ((SimpleItem) super.get(key)).getItem(); } return value; } }
true
true
public ExtendedItem extend(String key, Extender extender) { if (!super.containsKey(key)) { throw new IllegalArgumentException("Identifier " + key + " is not defined."); } Object item = super.get(key); if (item instanceof SimpleItem) { return new ExtendedItem((Item) super.get(key), this, extender); } throw new IllegalArgumentException("Identifier " + key + " does not contain an object definition."); }
public ExtendedItem extend(String key, Extender extender) { if (!super.containsKey(key)) { throw new IllegalArgumentException("Identifier " + key + " is not defined."); } Object item = super.get(key); if (item instanceof SimpleItem) { return new ExtendedItem((Item) this.raw(key), this, extender); } throw new IllegalArgumentException("Identifier " + key + " does not contain an object definition."); }
diff --git a/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscription.java b/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscription.java index 59c36ee68..441b0647f 100644 --- a/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscription.java +++ b/analytics/src/main/java/com/ning/billing/analytics/BusinessSubscription.java @@ -1,456 +1,456 @@ /* * Copyright 2010-2011 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.ning.billing.analytics; import com.ning.billing.analytics.utils.Rounder; import com.ning.billing.catalog.api.Catalog; import com.ning.billing.catalog.api.CatalogApiException; import com.ning.billing.catalog.api.Currency; import com.ning.billing.catalog.api.Duration; import com.ning.billing.catalog.api.Plan; import com.ning.billing.catalog.api.PlanPhase; import com.ning.billing.catalog.api.Product; import com.ning.billing.catalog.api.ProductCategory; import com.ning.billing.catalog.api.TimeUnit; import com.ning.billing.entitlement.api.user.Subscription; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.UUID; import static com.ning.billing.entitlement.api.user.Subscription.SubscriptionState; /** * Describe a subscription for Analytics purposes */ public class BusinessSubscription { private static final Logger log = LoggerFactory.getLogger(BusinessSubscription.class); private static final BigDecimal DAYS_IN_MONTH = BigDecimal.valueOf(30); private static final BigDecimal MONTHS_IN_YEAR = BigDecimal.valueOf(12); private static final Currency USD = Currency.valueOf("USD"); private final String productName; private final String productType; private final ProductCategory productCategory; private final String slug; private final String phase; private final String billingPeriod; private final BigDecimal price; private final String priceList; private final BigDecimal mrr; private final String currency; private final DateTime startDate; private final SubscriptionState state; private final UUID subscriptionId; private final UUID bundleId; public BusinessSubscription(final String productName, final String productType, final ProductCategory productCategory, final String slug, final String phase, final String billingPeriod, final BigDecimal price, final String priceList, final BigDecimal mrr, final String currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId) { this.productName = productName; this.productType = productType; this.productCategory = productCategory; this.slug = slug; this.phase = phase; this.billingPeriod = billingPeriod; this.price = price; this.priceList = priceList; this.mrr = mrr; this.currency = currency; this.startDate = startDate; this.state = state; this.subscriptionId = subscriptionId; this.bundleId = bundleId; } /** * For unit tests only. * <p/> * You can't really use this constructor in real life because the start date is likely not the one you want (you likely * want the phase start date). * * @param subscription Subscription to use as a model * @param currency Account currency */ BusinessSubscription(final Subscription subscription, final Currency currency, Catalog catalog) { this(subscription.getCurrentPriceList() == null ? null : subscription.getCurrentPriceList().getName(), subscription.getCurrentPlan().getName(), subscription.getCurrentPhase().getName(), currency, subscription.getStartDate(), subscription.getState(), subscription.getId(), subscription.getBundleId(), catalog); } public BusinessSubscription(final String priceList, final String currentPlan, final String currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId, Catalog catalog) { Plan thePlan = null; PlanPhase thePhase = null; try { - thePlan = catalog.findPlan(currentPlan, new DateTime(), startDate); - thePhase = catalog.findPhase(currentPhase, new DateTime(), startDate); + thePlan = (currentPlan != null) ? catalog.findPlan(currentPlan, new DateTime(), startDate) : null; + thePhase = (currentPhase != null) ? catalog.findPhase(currentPhase, new DateTime(), startDate) : null; } catch (CatalogApiException e) { log.error(String.format("Failed to retrieve Plan from catalog for plan %s, phase ", currentPlan, currentPhase)); } this.priceList = priceList; // Record plan information if (currentPlan != null && thePlan.getProduct() != null) { final Product product = thePlan.getProduct(); productName = product.getName(); productCategory = product.getCategory(); // TODO - we should keep the product type productType = product.getCatalogName(); } else { productName = null; productCategory = null; productType = null; } // Record phase information if (currentPhase != null) { slug = thePhase.getName(); if (thePhase.getPhaseType() != null) { phase = thePhase.getPhaseType().toString(); } else { phase = null; } if (thePhase.getBillingPeriod() != null) { billingPeriod = thePhase.getBillingPeriod().toString(); } else { billingPeriod = null; } if (thePhase.getRecurringPrice() != null) { //TODO check if this is the right way to handle exception BigDecimal tmpPrice = null; try { tmpPrice = thePhase.getRecurringPrice().getPrice(USD); } catch (CatalogApiException e) { tmpPrice = new BigDecimal(0); } price = tmpPrice; mrr = getMrrFromISubscription(thePhase.getDuration(), price); } else { price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } } else { slug = null; phase = null; billingPeriod = null; price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } if (currency != null) { this.currency = currency.toString(); } else { this.currency = null; } this.startDate = startDate; this.state = state; this.subscriptionId = subscriptionId; this.bundleId = bundleId; } public BusinessSubscription(final String priceList, final Plan currentPlan, final PlanPhase currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId) { this.priceList = priceList; // Record plan information if (currentPlan != null && currentPlan.getProduct() != null) { final Product product = currentPlan.getProduct(); productName = product.getName(); productCategory = product.getCategory(); // TODO - we should keep the product type productType = product.getCatalogName(); } else { productName = null; productCategory = null; productType = null; } // Record phase information if (currentPhase != null) { slug = currentPhase.getName(); if (currentPhase.getPhaseType() != null) { phase = currentPhase.getPhaseType().toString(); } else { phase = null; } if (currentPhase.getBillingPeriod() != null) { billingPeriod = currentPhase.getBillingPeriod().toString(); } else { billingPeriod = null; } if (currentPhase.getRecurringPrice() != null) { //TODO check if this is the right way to handle exception BigDecimal tmpPrice = null; try { tmpPrice = currentPhase.getRecurringPrice().getPrice(USD); } catch (CatalogApiException e) { tmpPrice = new BigDecimal(0); } price = tmpPrice; mrr = getMrrFromISubscription(currentPhase.getDuration(), price); } else { price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } } else { slug = null; phase = null; billingPeriod = null; price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } if (currency != null) { this.currency = currency.toString(); } else { this.currency = null; } this.startDate = startDate; this.state = state; this.subscriptionId = subscriptionId; this.bundleId = bundleId; } public String getBillingPeriod() { return billingPeriod; } public UUID getBundleId() { return bundleId; } public String getCurrency() { return currency; } public BigDecimal getMrr() { return mrr; } public double getRoundedMrr() { return Rounder.round(mrr); } public String getPhase() { return phase; } public BigDecimal getPrice() { return price; } public String getPriceList() { return priceList; } public double getRoundedPrice() { return Rounder.round(price); } public ProductCategory getProductCategory() { return productCategory; } public String getProductName() { return productName; } public String getProductType() { return productType; } public String getSlug() { return slug; } public DateTime getStartDate() { return startDate; } public SubscriptionState getState() { return state; } public UUID getSubscriptionId() { return subscriptionId; } static BigDecimal getMrrFromISubscription(final Duration duration, final BigDecimal price) { if (duration == null || duration.getUnit() == null || duration.getNumber() == 0) { return BigDecimal.ZERO; } if (duration.getUnit().equals(TimeUnit.UNLIMITED)) { return BigDecimal.ZERO; } else if (duration.getUnit().equals(TimeUnit.DAYS)) { return price.multiply(DAYS_IN_MONTH).multiply(BigDecimal.valueOf(duration.getNumber())); } else if (duration.getUnit().equals(TimeUnit.MONTHS)) { return price.divide(BigDecimal.valueOf(duration.getNumber()), Rounder.SCALE, BigDecimal.ROUND_HALF_UP); } else if (duration.getUnit().equals(TimeUnit.YEARS)) { return price.divide(BigDecimal.valueOf(duration.getNumber()), Rounder.SCALE, RoundingMode.HALF_UP).divide(MONTHS_IN_YEAR, Rounder.SCALE, RoundingMode.HALF_UP); } else { log.error("Unknown duration [" + duration + "], can't compute mrr"); return null; } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("BusinessSubscription"); sb.append("{billingPeriod='").append(billingPeriod).append('\''); sb.append(", productName='").append(productName).append('\''); sb.append(", productType='").append(productType).append('\''); sb.append(", productCategory=").append(productCategory); sb.append(", slug='").append(slug).append('\''); sb.append(", phase='").append(phase).append('\''); sb.append(", price=").append(price); sb.append(", priceList=").append(priceList); sb.append(", mrr=").append(mrr); sb.append(", currency='").append(currency).append('\''); sb.append(", startDate=").append(startDate); sb.append(", state=").append(state); sb.append(", subscriptionId=").append(subscriptionId); sb.append(", bundleId=").append(bundleId); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final BusinessSubscription that = (BusinessSubscription) o; if (billingPeriod != null ? !billingPeriod.equals(that.billingPeriod) : that.billingPeriod != null) { return false; } if (bundleId != null ? !bundleId.equals(that.bundleId) : that.bundleId != null) { return false; } if (currency != null ? !currency.equals(that.currency) : that.currency != null) { return false; } if (mrr != null ? !(Rounder.round(mrr) == Rounder.round(that.mrr)) : that.mrr != null) { return false; } if (phase != null ? !phase.equals(that.phase) : that.phase != null) { return false; } if (price != null ? !(Rounder.round(price) == Rounder.round(that.price)) : that.price != null) { return false; } if (priceList != null ? !priceList.equals(that.priceList) : that.priceList != null) { return false; } if (productCategory != null ? !productCategory.equals(that.productCategory) : that.productCategory != null) { return false; } if (productName != null ? !productName.equals(that.productName) : that.productName != null) { return false; } if (productType != null ? !productType.equals(that.productType) : that.productType != null) { return false; } if (slug != null ? !slug.equals(that.slug) : that.slug != null) { return false; } if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) { return false; } if (state != that.state) { return false; } if (subscriptionId != null ? !subscriptionId.equals(that.subscriptionId) : that.subscriptionId != null) { return false; } return true; } @Override public int hashCode() { int result = productName != null ? productName.hashCode() : 0; result = 31 * result + (productType != null ? productType.hashCode() : 0); result = 31 * result + (productCategory != null ? productCategory.hashCode() : 0); result = 31 * result + (slug != null ? slug.hashCode() : 0); result = 31 * result + (phase != null ? phase.hashCode() : 0); result = 31 * result + (price != null ? price.hashCode() : 0); result = 31 * result + (priceList != null ? priceList.hashCode() : 0); result = 31 * result + (mrr != null ? mrr.hashCode() : 0); result = 31 * result + (currency != null ? currency.hashCode() : 0); result = 31 * result + (startDate != null ? startDate.hashCode() : 0); result = 31 * result + (state != null ? state.hashCode() : 0); result = 31 * result + (subscriptionId != null ? subscriptionId.hashCode() : 0); result = 31 * result + (bundleId != null ? bundleId.hashCode() : 0); result = 31 * result + (billingPeriod != null ? billingPeriod.hashCode() : 0); return result; } }
true
true
public BusinessSubscription(final String priceList, final String currentPlan, final String currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId, Catalog catalog) { Plan thePlan = null; PlanPhase thePhase = null; try { thePlan = catalog.findPlan(currentPlan, new DateTime(), startDate); thePhase = catalog.findPhase(currentPhase, new DateTime(), startDate); } catch (CatalogApiException e) { log.error(String.format("Failed to retrieve Plan from catalog for plan %s, phase ", currentPlan, currentPhase)); } this.priceList = priceList; // Record plan information if (currentPlan != null && thePlan.getProduct() != null) { final Product product = thePlan.getProduct(); productName = product.getName(); productCategory = product.getCategory(); // TODO - we should keep the product type productType = product.getCatalogName(); } else { productName = null; productCategory = null; productType = null; } // Record phase information if (currentPhase != null) { slug = thePhase.getName(); if (thePhase.getPhaseType() != null) { phase = thePhase.getPhaseType().toString(); } else { phase = null; } if (thePhase.getBillingPeriod() != null) { billingPeriod = thePhase.getBillingPeriod().toString(); } else { billingPeriod = null; } if (thePhase.getRecurringPrice() != null) { //TODO check if this is the right way to handle exception BigDecimal tmpPrice = null; try { tmpPrice = thePhase.getRecurringPrice().getPrice(USD); } catch (CatalogApiException e) { tmpPrice = new BigDecimal(0); } price = tmpPrice; mrr = getMrrFromISubscription(thePhase.getDuration(), price); } else { price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } } else { slug = null; phase = null; billingPeriod = null; price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } if (currency != null) { this.currency = currency.toString(); } else { this.currency = null; } this.startDate = startDate; this.state = state; this.subscriptionId = subscriptionId; this.bundleId = bundleId; }
public BusinessSubscription(final String priceList, final String currentPlan, final String currentPhase, final Currency currency, final DateTime startDate, final SubscriptionState state, final UUID subscriptionId, final UUID bundleId, Catalog catalog) { Plan thePlan = null; PlanPhase thePhase = null; try { thePlan = (currentPlan != null) ? catalog.findPlan(currentPlan, new DateTime(), startDate) : null; thePhase = (currentPhase != null) ? catalog.findPhase(currentPhase, new DateTime(), startDate) : null; } catch (CatalogApiException e) { log.error(String.format("Failed to retrieve Plan from catalog for plan %s, phase ", currentPlan, currentPhase)); } this.priceList = priceList; // Record plan information if (currentPlan != null && thePlan.getProduct() != null) { final Product product = thePlan.getProduct(); productName = product.getName(); productCategory = product.getCategory(); // TODO - we should keep the product type productType = product.getCatalogName(); } else { productName = null; productCategory = null; productType = null; } // Record phase information if (currentPhase != null) { slug = thePhase.getName(); if (thePhase.getPhaseType() != null) { phase = thePhase.getPhaseType().toString(); } else { phase = null; } if (thePhase.getBillingPeriod() != null) { billingPeriod = thePhase.getBillingPeriod().toString(); } else { billingPeriod = null; } if (thePhase.getRecurringPrice() != null) { //TODO check if this is the right way to handle exception BigDecimal tmpPrice = null; try { tmpPrice = thePhase.getRecurringPrice().getPrice(USD); } catch (CatalogApiException e) { tmpPrice = new BigDecimal(0); } price = tmpPrice; mrr = getMrrFromISubscription(thePhase.getDuration(), price); } else { price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } } else { slug = null; phase = null; billingPeriod = null; price = BigDecimal.ZERO; mrr = BigDecimal.ZERO; } if (currency != null) { this.currency = currency.toString(); } else { this.currency = null; } this.startDate = startDate; this.state = state; this.subscriptionId = subscriptionId; this.bundleId = bundleId; }
diff --git a/src/com/example/gpstracker/Data.java b/src/com/example/gpstracker/Data.java index b72bf8b..72e7297 100644 --- a/src/com/example/gpstracker/Data.java +++ b/src/com/example/gpstracker/Data.java @@ -1,64 +1,65 @@ package com.example.gpstracker; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class Data { public static String login = "sygi"; public static String password = "?"; private static int lastSent = -1; public static ArrayList<Pin> pos = new ArrayList<Pin>(); public static void sendTo(String host){ JSONObject json = new JSONObject(); try { json.put("login", login); json.put("passwd", password); //TODO check if there's anything to send JSONArray p = new JSONArray(); for(int j = lastSent + 1; j < pos.size(); j++){ p.put(pos.get(j).toJson()); } json.put("positions", p); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringEntity se = null; try { se = new StringEntity(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //obiekt json i StringEntity utworzone HttpPost post = new HttpPost(host); post.setEntity(se); HttpClient client = new DefaultHttpClient(); try { Log.d("sygi", "sending"); client.execute(post); + lastSent = pos.size() - 1; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
public static void sendTo(String host){ JSONObject json = new JSONObject(); try { json.put("login", login); json.put("passwd", password); //TODO check if there's anything to send JSONArray p = new JSONArray(); for(int j = lastSent + 1; j < pos.size(); j++){ p.put(pos.get(j).toJson()); } json.put("positions", p); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringEntity se = null; try { se = new StringEntity(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //obiekt json i StringEntity utworzone HttpPost post = new HttpPost(host); post.setEntity(se); HttpClient client = new DefaultHttpClient(); try { Log.d("sygi", "sending"); client.execute(post); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static void sendTo(String host){ JSONObject json = new JSONObject(); try { json.put("login", login); json.put("passwd", password); //TODO check if there's anything to send JSONArray p = new JSONArray(); for(int j = lastSent + 1; j < pos.size(); j++){ p.put(pos.get(j).toJson()); } json.put("positions", p); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringEntity se = null; try { se = new StringEntity(json.toString()); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //obiekt json i StringEntity utworzone HttpPost post = new HttpPost(host); post.setEntity(se); HttpClient client = new DefaultHttpClient(); try { Log.d("sygi", "sending"); client.execute(post); lastSent = pos.size() - 1; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/bundles/org.eclipselabs.emongo.components/src/org/eclipselabs/emongo/components/MongoDatabaseConfigurationProviderComponent.java b/bundles/org.eclipselabs.emongo.components/src/org/eclipselabs/emongo/components/MongoDatabaseConfigurationProviderComponent.java index 44300a1..4853834 100644 --- a/bundles/org.eclipselabs.emongo.components/src/org/eclipselabs/emongo/components/MongoDatabaseConfigurationProviderComponent.java +++ b/bundles/org.eclipselabs.emongo.components/src/org/eclipselabs/emongo/components/MongoDatabaseConfigurationProviderComponent.java @@ -1,75 +1,75 @@ /******************************************************************************* * Copyright (c) 2012 Bryan Hunt. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bryan Hunt - initial API and implementation *******************************************************************************/ package org.eclipselabs.emongo.components; import java.util.Map; /** * @author bhunt * */ public class MongoDatabaseConfigurationProviderComponent extends AbstractComponent implements MongoAuthenticatedDatabaseConfigurationProvider { private volatile String alias; private volatile String databaseName; private volatile String clientId; private volatile String user; private volatile String password; public void activate(Map<String, Object> properties) { alias = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_ALIAS); clientId = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_CLIENT_ID); databaseName = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_DATABASE); user = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_USER); password = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_PASSWORD); if (alias == null || alias.isEmpty()) handleIllegalConfiguration("The database alias was not found in the configuration properties"); if (clientId == null || clientId.isEmpty()) handleIllegalConfiguration("The MongoDB client id was not found in the configuration properties"); if (databaseName == null || databaseName.isEmpty()) - handleIllegalConfiguration("The MongoDB client id was not found in the configuration properties"); + handleIllegalConfiguration("The MongoDB database name was not found in the configuration properties"); } @Override public String getAlias() { return alias; } @Override public String getDatabaseName() { return databaseName; } @Override public String getClientId() { return clientId; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } }
true
true
public void activate(Map<String, Object> properties) { alias = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_ALIAS); clientId = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_CLIENT_ID); databaseName = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_DATABASE); user = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_USER); password = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_PASSWORD); if (alias == null || alias.isEmpty()) handleIllegalConfiguration("The database alias was not found in the configuration properties"); if (clientId == null || clientId.isEmpty()) handleIllegalConfiguration("The MongoDB client id was not found in the configuration properties"); if (databaseName == null || databaseName.isEmpty()) handleIllegalConfiguration("The MongoDB client id was not found in the configuration properties"); }
public void activate(Map<String, Object> properties) { alias = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_ALIAS); clientId = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_CLIENT_ID); databaseName = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_DATABASE); user = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_USER); password = (String) properties.get(MongoAuthenticatedDatabaseConfigurationProvider.PROP_PASSWORD); if (alias == null || alias.isEmpty()) handleIllegalConfiguration("The database alias was not found in the configuration properties"); if (clientId == null || clientId.isEmpty()) handleIllegalConfiguration("The MongoDB client id was not found in the configuration properties"); if (databaseName == null || databaseName.isEmpty()) handleIllegalConfiguration("The MongoDB database name was not found in the configuration properties"); }
diff --git a/src/com/zavteam/plugins/Commands.java b/src/com/zavteam/plugins/Commands.java index 39f030b..b0f6c48 100644 --- a/src/com/zavteam/plugins/Commands.java +++ b/src/com/zavteam/plugins/Commands.java @@ -1,262 +1,264 @@ package com.zavteam.plugins; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.ChatPaginator; import com.zavteam.plugins.messageshandler.MessagesHandler; public class Commands implements CommandExecutor { private final static String noPerm = ChatColor.RED + "You do not have permission to do this."; public ZavAutoMessager plugin; public Commands(ZavAutoMessager instance) { plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; + plugin.mainConfig.saveConfig(); + plugin.ignoreConfig.saveConfig(); plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); cutBroadcastList = ChatPaginator.wordWrap(cutBroadcastList[0], 53); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); cutBroadcastList = ChatPaginator.wordWrap(cutBroadcastList[0], 53); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String freeVariable; if (args.length == 0 || args[0].equalsIgnoreCase("help")) { if (sender.hasPermission("zavautomessager.view")) { if (args.length == 1 || args.length == 0) { MessagesHandler.listHelpPage(1, sender); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You need to enter a valid page number to do this."); } if (Integer.parseInt(args[1]) > 0 && Integer.parseInt(args[1]) < 4) { MessagesHandler.listHelpPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(ChatColor.RED + "That is not a valid page number"); } } } else { sender.sendMessage(noPerm); } } else if (args.length >= 1) { if (args[0].equalsIgnoreCase("reload")) { if (sender.hasPermission("zavautomessager.reload")) { plugin.messageIt = 0; plugin.mainConfig.saveConfig(); plugin.ignoreConfig.saveConfig(); plugin.autoReload(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager's config has been reloaded."); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("on")) { if (sender.hasPermission("zavautomessager.toggle")) { if ((Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already enabled"); } else { plugin.mainConfig.set("enabled", true); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now on"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("off")) { if (sender.hasPermission("zavautomessager.toggle")) { if (!(Boolean) plugin.mainConfig.get("enabled", true)) { sender.sendMessage(ChatColor.RED + "Messages are already disabled"); } else { plugin.mainConfig.set("enabled", false); plugin.mainConfig.saveConfig(); sender.sendMessage(ChatColor.GREEN + "ZavAutoMessager is now off"); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("add")) { if (sender.hasPermission("zavautomessager.add")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a chat message to add."); } else { freeVariable = ""; for (int i = 1; i < args.length; i++) { freeVariable = freeVariable + args[i] + " "; } freeVariable = freeVariable.trim(); plugin.messageIt = 0; plugin.MessagesHandler.addMessage(freeVariable); sender.sendMessage(ChatColor.GREEN + "Your message has been added to the message list."); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("ignore")) { if (sender instanceof Player) { if (sender.hasPermission("zavautomessager.ignore")) { List<String> ignorePlayers = new ArrayList<String>(); ignorePlayers = plugin.ignoreConfig.getConfig().getStringList("players"); if (ignorePlayers.contains(sender.getName())) { ignorePlayers.remove(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are no longer ignoring automatic messages"); } else { ignorePlayers.add(sender.getName()); sender.sendMessage(ChatColor.GREEN + "You are now ignoring automatic messages"); } plugin.ignoreConfig.set("players", ignorePlayers); plugin.ignoreConfig.saveConfig(); } else { sender.sendMessage(noPerm); } } else { ZavAutoMessager.log.info("The console cannot use this command."); } } else if (args[0].equalsIgnoreCase("broadcast")) { String[] cutBroadcastList = new String[10]; if (sender.hasPermission("zavautomessager.broadcast")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You must enter a broadcast message"); } else { cutBroadcastList[0] = ""; for (int i = 1; i < args.length; i++) { cutBroadcastList[0] = cutBroadcastList[0] + args[i] + " "; } cutBroadcastList[0] = cutBroadcastList[0].trim(); cutBroadcastList[0] = ((String) plugin.mainConfig.get("chatformat", "[&6AutoMessager&f]: %msg")).replace("%msg", cutBroadcastList[0]); cutBroadcastList[0] = cutBroadcastList[0].replace("&", "\u00A7"); cutBroadcastList = ChatPaginator.wordWrap(cutBroadcastList[0], 53); plugin.MessagesHandler.handleChatMessage(cutBroadcastList, null); } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("about")) { if (sender.hasPermission("zavautomessager.about")) { sender.sendMessage(ChatColor.GOLD + "You are currently running ZavAutoMessage Version " + plugin.getDescription().getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "The latest version is currently version " + plugin.VersionConfig.getVersion() + "."); sender.sendMessage(ChatColor.GOLD + "This plugin was developed by the ZavCodingTeam."); sender.sendMessage(ChatColor.GOLD + "Please visit our Bukkit Dev Page for complete details on this plugin."); sender.sendMessage(ChatColor.GOLD + "http://dev.bukkit.org/server-mods/zavautomessager/"); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("remove")) { if (sender.hasPermission("zavautomessager.remove")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "You need to enter a message number to delete."); } else { try { Integer.parseInt(args[1]); } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + "You have to enter a round number to remove."); return false; } if (Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > plugin.messages.size() || plugin.messages.size() == 1) { sender.sendMessage(ChatColor.RED + "This is not a valid message number"); sender.sendMessage(ChatColor.RED + "Use /automessager list for a list of messages"); } else { plugin.messages.remove(Integer.parseInt(args[1]) - 1); sender.sendMessage(ChatColor.GREEN + "Your message has been removed."); Map<String, List<String>> list = new HashMap<String, List<String>>(); for (ChatMessage cm : plugin.messages) { if (list.containsKey(cm.getPermission())) { list.get(cm.getPermission()).add(cm.getMessage()); } else { List<String> mList = new ArrayList<String>(); mList.add(cm.getMessage()); list.put(cm.getPermission(), mList); } } plugin.mainConfig.set("messages", list); plugin.mainConfig.saveConfig(); plugin.messageIt = 0; plugin.autoReload(); } } } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("list")) { if (sender.hasPermission("zavautomessager.list")) { if (args.length < 2) { plugin.MessagesHandler.listPage(1, sender); return true; } try { plugin.messages.get((5 * Integer.parseInt(args[1])) - 5); } catch (IndexOutOfBoundsException e) { sender.sendMessage(ChatColor.RED + "You do not have that any messages on that page"); return false; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "You have to enter an invalid number to show help page."); return false; } plugin.MessagesHandler.listPage(Integer.parseInt(args[1]), sender); } else { sender.sendMessage(noPerm); } } else if (args[0].equalsIgnoreCase("set")) { if (sender.hasPermission("zavautomessager.set")) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + "A minimum of two parameters are required to set any configuration section."); return false; } if (ConfigSection.contains(args[1].toUpperCase())) { Boolean b = false; switch (ConfigSection.valueOf(args[1].toUpperCase())) { case DONTREPEATRANDOMMESSAGES:// Intentional fallthrough since all are pretty much the same case ENABLED: case MESSAGEINRANDOMORDER: case MESSAGESINCONSOLE: case PERMISSIONSENABLED: case REQUIREPLAYERSONLINE: case UPDATECHECKING: case WORDWRAP: try { plugin.mainConfig.set(args[1].toLowerCase(), Boolean.parseBoolean(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of boolean (true or false)."); } break; case DELAY: try { plugin.mainConfig.set(args[1].toLowerCase(), Integer.parseInt(args[2])); b = true; } catch (Exception e) { sender.sendMessage(ChatColor.RED + "These Config Sections require the type of Integer."); } break; default: break; } if (b) { sender.sendMessage(ChatColor.GOLD + args[1] + " has been set to " + args[2] + "."); } plugin.autoReload(); return true; } else if (args[1].equalsIgnoreCase("list")) { String s = ""; for (ConfigSection cs : ConfigSection.values()) { s = s + " " + cs.name().toLowerCase(); } s = s + "."; s = s.trim(); sender.sendMessage(ChatColor.GOLD + "Config Sections: " + s); } else { sender.sendMessage(ChatColor.RED + "That is an invalid configuration section"); return false; } } else { sender.sendMessage(noPerm); } } else { sender.sendMessage(ChatColor.RED + "ZavAutoMessager did not recognize this command."); sender.sendMessage(ChatColor.RED + "Use /automessager help to get a list of commands!"); } } return false; }
diff --git a/test/com/facebook/buck/testutil/RuleMap.java b/test/com/facebook/buck/testutil/RuleMap.java index a318c07e14..05236fb741 100644 --- a/test/com/facebook/buck/testutil/RuleMap.java +++ b/test/com/facebook/buck/testutil/RuleMap.java @@ -1,49 +1,50 @@ /* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.testutil; import com.facebook.buck.graph.MutableDirectedGraph; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DependencyGraph; import com.google.common.collect.ImmutableList; public class RuleMap { /** Utility class: do not instantiate. */ private RuleMap() {} public static DependencyGraph createGraphFromBuildRules(BuildRuleResolver params) { Iterable<BuildRule> rules = params.getBuildRules(); return createGraphFromBuildRules(rules); } public static DependencyGraph createGraphFromSingleRule(BuildRule buildRule) { return createGraphFromBuildRules(ImmutableList.of(buildRule)); } private static DependencyGraph createGraphFromBuildRules(Iterable<BuildRule> rules) { MutableDirectedGraph<BuildRule> graph = new MutableDirectedGraph<BuildRule>(); for (BuildRule rule : rules) { + graph.addNode(rule); for (BuildRule dep : rule.getDeps()) { graph.addEdge(rule, dep); } } return new DependencyGraph(graph); } }
true
true
private static DependencyGraph createGraphFromBuildRules(Iterable<BuildRule> rules) { MutableDirectedGraph<BuildRule> graph = new MutableDirectedGraph<BuildRule>(); for (BuildRule rule : rules) { for (BuildRule dep : rule.getDeps()) { graph.addEdge(rule, dep); } } return new DependencyGraph(graph); }
private static DependencyGraph createGraphFromBuildRules(Iterable<BuildRule> rules) { MutableDirectedGraph<BuildRule> graph = new MutableDirectedGraph<BuildRule>(); for (BuildRule rule : rules) { graph.addNode(rule); for (BuildRule dep : rule.getDeps()) { graph.addEdge(rule, dep); } } return new DependencyGraph(graph); }
diff --git a/src/net/slipcor/pvparena/command/PAAInfo.java b/src/net/slipcor/pvparena/command/PAAInfo.java index c786f496..b62ff172 100644 --- a/src/net/slipcor/pvparena/command/PAAInfo.java +++ b/src/net/slipcor/pvparena/command/PAAInfo.java @@ -1,265 +1,265 @@ package net.slipcor.pvparena.command; import java.util.HashMap; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaClass; import net.slipcor.pvparena.arena.ArenaTeam; import net.slipcor.pvparena.core.StringParser; import net.slipcor.pvparena.neworder.ArenaRegion; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; public class PAAInfo extends PAA_Command { @Override public void commit(Arena arena, CommandSender player, String[] args) { String type = arena.type().getName(); player.sendMessage("-----------------------------------------------------"); player.sendMessage("Arena Information about: " + ChatColor.AQUA + arena.name + "�f | [�a"+ arena.prefix +"�f]"); player.sendMessage("-----------------------------------------------------"); player.sendMessage("GameMode: " + ChatColor.AQUA + type + ChatColor.WHITE + " || " + "Teams: " + colorTeams(arena)); player.sendMessage("Classes: " + listClasses(arena)); player.sendMessage(""); player.sendMessage("�bRuntime:�f "+ StringParser.colorVar("Enabled", arena.cfg.getBoolean("general.enabled")) + " || " + StringParser.colorVar("EditMode", arena.edit) + " || " + StringParser.colorVar("Fighting", arena.fightInProgress) + " || " + StringParser.colorVar("preventDeath", arena.cfg .getBoolean("game.preventDeath"))+ " || " + StringParser.colorVar("refill", arena.cfg.getBoolean("game.refillInventory", false))); player.sendMessage( "�bMessaging:�f [" + StringParser.colorVar(arena.cfg.getString("messages.language")) + "] || " + StringParser.colorVar("chat", arena.cfg.getBoolean("messages.chat", false)) + " || " + StringParser.colorVar("defaultChat", arena.cfg.getBoolean("messages.defaultChat", false)) + " || " + StringParser.colorVar("onlyChat", arena.cfg.getBoolean("messages.onlyChat", false))); player.sendMessage("�bGeneral:�f " + StringParser.colorVar("classperms", arena.cfg.getBoolean("general.classperms")) + " || " + StringParser.colorVar("signs", arena.cfg.getBoolean("general.signs")) + " || " + StringParser.colorVar("random-reward", arena.cfg.getBoolean("general.random-reward")) + " || " + "Wand: " + Material.getMaterial(arena.cfg.getInt("setup.wand")) .toString()); player.sendMessage( "Time limit: " + StringParser.colorVar(arena.cfg.getInt("goal.timed")) + " || " + "MaxLives: " + StringParser.colorVar(arena.cfg.getInt("game.lives")) + " || " + StringParser.colorVar("TeamKill", arena.cfg.getBoolean("game.teamKill", false)) + " || " + StringParser.colorVar("woolHead", arena.cfg.getBoolean("game.woolHead", false))); player.sendMessage(""); player.sendMessage("�bRegions:�f " + listRegions(arena.regions)); player.sendMessage(StringParser.colorVar("Regionset", arena.name.equals(Arena.regionmodify)) + " || " + StringParser.colorVar("Check Regions", arena.cfg.getBoolean("periphery.checkRegions", false)) + ": " + StringParser.colorVar("Exit", arena.cfg.getBoolean("protection.checkExit", false)) + " | " + StringParser.colorVar("Lounges", arena.cfg.getBoolean("protection.checkLounges", false)) + " | " + StringParser.colorVar("Spectator", arena.cfg.getBoolean( "protection.checkSpectator", false))); player.sendMessage(""); player.sendMessage("�bJoining: " + StringParser.colorVar("manual", arena.cfg.getBoolean("join.manual", true)) + " | " + StringParser.colorVar("random", arena.cfg.getBoolean("join.random", true)) + " || " + StringParser.colorVar("forceEven", arena.cfg.getBoolean("join.forceEven", false)) + " || " + "Warmup: " + StringParser.colorVar(arena.cfg.getInt("join.warmup", 0))); player.sendMessage(StringParser.colorVar("explicitPermission", arena.cfg.getBoolean("join.explicitPermission", true)) + " | " + StringParser.colorVar("onCountdown", arena.cfg.getBoolean("join.onCountdown", true)) + " || " + StringParser.colorVar("inbattle", arena.cfg.getBoolean("join.inbattle", false)) + " || " + "JoinRange: " + StringParser.colorVar(arena.cfg.getInt("join.range", 0))); player.sendMessage(""); player.sendMessage(StringParser.colorVar("Protection", arena.cfg.getBoolean("protection.enabled", true))); player.sendMessage(StringParser.colorVar("firespread", arena.cfg.getBoolean("protection.firespread", true)) + " | " + StringParser.colorVar("blockdamage", arena.cfg.getBoolean("protection.blockdamage", true)) + " | " - + StringParser.colorVar("tntblockdamage", - arena.cfg.getBoolean("protection.tntblockdamage", true)) + + StringParser.colorVar("blocktntdamage", + arena.cfg.getBoolean("protection.blocktntdamage", true)) + " | " + StringParser.colorVar("blockplace", arena.cfg.getBoolean("protection.blockplace", true)) + " | " + StringParser.colorVar("piston", arena.cfg.getBoolean("protection.piston", true)) + " | " + StringParser.colorVar("lighter", arena.cfg.getBoolean("protection.lighter", true)) + " | " + StringParser.colorVar("tnt", arena.cfg.getBoolean("protection.tnt", true))); player.sendMessage(StringParser.colorVar("restore", arena.cfg.getBoolean("protection.restore", true)) + " | " + StringParser.colorVar("lavafirespread", arena.cfg.getBoolean("protection.lavafirespread", true)) + " | " + StringParser.colorVar("fluids", arena.cfg.getBoolean("protection.fluids", true)) + " | " + StringParser.colorVar("punish", arena.cfg.getBoolean("protection.punish", true)) + " | " + StringParser.colorVar("inventory", arena.cfg.getBoolean("protection.inventory", true)) + " | " + "spawn: " + StringParser.colorVar(arena.cfg.getInt("protection.spawn", 0))); player.sendMessage(""); player.sendMessage("�bStart:�f " + "countdown: " + StringParser.colorVar(arena.cfg.getInt("start.countdown")) + " | " + "health: " + StringParser.colorVar(arena.cfg.getInt("start.health")) + " | " + "foodLevel: " + StringParser.colorVar(arena.cfg.getInt("start.foodLevel")) + " | " + "saturation: " + StringParser.colorVar(arena.cfg.getInt("start.saturation")) + " | " + "exhaustion: " + StringParser.colorVar(arena.cfg.getDouble("start.exhaustion"))); player.sendMessage("�bReadying:�f " + "block: " + StringParser.colorVar(arena.cfg.getString("ready.block")) + " | " + StringParser.colorVar("checkEach", arena.cfg.getBoolean("ready.checkEach")) + " | " + StringParser.colorVar("checkEachTeam", arena.cfg.getBoolean("ready.checkEachTeam"))); player.sendMessage("startRatio: " + StringParser.colorVar(arena.cfg.getDouble("ready.startRatio")) + " | min: " + StringParser.colorVar(arena.cfg.getInt("ready.min")) + " | minTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.minTeam")) + " | max: " + StringParser.colorVar(arena.cfg.getInt("ready.max")) + " | maxTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.maxTeam")) + " | autoclass: " + StringParser.colorVar(arena.cfg.getString("ready.autoclass"))); player.sendMessage("�bTPs:�f exit: " + StringParser.colorVar(arena.cfg.getString("tp.exit", "exit")) + " | death: " + StringParser.colorVar(arena.cfg.getString("tp.death", "spectator")) + " | win: " + StringParser.colorVar(arena.cfg.getString("tp.win", "old")) + " | lose: " + StringParser.colorVar(arena.cfg.getString("tp.lose", "old"))); PVPArena.instance.getAmm().parseInfo(arena, player); } private String listClasses(Arena arena) { String result = ""; for (ArenaClass c : arena.getClasses()) { if (c.getName().equals("custom")) { continue; } if (!result.equals("")) { result += "�f, �e"; } result += "�e" + c.getName(); } return result; } /** * turn a hashmap into a pipe separated string * * @param arena * the input team map * @return the joined and colored string */ private String colorTeams(Arena arena) { String s = ""; for (ArenaTeam team : arena.getTeams()) { if (!s.equals("")) { s += " | "; } s += team.colorize() + ChatColor.WHITE; } return s; } /** * turn a hashmap into a pipe separated strong * * @param paRegions * the hashmap of regionname=>region * @return the joined string */ private String listRegions(HashMap<String, ArenaRegion> paRegions) { String s = ""; for (ArenaRegion p : paRegions.values()) { if (!s.equals("")) { s += " | "; } s += p.name + " (" + p.getShape().name().substring(0,3) + ")"; } return s; } @Override public String getName() { return "PAAInfo"; } }
true
true
public void commit(Arena arena, CommandSender player, String[] args) { String type = arena.type().getName(); player.sendMessage("-----------------------------------------------------"); player.sendMessage("Arena Information about: " + ChatColor.AQUA + arena.name + "�f | [�a"+ arena.prefix +"�f]"); player.sendMessage("-----------------------------------------------------"); player.sendMessage("GameMode: " + ChatColor.AQUA + type + ChatColor.WHITE + " || " + "Teams: " + colorTeams(arena)); player.sendMessage("Classes: " + listClasses(arena)); player.sendMessage(""); player.sendMessage("�bRuntime:�f "+ StringParser.colorVar("Enabled", arena.cfg.getBoolean("general.enabled")) + " || " + StringParser.colorVar("EditMode", arena.edit) + " || " + StringParser.colorVar("Fighting", arena.fightInProgress) + " || " + StringParser.colorVar("preventDeath", arena.cfg .getBoolean("game.preventDeath"))+ " || " + StringParser.colorVar("refill", arena.cfg.getBoolean("game.refillInventory", false))); player.sendMessage( "�bMessaging:�f [" + StringParser.colorVar(arena.cfg.getString("messages.language")) + "] || " + StringParser.colorVar("chat", arena.cfg.getBoolean("messages.chat", false)) + " || " + StringParser.colorVar("defaultChat", arena.cfg.getBoolean("messages.defaultChat", false)) + " || " + StringParser.colorVar("onlyChat", arena.cfg.getBoolean("messages.onlyChat", false))); player.sendMessage("�bGeneral:�f " + StringParser.colorVar("classperms", arena.cfg.getBoolean("general.classperms")) + " || " + StringParser.colorVar("signs", arena.cfg.getBoolean("general.signs")) + " || " + StringParser.colorVar("random-reward", arena.cfg.getBoolean("general.random-reward")) + " || " + "Wand: " + Material.getMaterial(arena.cfg.getInt("setup.wand")) .toString()); player.sendMessage( "Time limit: " + StringParser.colorVar(arena.cfg.getInt("goal.timed")) + " || " + "MaxLives: " + StringParser.colorVar(arena.cfg.getInt("game.lives")) + " || " + StringParser.colorVar("TeamKill", arena.cfg.getBoolean("game.teamKill", false)) + " || " + StringParser.colorVar("woolHead", arena.cfg.getBoolean("game.woolHead", false))); player.sendMessage(""); player.sendMessage("�bRegions:�f " + listRegions(arena.regions)); player.sendMessage(StringParser.colorVar("Regionset", arena.name.equals(Arena.regionmodify)) + " || " + StringParser.colorVar("Check Regions", arena.cfg.getBoolean("periphery.checkRegions", false)) + ": " + StringParser.colorVar("Exit", arena.cfg.getBoolean("protection.checkExit", false)) + " | " + StringParser.colorVar("Lounges", arena.cfg.getBoolean("protection.checkLounges", false)) + " | " + StringParser.colorVar("Spectator", arena.cfg.getBoolean( "protection.checkSpectator", false))); player.sendMessage(""); player.sendMessage("�bJoining: " + StringParser.colorVar("manual", arena.cfg.getBoolean("join.manual", true)) + " | " + StringParser.colorVar("random", arena.cfg.getBoolean("join.random", true)) + " || " + StringParser.colorVar("forceEven", arena.cfg.getBoolean("join.forceEven", false)) + " || " + "Warmup: " + StringParser.colorVar(arena.cfg.getInt("join.warmup", 0))); player.sendMessage(StringParser.colorVar("explicitPermission", arena.cfg.getBoolean("join.explicitPermission", true)) + " | " + StringParser.colorVar("onCountdown", arena.cfg.getBoolean("join.onCountdown", true)) + " || " + StringParser.colorVar("inbattle", arena.cfg.getBoolean("join.inbattle", false)) + " || " + "JoinRange: " + StringParser.colorVar(arena.cfg.getInt("join.range", 0))); player.sendMessage(""); player.sendMessage(StringParser.colorVar("Protection", arena.cfg.getBoolean("protection.enabled", true))); player.sendMessage(StringParser.colorVar("firespread", arena.cfg.getBoolean("protection.firespread", true)) + " | " + StringParser.colorVar("blockdamage", arena.cfg.getBoolean("protection.blockdamage", true)) + " | " + StringParser.colorVar("tntblockdamage", arena.cfg.getBoolean("protection.tntblockdamage", true)) + " | " + StringParser.colorVar("blockplace", arena.cfg.getBoolean("protection.blockplace", true)) + " | " + StringParser.colorVar("piston", arena.cfg.getBoolean("protection.piston", true)) + " | " + StringParser.colorVar("lighter", arena.cfg.getBoolean("protection.lighter", true)) + " | " + StringParser.colorVar("tnt", arena.cfg.getBoolean("protection.tnt", true))); player.sendMessage(StringParser.colorVar("restore", arena.cfg.getBoolean("protection.restore", true)) + " | " + StringParser.colorVar("lavafirespread", arena.cfg.getBoolean("protection.lavafirespread", true)) + " | " + StringParser.colorVar("fluids", arena.cfg.getBoolean("protection.fluids", true)) + " | " + StringParser.colorVar("punish", arena.cfg.getBoolean("protection.punish", true)) + " | " + StringParser.colorVar("inventory", arena.cfg.getBoolean("protection.inventory", true)) + " | " + "spawn: " + StringParser.colorVar(arena.cfg.getInt("protection.spawn", 0))); player.sendMessage(""); player.sendMessage("�bStart:�f " + "countdown: " + StringParser.colorVar(arena.cfg.getInt("start.countdown")) + " | " + "health: " + StringParser.colorVar(arena.cfg.getInt("start.health")) + " | " + "foodLevel: " + StringParser.colorVar(arena.cfg.getInt("start.foodLevel")) + " | " + "saturation: " + StringParser.colorVar(arena.cfg.getInt("start.saturation")) + " | " + "exhaustion: " + StringParser.colorVar(arena.cfg.getDouble("start.exhaustion"))); player.sendMessage("�bReadying:�f " + "block: " + StringParser.colorVar(arena.cfg.getString("ready.block")) + " | " + StringParser.colorVar("checkEach", arena.cfg.getBoolean("ready.checkEach")) + " | " + StringParser.colorVar("checkEachTeam", arena.cfg.getBoolean("ready.checkEachTeam"))); player.sendMessage("startRatio: " + StringParser.colorVar(arena.cfg.getDouble("ready.startRatio")) + " | min: " + StringParser.colorVar(arena.cfg.getInt("ready.min")) + " | minTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.minTeam")) + " | max: " + StringParser.colorVar(arena.cfg.getInt("ready.max")) + " | maxTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.maxTeam")) + " | autoclass: " + StringParser.colorVar(arena.cfg.getString("ready.autoclass"))); player.sendMessage("�bTPs:�f exit: " + StringParser.colorVar(arena.cfg.getString("tp.exit", "exit")) + " | death: " + StringParser.colorVar(arena.cfg.getString("tp.death", "spectator")) + " | win: " + StringParser.colorVar(arena.cfg.getString("tp.win", "old")) + " | lose: " + StringParser.colorVar(arena.cfg.getString("tp.lose", "old"))); PVPArena.instance.getAmm().parseInfo(arena, player); }
public void commit(Arena arena, CommandSender player, String[] args) { String type = arena.type().getName(); player.sendMessage("-----------------------------------------------------"); player.sendMessage("Arena Information about: " + ChatColor.AQUA + arena.name + "�f | [�a"+ arena.prefix +"�f]"); player.sendMessage("-----------------------------------------------------"); player.sendMessage("GameMode: " + ChatColor.AQUA + type + ChatColor.WHITE + " || " + "Teams: " + colorTeams(arena)); player.sendMessage("Classes: " + listClasses(arena)); player.sendMessage(""); player.sendMessage("�bRuntime:�f "+ StringParser.colorVar("Enabled", arena.cfg.getBoolean("general.enabled")) + " || " + StringParser.colorVar("EditMode", arena.edit) + " || " + StringParser.colorVar("Fighting", arena.fightInProgress) + " || " + StringParser.colorVar("preventDeath", arena.cfg .getBoolean("game.preventDeath"))+ " || " + StringParser.colorVar("refill", arena.cfg.getBoolean("game.refillInventory", false))); player.sendMessage( "�bMessaging:�f [" + StringParser.colorVar(arena.cfg.getString("messages.language")) + "] || " + StringParser.colorVar("chat", arena.cfg.getBoolean("messages.chat", false)) + " || " + StringParser.colorVar("defaultChat", arena.cfg.getBoolean("messages.defaultChat", false)) + " || " + StringParser.colorVar("onlyChat", arena.cfg.getBoolean("messages.onlyChat", false))); player.sendMessage("�bGeneral:�f " + StringParser.colorVar("classperms", arena.cfg.getBoolean("general.classperms")) + " || " + StringParser.colorVar("signs", arena.cfg.getBoolean("general.signs")) + " || " + StringParser.colorVar("random-reward", arena.cfg.getBoolean("general.random-reward")) + " || " + "Wand: " + Material.getMaterial(arena.cfg.getInt("setup.wand")) .toString()); player.sendMessage( "Time limit: " + StringParser.colorVar(arena.cfg.getInt("goal.timed")) + " || " + "MaxLives: " + StringParser.colorVar(arena.cfg.getInt("game.lives")) + " || " + StringParser.colorVar("TeamKill", arena.cfg.getBoolean("game.teamKill", false)) + " || " + StringParser.colorVar("woolHead", arena.cfg.getBoolean("game.woolHead", false))); player.sendMessage(""); player.sendMessage("�bRegions:�f " + listRegions(arena.regions)); player.sendMessage(StringParser.colorVar("Regionset", arena.name.equals(Arena.regionmodify)) + " || " + StringParser.colorVar("Check Regions", arena.cfg.getBoolean("periphery.checkRegions", false)) + ": " + StringParser.colorVar("Exit", arena.cfg.getBoolean("protection.checkExit", false)) + " | " + StringParser.colorVar("Lounges", arena.cfg.getBoolean("protection.checkLounges", false)) + " | " + StringParser.colorVar("Spectator", arena.cfg.getBoolean( "protection.checkSpectator", false))); player.sendMessage(""); player.sendMessage("�bJoining: " + StringParser.colorVar("manual", arena.cfg.getBoolean("join.manual", true)) + " | " + StringParser.colorVar("random", arena.cfg.getBoolean("join.random", true)) + " || " + StringParser.colorVar("forceEven", arena.cfg.getBoolean("join.forceEven", false)) + " || " + "Warmup: " + StringParser.colorVar(arena.cfg.getInt("join.warmup", 0))); player.sendMessage(StringParser.colorVar("explicitPermission", arena.cfg.getBoolean("join.explicitPermission", true)) + " | " + StringParser.colorVar("onCountdown", arena.cfg.getBoolean("join.onCountdown", true)) + " || " + StringParser.colorVar("inbattle", arena.cfg.getBoolean("join.inbattle", false)) + " || " + "JoinRange: " + StringParser.colorVar(arena.cfg.getInt("join.range", 0))); player.sendMessage(""); player.sendMessage(StringParser.colorVar("Protection", arena.cfg.getBoolean("protection.enabled", true))); player.sendMessage(StringParser.colorVar("firespread", arena.cfg.getBoolean("protection.firespread", true)) + " | " + StringParser.colorVar("blockdamage", arena.cfg.getBoolean("protection.blockdamage", true)) + " | " + StringParser.colorVar("blocktntdamage", arena.cfg.getBoolean("protection.blocktntdamage", true)) + " | " + StringParser.colorVar("blockplace", arena.cfg.getBoolean("protection.blockplace", true)) + " | " + StringParser.colorVar("piston", arena.cfg.getBoolean("protection.piston", true)) + " | " + StringParser.colorVar("lighter", arena.cfg.getBoolean("protection.lighter", true)) + " | " + StringParser.colorVar("tnt", arena.cfg.getBoolean("protection.tnt", true))); player.sendMessage(StringParser.colorVar("restore", arena.cfg.getBoolean("protection.restore", true)) + " | " + StringParser.colorVar("lavafirespread", arena.cfg.getBoolean("protection.lavafirespread", true)) + " | " + StringParser.colorVar("fluids", arena.cfg.getBoolean("protection.fluids", true)) + " | " + StringParser.colorVar("punish", arena.cfg.getBoolean("protection.punish", true)) + " | " + StringParser.colorVar("inventory", arena.cfg.getBoolean("protection.inventory", true)) + " | " + "spawn: " + StringParser.colorVar(arena.cfg.getInt("protection.spawn", 0))); player.sendMessage(""); player.sendMessage("�bStart:�f " + "countdown: " + StringParser.colorVar(arena.cfg.getInt("start.countdown")) + " | " + "health: " + StringParser.colorVar(arena.cfg.getInt("start.health")) + " | " + "foodLevel: " + StringParser.colorVar(arena.cfg.getInt("start.foodLevel")) + " | " + "saturation: " + StringParser.colorVar(arena.cfg.getInt("start.saturation")) + " | " + "exhaustion: " + StringParser.colorVar(arena.cfg.getDouble("start.exhaustion"))); player.sendMessage("�bReadying:�f " + "block: " + StringParser.colorVar(arena.cfg.getString("ready.block")) + " | " + StringParser.colorVar("checkEach", arena.cfg.getBoolean("ready.checkEach")) + " | " + StringParser.colorVar("checkEachTeam", arena.cfg.getBoolean("ready.checkEachTeam"))); player.sendMessage("startRatio: " + StringParser.colorVar(arena.cfg.getDouble("ready.startRatio")) + " | min: " + StringParser.colorVar(arena.cfg.getInt("ready.min")) + " | minTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.minTeam")) + " | max: " + StringParser.colorVar(arena.cfg.getInt("ready.max")) + " | maxTeam: " + StringParser.colorVar(arena.cfg.getInt("ready.maxTeam")) + " | autoclass: " + StringParser.colorVar(arena.cfg.getString("ready.autoclass"))); player.sendMessage("�bTPs:�f exit: " + StringParser.colorVar(arena.cfg.getString("tp.exit", "exit")) + " | death: " + StringParser.colorVar(arena.cfg.getString("tp.death", "spectator")) + " | win: " + StringParser.colorVar(arena.cfg.getString("tp.win", "old")) + " | lose: " + StringParser.colorVar(arena.cfg.getString("tp.lose", "old"))); PVPArena.instance.getAmm().parseInfo(arena, player); }
diff --git a/plugin/src/edu/berkeley/eduride/base_plugin/isafile/ISAVisitor.java b/plugin/src/edu/berkeley/eduride/base_plugin/isafile/ISAVisitor.java index 6a808fd..d3381bc 100644 --- a/plugin/src/edu/berkeley/eduride/base_plugin/isafile/ISAVisitor.java +++ b/plugin/src/edu/berkeley/eduride/base_plugin/isafile/ISAVisitor.java @@ -1,84 +1,84 @@ package edu.berkeley.eduride.base_plugin.isafile; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.JavaCore; import edu.berkeley.eduride.base_plugin.util.Console; /* * Calls ISAParse on all isa files. * */ public class ISAVisitor implements IResourceProxyVisitor { /** * Search the workspace and parse all ISAs * @return */ public static boolean processAllISAInWorkspace() { ISAVisitor isaVisitor = new ISAVisitor(); try { IWorkspace ws = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = ws.getRoot(); root.accept(isaVisitor, 0); return true; } catch (CoreException e) { // hm, no workspace yet? Console.err("Whoa, couldn't look for ISA files in workspace right now, or the visitor bombed. You should restart methinks."); Console.err(e); return false; } // do some post processing? // - } public static boolean processISAInProject(IProject proj) { ISAVisitor isaVisitor = new ISAVisitor(); try { proj.accept(isaVisitor, 0); return true; } catch (CoreException e) { Console.err("Whoa, couldn't look for ISA files in project "+ proj.getName() + ", or the visitor bombed. You should restart methinks."); Console.err(e); return false; } } // this should throw a CoreException if there is a problem processing ISAs? @Override public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.ROOT) { return true; } else if (proxy.getType() == IResource.PROJECT) { // Project? Keep visiting iff its a Java project IProject iproj = proxy.requestResource().getProject(); - return iproj.hasNature(JavaCore.NATURE_ID); + return (iproj.isOpen() && iproj.hasNature(JavaCore.NATURE_ID)); } else if (proxy.getType() == IResource.FOLDER) { //Folder. always visit. return true; } else if (proxy.getType() == IResource.FILE) { // FILE IFile ifile = (IFile) proxy.requestResource(); if (ISAUtil.isISAFile(ifile)) { ISAUtil.setAsISA(ifile.getProject()); ISAUtil.parseISA(ifile); } } return false; } }
true
true
public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.ROOT) { return true; } else if (proxy.getType() == IResource.PROJECT) { // Project? Keep visiting iff its a Java project IProject iproj = proxy.requestResource().getProject(); return iproj.hasNature(JavaCore.NATURE_ID); } else if (proxy.getType() == IResource.FOLDER) { //Folder. always visit. return true; } else if (proxy.getType() == IResource.FILE) { // FILE IFile ifile = (IFile) proxy.requestResource(); if (ISAUtil.isISAFile(ifile)) { ISAUtil.setAsISA(ifile.getProject()); ISAUtil.parseISA(ifile); } } return false; }
public boolean visit(IResourceProxy proxy) throws CoreException { if (proxy.getType() == IResource.ROOT) { return true; } else if (proxy.getType() == IResource.PROJECT) { // Project? Keep visiting iff its a Java project IProject iproj = proxy.requestResource().getProject(); return (iproj.isOpen() && iproj.hasNature(JavaCore.NATURE_ID)); } else if (proxy.getType() == IResource.FOLDER) { //Folder. always visit. return true; } else if (proxy.getType() == IResource.FILE) { // FILE IFile ifile = (IFile) proxy.requestResource(); if (ISAUtil.isISAFile(ifile)) { ISAUtil.setAsISA(ifile.getProject()); ISAUtil.parseISA(ifile); } } return false; }
diff --git a/src/me/Travja/HungerArena/SpawnsCommand.java b/src/me/Travja/HungerArena/SpawnsCommand.java index f550c15..39c2787 100644 --- a/src/me/Travja/HungerArena/SpawnsCommand.java +++ b/src/me/Travja/HungerArena/SpawnsCommand.java @@ -1,124 +1,153 @@ package me.Travja.HungerArena; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class SpawnsCommand implements CommandExecutor { public Main plugin; int i = 0; int a = 0; public SpawnsCommand(Main m) { this.plugin = m; } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player p = (Player) sender; if(cmd.getName().equalsIgnoreCase("StartPoint")){ if(p.hasPermission("HungerArena.StartPoint")){ if(!plugin.restricted || (plugin.restricted && plugin.worlds.contains(p.getWorld().getName()))){ Location loc = null; double x; double y; double z; if(args.length == 6){ String world = args[2]; x = Double.parseDouble(args[3]); y = Double.parseDouble(args[4]); z = Double.parseDouble(args[5]); loc = new Location(Bukkit.getWorld(world), x, y, z); + if(plugin.location.get(a)!= null){ + if(plugin.location.get(a).size()>= i){ + plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); + }else{ + plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); + } + }else{ + plugin.location.put(a, new HashMap<Integer, Location>()); + plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); + plugin.Playing.put(a, new ArrayList<String>()); + plugin.Ready.put(a, new ArrayList<String>()); + plugin.Dead.put(a, new ArrayList<String>()); + plugin.Quit.put(a, new ArrayList<String>()); + plugin.Out.put(a, new ArrayList<String>()); + plugin.Watching.put(a, new ArrayList<String>()); + plugin.NeedConfirm.put(a, new ArrayList<String>()); + plugin.inArena.put(a, new ArrayList<String>()); + plugin.Frozen.put(a, new ArrayList<String>()); + plugin.arena.put(a, new ArrayList<String>()); + plugin.canjoin.put(a, false); + plugin.open.put(a, true); + } + String coords = plugin.location.get(a).get(i).getWorld().getName() + "," + (plugin.location.get(a).get(i).getX()+.5) + "," + plugin.location.get(a).get(i).getY() + "," + (plugin.location.get(a).get(i).getZ()+.5); + p.sendMessage(coords); + plugin.spawns.set("Spawns." + a + "." + i, coords); + plugin.saveSpawns(); + plugin.maxPlayers.put(a, plugin.location.get(a).size()); + p.sendMessage(ChatColor.AQUA + "You have set the spawn location of Tribute " + i + " in arena " + a + "!"); + return true; } if(args.length>= 2){ try{ i = Integer.valueOf(args[1]); a = Integer.valueOf(args[0]); }catch(Exception e){ p.sendMessage(ChatColor.RED + "Argument not an integer!"); return true; } if(i >= 1 && i <= plugin.config.getInt("maxPlayers")){ if(plugin.restricted && !plugin.worlds.contains(p.getWorld().getName())){ p.sendMessage(ChatColor.GOLD + "We ran the command, however, this isn't a world you defined in the config..."); p.sendMessage(ChatColor.GOLD + "If this is the right world, please disregard this message."); } loc = p.getLocation().getBlock().getLocation(); x = loc.getX(); y = loc.getY(); z = loc.getZ(); if(plugin.location.get(a)!= null){ if(plugin.location.get(a).size()>= i){ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); }else{ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); } }else{ plugin.location.put(a, new HashMap<Integer, Location>()); plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); plugin.Playing.put(a, new ArrayList<String>()); plugin.Ready.put(a, new ArrayList<String>()); plugin.Dead.put(a, new ArrayList<String>()); plugin.Quit.put(a, new ArrayList<String>()); plugin.Out.put(a, new ArrayList<String>()); plugin.Watching.put(a, new ArrayList<String>()); plugin.NeedConfirm.put(a, new ArrayList<String>()); plugin.inArena.put(a, new ArrayList<String>()); plugin.Frozen.put(a, new ArrayList<String>()); plugin.arena.put(a, new ArrayList<String>()); plugin.canjoin.put(a, false); plugin.open.put(a, true); } String coords = plugin.location.get(a).get(i).getWorld().getName() + "," + (plugin.location.get(a).get(i).getX()+.5) + "," + plugin.location.get(a).get(i).getY() + "," + (plugin.location.get(a).get(i).getZ()+.5); p.sendMessage(coords); plugin.spawns.set("Spawns." + a + "." + i, coords); plugin.saveSpawns(); plugin.maxPlayers.put(a, plugin.location.get(a).size()); p.sendMessage(ChatColor.AQUA + "You have set the spawn location of Tribute " + i + " in arena " + a + "!"); }else{ p.sendMessage(ChatColor.RED + "You can't go past " + plugin.config.getInt("maxPlayers") + " players!"); } }else if(args.length == 1){ if (sender instanceof Player){ p = (Player) sender; a = Integer.parseInt(args[0]); if (plugin.spawns.get("Spawns." + a) != null){ int start = 1; while(start<plugin.config.getInt("maxPlayers")+2){ if (plugin.spawns.get("Spawns." + a + "." + start) != null){ start = start+1; if(start== plugin.config.getInt("maxPlayers")+1){ p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.GREEN + "All spawns set, type /startpoint [Arena #] [Spawn #] to over-ride previous points!"); return true; } }else{ int sloc = start; start = plugin.config.getInt("maxPlayers")+1; p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + sloc); plugin.setting.put(p.getName(), a + "-" + sloc); return true; } } } p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + 1); plugin.setting.put(p.getName(), a + "-" + 1); return true; }else{ sender.sendMessage(ChatColor.BLUE + "This Can Only Be Sent As A Player"); } }else return false; } }else{ p.sendMessage(ChatColor.RED + "You don't have permission!"); } } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player p = (Player) sender; if(cmd.getName().equalsIgnoreCase("StartPoint")){ if(p.hasPermission("HungerArena.StartPoint")){ if(!plugin.restricted || (plugin.restricted && plugin.worlds.contains(p.getWorld().getName()))){ Location loc = null; double x; double y; double z; if(args.length == 6){ String world = args[2]; x = Double.parseDouble(args[3]); y = Double.parseDouble(args[4]); z = Double.parseDouble(args[5]); loc = new Location(Bukkit.getWorld(world), x, y, z); } if(args.length>= 2){ try{ i = Integer.valueOf(args[1]); a = Integer.valueOf(args[0]); }catch(Exception e){ p.sendMessage(ChatColor.RED + "Argument not an integer!"); return true; } if(i >= 1 && i <= plugin.config.getInt("maxPlayers")){ if(plugin.restricted && !plugin.worlds.contains(p.getWorld().getName())){ p.sendMessage(ChatColor.GOLD + "We ran the command, however, this isn't a world you defined in the config..."); p.sendMessage(ChatColor.GOLD + "If this is the right world, please disregard this message."); } loc = p.getLocation().getBlock().getLocation(); x = loc.getX(); y = loc.getY(); z = loc.getZ(); if(plugin.location.get(a)!= null){ if(plugin.location.get(a).size()>= i){ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); }else{ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); } }else{ plugin.location.put(a, new HashMap<Integer, Location>()); plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); plugin.Playing.put(a, new ArrayList<String>()); plugin.Ready.put(a, new ArrayList<String>()); plugin.Dead.put(a, new ArrayList<String>()); plugin.Quit.put(a, new ArrayList<String>()); plugin.Out.put(a, new ArrayList<String>()); plugin.Watching.put(a, new ArrayList<String>()); plugin.NeedConfirm.put(a, new ArrayList<String>()); plugin.inArena.put(a, new ArrayList<String>()); plugin.Frozen.put(a, new ArrayList<String>()); plugin.arena.put(a, new ArrayList<String>()); plugin.canjoin.put(a, false); plugin.open.put(a, true); } String coords = plugin.location.get(a).get(i).getWorld().getName() + "," + (plugin.location.get(a).get(i).getX()+.5) + "," + plugin.location.get(a).get(i).getY() + "," + (plugin.location.get(a).get(i).getZ()+.5); p.sendMessage(coords); plugin.spawns.set("Spawns." + a + "." + i, coords); plugin.saveSpawns(); plugin.maxPlayers.put(a, plugin.location.get(a).size()); p.sendMessage(ChatColor.AQUA + "You have set the spawn location of Tribute " + i + " in arena " + a + "!"); }else{ p.sendMessage(ChatColor.RED + "You can't go past " + plugin.config.getInt("maxPlayers") + " players!"); } }else if(args.length == 1){ if (sender instanceof Player){ p = (Player) sender; a = Integer.parseInt(args[0]); if (plugin.spawns.get("Spawns." + a) != null){ int start = 1; while(start<plugin.config.getInt("maxPlayers")+2){ if (plugin.spawns.get("Spawns." + a + "." + start) != null){ start = start+1; if(start== plugin.config.getInt("maxPlayers")+1){ p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.GREEN + "All spawns set, type /startpoint [Arena #] [Spawn #] to over-ride previous points!"); return true; } }else{ int sloc = start; start = plugin.config.getInt("maxPlayers")+1; p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + sloc); plugin.setting.put(p.getName(), a + "-" + sloc); return true; } } } p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + 1); plugin.setting.put(p.getName(), a + "-" + 1); return true; }else{ sender.sendMessage(ChatColor.BLUE + "This Can Only Be Sent As A Player"); } }else return false; } }else{ p.sendMessage(ChatColor.RED + "You don't have permission!"); } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player p = (Player) sender; if(cmd.getName().equalsIgnoreCase("StartPoint")){ if(p.hasPermission("HungerArena.StartPoint")){ if(!plugin.restricted || (plugin.restricted && plugin.worlds.contains(p.getWorld().getName()))){ Location loc = null; double x; double y; double z; if(args.length == 6){ String world = args[2]; x = Double.parseDouble(args[3]); y = Double.parseDouble(args[4]); z = Double.parseDouble(args[5]); loc = new Location(Bukkit.getWorld(world), x, y, z); if(plugin.location.get(a)!= null){ if(plugin.location.get(a).size()>= i){ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); }else{ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); } }else{ plugin.location.put(a, new HashMap<Integer, Location>()); plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); plugin.Playing.put(a, new ArrayList<String>()); plugin.Ready.put(a, new ArrayList<String>()); plugin.Dead.put(a, new ArrayList<String>()); plugin.Quit.put(a, new ArrayList<String>()); plugin.Out.put(a, new ArrayList<String>()); plugin.Watching.put(a, new ArrayList<String>()); plugin.NeedConfirm.put(a, new ArrayList<String>()); plugin.inArena.put(a, new ArrayList<String>()); plugin.Frozen.put(a, new ArrayList<String>()); plugin.arena.put(a, new ArrayList<String>()); plugin.canjoin.put(a, false); plugin.open.put(a, true); } String coords = plugin.location.get(a).get(i).getWorld().getName() + "," + (plugin.location.get(a).get(i).getX()+.5) + "," + plugin.location.get(a).get(i).getY() + "," + (plugin.location.get(a).get(i).getZ()+.5); p.sendMessage(coords); plugin.spawns.set("Spawns." + a + "." + i, coords); plugin.saveSpawns(); plugin.maxPlayers.put(a, plugin.location.get(a).size()); p.sendMessage(ChatColor.AQUA + "You have set the spawn location of Tribute " + i + " in arena " + a + "!"); return true; } if(args.length>= 2){ try{ i = Integer.valueOf(args[1]); a = Integer.valueOf(args[0]); }catch(Exception e){ p.sendMessage(ChatColor.RED + "Argument not an integer!"); return true; } if(i >= 1 && i <= plugin.config.getInt("maxPlayers")){ if(plugin.restricted && !plugin.worlds.contains(p.getWorld().getName())){ p.sendMessage(ChatColor.GOLD + "We ran the command, however, this isn't a world you defined in the config..."); p.sendMessage(ChatColor.GOLD + "If this is the right world, please disregard this message."); } loc = p.getLocation().getBlock().getLocation(); x = loc.getX(); y = loc.getY(); z = loc.getZ(); if(plugin.location.get(a)!= null){ if(plugin.location.get(a).size()>= i){ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); }else{ plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); } }else{ plugin.location.put(a, new HashMap<Integer, Location>()); plugin.location.get(a).put(i, new Location(loc.getWorld(), x, y, z)); plugin.Playing.put(a, new ArrayList<String>()); plugin.Ready.put(a, new ArrayList<String>()); plugin.Dead.put(a, new ArrayList<String>()); plugin.Quit.put(a, new ArrayList<String>()); plugin.Out.put(a, new ArrayList<String>()); plugin.Watching.put(a, new ArrayList<String>()); plugin.NeedConfirm.put(a, new ArrayList<String>()); plugin.inArena.put(a, new ArrayList<String>()); plugin.Frozen.put(a, new ArrayList<String>()); plugin.arena.put(a, new ArrayList<String>()); plugin.canjoin.put(a, false); plugin.open.put(a, true); } String coords = plugin.location.get(a).get(i).getWorld().getName() + "," + (plugin.location.get(a).get(i).getX()+.5) + "," + plugin.location.get(a).get(i).getY() + "," + (plugin.location.get(a).get(i).getZ()+.5); p.sendMessage(coords); plugin.spawns.set("Spawns." + a + "." + i, coords); plugin.saveSpawns(); plugin.maxPlayers.put(a, plugin.location.get(a).size()); p.sendMessage(ChatColor.AQUA + "You have set the spawn location of Tribute " + i + " in arena " + a + "!"); }else{ p.sendMessage(ChatColor.RED + "You can't go past " + plugin.config.getInt("maxPlayers") + " players!"); } }else if(args.length == 1){ if (sender instanceof Player){ p = (Player) sender; a = Integer.parseInt(args[0]); if (plugin.spawns.get("Spawns." + a) != null){ int start = 1; while(start<plugin.config.getInt("maxPlayers")+2){ if (plugin.spawns.get("Spawns." + a + "." + start) != null){ start = start+1; if(start== plugin.config.getInt("maxPlayers")+1){ p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.GREEN + "All spawns set, type /startpoint [Arena #] [Spawn #] to over-ride previous points!"); return true; } }else{ int sloc = start; start = plugin.config.getInt("maxPlayers")+1; p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + sloc); plugin.setting.put(p.getName(), a + "-" + sloc); return true; } } } p.sendMessage(ChatColor.DARK_AQUA + "[HungerArena] " + ChatColor.RED + "Begin Setting For Arena " + a + " Starting From Point " + 1); plugin.setting.put(p.getName(), a + "-" + 1); return true; }else{ sender.sendMessage(ChatColor.BLUE + "This Can Only Be Sent As A Player"); } }else return false; } }else{ p.sendMessage(ChatColor.RED + "You don't have permission!"); } } return false; }
diff --git a/native/SampleApps/SmartSyncExplorer/src/com/salesforce/samples/smartsyncexplorer/ui/MainActivity.java b/native/SampleApps/SmartSyncExplorer/src/com/salesforce/samples/smartsyncexplorer/ui/MainActivity.java index 7e4503a71..f713a74ae 100644 --- a/native/SampleApps/SmartSyncExplorer/src/com/salesforce/samples/smartsyncexplorer/ui/MainActivity.java +++ b/native/SampleApps/SmartSyncExplorer/src/com/salesforce/samples/smartsyncexplorer/ui/MainActivity.java @@ -1,429 +1,431 @@ /* * Copyright (c) 2014, salesforce.com, inc. * All rights reserved. * Redistribution and use of this software in source and binary forms, with or * without modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of salesforce.com, inc. nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission of salesforce.com, inc. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.samples.smartsyncexplorer.ui; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.LoaderManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.Loader; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; 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.ArrayAdapter; import android.widget.Filter; import android.widget.ImageView; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import android.widget.SearchView.OnCloseListener; import android.widget.SearchView.OnQueryTextListener; import android.widget.TextView; import com.salesforce.androidsdk.accounts.UserAccount; import com.salesforce.androidsdk.rest.RestClient; import com.salesforce.androidsdk.smartstore.store.IndexSpec; import com.salesforce.androidsdk.smartstore.store.SmartStore; import com.salesforce.androidsdk.smartstore.store.SmartStore.Type; import com.salesforce.androidsdk.smartsync.app.SmartSyncSDKManager; import com.salesforce.androidsdk.smartsync.manager.SyncManager; import com.salesforce.androidsdk.smartsync.util.Constants; import com.salesforce.androidsdk.smartsync.util.SOQLBuilder; import com.salesforce.androidsdk.smartsync.util.SyncState; import com.salesforce.androidsdk.smartsync.util.SyncTarget; import com.salesforce.androidsdk.ui.sfnative.SalesforceListActivity; import com.salesforce.samples.smartsyncexplorer.R; import com.salesforce.samples.smartsyncexplorer.loaders.ContactListLoader; import com.salesforce.samples.smartsyncexplorer.objects.ContactObject; /** * Main activity. * * @author bhariharan */ public class MainActivity extends SalesforceListActivity implements OnQueryTextListener, OnCloseListener, LoaderManager.LoaderCallbacks<List<ContactObject>> { public static final String OBJECT_ID_KEY = "object_id"; public static final String OBJECT_TITLE_KEY = "object_title"; public static final String OBJECT_NAME_KEY = "object_name"; private static final String TAG = "SmartSyncExplorer: MainActivity"; private static final int CONTACT_LOADER_ID = 1; private static IndexSpec[] CONTACTS_INDEX_SPEC = { new IndexSpec("Id", Type.string), new IndexSpec("FirstName", Type.string), new IndexSpec("LastName", Type.string), new IndexSpec(SyncManager.LOCALLY_UPDATED, Type.string) }; private static final int CONTACT_COLORS[] = { Color.rgb(26, 188, 156), Color.rgb(46, 204, 113), Color.rgb(52, 152, 219), Color.rgb(155, 89, 182), Color.rgb(52, 73, 94), Color.rgb(22, 160, 133), Color.rgb(39, 174, 96), Color.rgb(41, 128, 185), Color.rgb(142, 68, 173), Color.rgb(44, 62, 80), Color.rgb(241, 196, 15), Color.rgb(230, 126, 34), Color.rgb(231, 76, 60), Color.rgb(149, 165, 166), Color.rgb(243, 156, 18), Color.rgb(211, 84, 0), Color.rgb(192, 57, 43), Color.rgb(189, 195, 199), Color.rgb(127, 140, 141) }; private SearchView searchView; private ContactListAdapter listAdapter; private UserAccount curAccount; private NameFieldFilter nameFilter; private List<ContactObject> originalData; private SyncReceiver syncReceiver; private SyncManager syncMgr; private SmartStore smartStore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); getActionBar().setTitle(R.string.main_activity_title); listAdapter = new ContactListAdapter(this, R.layout.list_item); getListView().setAdapter(listAdapter); nameFilter = new NameFieldFilter(listAdapter, originalData); syncReceiver = new SyncReceiver(); registerReceiver(syncReceiver, new IntentFilter(SyncManager.SYNC_INTENT_ACTION)); } @Override protected void refreshIfUserSwitched() { // TODO: User switch. Change 'client' and reload list. Also add logout functionality. } @Override public void onResume(RestClient client) { curAccount = SmartSyncSDKManager.getInstance().getUserAccountManager().getCurrentUser(); syncMgr = SyncManager.getInstance(curAccount); smartStore = SmartSyncSDKManager.getInstance().getSmartStore(curAccount); getLoaderManager().initLoader(CONTACT_LOADER_ID, null, this); syncDownContacts(); } @Override public void onDestroy() { unregisterReceiver(syncReceiver); getLoaderManager().destroyLoader(CONTACT_LOADER_ID); super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar_menu, menu); final MenuItem searchItem = menu.findItem(R.id.action_search); searchView = new SearchView(this); searchView.setOnQueryTextListener(this); searchView.setOnCloseListener(this); searchItem.setActionView(searchView); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: getLoaderManager().getLoader(CONTACT_LOADER_ID).forceLoad(); Toast.makeText(this, "Refresh complete!", Toast.LENGTH_LONG).show(); return true; default: return super.onOptionsItemSelected(item); } } @Override public Loader<List<ContactObject>> onCreateLoader(int id, Bundle args) { return new ContactListLoader(this, curAccount); } @Override public void onLoaderReset(Loader<List<ContactObject>> loader) { originalData = null; refreshList(null); } @Override public void onLoadFinished(Loader<List<ContactObject>> loader, List<ContactObject> data) { originalData = data; nameFilter.setOrigData(originalData); refreshList(data); } @Override public boolean onClose() { refreshList(originalData); return true; } @Override public boolean onQueryTextSubmit(String query) { filterList(query); return true; } @Override public boolean onQueryTextChange(String newText) { filterList(newText); return true; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { final ContactObject sObject = listAdapter.getItem(position); final Intent detailIntent = new Intent(this, DetailActivity.class); detailIntent.addCategory(Intent.CATEGORY_DEFAULT); detailIntent.putExtra(OBJECT_ID_KEY, sObject.getObjectId()); detailIntent.putExtra(OBJECT_TITLE_KEY, sObject.getTitle()); detailIntent.putExtra(OBJECT_NAME_KEY, sObject.getName()); startActivity(detailIntent); } private void refreshList(List<ContactObject> data) { listAdapter.setData(data); } private void filterList(String filterTerm) { nameFilter.filter(filterTerm); } private void syncDownContacts() { if (!smartStore.hasSoup(ContactListLoader.CONTACT_SOUP)) { smartStore.registerSoup(ContactListLoader.CONTACT_SOUP, CONTACTS_INDEX_SPEC); try { final String soqlQuery = SOQLBuilder.getInstanceWithFields(ContactObject.CONTACT_FIELDS) .from(Constants.CONTACT).limit(ContactListLoader.LIMIT).build(); final SyncTarget target = SyncTarget.targetForSOQLSyncDown(soqlQuery); syncMgr.syncDown(target, ContactListLoader.CONTACT_SOUP); } catch (JSONException e) { Log.e(TAG, "JSONException occurred while parsing", e); } } else { getLoaderManager().getLoader(CONTACT_LOADER_ID).forceLoad(); } } /** * Custom array adapter to supply data to the list view. * * @author bhariharan */ private static class ContactListAdapter extends ArrayAdapter<ContactObject> { private int listItemLayoutId; private List<ContactObject> sObjects; /** * Parameterized constructor. * * @param context Context. * @param listItemLayoutId List item view resource ID. */ public ContactListAdapter(Context context, int listItemLayoutId) { super(context, listItemLayoutId); this.listItemLayoutId = listItemLayoutId; } /** * Sets data to this adapter. * * @param data Data. */ public void setData(List<ContactObject> data) { clear(); sObjects = data; if (data != null) { addAll(data); notifyDataSetChanged(); } } @Override public View getView (int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(listItemLayoutId, null); } if (sObjects != null) { final ContactObject sObject = sObjects.get(position); if (sObject != null) { final TextView objName = (TextView) convertView.findViewById(R.id.obj_name); final TextView objType = (TextView) convertView.findViewById(R.id.obj_type); final TextView objImage = (TextView) convertView.findViewById(R.id.obj_image); if (objName != null) { objName.setText(sObject.getName()); } if (objType != null) { objType.setText(sObject.getTitle()); } if (objImage != null) { final String firstName = sObject.getFirstName(); String initials = Constants.EMPTY_STRING; if (firstName.length() > 0) { initials = firstName.substring(0, 1); } objImage.setText(initials); setBubbleColor(objImage, firstName); } final ImageView syncImage = (ImageView) convertView.findViewById(R.id.sync_status_view); if (syncImage != null && sObject.isLocallyModified()) { syncImage.setImageResource(R.drawable.sync_local); + } else { + syncImage.setImageResource(R.drawable.sync_success); } } } return convertView; } private void setBubbleColor(TextView tv, String firstName) { firstName = firstName.trim(); int code = 0; if (!TextUtils.isEmpty(firstName)) { for (int i = 0; i < firstName.length(); i++) { code += firstName.charAt(i); } } int colorIndex = code % CONTACT_COLORS.length; int color = CONTACT_COLORS[colorIndex]; final GradientDrawable drawable = new GradientDrawable(); drawable.setColor(color); drawable.setShape(GradientDrawable.OVAL); tv.setBackground(drawable); } } /** * A simple utility class to implement filtering. * * @author bhariharan */ private static class NameFieldFilter extends Filter { private ContactListAdapter adpater; private List<ContactObject> origList; /** * Parameterized constructor. * * @param adapter List adapter. * @param origList List to perform filtering against. */ public NameFieldFilter(ContactListAdapter adapter, List<ContactObject> origList) { this.adpater = adapter; this.origList = origList; } /** * Sets the original data set. * * @param origData Original data set. */ public void setOrigData(List<ContactObject> origData) { origList = origData; } @Override protected FilterResults performFiltering(CharSequence constraint) { if (origList == null) { return null; } final FilterResults results = new FilterResults(); if (TextUtils.isEmpty(constraint)) { results.values = origList; results.count = origList.size(); return results; } final String filterString = constraint.toString().toLowerCase(); int count = origList.size(); String filterableString; final List<ContactObject> resultSet = new ArrayList<ContactObject>(); for (int i = 0; i < count; i++) { filterableString = origList.get(i).getName(); if (filterableString.toLowerCase().contains(filterString)) { resultSet.add(origList.get(i)); } } results.values = resultSet; results.count = resultSet.size(); return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results != null && results.values != null) { adpater.setData((List<ContactObject>) results.values); } } } /** * A simple receiver for the sync completed event. * * @author bhariharan */ private class SyncReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent != null) { final String action = intent.getAction(); if (action != null && action.equals(SyncManager.SYNC_INTENT_ACTION)) { final String syncStatus = intent.getStringExtra(SyncState.SYNC_STATUS); if (syncStatus != null && syncStatus.equals(SyncState.Status.DONE.name())) { getLoaderManager().getLoader(CONTACT_LOADER_ID).forceLoad(); } } } } } }
true
true
public View getView (int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(listItemLayoutId, null); } if (sObjects != null) { final ContactObject sObject = sObjects.get(position); if (sObject != null) { final TextView objName = (TextView) convertView.findViewById(R.id.obj_name); final TextView objType = (TextView) convertView.findViewById(R.id.obj_type); final TextView objImage = (TextView) convertView.findViewById(R.id.obj_image); if (objName != null) { objName.setText(sObject.getName()); } if (objType != null) { objType.setText(sObject.getTitle()); } if (objImage != null) { final String firstName = sObject.getFirstName(); String initials = Constants.EMPTY_STRING; if (firstName.length() > 0) { initials = firstName.substring(0, 1); } objImage.setText(initials); setBubbleColor(objImage, firstName); } final ImageView syncImage = (ImageView) convertView.findViewById(R.id.sync_status_view); if (syncImage != null && sObject.isLocallyModified()) { syncImage.setImageResource(R.drawable.sync_local); } } } return convertView; }
public View getView (int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(listItemLayoutId, null); } if (sObjects != null) { final ContactObject sObject = sObjects.get(position); if (sObject != null) { final TextView objName = (TextView) convertView.findViewById(R.id.obj_name); final TextView objType = (TextView) convertView.findViewById(R.id.obj_type); final TextView objImage = (TextView) convertView.findViewById(R.id.obj_image); if (objName != null) { objName.setText(sObject.getName()); } if (objType != null) { objType.setText(sObject.getTitle()); } if (objImage != null) { final String firstName = sObject.getFirstName(); String initials = Constants.EMPTY_STRING; if (firstName.length() > 0) { initials = firstName.substring(0, 1); } objImage.setText(initials); setBubbleColor(objImage, firstName); } final ImageView syncImage = (ImageView) convertView.findViewById(R.id.sync_status_view); if (syncImage != null && sObject.isLocallyModified()) { syncImage.setImageResource(R.drawable.sync_local); } else { syncImage.setImageResource(R.drawable.sync_success); } } } return convertView; }
diff --git a/src/api/org/openmrs/util/OpenmrsUtil.java b/src/api/org/openmrs/util/OpenmrsUtil.java index ecec4f4e..a8492f3d 100644 --- a/src/api/org/openmrs/util/OpenmrsUtil.java +++ b/src/api/org/openmrs/util/OpenmrsUtil.java @@ -1,1511 +1,1512 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.Vector; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.openmrs.Cohort; import org.openmrs.Concept; import org.openmrs.ConceptNumeric; import org.openmrs.Drug; import org.openmrs.EncounterType; import org.openmrs.Form; import org.openmrs.Location; import org.openmrs.PersonAttributeType; import org.openmrs.Program; import org.openmrs.ProgramWorkflowState; import org.openmrs.User; import org.openmrs.api.APIException; import org.openmrs.api.AdministrationService; import org.openmrs.api.ConceptService; import org.openmrs.api.PatientIdentifierException; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.cohort.CohortSearchHistory; import org.openmrs.module.ModuleException; import org.openmrs.patient.IdentifierValidator; import org.openmrs.propertyeditor.CohortEditor; import org.openmrs.propertyeditor.ConceptEditor; import org.openmrs.propertyeditor.DrugEditor; import org.openmrs.propertyeditor.EncounterTypeEditor; import org.openmrs.propertyeditor.FormEditor; import org.openmrs.propertyeditor.LocationEditor; import org.openmrs.propertyeditor.PersonAttributeTypeEditor; import org.openmrs.propertyeditor.ProgramEditor; import org.openmrs.propertyeditor.ProgramWorkflowStateEditor; import org.openmrs.report.EvaluationContext; import org.openmrs.reporting.CohortFilter; import org.openmrs.reporting.PatientFilter; import org.openmrs.reporting.PatientSearch; import org.openmrs.reporting.PatientSearchReportObject; import org.openmrs.reporting.SearchArgument; import org.openmrs.xml.OpenmrsCycleStrategy; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.load.Persister; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; /** * Utility methods used in openmrs */ public class OpenmrsUtil { private static Log log = LogFactory.getLog(OpenmrsUtil.class); /** * * @param idWithoutCheckdigit * @return * @throws Exception * @deprecated Should be using PatientService.getPatientIdentifierValidator() */ public static int getCheckDigit(String idWithoutCheckdigit) throws Exception { PatientService ps = Context.getPatientService(); IdentifierValidator piv = ps.getDefaultIdentifierValidator(); String withCheckDigit = piv.getValidIdentifier(idWithoutCheckdigit); char checkDigitChar = withCheckDigit.charAt(withCheckDigit.length()-1); if(Character.isDigit(checkDigitChar)) return Integer.parseInt(""+checkDigitChar); else{ switch(checkDigitChar){ case 'A': case 'a' : return 0; case 'B': case 'b' : return 1; case 'C': case 'c' : return 2; case 'D': case 'd' : return 3; case 'E': case 'e' : return 4; case 'F': case 'f' : return 5; case 'G': case 'g' : return 6; case 'H': case 'h' : return 7; case 'I': case 'i' : return 8; case 'J': case 'j' : return 9; default: return 10; } } } /** * * @param id * @return true/false whether id has a valid check digit * @throws Exception * on invalid characters and invalid id formation * @deprecated Should be using PatientService.getPatientIdentifierValidator().isValid(); */ public static boolean isValidCheckDigit(String id) throws Exception { PatientService ps = Context.getPatientService(); IdentifierValidator piv = ps.getDefaultIdentifierValidator(); return piv.isValid(id); } /** * Compares origList to newList returning map of differences * * @param origList * @param newList * @return [List toAdd, List toDelete] with respect to origList */ public static <E extends Object> Collection<Collection<E>> compareLists(Collection<E> origList, Collection<E> newList) { // TODO finish function Collection<Collection<E>> returnList = new Vector<Collection<E>>(); Collection<E> toAdd = new LinkedList<E>(); Collection<E> toDel = new LinkedList<E>(); // loop over the new list. for (E currentNewListObj : newList) { // loop over the original list boolean foundInList = false; for (E currentOrigListObj : origList) { // checking if the current new list object is in the original // list if (currentNewListObj.equals(currentOrigListObj)) { foundInList = true; origList.remove(currentOrigListObj); break; } } if (!foundInList) toAdd.add(currentNewListObj); // all found new objects were removed from the orig list, // leaving only objects needing to be removed toDel = origList; } returnList.add(toAdd); returnList.add(toDel); return returnList; } public static boolean isStringInArray(String str, String[] arr) { boolean retVal = false; if (str != null && arr != null) { for (int i = 0; i < arr.length; i++) { if (str.equals(arr[i])) retVal = true; } } return retVal; } public static Boolean isInNormalNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiNormal() == null || concept.getLowNormal() == null) return false; return (value <= concept.getHiNormal() && value >= concept .getLowNormal()); } public static Boolean isInCriticalNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiCritical() == null || concept.getLowCritical() == null) return false; return (value <= concept.getHiCritical() && value >= concept .getLowCritical()); } public static Boolean isInAbsoluteNumericRange(Float value, ConceptNumeric concept) { if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null) return false; return (value <= concept.getHiAbsolute() && value >= concept .getLowAbsolute()); } public static Boolean isValidNumericValue(Float value, ConceptNumeric concept) { if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null) return true; return (value <= concept.getHiAbsolute() && value >= concept .getLowAbsolute()); } /** * Return a string representation of the given file * * @param file * @return String file contents * @throws IOException */ public static String getFileAsString(File file) throws IOException { StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader(new FileReader(file)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); return fileData.toString(); } /** * Return a byte array representation of the given file * * @param file * @return byte[] file contents * @throws IOException */ public static byte[] getFileAsBytes(File file) throws IOException { try { FileInputStream fileInputStream = new FileInputStream (file); byte[] b = new byte[fileInputStream.available ()]; fileInputStream.read(b); fileInputStream.close (); return b; } catch (Exception e) { log.error("Unable to get file as byte array", e); } return null; } /** * Copy file from inputStream onto the outputStream * * inputStream is not closed in this method * outputStream /is/ closed at completion of this method * * @param inputStream Stream to copy from * @param outputStream Stream/location to copy to * @throws IOException thrown if an error occurs during read/write */ public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { try { outputStream.close(); } catch (Exception e) { /* pass */ } } return; } InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(inputStream); out = new BufferedOutputStream(outputStream); while (true) { int data = in.read(); if (data == -1) { break; } out.write(data); } } finally { if (in != null) in.close(); if (out != null) out.close(); try { outputStream.close(); } catch (Exception e) { /* pass */ } } } /** * Look for a file named <code>filename</code> in folder * * @param folder * @param filename * @return true/false whether filename exists in folder */ public static boolean folderContains(File folder, String filename) { if (folder == null) return false; if (!folder.isDirectory()) return false; for (File f : folder.listFiles()) { if (f.getName().equals(filename)) return true; } return false; } /** * Initialize global settings * Find and load modules * * @param p properties from runtime configuration */ public static void startup(Properties p) { // Override global OpenMRS constants if specified by the user // Allow for "demo" mode where patient data is obscured String val = p.getProperty("obscure_patients", null); if (val != null && "true".equalsIgnoreCase(val)) OpenmrsConstants.OBSCURE_PATIENTS = true; val = p.getProperty("obscure_patients.family_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME = val; val = p.getProperty("obscure_patients.given_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME = val; val = p.getProperty("obscure_patients.middle_name", null); if (val != null) OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME = val; // Override the default "openmrs" database name val = p.getProperty("connection.database_name", null); if (val == null) { // the database name wasn't supplied explicitly, guess it // from the connection string val = p.getProperty("connection.url", null); if (val != null) { try { int endIndex = val.lastIndexOf("?"); if (endIndex == -1) endIndex = val.length(); int startIndex = val.lastIndexOf("/", endIndex); val = val.substring(startIndex + 1, endIndex); OpenmrsConstants.DATABASE_NAME = val; } catch (Exception e) { log.fatal("Database name cannot be configured from 'connection.url' ." + "Either supply 'connection.database_name' or correct the url", e); } } } // set the business database name val = p.getProperty("connection.database_business_name", null); if (val == null) val = OpenmrsConstants.DATABASE_NAME; OpenmrsConstants.DATABASE_BUSINESS_NAME = val; // set the application data directory val = p.getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY, null); if (val != null) OpenmrsConstants.APPLICATION_DATA_DIRECTORY = val; // set global log level applyLogLevels(); } /** * Set the org.openmrs log4j logger's level if global property log.level.openmrs * ( OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL ) exists. * Valid values for global property are trace, debug, info, * warn, error or fatal. */ public static void applyLogLevels() { AdministrationService adminService = Context.getAdministrationService(); String logLevel = adminService.getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL); String logClass = OpenmrsConstants.LOG_CLASS_DEFAULT; // potentially have different levels here. only doing org.openmrs right now applyLogLevel(logClass, logLevel); } /** * Set the log4j log level for class <code>logClass</code> to <code>logLevel</code>. * * * @param logClass optional string giving the class level to change. Defaults to * OpenmrsConstants.LOG_CLASS_DEFAULT . Should be something like org.openmrs.___ * @param level one of OpenmrsConstants.LOG_LEVEL_* */ public static void applyLogLevel(String logClass, String logLevel) { if(logLevel != null) { // the default log level is org.openmrs if (logClass == null || "".equals(logClass)) logClass = OpenmrsConstants.LOG_CLASS_DEFAULT; Logger logger = Logger.getLogger(logClass); logLevel = logLevel.toLowerCase(); if(OpenmrsConstants.LOG_LEVEL_TRACE.equals(logLevel) ) { logger.setLevel(Level.TRACE); } else if(OpenmrsConstants.LOG_LEVEL_DEBUG.equals(logLevel) ) { logger.setLevel(Level.DEBUG); } else if(OpenmrsConstants.LOG_LEVEL_INFO.equals(logLevel) ) { logger.setLevel(Level.INFO); } else if(OpenmrsConstants.LOG_LEVEL_WARN.equals(logLevel) ) { logger.setLevel(Level.WARN); } else if(OpenmrsConstants.LOG_LEVEL_ERROR.equals(logLevel) ) { logger.setLevel(Level.ERROR); } else if(OpenmrsConstants.LOG_LEVEL_FATAL.equals(logLevel) ) { logger.setLevel(Level.FATAL); } else { log.warn("Global property " + logLevel + " is invalid. " + "Valid values are trace, debug, info, warn, error or fatal"); } } } /** * Takes a String like "size=compact|order=date" and returns a Map<String,String> from the keys to the values. * @param paramList * @return */ public static Map<String, String> parseParameterList(String paramList) { Map<String, String> ret = new HashMap<String, String>(); if (paramList != null && paramList.length() > 0) { String[] args = paramList.split("\\|"); for (String s : args) { int ind = s.indexOf('='); if (ind <= 0) { throw new IllegalArgumentException("Misformed argument in dynamic page specification string: '" + s + "' is not 'key=value'."); } String name = s.substring(0, ind); String value = s.substring(ind + 1); ret.put(name, value); } } return ret; } public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) { if (d1 == null) return d2 == null; else if (d2 == null) return false; else return d1.equals(d2); } /** * Compares two java.util.Date objects, but handles java.sql.Timestamp (which is not directly comparable to a date) * by dropping its nanosecond value. */ public static int compare(Date d1, Date d2) { if (d1 instanceof Timestamp && d2 instanceof Timestamp) { return d1.compareTo(d2); } if (d1 instanceof Timestamp) d1 = new Date(((Timestamp) d1).getTime()); if (d2 instanceof Timestamp) d2 = new Date(((Timestamp) d2).getTime()); return d1.compareTo(d2); } /** * Compares two Date/Timestamp objects, treating null as the earliest possible date. */ public static int compareWithNullAsEarliest(Date d1, Date d2) { if (d1 == null && d2 == null) return 0; if (d1 == null) return -1; else if (d2 == null) return 1; else return compare(d1, d2); } /** * Compares two Date/Timestamp objects, treating null as the earliest possible date. */ public static int compareWithNullAsLatest(Date d1, Date d2) { if (d1 == null && d2 == null) return 0; if (d1 == null) return 1; else if (d2 == null) return -1; else return compare(d1, d2); } public static <E extends Comparable<E>> int compareWithNullAsLowest(E c1, E c2) { if (c1 == null && c2 == null) return 0; if (c1 == null) return -1; else if (c2 == null) return 1; else return c1.compareTo(c2); } public static <E extends Comparable<E>> int compareWithNullAsGreatest(E c1, E c2) { if (c1 == null && c2 == null) return 0; if (c1 == null) return 1; else if (c2 == null) return -1; else return c1.compareTo(c2); } public static Integer ageFromBirthdate(Date birthdate) { if (birthdate == null) return null; Calendar today = Calendar.getInstance(); Calendar bday = new GregorianCalendar(); bday.setTime(birthdate); int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR); //tricky bit: // set birthday calendar to this year // if the current date is less that the new 'birthday', subtract a year bday.set(Calendar.YEAR, today.get(Calendar.YEAR)); if (today.before(bday)) { age = age -1; } return age; } /** * Converts a collection to a String with a specified separator between all elements * @param c Collection to be joined * @param separator string to put between all elements * @return a String representing the toString() of all elements in c, separated by separator */ public static <E extends Object> String join(Collection<E> c, String separator) { if (c == null) return ""; StringBuilder ret = new StringBuilder(); for (Iterator<E> i = c.iterator(); i.hasNext(); ) { ret.append(i.next()); if (i.hasNext()) ret.append(separator); } return ret.toString(); } public static Set<Concept> conceptSetHelper(String descriptor) { Set<Concept> ret = new HashSet<Concept>(); if (descriptor == null || descriptor.length() == 0) return ret; ConceptService cs = Context.getConceptService(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens(); ) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) s = s.substring(4).trim(); Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) { } } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsInSet(c); ret.addAll(inSet); } else { ret.add(c); } } } return ret; } public static List<Concept> delimitedStringToConceptList( String delimitedString, String delimiter, Context context ) { List<Concept> ret = null; if ( delimitedString != null && context != null ) { String[] tokens = delimitedString.split(delimiter); for ( String token : tokens ) { Integer conceptId = null; try { conceptId = new Integer(token); } catch (NumberFormatException nfe) { conceptId = null; } Concept c = null; if ( conceptId != null ) { c = Context.getConceptService().getConcept(conceptId); } else { c = Context.getConceptService().getConceptByName(token); } if ( c != null ) { if ( ret == null ) ret = new ArrayList<Concept>(); ret.add(c); } } } return ret; } public static Map<String, Concept> delimitedStringToConceptMap( String delimitedString, String delimiter) { Map<String,Concept> ret = null; if ( delimitedString != null) { String[] tokens = delimitedString.split(delimiter); for ( String token : tokens ) { Concept c = OpenmrsUtil.getConceptByIdOrName(token); if ( c != null ) { if ( ret == null ) ret = new HashMap<String, Concept>(); ret.put(token, c); } } } return ret; } // DEPRECATED: This method should now be replaced with ConceptService.getConceptByIdOrName() public static Concept getConceptByIdOrName(String idOrName) { Concept c = null; Integer conceptId = null; try { conceptId = new Integer(idOrName); } catch (NumberFormatException nfe) { conceptId = null; } if ( conceptId != null ) { c = Context.getConceptService().getConcept(conceptId); } else { c = Context.getConceptService().getConceptByName(idOrName); } return c; } // TODO: properly handle duplicates public static List<Concept> conceptListHelper(String descriptor) { List<Concept> ret = new ArrayList<Concept>(); if (descriptor == null || descriptor.length() == 0) return ret; ConceptService cs = Context.getConceptService(); for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens(); ) { String s = st.nextToken().trim(); boolean isSet = s.startsWith("set:"); if (isSet) s = s.substring(4).trim(); Concept c = null; if (s.startsWith("name:")) { String name = s.substring(5).trim(); c = cs.getConceptByName(name); } else { try { c = cs.getConcept(Integer.valueOf(s.trim())); } catch (Exception ex) { } } if (c != null) { if (isSet) { List<Concept> inSet = cs.getConceptsInSet(c); ret.addAll(inSet); } else { ret.add(c); } } } return ret; } public static Date lastSecondOfDay(Date date) { if (date == null) return null; Calendar c = new GregorianCalendar(); c.setTime(date); // TODO: figure out the right way to do this (or at least set milliseconds to zero) c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.add(Calendar.DAY_OF_MONTH, 1); c.add(Calendar.SECOND, -1); return c.getTime(); } public static Date safeDate(Date d1) { return new Date(d1.getTime()); } /** * Recursively deletes files in the given <code>dir</code> folder * * @param dir File directory to delete * @return true/false whether the delete was completed successfully * @throws IOException if <code>dir</code> is not a directory */ public static boolean deleteDirectory(File dir) throws IOException { if (!dir.exists() || !dir.isDirectory()) throw new IOException("Could not delete directory '" + dir.getAbsolutePath() + "' (not a directory)"); if (log.isDebugEnabled()) log.debug("Deleting directory " + dir.getAbsolutePath()); File[] fileList = dir.listFiles(); for (File f : fileList) { if (f.isDirectory()) deleteDirectory(f); boolean success = f.delete(); if (log.isDebugEnabled()) log.debug(" deleting " + f.getName() + " : " + (success ? "ok" : "failed")); if (!success) f.deleteOnExit(); } boolean success = dir.delete(); if (!success) { log.warn(" ...could not remove directory: " + dir.getAbsolutePath()); dir.deleteOnExit(); } if (success && log.isDebugEnabled()) log.debug(" ...and directory itself"); return success; } /** * Utility method to convert local URL to a File object. * @param url an URL * @return file object for given URL or <code>null</code> if URL is not * local */ public static File url2file(final URL url) { if (!"file".equalsIgnoreCase(url.getProtocol())) { return null; } return new File(url.getFile().replaceAll("%20", " ")); } /** * Opens input stream for given resource. This method behaves differently * for different URL types: * <ul> * <li>for <b>local files</b> it returns buffered file input stream;</li> * <li>for <b>local JAR files</b> it reads resource content into memory * buffer and returns byte array input stream that wraps those * buffer (this prevents locking JAR file);</li> * <li>for <b>common URL's</b> this method simply opens stream to that URL * using standard URL API.</li> * </ul> * It is not recommended to use this method for big resources within JAR * files. * @param url resource URL * @return input stream for given resource * @throws IOException if any I/O error has occurred */ public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { //JAR URL points to a root entry throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) {// non-local JAR file URL return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyFile(in, out); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } } /** * @return The path to the directory on the file system that will hold miscellaneous * data about the application (runtime properties, modules, etc) */ public static String getApplicationDataDirectory() { String filepath = null; if (OpenmrsConstants.APPLICATION_DATA_DIRECTORY != null) { filepath = OpenmrsConstants.APPLICATION_DATA_DIRECTORY; } else { if (OpenmrsConstants.OPERATING_SYSTEM_LINUX.equalsIgnoreCase(OpenmrsConstants.OPERATING_SYSTEM) || OpenmrsConstants.OPERATING_SYSTEM_FREEBSD.equalsIgnoreCase(OpenmrsConstants.OPERATING_SYSTEM) || OpenmrsConstants.OPERATING_SYSTEM_OSX.equalsIgnoreCase(OpenmrsConstants.OPERATING_SYSTEM)) filepath = System.getProperty("user.home") + File.separator + ".OpenMRS"; else filepath = System.getProperty("user.home") + File.separator + "Application Data" + File.separator + "OpenMRS"; filepath = filepath + File.separator; } File folder = new File(filepath); if (!folder.exists()) folder.mkdirs(); return filepath; } /** * Find the given folderName in the application data directory. Or, treat * folderName like an absolute url to a directory * * @param folderName * @return folder capable of storing information */ public static File getDirectoryInApplicationDataDirectory(String folderName) throws APIException { // try to load the repository folder straight away. File folder = new File(folderName); // if the property wasn't a full path already, assume it was intended to be a folder in the // application directory if (!folder.isAbsolute()) { folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName); } // now create the directory folder if it doesn't exist if (!folder.exists()) { log.warn("'" + folder.getAbsolutePath() + "' doesn't exist. Creating directories now."); folder.mkdirs(); } if (!folder.isDirectory()) throw new APIException("'" + folder.getAbsolutePath() + "' should be a directory but it is not"); return folder; } /** * Save the given xml document to the given outfile * @param doc Document to be saved * @param outFile file pointer to the location the xml file is to be saved to */ public static void saveDocument(Document doc, File outFile) { OutputStream outStream = null; try { outStream = new FileOutputStream(outFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DocumentType doctype = doc.getDoctype(); if (doctype != null) { transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(outStream); transformer.transform(source, result); } catch (TransformerException e) { throw new ModuleException("Error while saving dwrmodulexml back to dwr-modules.xml", e); } catch (FileNotFoundException e) { throw new ModuleException("/WEB-INF/dwr-modules.xml file doesn't exist.", e); } finally { try { if (outStream != null) outStream.close(); } catch (Exception e) { log.warn("Unable to close outstream", e); } } } public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) { List<Integer> ret = new ArrayList<Integer>(); String[] tokens = delimitedString.split(delimiter); for (String token : tokens) { token = token.trim(); if (token.length() == 0) continue; else ret.add(Integer.valueOf(token)); } return ret; } public static boolean isConceptInList(Concept concept, List<Concept> list) { boolean ret = false; if ( concept != null && list != null ) { for ( Concept c : list ) { if ( c.equals(concept) ) { ret = true; break; } } } return ret; } public static Date fromDateHelper( Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) { Date ret = null; if (withinLastDays != null || withinLastMonths != null) { Calendar gc = new GregorianCalendar(); gc.setTime(comparisonDate != null ? comparisonDate : new Date()); if (withinLastDays != null) gc.add(Calendar.DAY_OF_MONTH, -withinLastDays); if (withinLastMonths != null) gc.add(Calendar.MONTH, -withinLastMonths); ret = gc.getTime(); } if (sinceDate != null && (ret == null || sinceDate.after(ret))) ret = sinceDate; return ret; } public static Date toDateHelper( Date comparisonDate, Integer withinLastDays, Integer withinLastMonths, Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) { Date ret = null; if (untilDaysAgo != null || untilMonthsAgo != null) { Calendar gc = new GregorianCalendar(); gc.setTime(comparisonDate != null ? comparisonDate : new Date()); if (untilDaysAgo != null) gc.add(Calendar.DAY_OF_MONTH, -untilDaysAgo); if (untilMonthsAgo != null) gc.add(Calendar.MONTH, -untilMonthsAgo); ret = gc.getTime(); } if (untilDate != null && (ret == null || untilDate.before(ret))) ret = untilDate; return ret; } /** * @param collection * @param elements * @return Whether _collection_ contains any of _elements_ */ public static <T> boolean containsAny(Collection<T> collection, Collection<T> elements) { for (T obj : elements) { if (collection.contains(obj)) return true; } return false; } /** * Allows easy manipulation of a Map<?, Set> */ public static <K, V> void addToSetMap(Map<K, Set<V>> map, K key, V obj) { Set<V> set = map.get(key); if (set == null) { set = new HashSet<V>(); map.put(key, set); } set.add(obj); } public static <K, V> void addToListMap(Map<K, List<V>> map, K key, V obj) { List<V> list = map.get(key); if (list == null) { list = new ArrayList<V>(); map.put(key, list); } list.add(obj); } /** * Get the current user's date format * Will look similar to "mm-dd-yyyy". Depends on user's locale. * * @return a simple date format */ public static SimpleDateFormat getDateFormat() { String localeKey = Context.getLocale().toString().toLowerCase(); // get the actual pattern from the constants String pattern = OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(localeKey); // default to the "first" locale pattern if (pattern == null) pattern = OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(0); return new SimpleDateFormat(pattern, Context.getLocale()); } public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history) { return toPatientFilter(search, history, null); } /** * Takes a String (e.g. a user-entered one) and parses it into an object of the specified class * * @param string * @param clazz * @return */ public static Object parse(String string, Class clazz) { try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = clazz.getMethod("valueOf", String.class ); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { return valueOfMethod.invoke(null, string); } else if (clazz.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants()); for (Enum e : constants) if (e.toString().equals(string)) return e; throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz); } else if (String.class.equals(clazz)) { return string; } else if (Location.class.equals(clazz)) { try { Integer.parseInt(string); LocationEditor ed = new LocationEditor(); ed.setAsText(string); return ed.getValue(); } catch (NumberFormatException ex) { return Context.getEncounterService().getLocationByName(string); } } else if (Concept.class.equals(clazz)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(string); return ed.getValue(); } else if (Program.class.equals(clazz)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(string); return ed.getValue(); } else if (ProgramWorkflowState.class.equals(clazz)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(string); return ed.getValue(); } else if (EncounterType.class.equals(clazz)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Form.class.equals(clazz)) { FormEditor ed = new FormEditor(); ed.setAsText(string); return ed.getValue(); } else if (Drug.class.equals(clazz)) { DrugEditor ed = new DrugEditor(); ed.setAsText(string); return ed.getValue(); } else if (PersonAttributeType.class.equals(clazz)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(string); return ed.getValue(); } else if (Cohort.class.equals(clazz)) { CohortEditor ed = new CohortEditor(); ed.setAsText(string); return ed.getValue(); } else if (Date.class.equals(clazz)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(string); return ed.getValue(); } else if (Object.class.equals(clazz)) { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String return string; } else { throw new IllegalArgumentException("Don't know how to handle class: " + clazz); } } catch (Exception ex) { log.error("error converting \"" + string + "\" to " + clazz, ex); throw new IllegalArgumentException(ex); } } /** * Uses reflection to translate a PatientSearch into a PatientFilter */ @SuppressWarnings("unchecked") public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { return new CohortFilter(Context.getCohortService().getCohort(search.getSavedCohortId())); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument - String valueAsString = search.getArgumentValue(sa.getName()); - if (evalContext != null && EvaluationContext.isExpression(valueAsString)) { - log.debug("found expression: " + valueAsString); - Object evaluated = evalContext.evaluateExpression(valueAsString); + String valueAsString = sa.getValue(); + String testForExpression = search.getArgumentValue(sa.getName()); + if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { + log.debug("found expression: " + testForExpression); + Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("evaluated to: " + valueAsString); } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } } /** * Loops over the collection to check to see if the given object is in that * collection. * * This method <i>only</i> uses the .equals() method for comparison. This should * be used in the patient/person objects on their collections. Their collections * are SortedSets which use the compareTo method for equality as well. The compareTo * method is currently optimized for sorting, not for equality * * A null <code>obj</code> will return false * * @param objects collection to loop over * @param obj Object to look for in the <code>objects</code> * @return true/false whether the given object is found */ public static boolean collectionContains(Collection<?> objects, Object obj) { if (obj == null || objects == null) return false; for (Object o : objects) { if (o.equals(obj)) return true; } return false; } /** * Get a serializer that will do the common type of serialization and deserialization. * Cycles of objects are taken into account * * @return Serializer to do the (de)serialization */ public static Serializer getSerializer() { return new Persister(new OpenmrsCycleStrategy()); } /** * Get a short serializer that will only do the very basic serialization * necessary. This is controlled by the objects that are being serialized * via the @Replace methods * * @return Serializer to do the short (de)serialization * * @see OpenmrsConstants#SHORT_SERIALIZATION */ public static Serializer getShortSerializer() { return new Persister(new OpenmrsCycleStrategy(true)); } /** * True/false whether the current serialization is supposed to be a short serialization. * A shortened serialization * * This should be called from methods marked with the @Replace notation that take in * a single <code>Map</code> parameter. * * @param sessionMap current serialization session * @return true/false whether or not to do the shortened serialization */ public static boolean isShortSerialization(Map<?, ?> sessionMap) { return sessionMap.containsKey(OpenmrsConstants.SHORT_SERIALIZATION); } /** * Gets an out File object. If date is not provided, the current * timestamp is used. * * If user is not provided, the user id is not put into the filename. * * Assumes dir is already created * * @param dir directory to make the random filename in * @param date optional Date object used for the name * @param user optional User creating this file object * @return file new file that is able to be written to */ public static File getOutFile(File dir, Date date, User user) { File outFile; do { // format to print date in filenmae DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd-HHmm-ssSSS"); // use current date if none provided if (date == null) date = new Date(); StringBuilder filename = new StringBuilder(); // the start of the filename is the time so we can do some sorting filename.append(dateFormat.format(date)); // insert the user id if they provided it if (user != null) { filename.append("-"); filename.append(user.getUserId()); filename.append("-"); } // the end of the filename is a randome number between 0 and 10000 filename.append((int)(Math.random() * 10000)); filename.append(".xml"); outFile = new File(dir, filename.toString()); // set to null to avoid very minimal possiblity of an infinite loop date = null; } while (outFile.exists()); return outFile; } /** * Creates a relatively acceptable unique string of the give size * * @return unique string */ public static String generateUid(Integer size) { StringBuffer sb = new StringBuffer(size); for (int i = 0; i < size; i++) { int ch = (int) (Math.random() * 62); if (ch < 10) // 0-9 sb.append(ch); else if (ch < 36) // a-z sb.append((char) (ch - 10 + 'a')); else sb.append((char) (ch - 36 + 'A')); } return sb.toString(); } /** * Creates a uid of length 20 * * @see #generateUid(Integer) */ public static String generateUid() { return generateUid(20); } }
true
true
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { return new CohortFilter(Context.getCohortService().getCohort(search.getSavedCohortId())); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = search.getArgumentValue(sa.getName()); if (evalContext != null && EvaluationContext.isExpression(valueAsString)) { log.debug("found expression: " + valueAsString); Object evaluated = evalContext.evaluateExpression(valueAsString); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("evaluated to: " + valueAsString); } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { return new CohortFilter(Context.getCohortService().getCohort(search.getSavedCohortId())); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) throw new IllegalArgumentException("You can't evaluate this search without a history"); else return search.cloneCompositionAsFilter(history, evalContext); } else { Class clz = search.getFilterClass(); if (clz == null) throw new IllegalArgumentException("search must be saved, composition, or must have a class specified"); log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { log.debug("found expression: " + testForExpression); Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) valueAsString = Context.getDateFormat().format((Date) evaluated); else valueAsString = evaluated.toString(); } log.debug("evaluated to: " + valueAsString); } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching. DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else { // TODO: Decide whether this is a hack. Currently setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. I'm going with the following rules, which should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
diff --git a/core/src/com/google/zxing/multi/GenericMultipleBarcodeReader.java b/core/src/com/google/zxing/multi/GenericMultipleBarcodeReader.java index 3cd392ee..25079e19 100644 --- a/core/src/com/google/zxing/multi/GenericMultipleBarcodeReader.java +++ b/core/src/com/google/zxing/multi/GenericMultipleBarcodeReader.java @@ -1,147 +1,153 @@ /* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.multi; import com.google.zxing.Reader; import com.google.zxing.Result; import com.google.zxing.BinaryBitmap; import com.google.zxing.ReaderException; import com.google.zxing.ResultPoint; import java.util.Hashtable; import java.util.Vector; /** * <p>Attempts to locate multiple barcodes in an image by repeatedly decoding portion of the image. * After one barcode is found, the areas left, above, right and below the barcode's * {@link com.google.zxing.ResultPoint}s are scanned, recursively.</p> * * <p>A caller may want to also employ {@link ByQuadrantReader} when attempting to find multiple * 2D barcodes, like QR Codes, in an image, where the presence of multiple barcodes might prevent * detecting any one of them.</p> * * <p>That is, instead of passing a {@link Reader} a caller might pass * <code>new ByQuadrantReader(reader)</code>.</p> * * @author Sean Owen */ public final class GenericMultipleBarcodeReader implements MultipleBarcodeReader { private static final int MIN_DIMENSION_TO_RECUR = 30; private final Reader delegate; public GenericMultipleBarcodeReader(Reader delegate) { this.delegate = delegate; } public Result[] decodeMultiple(BinaryBitmap image) throws ReaderException { return decodeMultiple(image, null); } public Result[] decodeMultiple(BinaryBitmap image, Hashtable hints) throws ReaderException { Vector results = new Vector(); doDecodeMultiple(image, hints, results, 0, 0); if (results.isEmpty()) { throw ReaderException.getInstance(); } int numResults = results.size(); Result[] resultArray = new Result[numResults]; for (int i = 0; i < numResults; i++) { resultArray[i] = (Result) results.elementAt(i); } return resultArray; } private void doDecodeMultiple(BinaryBitmap image, Hashtable hints, Vector results, int xOffset, int yOffset) { Result result; try { result = delegate.decode(image, hints); } catch (ReaderException re) { return; } boolean alreadyFound = false; for (int i = 0; i < results.size(); i++) { Result existingResult = (Result) results.elementAt(i); if (existingResult.getText().equals(result.getText())) { alreadyFound = true; break; } } if (alreadyFound) { return; } results.addElement(translateResultPoints(result, xOffset, yOffset)); ResultPoint[] resultPoints = result.getResultPoints(); if (resultPoints == null || resultPoints.length == 0) { return; } int width = image.getWidth(); int height = image.getHeight(); float minX = width; float minY = height; float maxX = 0.0f; float maxY = 0.0f; for (int i = 0; i < resultPoints.length; i++) { ResultPoint point = resultPoints[i]; float x = point.getX(); float y = point.getY(); if (x < minX) { minX = x; } if (y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } + // Decode left of barcode if (minX > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, 0, 0); } + // Decode above barcode if (minY > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, 0, 0); } + // Decode right of barcode if (maxX < width - MIN_DIMENSION_TO_RECUR) { - doDecodeMultiple(image.crop((int) maxX, 0, width, height), hints, results, (int) maxX, 0); + doDecodeMultiple(image.crop((int) maxX, 0, MIN_DIMENSION_TO_RECUR - (int) maxX, height), + hints, results, (int) maxX, 0); } + // Decode below barcode if (maxY < height - MIN_DIMENSION_TO_RECUR) { - doDecodeMultiple(image.crop(0, (int) maxY, width, height), hints, results, 0, (int) maxY); + doDecodeMultiple(image.crop(0, (int) maxY, width, MIN_DIMENSION_TO_RECUR - (int) maxY), + hints, results, 0, (int) maxY); } } private static Result translateResultPoints(Result result, int xOffset, int yOffset) { ResultPoint[] oldResultPoints = result.getResultPoints(); ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length]; for (int i = 0; i < oldResultPoints.length; i++) { ResultPoint oldPoint = oldResultPoints[i]; newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset); } return new Result(result.getText(), result.getRawBytes(), newResultPoints, result.getBarcodeFormat()); } }
false
true
private void doDecodeMultiple(BinaryBitmap image, Hashtable hints, Vector results, int xOffset, int yOffset) { Result result; try { result = delegate.decode(image, hints); } catch (ReaderException re) { return; } boolean alreadyFound = false; for (int i = 0; i < results.size(); i++) { Result existingResult = (Result) results.elementAt(i); if (existingResult.getText().equals(result.getText())) { alreadyFound = true; break; } } if (alreadyFound) { return; } results.addElement(translateResultPoints(result, xOffset, yOffset)); ResultPoint[] resultPoints = result.getResultPoints(); if (resultPoints == null || resultPoints.length == 0) { return; } int width = image.getWidth(); int height = image.getHeight(); float minX = width; float minY = height; float maxX = 0.0f; float maxY = 0.0f; for (int i = 0; i < resultPoints.length; i++) { ResultPoint point = resultPoints[i]; float x = point.getX(); float y = point.getY(); if (x < minX) { minX = x; } if (y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } if (minX > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, 0, 0); } if (minY > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, 0, 0); } if (maxX < width - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop((int) maxX, 0, width, height), hints, results, (int) maxX, 0); } if (maxY < height - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, (int) maxY, width, height), hints, results, 0, (int) maxY); } }
private void doDecodeMultiple(BinaryBitmap image, Hashtable hints, Vector results, int xOffset, int yOffset) { Result result; try { result = delegate.decode(image, hints); } catch (ReaderException re) { return; } boolean alreadyFound = false; for (int i = 0; i < results.size(); i++) { Result existingResult = (Result) results.elementAt(i); if (existingResult.getText().equals(result.getText())) { alreadyFound = true; break; } } if (alreadyFound) { return; } results.addElement(translateResultPoints(result, xOffset, yOffset)); ResultPoint[] resultPoints = result.getResultPoints(); if (resultPoints == null || resultPoints.length == 0) { return; } int width = image.getWidth(); int height = image.getHeight(); float minX = width; float minY = height; float maxX = 0.0f; float maxY = 0.0f; for (int i = 0; i < resultPoints.length; i++) { ResultPoint point = resultPoints[i]; float x = point.getX(); float y = point.getY(); if (x < minX) { minX = x; } if (y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } // Decode left of barcode if (minX > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, 0, 0); } // Decode above barcode if (minY > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, 0, 0); } // Decode right of barcode if (maxX < width - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop((int) maxX, 0, MIN_DIMENSION_TO_RECUR - (int) maxX, height), hints, results, (int) maxX, 0); } // Decode below barcode if (maxY < height - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, (int) maxY, width, MIN_DIMENSION_TO_RECUR - (int) maxY), hints, results, 0, (int) maxY); } }
diff --git a/plugins/test/kg/apc/jmeter/functions/FifoSizeTest.java b/plugins/test/kg/apc/jmeter/functions/FifoSizeTest.java index 383aa7f2..cd5e1bf9 100644 --- a/plugins/test/kg/apc/jmeter/functions/FifoSizeTest.java +++ b/plugins/test/kg/apc/jmeter/functions/FifoSizeTest.java @@ -1,94 +1,94 @@ package kg.apc.jmeter.functions; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author undera */ public class FifoSizeTest { public FifoSizeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of execute method, of class FifoSize. */ @Test public void testExecute() throws Exception { System.out.println("execute"); SampleResult previousResult = null; Sampler currentSampler = null; LinkedList<CompoundVariable> list = new LinkedList<CompoundVariable>(); list.add(new CompoundVariable("test")); list.add(new CompoundVariable("test")); FifoSize instance = new FifoSize(); instance.setParameters(list); - String expResult = ""; + String expResult = "0"; String result = instance.execute(previousResult, currentSampler); assertEquals(expResult, result); } /** * Test of setParameters method, of class FifoSize. */ @Test public void testSetParameters() throws Exception { System.out.println("setParameters"); LinkedList<CompoundVariable> list = new LinkedList<CompoundVariable>(); list.add(new CompoundVariable("test")); list.add(new CompoundVariable("test")); FifoSize instance = new FifoSize(); instance.setParameters(list); } /** * Test of getReferenceKey method, of class FifoSize. */ @Test public void testGetReferenceKey() { System.out.println("getReferenceKey"); FifoSize instance = new FifoSize(); String expResult = "__fifoSize"; String result = instance.getReferenceKey(); assertEquals(expResult, result); } /** * Test of getArgumentDesc method, of class FifoSize. */ @Test public void testGetArgumentDesc() { System.out.println("getArgumentDesc"); FifoSize instance = new FifoSize(); List result = instance.getArgumentDesc(); assertEquals(2, result.size()); } }
true
true
public void testExecute() throws Exception { System.out.println("execute"); SampleResult previousResult = null; Sampler currentSampler = null; LinkedList<CompoundVariable> list = new LinkedList<CompoundVariable>(); list.add(new CompoundVariable("test")); list.add(new CompoundVariable("test")); FifoSize instance = new FifoSize(); instance.setParameters(list); String expResult = ""; String result = instance.execute(previousResult, currentSampler); assertEquals(expResult, result); }
public void testExecute() throws Exception { System.out.println("execute"); SampleResult previousResult = null; Sampler currentSampler = null; LinkedList<CompoundVariable> list = new LinkedList<CompoundVariable>(); list.add(new CompoundVariable("test")); list.add(new CompoundVariable("test")); FifoSize instance = new FifoSize(); instance.setParameters(list); String expResult = "0"; String result = instance.execute(previousResult, currentSampler); assertEquals(expResult, result); }
diff --git a/src/main/java/fr/jules_cesar/Paintball/Util/Objet.java b/src/main/java/fr/jules_cesar/Paintball/Util/Objet.java index bf8a118..6540db2 100644 --- a/src/main/java/fr/jules_cesar/Paintball/Util/Objet.java +++ b/src/main/java/fr/jules_cesar/Paintball/Util/Objet.java @@ -1,54 +1,54 @@ package fr.jules_cesar.Paintball.Util; import java.util.ArrayList; import java.util.Map; import java.util.Set; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; public class Objet { private int id, data, quantite; private Map<String, Object> itemMeta; public Objet(ItemStack objet){ this.id = objet.getTypeId(); this.data = objet.getDurability(); this.quantite = objet.getAmount(); if(objet.hasItemMeta()) itemMeta = objet.getItemMeta().serialize(); } public ItemStack recuperer(){ ItemStack item = new ItemStack(this.id, this.quantite, (short) this.data); item.setDurability((short) this.data); if(itemMeta != null){ item.setItemMeta(deserializeItemMeta(item.getItemMeta(), itemMeta)); if(itemMeta.containsKey("pages")) item.setItemMeta(deserializeBook((BookMeta) item.getItemMeta(), itemMeta)); } return item; } @SuppressWarnings("unchecked") private ItemMeta deserializeBook(BookMeta meta, Map<String, Object> args) { if(args.containsKey("title")) meta.setTitle((String) args.get("title")); if(args.containsKey("author")) meta.setAuthor((String) args.get("author")); ArrayList<String> pages = (ArrayList<String>) args.get("pages"); for(String page : pages) meta.addPage(page); return meta; } @SuppressWarnings("unchecked") public static ItemMeta deserializeItemMeta(ItemMeta meta, Map<String, Object> args) { if(args.containsKey("display-name")) meta.setDisplayName((String) args.get("display-name")); if(args.containsKey("enchants")){ Map<String, Double> enchantements = (Map<String, Double>) args.get("enchants"); Set<String> liste = enchantements.keySet(); for(String e : liste) - meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), false); + meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), true); } return meta; } }
true
true
public static ItemMeta deserializeItemMeta(ItemMeta meta, Map<String, Object> args) { if(args.containsKey("display-name")) meta.setDisplayName((String) args.get("display-name")); if(args.containsKey("enchants")){ Map<String, Double> enchantements = (Map<String, Double>) args.get("enchants"); Set<String> liste = enchantements.keySet(); for(String e : liste) meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), false); } return meta; }
public static ItemMeta deserializeItemMeta(ItemMeta meta, Map<String, Object> args) { if(args.containsKey("display-name")) meta.setDisplayName((String) args.get("display-name")); if(args.containsKey("enchants")){ Map<String, Double> enchantements = (Map<String, Double>) args.get("enchants"); Set<String> liste = enchantements.keySet(); for(String e : liste) meta.addEnchant(Enchantment.getByName(e), enchantements.get(e).intValue(), true); } return meta; }
diff --git a/src/com/zford/jobs/Jobs.java b/src/com/zford/jobs/Jobs.java index 7779075..7a90c50 100644 --- a/src/com/zford/jobs/Jobs.java +++ b/src/com/zford/jobs/Jobs.java @@ -1,1337 +1,1343 @@ /* * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.zford.jobs; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.ServerListener; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.mbertoli.jfep.Parser; import com.nidefawl.Stats.Stats; import com.nijikokun.bukkit.Permissions.Permissions; import com.zford.jobs.config.JobConfig; import com.zford.jobs.config.JobsConfiguration; import com.zford.jobs.config.MessageConfig; import com.zford.jobs.config.container.Job; import com.zford.jobs.config.container.JobProgression; import com.zford.jobs.config.container.JobsMaterialInfo; import com.zford.jobs.config.container.JobsLivingEntityInfo; import com.zford.jobs.config.container.PlayerJobInfo; import com.zford.jobs.economy.JobsBOSEconomyLink; import com.zford.jobs.economy.JobsEssentialsLink; import com.zford.jobs.economy.JobsiConomy5Link; import com.zford.jobs.economy.JobsiConomy6Link; import com.zford.jobs.event.JobsJoinEvent; import com.zford.jobs.event.JobsLeaveEvent; import com.zford.jobs.fake.JobsPlayer; import com.zford.jobs.listener.JobsBlockPaymentListener; import com.zford.jobs.listener.JobsCraftPaymentListener; import com.zford.jobs.listener.JobsFishPaymentListener; import com.zford.jobs.listener.JobsJobListener; import com.zford.jobs.listener.JobsKillPaymentListener; import com.zford.jobs.listener.JobsPlayerListener; import cosine.boseconomy.BOSEconomy; import com.earth2me.essentials.Essentials; /** * Jobs main class * @author Alex * @author Zak Ford <[email protected]> */ public class Jobs extends JavaPlugin{ private HashMap<Player, PlayerJobInfo> players = null; private static Jobs plugin = null; private JobsBlockPaymentListener blockListener; private JobsJobListener jobListener; private JobsKillPaymentListener killListener; private JobsPlayerListener playerListener; private JobsFishPaymentListener fishListener; private JobsCraftPaymentListener craftListener; public Jobs() { blockListener = new JobsBlockPaymentListener(this); jobListener = new JobsJobListener(this); killListener = new JobsKillPaymentListener(this); playerListener = new JobsPlayerListener(this); fishListener = new JobsFishPaymentListener(this); plugin = this; } /** * Method called when you disable the plugin */ public void onDisable() { // kill all scheduled tasks associated to this. getServer().getScheduler().cancelTasks(this); // save all if(JobsConfiguration.getInstance().getJobsDAO() != null){ saveAll(); } for(Entry<Player, PlayerJobInfo> online: players.entrySet()){ // wipe the honorific online.getKey().setDisplayName(online.getKey().getDisplayName().replace(online.getValue().getDisplayHonorific()+" ", "").trim()); } getServer().getLogger().info("[Jobs v" + getDescription().getVersion() + "] has been disabled succesfully."); // wipe the hashMap players.clear(); } /** * Method called when the plugin is enabled */ public void onEnable() { // load the jobConfogiration players = new HashMap<Player, PlayerJobInfo>(); reloadConfigurations(); if(isEnabled()){ // set the system to auto save if(JobsConfiguration.getInstance().getSavePeriod() > 0){ getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ public void run(){ saveAll(); } }, 20*60*JobsConfiguration.getInstance().getSavePeriod(), 20*60*JobsConfiguration.getInstance().getSavePeriod()); } // enable the link for economy plugins getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new ServerListener() { @Override public void onPluginEnable(PluginEnableEvent event) { JobsConfiguration jc = JobsConfiguration.getInstance(); PluginManager pm = getServer().getPluginManager(); // economy plugins if(jc.getEconomyLink() == null){ if(pm.getPlugin("iConomy") != null || pm.getPlugin("BOSEconomy") != null || pm.getPlugin("Essentials") != null) { if(pm.getPlugin("iConomy") != null && (jc.getDefaultEconomy() == null || jc.getDefaultEconomy().equalsIgnoreCase("iconomy")) && pm.getPlugin("iConomy").getDescription().getVersion().startsWith("5")) { jc.setEconomyLink(new JobsiConomy5Link((com.iConomy.iConomy)pm.getPlugin("iConomy"))); System.out.println("[Jobs] Successfully linked with iConomy 5."); } else if(pm.getPlugin("iConomy") != null && (jc.getDefaultEconomy() == null || jc.getDefaultEconomy().equalsIgnoreCase("iconomy")) && pm.getPlugin("iConomy").getDescription().getVersion().startsWith("6")) { jc.setEconomyLink(new JobsiConomy6Link((com.iCo6.iConomy)pm.getPlugin("iConomy"))); System.out.println("[Jobs] Successfully linked with iConomy 6."); } else if(pm.getPlugin("BOSEconomy") != null && (jc.getDefaultEconomy() == null || jc.getDefaultEconomy().equalsIgnoreCase("boseconomy"))) { jc.setEconomyLink(new JobsBOSEconomyLink((BOSEconomy)pm.getPlugin("BOSEconomy"))); System.out.println("[Jobs] Successfully linked with BOSEconomy."); } else if(pm.getPlugin("Essentials") != null && (jc.getDefaultEconomy() == null || jc.getDefaultEconomy().equalsIgnoreCase("essentials"))) { jc.setEconomyLink(new JobsEssentialsLink((Essentials)pm.getPlugin("Essentials"))); System.out.println("[Jobs] Successfully linked with Essentials."); } } } // stats if(jc.getStats() == null && jc.isStatsEnabled()){ if(pm.getPlugin("Stats") != null){ jc.setStats((Stats)pm.getPlugin("Stats")); System.out.println("[Jobs] Successfully linked with Stats."); } } // permissions if(jc.getPermissions() == null){ if(pm.getPlugin("Permissions") != null){ jc.setPermissions((Permissions)pm.getPlugin("Permissions")); System.out.println("[Jobs] Successfully linked with Permissions."); } } // spout if(craftListener == null){ if(getServer().getPluginManager().getPlugin("Spout") != null){ craftListener = new JobsCraftPaymentListener(plugin); getServer().getPluginManager().registerEvent(Event.Type.CUSTOM_EVENT, craftListener, Event.Priority.Monitor, plugin); System.out.println("[Jobs] Successfully linked with Spout."); } } } @Override public void onPluginDisable(PluginDisableEvent event) { JobsConfiguration jc = JobsConfiguration.getInstance(); if(jc.getEconomyLink() instanceof JobsiConomy5Link && event.getPlugin().getDescription().getName().equalsIgnoreCase("iConomy") || jc.getEconomyLink() instanceof JobsBOSEconomyLink && event.getPlugin().getDescription().getName().equalsIgnoreCase("BOSEconomy") || jc.getEconomyLink() instanceof JobsEssentialsLink && event.getPlugin().getDescription().getName().equalsIgnoreCase("Essentials") ) { jc.setEconomyLink(null); System.out.println("[Jobs] Economy system successfully unlinked."); } // stats if(event.getPlugin().getDescription().getName().equalsIgnoreCase("Stats")){ jc.setStats(null); System.out.println("[Jobs] Successfully unlinked with Stats."); } // permissions if(event.getPlugin().getDescription().getName().equalsIgnoreCase("Permissions")){ jc.setPermissions(null); System.out.println("[Jobs] Successfully unlinked with Permissions."); } } }, Event.Priority.Monitor, this); // register the listeners getServer().getPluginManager().registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.BLOCK_PLACE, blockListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.CUSTOM_EVENT, jobListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.ENTITY_DEATH, killListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.PLAYER_FISH, fishListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Event.Priority.Monitor, this); getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, playerListener, Event.Priority.Monitor, this); // add all online players for(Player online: getServer().getOnlinePlayers()){ addPlayer(online); } // all loaded properly. getServer().getLogger().info("[Jobs v" + getDescription().getVersion() + "] has been enabled succesfully."); } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!label.equalsIgnoreCase("jobs")){ return true; } if(sender instanceof Player){ // player only commands // join if(args.length == 2 && args[0].equalsIgnoreCase("join")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null && !jobName.equalsIgnoreCase("None")){ if((JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+jobName)) || ((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(JobsConfiguration.getInstance().getMaxJobs() == null || players.get((Player)sender).getJobs().size() < JobsConfiguration.getInstance().getMaxJobs()){ getServer().getPluginManager().callEvent(new JobsJoinEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); return true; } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("join-too-many-job")); return true; } } else { // you do not have permission to join the job Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-permission")); return true; } } else{ // job does not exist Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); return true; } } // leave else if(args.length >= 2 && args[0].equalsIgnoreCase("leave")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null){ getServer().getPluginManager().callEvent(new JobsLeaveEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); } return true; } // stats else if(args.length >= 1 && args[0].equalsIgnoreCase("stats")){ Player statsPlayer = (Player)sender; if(args.length == 2) { if(JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.stats")) { statsPlayer = getServer().getPlayer(args[1]); } else { sender.sendMessage(ChatColor.RED + "There was an error in your command"); return true; } } if(getJob(statsPlayer).getJobsProgression().size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("stats-no-job")); return true; } else{ for(JobProgression jobProg: getJob(statsPlayer).getJobsProgression()){ sendMessageByLine(sender, jobStatsMessage(jobProg)); } return true; } } // jobs info <jobname> <break, place, kill> else if(args.length >= 2 && args[0].equalsIgnoreCase("info")){ Job job = JobConfig.getInstance().getJob(args[1]); String type = ""; if(args.length >= 3) { type = args[2]; } sendMessageByLine(sender, jobInfoMessage((Player)sender, job, type)); return true; } } if(sender instanceof ConsoleCommandSender || sender instanceof Player){ // browse if(args.length >= 1 && args[0].equalsIgnoreCase("browse")){ ArrayList<String> jobs = new ArrayList<String>(); for(Job temp: JobConfig.getInstance().getJobs()){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+temp.getName())) || ((JobsConfiguration.getInstance().getPermissions() == null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(!temp.getName().equalsIgnoreCase("None")) { if(temp.getMaxLevel() == null){ jobs.add(temp.getChatColour() + temp.getName()); } else{ jobs.add(temp.getChatColour() + temp.getName() + ChatColor.WHITE + " - max lvl: " + temp.getMaxLevel()); } } } } if(jobs.size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-no-jobs")); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-header")); for(String job : jobs) { sender.sendMessage(" "+job); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-footer")); } return true; } // admin commands else if(args.length >= 2 && args[0].equalsIgnoreCase("admininfo")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } String message = ""; message += "----------------\n"; for(JobProgression jobProg: getJob(target).getJobsProgression()){ Job job = jobProg.getJob(); message += jobStatsMessage(jobProg); message += jobInfoMessage(target, job, ""); message += "----------------\n"; } sendMessageByLine(sender, message); } return true; } if(args.length == 1 && args[0].equalsIgnoreCase("reload")) { if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ try { if(isEnabled()) { + for(Player player : this.getServer().getOnlinePlayers()) { + removePlayer(player); + } reloadConfigurations(); + for(Player player : this.getServer().getOnlinePlayers()) { + addPlayer(player); + } if(sender instanceof Player) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } } catch (Exception e) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } return true; } } if(args.length == 3){ if(args[0].equalsIgnoreCase("fire")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player even has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsLeaveEvent(target, job)); String message = MessageConfig.getInstance().getMessage("fire-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } else{ String message = MessageConfig.getInstance().getMessage("fire-target-no-job"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(sender, message); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("employ")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ."+args[2])) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(!info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsJoinEvent(target, job)); String message = MessageConfig.getInstance().getMessage("employ-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } } return true; } else if(args.length == 4){ if(args[0].equalsIgnoreCase("promote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsGained = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getJob().getMaxLevel() != null && levelsGained + info.getJobsProgression(job).getLevel() > info.getJobsProgression(job).getJob().getMaxLevel()){ levelsGained = info.getJobsProgression(job).getJob().getMaxLevel() - info.getJobsProgression(job).getLevel(); } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() + levelsGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("promote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelsgained%", levelsGained.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("demote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsLost = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getLevel() - levelsLost < 1){ levelsLost = info.getJobsProgression(job).getLevel() - 1; } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() - levelsLost); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("demote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelslost%", levelsLost.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("grantxp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expGained; try{ expGained = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expGained = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() + expGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("grantxp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%expgained%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("removexp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expLost; try{ expLost = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expLost = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() - expLost); { String message = MessageConfig.getInstance().getMessage("removexp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%explost%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("transfer")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job oldjob = JobConfig.getInstance().getJob(args[2]); Job newjob = JobConfig.getInstance().getJob(args[3]); if(target != null && oldjob != null & newjob != null){ try{ PlayerJobInfo info = players.get(target); if (info == null){ info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(oldjob) && !info.isInJob(newjob)){ info.transferJob(oldjob, newjob); if(newjob.getMaxLevel() != null && info.getJobsProgression(newjob).getLevel() > newjob.getMaxLevel()){ info.getJobsProgression(newjob).setLevel(newjob.getMaxLevel()); } if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.reloadHonorific(); info.checkLevels(); } // quit old job JobsConfiguration.getInstance().getJobsDAO().quitJob(target, oldjob); // join new job JobsConfiguration.getInstance().getJobsDAO().joinJob(target, newjob); // save data JobsConfiguration.getInstance().getJobsDAO().save(info); { String message = MessageConfig.getInstance().getMessage("transfer-target"); message = message.replace("%oldjobcolour%", oldjob.getChatColour().toString()); message = message.replace("%oldjobname%", oldjob.getName()); message = message.replace("%newjobcolour%", newjob.getChatColour().toString()); message = message.replace("%newjobname%", newjob.getName()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); // stats plugin integration if(JobsConfiguration.getInstance().getStats() != null && JobsConfiguration.getInstance().getStats().isEnabled()){ Stats stats = JobsConfiguration.getInstance().getStats(); if(info.getJobsProgression(newjob).getLevel() > stats.get(target.getName(), "job", newjob.getName())){ stats.setStat(target.getName(), "job", newjob.getName(), info.getJobsProgression(newjob).getLevel()); stats.saveAll(); } } } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } } if(args.length > 0){ sender.sendMessage(ChatColor.RED + "There was an error in your command"); } // jobs-browse Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-browse")); if(sender instanceof Player){ // jobs-join Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-join")); //jobs-leave Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-leave")); //jobs-stats Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-stats")); //jobs-info Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-info")); } //jobs-admin-info if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-info")); } //jobs-admin-fire if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-fire")); } //jobs-admin-employ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-employ")); } //jobs-admin-promote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-promote")); } //jobs-admin-demote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-demote")); } //jobs-admin-grantxp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-grantxp")); } //jobs-admin-removexp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-removexp")); } //jobs-admin-transfer if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-transfer")); } if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-reload")); } } return true; } /** * Displays info about a job * @param player - the player of the job * @param job - the job we are displaying info about * @param type - type of info * @return the message */ private String jobInfoMessage(Player player, Job job, String type) { if(job == null){ // job doesn't exist return MessageConfig.getInstance().getMessage("error-no-job"); } String message = ""; int showAllTypes = 1; if(type.equalsIgnoreCase("break") || type.equalsIgnoreCase("place") || type.equalsIgnoreCase("kill") || type.equalsIgnoreCase("fish") || type.equalsIgnoreCase("craft")) { showAllTypes = 0; } if(type.equalsIgnoreCase("break") || showAllTypes == 1){ // break HashMap<String, JobsMaterialInfo> jobBreakInfo = job.getBreakInfo(); if(jobBreakInfo != null){ message += jobInfoBreakMessage(player, job, jobBreakInfo); } else if(showAllTypes == 0) { String myMessage = MessageConfig.getInstance().getMessage("break-none"); myMessage = myMessage.replace("%jobcolour%", job.getChatColour().toString()); myMessage = myMessage.replace("%jobname%", job.getName()); message += myMessage; } } if(type.equalsIgnoreCase("place") || showAllTypes == 1){ // place HashMap<String, JobsMaterialInfo> jobPlaceInfo = job.getPlaceInfo(); if(jobPlaceInfo != null){ message += jobInfoPlaceMessage(player, job, jobPlaceInfo); } else if(showAllTypes == 0) { String myMessage = MessageConfig.getInstance().getMessage("place-none"); myMessage = myMessage.replace("%jobcolour%", job.getChatColour().toString()); myMessage = myMessage.replace("%jobname%", job.getName()); message += myMessage; } } if(type.equalsIgnoreCase("kill") || showAllTypes == 1){ // kill HashMap<String, JobsLivingEntityInfo> jobKillInfo = job.getKillInfo(); if(jobKillInfo != null){ message += jobInfoKillMessage(player, job, jobKillInfo); } else if(showAllTypes == 0) { String myMessage = MessageConfig.getInstance().getMessage("kill-none"); myMessage = myMessage.replace("%jobcolour%", job.getChatColour().toString()); myMessage = myMessage.replace("%jobname%", job.getName()); message += myMessage; } } if(type.equalsIgnoreCase("fish") || showAllTypes == 1){ // fish HashMap<String, JobsMaterialInfo> jobFishInfo = job.getFishInfo(); if(jobFishInfo != null){ message += jobInfoFishMessage(player, job, jobFishInfo); } else if(showAllTypes == 0) { String myMessage = MessageConfig.getInstance().getMessage("fish-none"); myMessage = myMessage.replace("%jobcolour%", job.getChatColour().toString()); myMessage = myMessage.replace("%jobname%", job.getName()); message += myMessage; } } if(getServer().getPluginManager().getPlugin("Spout") != null){ if(type.equalsIgnoreCase("craft") || showAllTypes == 1){ // craft HashMap<String, JobsMaterialInfo> jobCraftInfo = job.getCraftInfo(); if(jobCraftInfo != null){ message += jobInfoCraftMessage(player, job, jobCraftInfo); } else if(showAllTypes == 0) { String myMessage = MessageConfig.getInstance().getMessage("craft-none"); myMessage = myMessage.replace("%jobcolour%", job.getChatColour().toString()); myMessage = myMessage.replace("%jobname%", job.getName()); message += myMessage; } } } return message; } /** * Displays info about breaking blocks * @param player - the player of the job * @param job - the job we are displaying info about * @param jobBreakInfo - the information to display * @return the message */ private String jobInfoBreakMessage(Player player, Job job, HashMap<String, JobsMaterialInfo> jobBreakInfo) { String message = ""; message += MessageConfig.getInstance().getMessage("break-header"); DecimalFormat format = new DecimalFormat("#.##"); JobProgression prog = getJob(player).getJobsProgression(job); Parser expEquation = job.getExpEquation(); Parser incomeEquation = job.getIncomeEquation(); if(prog != null){ expEquation.setVariable("joblevel", prog.getLevel()); incomeEquation.setVariable("joblevel", prog.getLevel()); } else { expEquation.setVariable("joblevel", 1); incomeEquation.setVariable("joblevel", 1); } expEquation.setVariable("numjobs", getJob(player).getJobs().size()); incomeEquation.setVariable("numjobs", getJob(player).getJobs().size()); for(Entry<String, JobsMaterialInfo> temp: jobBreakInfo.entrySet()){ expEquation.setVariable("baseexperience", temp.getValue().getXpGiven()); incomeEquation.setVariable("baseincome", temp.getValue().getMoneyGiven()); String myMessage; if(temp.getKey().contains(":")){ myMessage = MessageConfig.getInstance().getMessage("break-info-sub"); } else { myMessage = MessageConfig.getInstance().getMessage("break-info-no-sub"); } if(temp.getKey().contains(":")){ myMessage = myMessage.replace("%item%", temp.getKey().split(":")[0].replace("_", " ").toLowerCase()); myMessage = myMessage.replace("%subitem%", temp.getKey().split(":")[1]); } else{ myMessage = myMessage.replace("%item%", temp.getKey().replace("_", " ").toLowerCase()); } myMessage = myMessage.replace("%income%", format.format(incomeEquation.getValue())); myMessage = myMessage.replace("%experience%", format.format(expEquation.getValue())); message += myMessage; } return message; } /** * Displays info about placing blocks * @param player - the player of the job * @param job - the job we are displaying info about * @param jobPlaceInfo - the information to display * @return the message */ private String jobInfoPlaceMessage(Player player, Job job, HashMap<String, JobsMaterialInfo> jobPlaceInfo) { String message = ""; message += MessageConfig.getInstance().getMessage("place-header"); DecimalFormat format = new DecimalFormat("#.##"); JobProgression prog = getJob(player).getJobsProgression(job); Parser expEquation = job.getExpEquation(); Parser incomeEquation = job.getIncomeEquation(); if(prog != null){ expEquation.setVariable("joblevel", prog.getLevel()); incomeEquation.setVariable("joblevel", prog.getLevel()); } else { expEquation.setVariable("joblevel", 1); incomeEquation.setVariable("joblevel", 1); } expEquation.setVariable("numjobs", getJob(player).getJobs().size()); incomeEquation.setVariable("numjobs", getJob(player).getJobs().size()); for(Entry<String, JobsMaterialInfo> temp: jobPlaceInfo.entrySet()){ expEquation.setVariable("baseexperience", temp.getValue().getXpGiven()); incomeEquation.setVariable("baseincome", temp.getValue().getMoneyGiven()); String myMessage; if(temp.getKey().contains(":")){ myMessage = MessageConfig.getInstance().getMessage("place-info-sub"); } else { myMessage = MessageConfig.getInstance().getMessage("place-info-no-sub"); } if(temp.getKey().contains(":")){ myMessage = myMessage.replace("%item%", temp.getKey().split(":")[0].replace("_", " ").toLowerCase()); myMessage = myMessage.replace("%subitem%", temp.getKey().split(":")[1]); } else{ myMessage = myMessage.replace("%item%", temp.getKey().replace("_", " ").toLowerCase()); } myMessage = myMessage.replace("%income%", format.format(incomeEquation.getValue())); myMessage = myMessage.replace("%experience%", format.format(expEquation.getValue())); message += myMessage; } return message; } /** * Displays info about killing entities * @param player - the player of the job * @param job - the job we are displaying info about * @param jobKillInfo - the information to display * @return the message */ private String jobInfoKillMessage(Player player, Job job, HashMap<String, JobsLivingEntityInfo> jobKillInfo) { String message = ""; message += MessageConfig.getInstance().getMessage("kill-header"); DecimalFormat format = new DecimalFormat("#.##"); JobProgression prog = getJob(player).getJobsProgression(job); Parser expEquation = job.getExpEquation(); Parser incomeEquation = job.getIncomeEquation(); if(prog != null){ expEquation.setVariable("joblevel", prog.getLevel()); incomeEquation.setVariable("joblevel", prog.getLevel()); } else { expEquation.setVariable("joblevel", 1); incomeEquation.setVariable("joblevel", 1); } expEquation.setVariable("numjobs", getJob(player).getJobs().size()); incomeEquation.setVariable("numjobs", getJob(player).getJobs().size()); for(Entry<String, JobsLivingEntityInfo> temp: jobKillInfo.entrySet()){ expEquation.setVariable("baseexperience", temp.getValue().getXpGiven()); incomeEquation.setVariable("baseincome", temp.getValue().getMoneyGiven()); String myMessage; if(temp.getKey().contains(":")){ myMessage = MessageConfig.getInstance().getMessage("kill-info-sub"); } else { myMessage = MessageConfig.getInstance().getMessage("kill-info-no-sub"); } if(temp.getKey().contains(":")){ myMessage = myMessage.replace("%item%", temp.getKey().split(":")[0].replace("org.bukkit.craftbukkit.entity.Craft", "")); myMessage = myMessage.replace("%subitem%", temp.getKey().split(":")[1]); } else{ myMessage = myMessage.replace("%item%", temp.getKey().replace("org.bukkit.craftbukkit.entity.Craft", "")); } myMessage = myMessage.replace("%income%", format.format(incomeEquation.getValue())); myMessage = myMessage.replace("%experience%", format.format(expEquation.getValue())); message += myMessage; } return message; } /** * Displays info about fishing * @param player - the player of the job * @param job - the job we are displaying info about * @param jobFishInfo - the information to display * @return the message */ private String jobInfoFishMessage(Player player, Job job, HashMap<String, JobsMaterialInfo> jobFishInfo) { String message = ""; message += MessageConfig.getInstance().getMessage("fish-header"); DecimalFormat format = new DecimalFormat("#.##"); JobProgression prog = getJob(player).getJobsProgression(job); Parser expEquation = job.getExpEquation(); Parser incomeEquation = job.getIncomeEquation(); if(prog != null){ expEquation.setVariable("joblevel", prog.getLevel()); incomeEquation.setVariable("joblevel", prog.getLevel()); } else { expEquation.setVariable("joblevel", 1); incomeEquation.setVariable("joblevel", 1); } expEquation.setVariable("numjobs", getJob(player).getJobs().size()); incomeEquation.setVariable("numjobs", getJob(player).getJobs().size()); for(Entry<String, JobsMaterialInfo> temp: jobFishInfo.entrySet()){ expEquation.setVariable("baseexperience", temp.getValue().getXpGiven()); incomeEquation.setVariable("baseincome", temp.getValue().getMoneyGiven()); String myMessage; if(temp.getKey().contains(":")){ myMessage = MessageConfig.getInstance().getMessage("fish-info-sub"); } else { myMessage = MessageConfig.getInstance().getMessage("fish-info-no-sub"); } if(temp.getKey().contains(":")){ myMessage = myMessage.replace("%item%", temp.getKey().split(":")[0].replace("_", " ").toLowerCase()); myMessage = myMessage.replace("%subitem%", temp.getKey().split(":")[1]); } else{ myMessage = myMessage.replace("%item%", temp.getKey().replace("_", " ").toLowerCase()); } myMessage = myMessage.replace("%income%", format.format(incomeEquation.getValue())); myMessage = myMessage.replace("%experience%", format.format(expEquation.getValue())); message += myMessage; } return message; } /** * Displays info about fishing * @param player - the player of the job * @param job - the job we are displaying info about * @param jobFishInfo - the information to display * @return the message */ private String jobInfoCraftMessage(Player player, Job job, HashMap<String, JobsMaterialInfo> jobFishInfo) { String message = ""; message += MessageConfig.getInstance().getMessage("craft-header"); DecimalFormat format = new DecimalFormat("#.##"); JobProgression prog = getJob(player).getJobsProgression(job); Parser expEquation = job.getExpEquation(); Parser incomeEquation = job.getIncomeEquation(); if(prog != null){ expEquation.setVariable("joblevel", prog.getLevel()); incomeEquation.setVariable("joblevel", prog.getLevel()); } else { expEquation.setVariable("joblevel", 1); incomeEquation.setVariable("joblevel", 1); } expEquation.setVariable("numjobs", getJob(player).getJobs().size()); incomeEquation.setVariable("numjobs", getJob(player).getJobs().size()); for(Entry<String, JobsMaterialInfo> temp: jobFishInfo.entrySet()){ expEquation.setVariable("baseexperience", temp.getValue().getXpGiven()); incomeEquation.setVariable("baseincome", temp.getValue().getMoneyGiven()); String myMessage; if(temp.getKey().contains(":")){ myMessage = MessageConfig.getInstance().getMessage("craft-info-sub"); } else { myMessage = MessageConfig.getInstance().getMessage("craft-info-no-sub"); } if(temp.getKey().contains(":")){ myMessage = myMessage.replace("%item%", temp.getKey().split(":")[0].replace("_", " ").toLowerCase()); myMessage = myMessage.replace("%subitem%", temp.getKey().split(":")[1]); } else{ myMessage = myMessage.replace("%item%", temp.getKey().replace("_", " ").toLowerCase()); } myMessage = myMessage.replace("%income%", format.format(incomeEquation.getValue())); myMessage = myMessage.replace("%experience%", format.format(expEquation.getValue())); message += myMessage; } return message; } /** * Displays job stats about a particular player's job * @param jobProg - the job progress of the players job * @return the message */ private String jobStatsMessage(JobProgression jobProg) { String message = MessageConfig.getInstance().getMessage("stats-job"); message = message.replace("%joblevel%", Integer.valueOf(jobProg.getLevel()).toString()); message = message.replace("%jobcolour%", jobProg.getJob().getChatColour().toString()); message = message.replace("%jobname%", jobProg.getJob().getName()); message = message.replace("%jobexp%", Integer.toString((int)jobProg.getExperience())); message = message.replace("%jobmaxexp%", Integer.toString(jobProg.getMaxExperience())); return message; } /** * Sends a message to line by line * @param sender - who receives info * @param message - message which needs to be sent */ private static void sendMessageByLine(CommandSender sender, String message) { for(String line : message.split("\n")) { sender.sendMessage(line); } } /** * Add a player to the plugin to me managed. * @param player */ public void addPlayer(Player player){ players.put(player, new PlayerJobInfo(player, JobsConfiguration.getInstance().getJobsDAO())); } /** * Remove a player from the plugin. * @param player */ public void removePlayer(Player player){ save(player); players.remove(player); } /** * Get the playerJobInfo for the player * @param player - the player you want the job info for * @return the job info for the player */ public PlayerJobInfo getJob(Player player){ if(player == null) { return null; } PlayerJobInfo info = players.get(player); if(info == null) { info = new PlayerJobInfo(player, JobsConfiguration.getInstance().getJobsDAO()); } return info; } /** * Save all the information of all of the players in the game */ public void saveAll(){ for(Player player: players.keySet()){ save(player); } } /** * Save the information for the specific player * @param player - the player who's data is getting saved */ private void save(Player player){ if(player != null){ JobsConfiguration.getInstance().getJobsDAO().save(players.get(player)); } } /** * Get the player job info for specific player * @param player - the player who's job you're getting * @return the player job info of the player */ public PlayerJobInfo getPlayerJobInfo(Player player){ return players.get(player); } /** * Get the current plugin * @return a refference to the plugin */ private static Jobs getPlugin(){ return plugin; } /** * Disable the plugin */ public static void disablePlugin(){ if(Jobs.getPlugin() != null){ Jobs.getPlugin().setEnabled(false); } } /** * Get the server * @return the server */ public static Server getJobsServer(){ if(plugin != null){ return plugin.getServer(); } return null; } /** * Reloads all configuration files */ public static void reloadConfigurations() { MessageConfig.getInstance().reload(); JobsConfiguration.getInstance().reload(); JobConfig.getInstance().reload(); } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!label.equalsIgnoreCase("jobs")){ return true; } if(sender instanceof Player){ // player only commands // join if(args.length == 2 && args[0].equalsIgnoreCase("join")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null && !jobName.equalsIgnoreCase("None")){ if((JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+jobName)) || ((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(JobsConfiguration.getInstance().getMaxJobs() == null || players.get((Player)sender).getJobs().size() < JobsConfiguration.getInstance().getMaxJobs()){ getServer().getPluginManager().callEvent(new JobsJoinEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); return true; } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("join-too-many-job")); return true; } } else { // you do not have permission to join the job Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-permission")); return true; } } else{ // job does not exist Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); return true; } } // leave else if(args.length >= 2 && args[0].equalsIgnoreCase("leave")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null){ getServer().getPluginManager().callEvent(new JobsLeaveEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); } return true; } // stats else if(args.length >= 1 && args[0].equalsIgnoreCase("stats")){ Player statsPlayer = (Player)sender; if(args.length == 2) { if(JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.stats")) { statsPlayer = getServer().getPlayer(args[1]); } else { sender.sendMessage(ChatColor.RED + "There was an error in your command"); return true; } } if(getJob(statsPlayer).getJobsProgression().size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("stats-no-job")); return true; } else{ for(JobProgression jobProg: getJob(statsPlayer).getJobsProgression()){ sendMessageByLine(sender, jobStatsMessage(jobProg)); } return true; } } // jobs info <jobname> <break, place, kill> else if(args.length >= 2 && args[0].equalsIgnoreCase("info")){ Job job = JobConfig.getInstance().getJob(args[1]); String type = ""; if(args.length >= 3) { type = args[2]; } sendMessageByLine(sender, jobInfoMessage((Player)sender, job, type)); return true; } } if(sender instanceof ConsoleCommandSender || sender instanceof Player){ // browse if(args.length >= 1 && args[0].equalsIgnoreCase("browse")){ ArrayList<String> jobs = new ArrayList<String>(); for(Job temp: JobConfig.getInstance().getJobs()){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+temp.getName())) || ((JobsConfiguration.getInstance().getPermissions() == null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(!temp.getName().equalsIgnoreCase("None")) { if(temp.getMaxLevel() == null){ jobs.add(temp.getChatColour() + temp.getName()); } else{ jobs.add(temp.getChatColour() + temp.getName() + ChatColor.WHITE + " - max lvl: " + temp.getMaxLevel()); } } } } if(jobs.size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-no-jobs")); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-header")); for(String job : jobs) { sender.sendMessage(" "+job); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-footer")); } return true; } // admin commands else if(args.length >= 2 && args[0].equalsIgnoreCase("admininfo")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } String message = ""; message += "----------------\n"; for(JobProgression jobProg: getJob(target).getJobsProgression()){ Job job = jobProg.getJob(); message += jobStatsMessage(jobProg); message += jobInfoMessage(target, job, ""); message += "----------------\n"; } sendMessageByLine(sender, message); } return true; } if(args.length == 1 && args[0].equalsIgnoreCase("reload")) { if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ try { if(isEnabled()) { reloadConfigurations(); if(sender instanceof Player) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } } catch (Exception e) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } return true; } } if(args.length == 3){ if(args[0].equalsIgnoreCase("fire")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player even has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsLeaveEvent(target, job)); String message = MessageConfig.getInstance().getMessage("fire-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } else{ String message = MessageConfig.getInstance().getMessage("fire-target-no-job"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(sender, message); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("employ")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ."+args[2])) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(!info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsJoinEvent(target, job)); String message = MessageConfig.getInstance().getMessage("employ-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } } return true; } else if(args.length == 4){ if(args[0].equalsIgnoreCase("promote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsGained = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getJob().getMaxLevel() != null && levelsGained + info.getJobsProgression(job).getLevel() > info.getJobsProgression(job).getJob().getMaxLevel()){ levelsGained = info.getJobsProgression(job).getJob().getMaxLevel() - info.getJobsProgression(job).getLevel(); } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() + levelsGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("promote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelsgained%", levelsGained.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("demote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsLost = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getLevel() - levelsLost < 1){ levelsLost = info.getJobsProgression(job).getLevel() - 1; } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() - levelsLost); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("demote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelslost%", levelsLost.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("grantxp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expGained; try{ expGained = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expGained = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() + expGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("grantxp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%expgained%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("removexp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expLost; try{ expLost = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expLost = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() - expLost); { String message = MessageConfig.getInstance().getMessage("removexp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%explost%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("transfer")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job oldjob = JobConfig.getInstance().getJob(args[2]); Job newjob = JobConfig.getInstance().getJob(args[3]); if(target != null && oldjob != null & newjob != null){ try{ PlayerJobInfo info = players.get(target); if (info == null){ info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(oldjob) && !info.isInJob(newjob)){ info.transferJob(oldjob, newjob); if(newjob.getMaxLevel() != null && info.getJobsProgression(newjob).getLevel() > newjob.getMaxLevel()){ info.getJobsProgression(newjob).setLevel(newjob.getMaxLevel()); } if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.reloadHonorific(); info.checkLevels(); } // quit old job JobsConfiguration.getInstance().getJobsDAO().quitJob(target, oldjob); // join new job JobsConfiguration.getInstance().getJobsDAO().joinJob(target, newjob); // save data JobsConfiguration.getInstance().getJobsDAO().save(info); { String message = MessageConfig.getInstance().getMessage("transfer-target"); message = message.replace("%oldjobcolour%", oldjob.getChatColour().toString()); message = message.replace("%oldjobname%", oldjob.getName()); message = message.replace("%newjobcolour%", newjob.getChatColour().toString()); message = message.replace("%newjobname%", newjob.getName()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); // stats plugin integration if(JobsConfiguration.getInstance().getStats() != null && JobsConfiguration.getInstance().getStats().isEnabled()){ Stats stats = JobsConfiguration.getInstance().getStats(); if(info.getJobsProgression(newjob).getLevel() > stats.get(target.getName(), "job", newjob.getName())){ stats.setStat(target.getName(), "job", newjob.getName(), info.getJobsProgression(newjob).getLevel()); stats.saveAll(); } } } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } } if(args.length > 0){ sender.sendMessage(ChatColor.RED + "There was an error in your command"); } // jobs-browse Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-browse")); if(sender instanceof Player){ // jobs-join Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-join")); //jobs-leave Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-leave")); //jobs-stats Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-stats")); //jobs-info Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-info")); } //jobs-admin-info if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-info")); } //jobs-admin-fire if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-fire")); } //jobs-admin-employ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-employ")); } //jobs-admin-promote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-promote")); } //jobs-admin-demote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-demote")); } //jobs-admin-grantxp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-grantxp")); } //jobs-admin-removexp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-removexp")); } //jobs-admin-transfer if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-transfer")); } if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-reload")); } } return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!label.equalsIgnoreCase("jobs")){ return true; } if(sender instanceof Player){ // player only commands // join if(args.length == 2 && args[0].equalsIgnoreCase("join")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null && !jobName.equalsIgnoreCase("None")){ if((JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+jobName)) || ((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(JobsConfiguration.getInstance().getMaxJobs() == null || players.get((Player)sender).getJobs().size() < JobsConfiguration.getInstance().getMaxJobs()){ getServer().getPluginManager().callEvent(new JobsJoinEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); return true; } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("join-too-many-job")); return true; } } else { // you do not have permission to join the job Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-permission")); return true; } } else{ // job does not exist Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); return true; } } // leave else if(args.length >= 2 && args[0].equalsIgnoreCase("leave")){ String jobName = args[1].trim(); if(JobConfig.getInstance().getJob(jobName) != null){ getServer().getPluginManager().callEvent(new JobsLeaveEvent( (Player)sender, JobConfig.getInstance().getJob(jobName))); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("error-no-job")); } return true; } // stats else if(args.length >= 1 && args[0].equalsIgnoreCase("stats")){ Player statsPlayer = (Player)sender; if(args.length == 2) { if(JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.stats")) { statsPlayer = getServer().getPlayer(args[1]); } else { sender.sendMessage(ChatColor.RED + "There was an error in your command"); return true; } } if(getJob(statsPlayer).getJobsProgression().size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("stats-no-job")); return true; } else{ for(JobProgression jobProg: getJob(statsPlayer).getJobsProgression()){ sendMessageByLine(sender, jobStatsMessage(jobProg)); } return true; } } // jobs info <jobname> <break, place, kill> else if(args.length >= 2 && args[0].equalsIgnoreCase("info")){ Job job = JobConfig.getInstance().getJob(args[1]); String type = ""; if(args.length >= 3) { type = args[2]; } sendMessageByLine(sender, jobInfoMessage((Player)sender, job, type)); return true; } } if(sender instanceof ConsoleCommandSender || sender instanceof Player){ // browse if(args.length >= 1 && args[0].equalsIgnoreCase("browse")){ ArrayList<String> jobs = new ArrayList<String>(); for(Job temp: JobConfig.getInstance().getJobs()){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.join."+temp.getName())) || ((JobsConfiguration.getInstance().getPermissions() == null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled()))){ if(!temp.getName().equalsIgnoreCase("None")) { if(temp.getMaxLevel() == null){ jobs.add(temp.getChatColour() + temp.getName()); } else{ jobs.add(temp.getChatColour() + temp.getName() + ChatColor.WHITE + " - max lvl: " + temp.getMaxLevel()); } } } } if(jobs.size() == 0){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-no-jobs")); } else{ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-header")); for(String job : jobs) { sender.sendMessage(" "+job); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("browse-jobs-footer")); } return true; } // admin commands else if(args.length >= 2 && args[0].equalsIgnoreCase("admininfo")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } String message = ""; message += "----------------\n"; for(JobProgression jobProg: getJob(target).getJobsProgression()){ Job job = jobProg.getJob(); message += jobStatsMessage(jobProg); message += jobInfoMessage(target, job, ""); message += "----------------\n"; } sendMessageByLine(sender, message); } return true; } if(args.length == 1 && args[0].equalsIgnoreCase("reload")) { if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ try { if(isEnabled()) { for(Player player : this.getServer().getOnlinePlayers()) { removePlayer(player); } reloadConfigurations(); for(Player player : this.getServer().getOnlinePlayers()) { addPlayer(player); } if(sender instanceof Player) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } } catch (Exception e) { Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } return true; } } if(args.length == 3){ if(args[0].equalsIgnoreCase("fire")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player even has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsLeaveEvent(target, job)); String message = MessageConfig.getInstance().getMessage("fire-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } else{ String message = MessageConfig.getInstance().getMessage("fire-target-no-job"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(sender, message); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("employ")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ."+args[2])) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(!info.isInJob(job)){ getServer().getPluginManager().callEvent(new JobsJoinEvent(target, job)); String message = MessageConfig.getInstance().getMessage("employ-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); Jobs.sendMessageByLine(target, message); Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } } return true; } else if(args.length == 4){ if(args[0].equalsIgnoreCase("promote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsGained = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getJob().getMaxLevel() != null && levelsGained + info.getJobsProgression(job).getLevel() > info.getJobsProgression(job).getJob().getMaxLevel()){ levelsGained = info.getJobsProgression(job).getJob().getMaxLevel() - info.getJobsProgression(job).getLevel(); } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() + levelsGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("promote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelsgained%", levelsGained.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("demote")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ try{ // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ Integer levelsLost = Integer.parseInt(args[3]); if (info.getJobsProgression(job).getLevel() - levelsLost < 1){ levelsLost = info.getJobsProgression(job).getLevel() - 1; } info.getJobsProgression(job).setLevel(info.getJobsProgression(job).getLevel() - levelsLost); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("demote-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%levelslost%", levelsLost.toString()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } else if(args[0].equalsIgnoreCase("grantxp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expGained; try{ expGained = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expGained = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() + expGained); if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.checkLevels(); } { String message = MessageConfig.getInstance().getMessage("grantxp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%expgained%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("removexp")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job job = JobConfig.getInstance().getJob(args[2]); if(target != null && job != null){ Double expLost; try{ expLost = Double.parseDouble(args[3]); } catch (ClassCastException ex){ expLost = (double) Integer.parseInt(args[3]); } catch(Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); return true; } // check if player already has the job PlayerJobInfo info = players.get(target); if(info == null){ // player isn't online info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(job)){ info.getJobsProgression(job).setExperience(info.getJobsProgression(job).getExperience() - expLost); { String message = MessageConfig.getInstance().getMessage("removexp-target"); message = message.replace("%jobcolour%", job.getChatColour().toString()); message = message.replace("%jobname%", job.getName()); message = message.replace("%explost%", args[3]); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); } if(target instanceof JobsPlayer){ JobsConfiguration.getInstance().getJobsDAO().save(info); } } } return true; } else if(args[0].equalsIgnoreCase("transfer")){ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Player target = getServer().getPlayer(args[1]); if(target == null){ target = new JobsPlayer(args[1]); } Job oldjob = JobConfig.getInstance().getJob(args[2]); Job newjob = JobConfig.getInstance().getJob(args[3]); if(target != null && oldjob != null & newjob != null){ try{ PlayerJobInfo info = players.get(target); if (info == null){ info = new PlayerJobInfo(target, JobsConfiguration.getInstance().getJobsDAO()); } if(info.isInJob(oldjob) && !info.isInJob(newjob)){ info.transferJob(oldjob, newjob); if(newjob.getMaxLevel() != null && info.getJobsProgression(newjob).getLevel() > newjob.getMaxLevel()){ info.getJobsProgression(newjob).setLevel(newjob.getMaxLevel()); } if(!(target instanceof JobsPlayer)){ info.reloadMaxExperience(); info.reloadHonorific(); info.checkLevels(); } // quit old job JobsConfiguration.getInstance().getJobsDAO().quitJob(target, oldjob); // join new job JobsConfiguration.getInstance().getJobsDAO().joinJob(target, newjob); // save data JobsConfiguration.getInstance().getJobsDAO().save(info); { String message = MessageConfig.getInstance().getMessage("transfer-target"); message = message.replace("%oldjobcolour%", oldjob.getChatColour().toString()); message = message.replace("%oldjobname%", oldjob.getName()); message = message.replace("%newjobcolour%", newjob.getChatColour().toString()); message = message.replace("%newjobname%", newjob.getName()); Jobs.sendMessageByLine(target, message); } Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-success")); // stats plugin integration if(JobsConfiguration.getInstance().getStats() != null && JobsConfiguration.getInstance().getStats().isEnabled()){ Stats stats = JobsConfiguration.getInstance().getStats(); if(info.getJobsProgression(newjob).getLevel() > stats.get(target.getName(), "job", newjob.getName())){ stats.setStat(target.getName(), "job", newjob.getName(), info.getJobsProgression(newjob).getLevel()); stats.saveAll(); } } } } catch (Exception e){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("admin-command-failed")); } } } return true; } } if(args.length > 0){ sender.sendMessage(ChatColor.RED + "There was an error in your command"); } // jobs-browse Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-browse")); if(sender instanceof Player){ // jobs-join Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-join")); //jobs-leave Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-leave")); //jobs-stats Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-stats")); //jobs-info Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-info")); } //jobs-admin-info if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.info")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-info")); } //jobs-admin-fire if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.fire")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-fire")); } //jobs-admin-employ if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.employ")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-employ")); } //jobs-admin-promote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.promote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-promote")); } //jobs-admin-demote if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.demote")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-demote")); } //jobs-admin-grantxp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.grantxp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-grantxp")); } //jobs-admin-removexp if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.removexp")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-removexp")); } //jobs-admin-transfer if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.transfer")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-transfer")); } if(sender instanceof ConsoleCommandSender || (JobsConfiguration.getInstance().getPermissions()!= null && JobsConfiguration.getInstance().getPermissions().isEnabled() && JobsConfiguration.getInstance().getPermissions().getHandler().has((Player)sender, "jobs.admin.reload")) || (((JobsConfiguration.getInstance().getPermissions()== null) || !(JobsConfiguration.getInstance().getPermissions().isEnabled())) && sender.isOp())){ Jobs.sendMessageByLine(sender, MessageConfig.getInstance().getMessage("jobs-admin-reload")); } } return true; }
diff --git a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java index 21d38187..78d9bbb8 100644 --- a/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java +++ b/src/plugin/index-more/src/java/org/apache/nutch/indexer/more/MoreIndexingFilter.java @@ -1,298 +1,299 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nutch.indexer.more; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.oro.text.regex.Perl5Pattern; import org.apache.oro.text.regex.PatternMatcher; import org.apache.oro.text.regex.MatchResult; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.tika.mime.MimeType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.nutch.metadata.Metadata; import org.apache.nutch.net.protocols.HttpDateFormat; import org.apache.nutch.net.protocols.Response; import org.apache.nutch.parse.Parse; import org.apache.nutch.indexer.IndexingFilter; import org.apache.nutch.indexer.IndexingException; import org.apache.nutch.indexer.NutchDocument; import org.apache.nutch.crawl.CrawlDatum; import org.apache.nutch.crawl.Inlinks; import org.apache.nutch.parse.ParseData; import org.apache.nutch.util.MimeUtil; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import org.apache.commons.lang.time.DateUtils; /** * Add (or reset) a few metaData properties as respective fields * (if they are available), so that they can be displayed by more.jsp * (called by search.jsp). * * content-type is indexed to support query by type: * last-modifed is indexed to support query by date: * * Still need to make content-length searchable! * * @author John Xing */ public class MoreIndexingFilter implements IndexingFilter { public static final Log LOG = LogFactory.getLog(MoreIndexingFilter.class); /** A flag that tells if magic resolution must be performed */ private boolean MAGIC; /** Get the MimeTypes resolver instance. */ private MimeUtil MIME; public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException { String url_s = url.toString(); addTime(doc, parse.getData(), url_s, datum); addLength(doc, parse.getData(), url_s); addType(doc, parse.getData(), url_s); resetTitle(doc, parse.getData(), url_s); return doc; } // Add time related meta info. Add last-modified if present. Index date as // last-modified, or, if that's not present, use fetch time. private NutchDocument addTime(NutchDocument doc, ParseData data, String url, CrawlDatum datum) { long time = -1; String lastModified = data.getMeta(Metadata.LAST_MODIFIED); if (lastModified != null) { // try parse last-modified time = getTime(lastModified,url); // use as time // store as string doc.add("lastModified", Long.toString(time)); } if (time == -1) { // if no last-modified time = datum.getFetchTime(); // use fetch time } // add support for query syntax date: // query filter is implemented in DateQueryFilter.java SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String dateString = sdf.format(new Date(time)); // un-stored, indexed and un-tokenized doc.add("date", dateString); return doc; } private long getTime(String date, String url) { long time = -1; try { time = HttpDateFormat.toLong(date); } catch (ParseException e) { // try to parse it as date in alternative format try { Date parsedDate = DateUtils.parseDate(date, new String [] { "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", + "EEE MMM dd HH:mm:ss zzz yyyy", "EEE, MMM dd HH:mm:ss yyyy zzz", "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss", "EEE, dd-MMM-yy HH:mm:ss zzz", "yyyy/MM/dd HH:mm:ss.SSS zzz", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm", "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz", "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy zzz" }); time = parsedDate.getTime(); // if (LOG.isWarnEnabled()) { // LOG.warn(url + ": parsed date: " + date +" to:"+time); // } } catch (Exception e2) { if (LOG.isWarnEnabled()) { LOG.warn(url + ": can't parse erroneous date: " + date); } } } return time; } // Add Content-Length private NutchDocument addLength(NutchDocument doc, ParseData data, String url) { String contentLength = data.getMeta(Response.CONTENT_LENGTH); if (contentLength != null) doc.add("contentLength", contentLength); return doc; } /** * <p> * Add Content-Type and its primaryType and subType add contentType, * primaryType and subType to field "type" as un-stored, indexed and * un-tokenized, so that search results can be confined by contentType or its * primaryType or its subType. * </p> * <p> * For example, if contentType is application/vnd.ms-powerpoint, search can be * done with one of the following qualifiers * type:application/vnd.ms-powerpoint type:application type:vnd.ms-powerpoint * all case insensitive. The query filter is implemented in * {@link TypeQueryFilter}. * </p> * * @param doc * @param data * @param url * @return */ private NutchDocument addType(NutchDocument doc, ParseData data, String url) { MimeType mimeType = null; String contentType = data.getMeta(Response.CONTENT_TYPE); if (contentType == null) { // Note by Jerome Charron on 20050415: // Content Type not solved by a previous plugin // Or unable to solve it... Trying to find it // Should be better to use the doc content too // (using MimeTypes.getMimeType(byte[], String), but I don't know // which field it is? // if (MAGIC) { // contentType = MIME.getMimeType(url, content); // } else { // contentType = MIME.getMimeType(url); // } mimeType = MIME.getMimeType(url); } else { mimeType = MIME.forName(MimeUtil.cleanMimeType(contentType)); } // Checks if we solved the content-type. if (mimeType == null) { return doc; } contentType = mimeType.getName(); doc.add("type", contentType); String[] parts = getParts(contentType); for(String part: parts) { doc.add("type", part); } // leave this for future improvement //MimeTypeParameterList parameterList = mimeType.getParameters() return doc; } /** * Utility method for splitting mime type into type and subtype. * @param mimeType * @return */ static String[] getParts(String mimeType) { return mimeType.split("/"); } // Reset title if we see non-standard HTTP header "Content-Disposition". // It's a good indication that content provider wants filename therein // be used as the title of this url. // Patterns used to extract filename from possible non-standard // HTTP header "Content-Disposition". Typically it looks like: // Content-Disposition: inline; filename="foo.ppt" private PatternMatcher matcher = new Perl5Matcher(); private Configuration conf; static Perl5Pattern patterns[] = {null, null}; static { Perl5Compiler compiler = new Perl5Compiler(); try { // order here is important patterns[0] = (Perl5Pattern) compiler.compile("\\bfilename=['\"](.+)['\"]"); patterns[1] = (Perl5Pattern) compiler.compile("\\bfilename=(\\S+)\\b"); } catch (MalformedPatternException e) { // just ignore } } private NutchDocument resetTitle(NutchDocument doc, ParseData data, String url) { String contentDisposition = data.getMeta(Metadata.CONTENT_DISPOSITION); if (contentDisposition == null) return doc; MatchResult result; for (int i=0; i<patterns.length; i++) { if (matcher.contains(contentDisposition,patterns[i])) { result = matcher.getMatch(); doc.add("title", result.group(1)); break; } } return doc; } public void setConf(Configuration conf) { this.conf = conf; MIME = new MimeUtil(conf); } public Configuration getConf() { return this.conf; } }
true
true
private long getTime(String date, String url) { long time = -1; try { time = HttpDateFormat.toLong(date); } catch (ParseException e) { // try to parse it as date in alternative format try { Date parsedDate = DateUtils.parseDate(date, new String [] { "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", "EEE, MMM dd HH:mm:ss yyyy zzz", "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss", "EEE, dd-MMM-yy HH:mm:ss zzz", "yyyy/MM/dd HH:mm:ss.SSS zzz", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm", "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz", "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy zzz" }); time = parsedDate.getTime(); // if (LOG.isWarnEnabled()) { // LOG.warn(url + ": parsed date: " + date +" to:"+time); // } } catch (Exception e2) { if (LOG.isWarnEnabled()) { LOG.warn(url + ": can't parse erroneous date: " + date); } } } return time; }
private long getTime(String date, String url) { long time = -1; try { time = HttpDateFormat.toLong(date); } catch (ParseException e) { // try to parse it as date in alternative format try { Date parsedDate = DateUtils.parseDate(date, new String [] { "EEE MMM dd HH:mm:ss yyyy", "EEE MMM dd HH:mm:ss yyyy zzz", "EEE MMM dd HH:mm:ss zzz yyyy", "EEE, MMM dd HH:mm:ss yyyy zzz", "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE,dd MMM yyyy HH:mm:ss zzz", "EEE, dd MMM yyyy HH:mm:sszzz", "EEE, dd MMM yyyy HH:mm:ss", "EEE, dd-MMM-yy HH:mm:ss zzz", "yyyy/MM/dd HH:mm:ss.SSS zzz", "yyyy/MM/dd HH:mm:ss.SSS", "yyyy/MM/dd HH:mm:ss zzz", "yyyy/MM/dd", "yyyy.MM.dd HH:mm:ss", "yyyy-MM-dd HH:mm", "MMM dd yyyy HH:mm:ss. zzz", "MMM dd yyyy HH:mm:ss zzz", "dd.MM.yyyy HH:mm:ss zzz", "dd MM yyyy HH:mm:ss zzz", "dd.MM.yyyy; HH:mm:ss", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy zzz" }); time = parsedDate.getTime(); // if (LOG.isWarnEnabled()) { // LOG.warn(url + ": parsed date: " + date +" to:"+time); // } } catch (Exception e2) { if (LOG.isWarnEnabled()) { LOG.warn(url + ": can't parse erroneous date: " + date); } } } return time; }
diff --git a/src/org/melonbrew/fe/database/databases/SQLDB.java b/src/org/melonbrew/fe/database/databases/SQLDB.java index e0ce855..65180ac 100755 --- a/src/org/melonbrew/fe/database/databases/SQLDB.java +++ b/src/org/melonbrew/fe/database/databases/SQLDB.java @@ -1,215 +1,215 @@ package org.melonbrew.fe.database.databases; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.melonbrew.fe.Fe; import org.melonbrew.fe.database.Account; import org.melonbrew.fe.database.Database; import com.niccholaspage.nSQL.Table; import com.niccholaspage.nSQL.query.SelectQuery; public abstract class SQLDB extends Database { private final Fe plugin; private final boolean supportsModification; private Connection connection; private String accountsName; private Table accounts; public SQLDB(Fe plugin, boolean supportsModification){ super(plugin); this.plugin = plugin; this.supportsModification = supportsModification; accountsName = "fe_accounts"; } public void setAccountTable(String accountsName){ this.accountsName = accountsName; } public boolean init(){ if (!checkConnection()){ return false; } return true; } public boolean checkConnection(){ try { if (connection == null || connection.isClosed()){ connection = getNewConnection(); if (connection.isClosed()){ return false; } accounts = new Table(connection, accountsName); accounts.create().create("name varchar(64)").create("money double").execute(); if (supportsModification){ query("ALTER TABLE " + accounts + " MODIFY name varchar(64)"); } } } catch (SQLException e){ e.printStackTrace(); return false; } return true; } protected abstract Connection getNewConnection(); public boolean query(String sql){ try { return connection.createStatement().execute(sql); } catch (SQLException e){ e.printStackTrace(); return false; } } public Connection getConnection(){ return connection; } public void close(){ try { connection.close(); } catch (SQLException e){ e.printStackTrace(); } } public List<Account> getTopAccounts(int size){ checkConnection(); String sql = "SELECT name FROM " + accountsName + " ORDER BY money DESC limit " + size; List<Account> topAccounts = new ArrayList<Account>(); try { ResultSet set = connection.createStatement().executeQuery(sql); while (set.next()){ topAccounts.add(getAccount(set.getString("name"))); } } catch (SQLException e){ } return topAccounts; } public List<Account> getAccounts(){ checkConnection(); List<Account> accounts = new ArrayList<Account>(); ResultSet set = this.accounts.select("name").execute(); try { while (set.next()){ accounts.add(getAccount(set.getString("name"))); } } catch (SQLException e){ } return accounts; } public double loadAccountMoney(String name){ checkConnection(); double money = -1; try { SelectQuery query = accounts.select().where("name", name); ResultSet set = query.execute(); while (set.next()){ money = set.getDouble("money"); } query.close(); } catch (SQLException e){ e.printStackTrace(); return -1; } return money; } public void removeAccount(String name){ checkConnection(); accounts.delete().where("name", name); } protected void saveAccount(String name, double money){ checkConnection(); if (accountExists(name)){ accounts.update().set("money", money).where("name", name).execute(); }else { accounts.insert().insert("name").insert("money").value(name).value(money).execute(); } } public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; StringBuilder builder = new StringBuilder("DELETE FROM " + accounts + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); - builder.delete(0, builder.length() - 2).append(")"); + builder.delete(builder.length() - 3, builder.length() - 1).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } } }
true
true
public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; StringBuilder builder = new StringBuilder("DELETE FROM " + accounts + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); builder.delete(0, builder.length() - 2).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } }
public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; StringBuilder builder = new StringBuilder("DELETE FROM " + accounts + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); builder.delete(builder.length() - 3, builder.length() - 1).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } }
diff --git a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java index c84b308ae..719af2560 100644 --- a/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java +++ b/software/base/src/test/java/brooklyn/entity/software/mysql/DynamicToyMySqlEntityBuilder.java @@ -1,162 +1,162 @@ package brooklyn.entity.software.mysql; import java.io.File; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.entity.Entity; import brooklyn.entity.basic.Attributes; import brooklyn.entity.basic.BasicStartable; import brooklyn.entity.basic.BrooklynTasks; import brooklyn.entity.basic.EntityLocal; import brooklyn.entity.proxying.EntityInitializer; import brooklyn.entity.proxying.EntitySpec; import brooklyn.entity.software.MachineLifecycleEffectorTasks; import brooklyn.entity.software.SshEffectorTasks; import brooklyn.location.MachineLocation; import brooklyn.location.OsDetails; import brooklyn.location.basic.BasicOsDetails.OsVersions; import brooklyn.location.basic.LocalhostMachineProvisioningLocation.LocalhostMachine; import brooklyn.location.basic.SshMachineLocation; import brooklyn.util.ssh.BashCommands; import brooklyn.util.task.DynamicTasks; import brooklyn.util.task.Tasks; import brooklyn.util.task.ssh.SshTasks; import brooklyn.util.task.system.ProcessTaskWrapper; import brooklyn.util.text.ComparableVersion; import brooklyn.util.time.Duration; import brooklyn.util.time.Time; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.Iterables; public class DynamicToyMySqlEntityBuilder { private static final Logger log = LoggerFactory.getLogger(DynamicToyMySqlEntityBuilder.class); public static EntitySpec<? extends Entity> spec() { return EntitySpec.create(BasicStartable.class).addInitializer(MySqlEntityInitializer.class); } public static final String downloadUrl(Entity e, boolean isLocalhost) { if (isLocalhost) { for (int i=50; i>20; i--) { String f = System.getProperty("user.home")+"/.brooklyn/repository/MySqlNode/5.5."+i+"/mysql-5.5."+i+"-osx10.6-x86_64.tar.gz"; if (new File(f).exists()) return "file://"+f; } } // download String version = "5.5.35"; String osTag = getOsTag(e); String mirrorUrl = "http://www.mirrorservice.org/sites/ftp.mysql.com/"; return "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-"+version+"-"+osTag+".tar.gz/from/"+mirrorUrl; } public static final String installDir(Entity e, boolean isLocalhost) { String url = downloadUrl(e, isLocalhost); String archive = Iterables.find(Splitter.on('/').omitEmptyStrings().split(url), Predicates.containsPattern(".tar.gz")); return archive.replace(".tar.gz", ""); } public static final String dir(Entity e) { return "/tmp/brooklyn-mysql-"+e.getId(); } // copied from MySqlSshDriver public static String getOsTag(Entity e) { // e.g. "osx10.6-x86_64"; see http://www.mysql.com/downloads/mysql/#downloads OsDetails os = ((SshMachineLocation)Iterables.getOnlyElement(e.getLocations())).getOsDetails(); if (os == null) return "linux2.6-i686"; if (os.isMac()) { String osp1 = os.getVersion()==null ? "osx10.5" //lowest common denominator : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_6) ? "osx10.6" : new ComparableVersion(os.getVersion()).isGreaterThanOrEqualTo(OsVersions.MAC_10_5) ? "osx10.5" : "osx10.5"; //lowest common denominator String osp2 = os.is64bit() ? "x86_64" : "x86"; return osp1+"-"+osp2; } //assume generic linux String osp1 = "linux2.6"; String osp2 = os.is64bit() ? "x86_64" : "i686"; return osp1+"-"+osp2; } public static class MySqlEntityInitializer implements EntityInitializer { public void apply(final EntityLocal entity) { new MachineLifecycleEffectorTasks() { @Override protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { DynamicTasks.queue( SshEffectorTasks.ssh( "mkdir "+dir(entity), "cd "+dir(entity), BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); if (isLinux(machineS)) { DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); } DynamicTasks.queue( SshEffectorTasks.put(".my.cnf") .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./scripts/mysql_install_db", - "nohup ./support-files/mysql.server start > out.log 2> err.log < /dev/null &" + "./support-files/mysql.server start > out.log 2> err.log < /dev/null" ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); return "submitted start"; } protected void postStartCustom() { // if it's still up after 5s assume we are good Time.sleep(Duration.FIVE_SECONDS); if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) { // but if it's not up add a bunch of other info log.warn("MySQL did not start: "+dir(entity)); ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "cat out.log", "cat err.log > /dev/stderr")).block(); log.info("STDOUT:\n"+info.getStdout()); log.info("STDERR:\n"+info.getStderr()); BrooklynTasks.addTagsDynamically(Tasks.current(), BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null), BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null)); throw new IllegalStateException("MySQL appears not to be running"); } // and set the PID entity().setAttribute(Attributes.PID, Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim())); } @Override protected String stopProcessesAtMachine() { Integer pid = entity().getAttribute(Attributes.PID); if (pid==null) { log.info("mysql not running"); return "No pid -- is it running?"; } DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./support-files/mysql.server stop" ).summary("stop mysql")); return "submitted stop"; } }.attachLifecycleEffectors(entity); } } private static boolean isLocalhost(Supplier<MachineLocation> machineS) { return machineS.get() instanceof LocalhostMachine; } private static boolean isLinux(Supplier<MachineLocation> machineS) { return machineS.get().getOsDetails().isLinux(); } }
true
true
public void apply(final EntityLocal entity) { new MachineLifecycleEffectorTasks() { @Override protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { DynamicTasks.queue( SshEffectorTasks.ssh( "mkdir "+dir(entity), "cd "+dir(entity), BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); if (isLinux(machineS)) { DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); } DynamicTasks.queue( SshEffectorTasks.put(".my.cnf") .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./scripts/mysql_install_db", "nohup ./support-files/mysql.server start > out.log 2> err.log < /dev/null &" ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); return "submitted start"; } protected void postStartCustom() { // if it's still up after 5s assume we are good Time.sleep(Duration.FIVE_SECONDS); if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) { // but if it's not up add a bunch of other info log.warn("MySQL did not start: "+dir(entity)); ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "cat out.log", "cat err.log > /dev/stderr")).block(); log.info("STDOUT:\n"+info.getStdout()); log.info("STDERR:\n"+info.getStderr()); BrooklynTasks.addTagsDynamically(Tasks.current(), BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null), BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null)); throw new IllegalStateException("MySQL appears not to be running"); } // and set the PID entity().setAttribute(Attributes.PID, Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim())); } @Override protected String stopProcessesAtMachine() { Integer pid = entity().getAttribute(Attributes.PID); if (pid==null) { log.info("mysql not running"); return "No pid -- is it running?"; } DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./support-files/mysql.server stop" ).summary("stop mysql")); return "submitted stop"; } }.attachLifecycleEffectors(entity); }
public void apply(final EntityLocal entity) { new MachineLifecycleEffectorTasks() { @Override protected String startProcessesAtMachine(Supplier<MachineLocation> machineS) { DynamicTasks.queue( SshEffectorTasks.ssh( "mkdir "+dir(entity), "cd "+dir(entity), BashCommands.downloadToStdout(downloadUrl(entity, isLocalhost(machineS)))+" | tar xvz" ).summary("download mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); if (isLinux(machineS)) { DynamicTasks.queue(SshEffectorTasks.ssh(BashCommands.installPackage("libaio1"))); } DynamicTasks.queue( SshEffectorTasks.put(".my.cnf") .contents(String.format("[mysqld]\nbasedir=%s/%s\n", dir(entity), installDir(entity, isLocalhost(machineS)))), SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./scripts/mysql_install_db", "./support-files/mysql.server start > out.log 2> err.log < /dev/null" ).summary("setup and run mysql").returning(SshTasks.returningStdoutLoggingInfo(log, true))); return "submitted start"; } protected void postStartCustom() { // if it's still up after 5s assume we are good Time.sleep(Duration.FIVE_SECONDS); if (!DynamicTasks.queue(SshEffectorTasks.isPidFromFileRunning(dir(entity)+"/*/data/*.pid")).get()) { // but if it's not up add a bunch of other info log.warn("MySQL did not start: "+dir(entity)); ProcessTaskWrapper<Integer> info = DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "cat out.log", "cat err.log > /dev/stderr")).block(); log.info("STDOUT:\n"+info.getStdout()); log.info("STDERR:\n"+info.getStderr()); BrooklynTasks.addTagsDynamically(Tasks.current(), BrooklynTasks.tagForStream("console (nohup stdout)", Suppliers.ofInstance(info.getStdout()), null), BrooklynTasks.tagForStream("console (nohup stderr)", Suppliers.ofInstance(info.getStderr()), null)); throw new IllegalStateException("MySQL appears not to be running"); } // and set the PID entity().setAttribute(Attributes.PID, Integer.parseInt(DynamicTasks.queue(SshEffectorTasks.ssh("cat "+dir(entity)+"/*/data/*.pid")).block().getStdout().trim())); } @Override protected String stopProcessesAtMachine() { Integer pid = entity().getAttribute(Attributes.PID); if (pid==null) { log.info("mysql not running"); return "No pid -- is it running?"; } DynamicTasks.queue(SshEffectorTasks.ssh( "cd "+dir(entity)+"/*", "./support-files/mysql.server stop" ).summary("stop mysql")); return "submitted stop"; } }.attachLifecycleEffectors(entity); }
diff --git a/src/net/sf/freecol/client/control/InGameInputHandler.java b/src/net/sf/freecol/client/control/InGameInputHandler.java index d08a93bee..a8a0188a3 100644 --- a/src/net/sf/freecol/client/control/InGameInputHandler.java +++ b/src/net/sf/freecol/client/control/InGameInputHandler.java @@ -1,1744 +1,1744 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.control; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import net.sf.freecol.FreeCol; import net.sf.freecol.client.ClientOptions; import net.sf.freecol.client.FreeColClient; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.panel.VictoryPanel; import net.sf.freecol.client.gui.animation.UnitMoveAnimation; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.common.Specification; import net.sf.freecol.common.model.AbstractUnit; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.CombatModel.CombatResult; import net.sf.freecol.common.model.CombatModel.CombatResultType; import net.sf.freecol.common.model.DiplomaticTrade; import net.sf.freecol.common.model.FoundingFather; import net.sf.freecol.common.model.FoundingFather.FoundingFatherType; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.LostCityRumour.RumourType; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Map.Direction; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Modifier; import net.sf.freecol.common.model.Monarch; import net.sf.freecol.common.model.Monarch.MonarchAction; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.Player.Stance; import net.sf.freecol.common.model.Settlement; import net.sf.freecol.common.model.Tension; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import net.sf.freecol.common.util.Utils; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Handles the network messages that arrives while in the getGame(). */ public final class InGameInputHandler extends InputHandler { private static final Logger logger = Logger.getLogger(InGameInputHandler.class.getName()); /** * The constructor to use. * * @param freeColClient The main controller. */ public InGameInputHandler(FreeColClient freeColClient) { super(freeColClient); } /** * Deals with incoming messages that have just been received. * * @param connection The <code>Connection</code> the message was received * on. * @param element The root element of the message. * @return The reply. */ @Override public Element handle(Connection connection, Element element) { Element reply = null; if (element != null) { String type = element.getTagName(); logger.log(Level.FINEST, "Received message " + type); if (type.equals("update")) { reply = update(element); } else if (type.equals("remove")) { reply = remove(element); } else if (type.equals("opponentMove")) { reply = opponentMove(element); } else if (type.equals("opponentAttack")) { reply = opponentAttack(element); } else if (type.equals("setCurrentPlayer")) { reply = setCurrentPlayer(element); } else if (type.equals("newTurn")) { reply = newTurn(element); } else if (type.equals("setDead")) { reply = setDead(element); } else if (type.equals("gameEnded")) { reply = gameEnded(element); } else if (type.equals("chat")) { reply = chat(element); } else if (type.equals("disconnect")) { reply = disconnect(element); } else if (type.equals("error")) { reply = error(element); } else if (type.equals("chooseFoundingFather")) { reply = chooseFoundingFather(element); } else if (type.equals("deliverGift")) { reply = deliverGift(element); } else if (type.equals("indianDemand")) { reply = indianDemand(element); } else if (type.equals("reconnect")) { reply = reconnect(element); } else if (type.equals("setAI")) { reply = setAI(element); } else if (type.equals("monarchAction")) { reply = monarchAction(element); } else if (type.equals("removeGoods")) { reply = removeGoods(element); } else if (type.equals("lostCityRumour")) { reply = lostCityRumour(element); } else if (type.equals("setStance")) { reply = setStance(element); } else if (type.equals("giveIndependence")) { reply = giveIndependence(element); } else if (type.equals("newConvert")) { reply = newConvert(element); } else if (type.equals("diplomaticTrade")) { reply = diplomaticTrade(element); } else if (type.equals("marketElement")) { reply = marketElement(element); } else if (type.equals("addPlayer")) { reply = addPlayer(element); } else { logger.warning("Message is of unsupported type \"" + type + "\"."); } logger.log(Level.FINEST, "Handled message " + type); } else { throw new RuntimeException("Received empty (null) message! - should never happen"); } return reply; } /** * Handles an "reconnect"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element reconnect(Element element) { logger.finest("Entered reconnect..."); if (new ShowConfirmDialogSwingTask("reconnect.text", "reconnect.yes", "reconnect.no").confirm()) { logger.finest("User wants to reconnect, do it!"); new ReconnectSwingTask().invokeLater(); } else { // This fairly drastic operation can be done in any thread, // no need to use SwingUtilities. logger.finest("No reconnect, quit."); getFreeColClient().quit(); } return null; } /** * Handles an "update"-message. * * @param updateElement The element (root element in a DOM-parsed XML tree) * that holds all the information. * @return The reply. */ public Element update(Element updateElement) { updateGameObjects(updateElement.getChildNodes()); new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Updates all FreeColGameObjects from the childNodes of the message * @param nodeList The list of nodes from the message */ private void updateGameObjects(NodeList nodeList) { for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); FreeColGameObject fcgo = getGame().getFreeColGameObjectSafely(element.getAttribute("ID")); if (fcgo != null) { fcgo.readFromXMLElement(element); } else { logger.warning("Could not find 'FreeColGameObject' with ID: " + element.getAttribute("ID")); } } } /** * Handles a "remove"-message. * * @param removeElement The element (root element in a DOM-parsed XML tree) * that holds all the information. */ private Element remove(Element removeElement) { NodeList nodeList = removeElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Element element = (Element) nodeList.item(i); FreeColGameObject fcgo = getGame().getFreeColGameObject(element.getAttribute("ID")); if (fcgo != null) { fcgo.dispose(); } else { logger.warning("Could not find 'FreeColGameObject' with ID: " + element.getAttribute("ID")); } } new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Handles an "opponentMove"-message. * * @param opponentMoveElement The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element opponentMove(Element opponentMoveElement) { Map map = getGame().getMap(); Direction direction = Enum.valueOf(Direction.class, opponentMoveElement.getAttribute("direction")); if (opponentMoveElement.hasAttribute("fromTile")) { // The unit moving should be already visible final Unit unit = (Unit) getGame().getFreeColGameObjectSafely(opponentMoveElement.getAttribute("unit")); if (unit == null) { logger.warning("Could not find the 'unit' in 'opponentMove'. Unit ID: " + opponentMoveElement.getAttribute("unit")); return null; } final Tile fromTile = (Tile) getGame().getFreeColGameObjectSafely(opponentMoveElement.getAttribute("fromTile")); if (fromTile == null) { logger.warning("Ignoring opponentMove, unit " + unit.getId() + " has no tile!"); return null; } final Tile toTile = map.getNeighbourOrNull(direction, fromTile); if (toTile==null) { // TODO: find out why this can happen } else { final String key = (getFreeColClient().getMyPlayer() == unit.getOwner()) ? ClientOptions.MOVE_ANIMATION_SPEED : ClientOptions.ENEMY_MOVE_ANIMATION_SPEED; if (getFreeColClient().getClientOptions().getInteger(key) > 0) { //Playing the animation before actually moving the unit try { new UnitMoveAnimationCanvasSwingTask(unit, toTile).invokeAndWait(); } catch (InvocationTargetException exception) { logger.warning("UnitMoveAnimationCanvasSwingTask raised " + exception.toString()); } } else { // Just refresh both Tiles new RefreshTilesSwingTask(unit.getTile(), toTile).invokeLater(); } } if (toTile!=null && getFreeColClient().getMyPlayer().canSee(toTile)) { unit.moveToTile(toTile); } else { unit.dispose(); } } else { // the unit reveals itself, after leaving a settlement or carrier String tileID = opponentMoveElement.getAttribute("toTile"); Element unitElement = Message.getChildElement(opponentMoveElement, Unit.getXMLElementTagName()); if (unitElement == null) { logger.warning("unitElement == null"); throw new NullPointerException("unitElement == null"); } Unit u = (Unit) getGame().getFreeColGameObjectSafely(unitElement.getAttribute("ID")); if (u == null) { u = new Unit(getGame(), unitElement); } else { u.readFromXMLElement(unitElement); } final Unit unit = u; if (opponentMoveElement.hasAttribute("inUnit")) { String inUnitID = opponentMoveElement.getAttribute("inUnit"); Unit inUnit = (Unit) getGame().getFreeColGameObjectSafely(inUnitID); NodeList units = opponentMoveElement.getElementsByTagName(Unit.getXMLElementTagName()); Element locationElement = null; for (int i = 0; i < units.getLength() && locationElement == null; i++) { Element element = (Element) units.item(i); if (element.getAttribute("ID").equals(inUnitID)) locationElement = element; } if (locationElement != null) { if (inUnit == null) { inUnit = new Unit(getGame(), locationElement); } else { inUnit.readFromXMLElement(locationElement); } } } if (getGame().getFreeColGameObject(tileID) == null) { logger.warning("Could not find tile with id: " + tileID); unit.setLocation(null); // Can't go on without the tile return null; } final Tile newTile = (Tile) getGame().getFreeColGameObject(tileID); if (unit.getLocation() == null) { // Getting the previous tile so we can animate the movement properly final Tile oldTile = map.getNeighbourOrNull(direction.getReverseDirection(), newTile); unit.setLocationNoUpdate(oldTile); } final String key = (getFreeColClient().getMyPlayer() == unit.getOwner()) ? ClientOptions.MOVE_ANIMATION_SPEED : ClientOptions.ENEMY_MOVE_ANIMATION_SPEED; if (getFreeColClient().getClientOptions().getInteger(key) > 0) { //Playing the animation before actually moving the unit try { new UnitMoveAnimationCanvasSwingTask(unit, newTile).invokeAndWait(); } catch (InvocationTargetException exception) { logger.warning("UnitMoveAnimationCanvasSwingTask raised " + exception.toString()); } } else { // Just refresh both Tiles new RefreshTilesSwingTask(unit.getTile(), newTile).invokeLater(); } unit.setLocation(newTile); } return null; } /** * Handles an "opponentAttack"-message. * * @param opponentAttackElement The element (root element in a DOM-parsed * XML tree) that holds all the information. */ private Element opponentAttack(Element opponentAttackElement) { Unit unit = (Unit) getGame().getFreeColGameObject(opponentAttackElement.getAttribute("unit")); Colony colony = (Colony) getGame().getFreeColGameObjectSafely(opponentAttackElement.getAttribute("colony")); Unit defender = (Unit) getGame().getFreeColGameObjectSafely(opponentAttackElement.getAttribute("defender")); CombatResultType result = Enum.valueOf(CombatResultType.class, opponentAttackElement.getAttribute("result")); int damage = Integer.parseInt(opponentAttackElement.getAttribute("damage")); int plunderGold = Integer.parseInt(opponentAttackElement.getAttribute("plunderGold")); if (opponentAttackElement.hasAttribute("update")) { String updateAttribute = opponentAttackElement.getAttribute("update"); if (updateAttribute.equals("unit")) { Element unitElement = Message.getChildElement(opponentAttackElement, Unit.getXMLElementTagName()); unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } if (unit.getTile() == null) { throw new NullPointerException("unit.getTile() == null"); } unit.setLocation(unit.getTile()); } else if (updateAttribute.equals("defender")) { Element defenderTileElement = Message.getChildElement(opponentAttackElement, Tile .getXMLElementTagName()); if (defenderTileElement != null) { Tile defenderTile = (Tile) getGame().getFreeColGameObject(defenderTileElement.getAttribute("ID")); defenderTile.readFromXMLElement(defenderTileElement); } Element defenderElement = Message.getChildElement(opponentAttackElement, Unit.getXMLElementTagName()); defender = (Unit) getGame().getFreeColGameObject(defenderElement.getAttribute("ID")); if (defender == null) { defender = new Unit(getGame(), defenderElement); } else { defender.readFromXMLElement(defenderElement); } if (defender.getTile() == null) { throw new NullPointerException("defender.getTile() == null"); } defender.setLocation(defender.getTile()); } else if (updateAttribute.equals("tile")) { Element tileElement = Message.getChildElement(opponentAttackElement, Tile .getXMLElementTagName()); Tile tile = (Tile) getGame().getFreeColGameObject(tileElement.getAttribute("ID")); if (tile == null) { tile = new Tile(getGame(), tileElement); } else { tile.readFromXMLElement(tileElement); } colony = tile.getColony(); } else { throw new IllegalStateException("Unknown update " + updateAttribute); } } if (unit == null && colony == null) { throw new NullPointerException("unit == null && colony == null"); } if (defender == null) { throw new NullPointerException("defender == null"); } if (colony != null) { unit.getGame().getCombatModel().bombard(colony, defender, new CombatResult(result, damage)); } else { unit.getGame().getCombatModel().attack(unit, defender, new CombatResult(result, damage), plunderGold); if (!unit.isDisposed() && (unit.getLocation() == null || !unit.isVisibleTo(getFreeColClient().getMyPlayer()))) { unit.dispose(); } } if (!defender.isDisposed() && (defender.getLocation() == null || !defender.isVisibleTo(getFreeColClient().getMyPlayer()))) { if (result == CombatResultType.DONE_SETTLEMENT && defender.getColony() != null && !defender.getColony().isDisposed()) { defender.getColony().setUnitCount(defender.getColony().getUnitCount()); } defender.dispose(); } new RefreshCanvasSwingTask().invokeLater(); return null; } /** * Handles a "setCurrentPlayer"-message. * * @param setCurrentPlayerElement The element (root element in a DOM-parsed * XML tree) that holds all the information. */ private Element setCurrentPlayer(Element setCurrentPlayerElement) { final Player currentPlayer = (Player) getGame().getFreeColGameObject(setCurrentPlayerElement.getAttribute("player")); logger.finest("About to set currentPlayer to " + currentPlayer.getName()); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { getFreeColClient().getInGameController().setCurrentPlayer(currentPlayer); getFreeColClient().getActionManager().update(); } }); } catch (InterruptedException e) { // Ignore } catch (InvocationTargetException e) { // Ignore } logger.finest("Succeeded in setting currentPlayer to " + currentPlayer.getName()); new RefreshCanvasSwingTask(true).invokeLater(); return null; } /** * Handles a "newTurn"-message. * * @param newTurnElement The element (root element in a DOM-parsed XML tree) * that holds all the information. */ private Element newTurn(Element newTurnElement) { getGame().newTurn(); new UpdateMenuBarSwingTask().invokeLater(); return null; } /** * Handles a "setDead"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setDead(Element element) { FreeColClient freeColClient = getFreeColClient(); Player player = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); player.setDead(true); if (player == freeColClient.getMyPlayer()) { if (freeColClient.isSingleplayer()) { if (!new ShowConfirmDialogSwingTask("defeatedSingleplayer.text", "defeatedSingleplayer.yes", "defeatedSingleplayer.no").confirm()) { freeColClient.quit(); } else { freeColClient.getFreeColServer().enterRevengeMode(player.getName()); } } else { if (!new ShowConfirmDialogSwingTask("defeated.text", "defeated.yes", "defeated.no").confirm()) { freeColClient.quit(); } } } return null; } /** * Handles a "gameEnded"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element gameEnded(Element element) { FreeColClient freeColClient = getFreeColClient(); Player winner = (Player) getGame().getFreeColGameObject(element.getAttribute("winner")); if (winner == freeColClient.getMyPlayer()) { new ShowVictoryPanelSwingTask().invokeLater(); } // else: The client has already received the message of defeat. return null; } /** * Handles a "chat"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element chat(Element element) { final Player sender = (Player) getGame().getFreeColGameObjectSafely(element.getAttribute("sender")); final String message = element.getAttribute("message"); final boolean privateChat = Boolean.valueOf(element.getAttribute("privateChat")).booleanValue(); SwingUtilities.invokeLater(new Runnable() { public void run() { getFreeColClient().getCanvas().displayChatMessage(sender, message, privateChat); } }); return null; } /** * Handles an "error"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element error(Element element) { new ShowErrorMessageSwingTask(element.hasAttribute("messageID") ? element.getAttribute("messageID") : null, element.getAttribute("message")).show(); return null; } /** * Handles a "setAI"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setAI(Element element) { Player p = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); p.setAI(Boolean.valueOf(element.getAttribute("ai")).booleanValue()); return null; } /** * Handles an "chooseFoundingFather"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element chooseFoundingFather(Element element) { final List<FoundingFather> possibleFoundingFathers = new ArrayList<FoundingFather>(); for (FoundingFatherType type : FoundingFatherType.values()) { String id = element.getAttribute(type.toString()); if (id != null && !id.equals("")) { possibleFoundingFathers.add(FreeCol.getSpecification().getFoundingFather(id)); } } FoundingFather foundingFather = new ShowSelectFoundingFatherSwingTask(possibleFoundingFathers).select(); Element reply = Message.createNewRootElement("chosenFoundingFather"); reply.setAttribute("foundingFather", foundingFather.getId()); getFreeColClient().getMyPlayer().setCurrentFather(foundingFather); return reply; } /** * Handles a "newConvert"-request. * * @param element The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element newConvert(Element element) { Tile tile = (Tile) getGame().getFreeColGameObject(element.getAttribute("colonyTile")); Colony colony = tile.getColony(); String nation = Specification.getSpecification().getNation(element.getAttribute("nation")).getName(); Element unitElement = (Element) element.getFirstChild(); Unit convert = new Unit(getGame(), unitElement); tile.add(convert); ModelMessage message = new ModelMessage(convert, ModelMessage.MessageType.UNIT_ADDED, convert, "model.colony.newConvert", "%nation%", nation, "%colony%", colony.getName()); getFreeColClient().getMyPlayer().addModelMessage(message); return null; } /** * Handles a "diplomaticTrade"-request. Returns either an "accept" * element, if the offer was accepted, or "null", if it was not. * * @param element The element (root element in a DOM-parsed XML * tree) that holds all the information. */ private Element diplomaticTrade(Element element) { Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); if (unit == null) { throw new IllegalArgumentException("Could not find 'Unit' with specified ID: " + element.getAttribute("unit")); } Direction direction = Enum.valueOf(Direction.class, element.getAttribute("direction")); Tile tile = getGame().getMap().getNeighbourOrNull(direction, unit.getTile()); if (tile == null) { throw new IllegalArgumentException("Could not find 'Tile' in direction " + direction); } Settlement settlement = tile.getSettlement(); if (settlement == null) { throw new IllegalArgumentException("No settlement on 'Tile' " + tile.getId()); } NodeList childElements = element.getChildNodes(); Element childElement = (Element) childElements.item(0); DiplomaticTrade proposal = new DiplomaticTrade(getGame(), childElement); if (proposal.isAccept()) { new ShowInformationMessageSwingTask("negotiationDialog.offerAccepted", "%nation%", unit.getOwner().getNationAsString()).show(); proposal.makeTrade(); } else { DiplomaticTrade agreement = new ShowNegotiationDialogSwingTask(unit, settlement, proposal).select(); if (agreement != null) { Element diplomaticElement = Message.createNewRootElement("diplomaticTrade"); if (agreement.isAccept()) { diplomaticElement.setAttribute("accept", "accept"); } else { diplomaticElement.setAttribute("unit", unit.getId()); diplomaticElement.setAttribute("direction", String.valueOf(direction)); diplomaticElement.appendChild(agreement.toXMLElement(null, diplomaticElement.getOwnerDocument())); } return diplomaticElement; } } return null; } /** * Handles an "deliverGift"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element deliverGift(Element element) { Element unitElement = Message.getChildElement(element, Unit.getXMLElementTagName()); Unit unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); unit.readFromXMLElement(unitElement); Settlement settlement = (Settlement) getGame().getFreeColGameObject(element.getAttribute("settlement")); Goods goods = new Goods(getGame(), Message.getChildElement(element, Goods.getXMLElementTagName())); unit.deliverGift(settlement, goods); return null; } /** * Handles an "indianDemand"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element indianDemand(Element element) { Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); Colony colony = (Colony) getGame().getFreeColGameObject(element.getAttribute("colony")); int gold = 0; Goods goods = null; boolean accepted; Element unitElement = Message.getChildElement(element, Unit.getXMLElementTagName()); if (unitElement != null) { if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } } Element goodsElement = Message.getChildElement(element, Goods.getXMLElementTagName()); if (goodsElement == null) { gold = Integer.parseInt(element.getAttribute("gold")); accepted = new ShowConfirmDialogSwingTask("indianDemand.gold.text", "indianDemand.gold.yes", "indianDemand.gold.no", "%nation%", unit.getOwner().getNationAsString(), "%colony%", colony.getName(), "%amount%", String.valueOf(gold)).confirm(); if (accepted) { colony.getOwner().modifyGold(-gold); } } else { goods = new Goods(getGame(), goodsElement); if (goods.getType() == Goods.FOOD) { accepted = new ShowConfirmDialogSwingTask("indianDemand.food.text", "indianDemand.food.yes", "indianDemand.food.no", "%nation%", unit.getOwner().getNationAsString(), "%colony%", colony.getName()).confirm(); } else { accepted = new ShowConfirmDialogSwingTask("indianDemand.other.text", "indianDemand.other.yes", "indianDemand.other.no", "%nation%", unit.getOwner().getNationAsString(), "%colony%", colony.getName(), "%amount%", String.valueOf(goods.getAmount()), "%goods%", goods.getName()).confirm(); } if (accepted) { colony.getGoodsContainer().removeGoods(goods); } } element.setAttribute("accepted", String.valueOf(accepted)); return element; } /** * Handles a "monarchAction"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final MonarchAction action = Enum.valueOf(MonarchAction.class, element.getAttribute("action")); Element reply; switch (action) { case RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); if (new ShowMonarchPanelSwingTask(action, "%replace%", element.getAttribute("amount"), "%goods%", element.getAttribute("goods")).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case LOWER_TAX: final int newTax = new Integer(element.getAttribute("amount")).intValue(); final int difference = freeColClient.getMyPlayer().getTax() - newTax; freeColClient.getMyPlayer().setTax(newTax); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.lowerTax", "%difference%",String.valueOf(difference), "%newTax%", String.valueOf(newTax))); break; case ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); ArrayList<String> unitNames = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); unitNames.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.addToREF", "%addition%", Utils.join(" " + Messages.message("and") + " ", unitNames))); break; case DECLARE_WAR: Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("enemy")); player.changeRelationWithPlayer(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getNationAsString()}}, ModelMessage.MessageType.WARNING)); break; case SUPPORT_LAND: case SUPPORT_SEA: case ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } - //player.getEurope().add(newUnit); + player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == MonarchAction.ADD_UNITS || !canvas.showMonarchPanel(action))) { canvas.showEuropePanel(); } } }); break; case OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<String> mercenaries = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } if (new ShowMonarchPanelSwingTask(action, "%gold%", element.getAttribute("price"), "%mercenaries%", Utils.join(" " + Messages.message("and") + " ", mercenaries)).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; } /** * Handles a "setStance"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element setStance(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Stance stance = Enum.valueOf(Stance.class, element.getAttribute("stance")); Player first = (Player) getGame().getFreeColGameObject(element.getAttribute("first")); Player second = (Player) getGame().getFreeColGameObject(element.getAttribute("second")); /* * War declared messages are sometimes not shown, because opponentAttack * message arrives before and when setStance message arrives the player * has the new stance. So not check stance is going to change. */ /* * if (first.getStance(second) == stance) { return null; } */ first.setStance(second, stance); if (stance == Stance.WAR) { if (player.equals(second)) { player.addModelMessage(new ModelMessage(first, "model.diplomacy.war.declared", new String[][] { {"%nation%", first.getNationAsString()}}, ModelMessage.MessageType.FOREIGN_DIPLOMACY)); } else { player.addModelMessage(new ModelMessage(first, "model.diplomacy.war.others", new String[][] { { "%attacker%", first.getNationAsString() }, { "%defender%", second.getNationAsString() } }, ModelMessage.MessageType.FOREIGN_DIPLOMACY)); } } return null; } /** * Handles a "giveIndependence"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element giveIndependence(Element element) { Player player = (Player) getGame().getFreeColGameObject(element.getAttribute("player")); player.giveIndependence(); return null; } /** * Handles an "addPlayer"-message. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element addPlayer(Element element) { Element playerElement = (Element) element.getElementsByTagName(Player.getXMLElementTagName()).item(0); if (getGame().getFreeColGameObject(playerElement.getAttribute("ID")) == null) { Player newPlayer = new Player(getGame(), playerElement); getGame().addPlayer(newPlayer); } else { getGame().getFreeColGameObject(playerElement.getAttribute("ID")).readFromXMLElement(playerElement); } return null; } /** * Handles a "marketElement"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element marketElement(Element element) { final Player player = getFreeColClient().getMyPlayer(); GoodsType type = FreeCol.getSpecification().getGoodsType(element.getAttribute("type")); int amount = Integer.parseInt(element.getAttribute("amount")); if (amount > 0) { player.getMarket().add(type, amount); } else { player.getMarket().remove(type, -amount); } return null; } /** * Handles a "removeGoods"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element removeGoods(Element element) { final FreeColClient freeColClient = getFreeColClient(); NodeList nodeList = element.getChildNodes(); Element goodsElement = (Element) nodeList.item(0); if (goodsElement == null) { // player has no colony or nothing to trade new ShowMonarchPanelSwingTask(MonarchAction.WAIVE_TAX).confirm(); } else { final Goods goods = new Goods(getGame(), goodsElement); final Colony colony = (Colony) goods.getLocation(); colony.removeGoods(goods); // JACOB_FUGGER does not protect against new boycotts freeColClient.getMyPlayer().setArrears(goods); String messageID = goods.getType().getId() + ".destroyed"; if (!Messages.containsKey(messageID)) { if (colony.isLandLocked()) { messageID = "model.monarch.colonyGoodsParty.landLocked"; } else { messageID = "model.monarch.colonyGoodsParty.harbour"; } } colony.getFeatureContainer().addModifier(Modifier .createTeaPartyModifier(getGame().getTurn())); new ShowModelMessageSwingTask(new ModelMessage(colony, ModelMessage.MessageType.WARNING, null, messageID, "%colony%", colony.getName(), "%amount%", String.valueOf(goods.getAmount()), "%goods%", goods.getName())).invokeLater(); } return null; } /** * Handles a "lostCityRumour"-request. * * @param element The element (root element in a DOM-parsed XML tree) that * holds all the information. */ private Element lostCityRumour(Element element) { final FreeColClient freeColClient = getFreeColClient(); final Player player = freeColClient.getMyPlayer(); RumourType type = Enum.valueOf(RumourType.class, element.getAttribute("type")); Unit unit = (Unit) getGame().getFreeColGameObject(element.getAttribute("unit")); if (unit == null) { throw new IllegalArgumentException("Unit is null."); } Tile tile = unit.getTile(); tile.setLostCityRumour(false); // center on the explorer freeColClient.getGUI().setFocusImmediately(tile.getPosition()); Unit newUnit; NodeList unitList; ModelMessage m; switch (type) { case BURIAL_GROUND: Player indianPlayer = tile.getOwner(); indianPlayer.modifyTension(player, Tension.Level.HATEFUL.getLimit()); m = new ModelMessage(unit, "lostCityRumour.BurialGround", new String[][] { { "%nation%", indianPlayer.getNationAsString() } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); break; case EXPEDITION_VANISHES: m = new ModelMessage(unit, "lostCityRumour.ExpeditionVanishes", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); unit.dispose(); break; case NOTHING: m = new ModelMessage(unit, "lostCityRumour.Nothing", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); break; case LEARN: m = new ModelMessage(unit, "lostCityRumour.SeasonedScout", new String[][] { { "%unit%", unit.getName() } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); unit.setType(FreeCol.getSpecification().getUnitType(element.getAttribute("unitType"))); break; case TRIBAL_CHIEF: String amount = element.getAttribute("amount"); m = new ModelMessage(unit, "lostCityRumour.TribalChief", new String[][] { { "%money%", amount } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); player.modifyGold(Integer.parseInt(amount)); break; case COLONIST: m = new ModelMessage(unit, ModelMessage.MessageType.LOST_CITY_RUMOUR, null, "lostCityRumour.Colonist"); unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } tile.add(newUnit); } break; case TREASURE: String treasure = element.getAttribute("amount"); m = new ModelMessage(unit, "lostCityRumour.TreasureTrain", new String[][] { { "%money%", treasure } }, ModelMessage.MessageType.LOST_CITY_RUMOUR); unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } tile.add(newUnit); } break; case FOUNTAIN_OF_YOUTH: if (player.getEurope() == null) { m = new ModelMessage(player, "lostCityRumour.FountainOfYouthWithoutEurope", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); } else { freeColClient.playMusicOnce("fountain"); m = new ModelMessage(player.getEurope(), "lostCityRumour.FountainOfYouth", null, ModelMessage.MessageType.LOST_CITY_RUMOUR); if (player.hasAbility("model.ability.selectRecruit")) { final int emigrants = Integer.parseInt(element.getAttribute("emigrants")); SwingUtilities.invokeLater(new Runnable() { public void run() { for (int i = 0; i < emigrants; i++) { int slot = getFreeColClient().getCanvas().showEmigrationPanel(true); Element selectElement = Message.createNewRootElement("selectFromFountainYouth"); selectElement.setAttribute("slot", Integer.toString(slot)); Element reply = freeColClient.getClient().ask(selectElement); Element unitElement = (Element) reply.getChildNodes().item(0); Unit unit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (unit == null) { unit = new Unit(getGame(), unitElement); } else { unit.readFromXMLElement(unitElement); } player.getEurope().add(unit); String newRecruitableStr = reply.getAttribute("newRecruitable"); UnitType newRecruitable = FreeCol.getSpecification().getUnitType(newRecruitableStr); player.getEurope().setRecruitable(slot, newRecruitable); } } }); } else { unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } } } break; default: throw new IllegalStateException("No such rumour."); } player.addModelMessage(m); return null; } /** * This utility class is the base class for tasks that need to run in the * event dispatch thread. */ abstract static class SwingTask implements Runnable { private static final Logger taskLogger = Logger.getLogger(SwingTask.class.getName()); /** * Run the task and wait for it to complete. * * @return return value from {@link #doWork()}. * @throws InvocationTargetException on unexpected exceptions. */ public Object invokeAndWait() throws InvocationTargetException { verifyNotStarted(); markStarted(true); try { SwingUtilities.invokeAndWait(this); } catch (InterruptedException e) { throw new InvocationTargetException(e); } return _result; } /** * Run the task at some later time. Any exceptions will occur in the * event dispatch thread. The return value will be set, but at present * there is no good way to know if it is valid yet. */ public void invokeLater() { verifyNotStarted(); markStarted(false); SwingUtilities.invokeLater(this); } /** * Mark started and set the synchronous flag. * * @param synchronous The synch/asynch flag. */ private synchronized void markStarted(boolean synchronous) { _synchronous = synchronous; _started = true; } /** * Mark finished. */ private synchronized void markDone() { _started = false; } /** * Throw an exception if the task is started. */ private synchronized void verifyNotStarted() { if (_started) { throw new IllegalStateException("Swing task already started!"); } } /** * Check if the client is waiting. * * @return true if client is waiting for a result. */ private synchronized boolean isSynchronous() { return _synchronous; } /** * Run method, call {@link #doWork()} and save the return value. Also * catch any exceptions. In synchronous mode they will be rethrown to * the original thread, in asynchronous mode they will be logged and * ignored. Nothing is gained by crashing the event dispatch thread. */ public final void run() { try { if (taskLogger.isLoggable(Level.FINEST)) { taskLogger.log(Level.FINEST, "Running Swing task " + getClass().getName() + "..."); } setResult(doWork()); if (taskLogger.isLoggable(Level.FINEST)) { taskLogger.log(Level.FINEST, "Swing task " + getClass().getName() + " returned " + _result); } } catch (RuntimeException e) { taskLogger.log(Level.WARNING, "Swing task " + getClass().getName() + " failed!", e); // Let the exception bubble up if the calling thread is waiting if (isSynchronous()) { throw e; } } finally { markDone(); } } /** * Get the return vale from {@link #doWork()}. * * @return result. */ public synchronized Object getResult() { return _result; } /** * Save result. * * @param r The result. */ private synchronized void setResult(Object r) { _result = r; } /** * Override this method to do the actual work. * * @return result. */ protected abstract Object doWork(); private Object _result; private boolean _synchronous; private boolean _started; } /** * Base class for Swing tasks that need to do a simple update without return * value using the canvas. */ abstract class NoResultCanvasSwingTask extends SwingTask { protected Object doWork() { doWork(getFreeColClient().getCanvas()); return null; } abstract void doWork(Canvas canvas); } /** * This task refreshes the entire canvas. */ class RefreshCanvasSwingTask extends NoResultCanvasSwingTask { /** * Default constructor, simply refresh canvas. */ public RefreshCanvasSwingTask() { this(false); } /** * Constructor. * * @param requestFocus True to request focus after refresh. */ public RefreshCanvasSwingTask(boolean requestFocus) { _requestFocus = requestFocus; } protected void doWork(Canvas canvas) { canvas.refresh(); if (_requestFocus && !canvas.isShowingSubPanel()) { canvas.requestFocusInWindow(); } } private final boolean _requestFocus; } class RefreshTilesSwingTask extends NoResultCanvasSwingTask { public RefreshTilesSwingTask(Tile oldTile, Tile newTile) { super(); _oldTile = oldTile; _newTile = newTile; } void doWork(Canvas canvas) { canvas.refreshTile(_oldTile); canvas.refreshTile(_newTile); } private final Tile _oldTile; private final Tile _newTile; } /** * This task plays an unit movement animation in the Canvas. */ class UnitMoveAnimationCanvasSwingTask extends NoResultCanvasSwingTask { /** * Constructor - Play the unit movement animation, focusing the unit * @param unit The unit that is moving * @param destinationTile The Tile where the unit will be moving to. */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Tile destinationTile) { this(unit, destinationTile, true); } /** * Constructor - Play the unit movement animation, focusing the unit * @param unit The unit that is moving * @param direction The Direction in which the Unit will be moving. */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Direction direction) { this(unit, unit.getGame().getMap().getNeighbourOrNull(direction, unit.getTile()), true); } /** * Constructor * @param unit The unit that is moving * @param destinationTile The Tile where the unit will be moving to. * @param focus If before the animation the screen should focus the unit */ public UnitMoveAnimationCanvasSwingTask(Unit unit, Tile destinationTile, boolean focus) { _unit = unit; _destinationTile = destinationTile; _focus = focus; } protected void doWork(Canvas canvas) { if (_focus) canvas.getGUI().setFocusImmediately(_unit.getTile().getPosition()); new UnitMoveAnimation(canvas, _unit, _destinationTile).animate(); canvas.refresh(); } private final Unit _unit; private final Tile _destinationTile; private boolean _focus; } /** * This task reconnects to the server. */ class ReconnectSwingTask extends SwingTask { protected Object doWork() { getFreeColClient().getConnectController().reconnect(); return null; } } /** * This task updates the menu bar. */ class UpdateMenuBarSwingTask extends NoResultCanvasSwingTask { protected void doWork(Canvas canvas) { canvas.updateJMenuBar(); } } /** * This task shows the victory panel. */ class ShowVictoryPanelSwingTask extends NoResultCanvasSwingTask { protected void doWork(Canvas canvas) { canvas.showPanel(new VictoryPanel(canvas)); } } /** * This class shows a dialog and saves the answer (ok/cancel). */ class ShowConfirmDialogSwingTask extends SwingTask { /** * Constructor. * * @param text The key for the question. * @param okText The key for the OK button. * @param cancelText The key for the Cancel button. * @param replace The replacement values. */ public ShowConfirmDialogSwingTask(String text, String okText, String cancelText, String... replace) { _text = text; _okText = okText; _cancelText = cancelText; _replace = replace; } /** * Show dialog and wait for selection. * * @return true if OK, false if Cancel. */ public boolean confirm() { try { Object result = invokeAndWait(); return ((Boolean) result).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { boolean choice = getFreeColClient().getCanvas().showConfirmDialog(_text, _okText, _cancelText, _replace); return Boolean.valueOf(choice); } private String _text; private String _okText; private String _cancelText; private String[] _replace; } /** * Base class for dialog SwingTasks. */ abstract class ShowMessageSwingTask extends SwingTask { /** * Show dialog and wait for the user to dismiss it. */ public void show() { try { invokeAndWait(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class shows a model message. */ class ShowModelMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param modelMessage The model message to show. */ public ShowModelMessageSwingTask(ModelMessage modelMessage) { _modelMessage = modelMessage; } protected Object doWork() { getFreeColClient().getCanvas().showModelMessages(_modelMessage); return null; } private ModelMessage _modelMessage; } /** * This class shows an informational dialog. */ class ShowInformationMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param messageId The key for the message. * @param replace The values to replace text with. */ public ShowInformationMessageSwingTask(String messageId, String... replace) { _messageId = messageId; _replace = replace; } protected Object doWork() { getFreeColClient().getCanvas().showInformationMessage(_messageId, _replace); return null; } private String _messageId; private String[] _replace; } /** * This class shows an error dialog. */ class ShowErrorMessageSwingTask extends ShowMessageSwingTask { /** * Constructor. * * @param messageId The i18n-keyname of the error message to display. * @param message An alternative message to display if the resource * specified by <code>messageID</code> is unavailable. */ public ShowErrorMessageSwingTask(String messageId, String message) { _messageId = messageId; _message = message; } protected Object doWork() { getFreeColClient().getCanvas().errorMessage(_messageId, _message); return null; } private String _messageId; private String _message; } /** * This class displays a dialog that lets the player pick a Founding Father. */ abstract class ShowSelectSwingTask extends SwingTask { /** * Show dialog and wait for selection. * * @return selection. */ public int select() { try { Object result = invokeAndWait(); return ((Integer) result).intValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class displays a dialog that lets the player pick a Founding Father. */ class ShowSelectFoundingFatherSwingTask extends SwingTask { private List<FoundingFather> choices; /** * Constructor. * * @param choices The possible founding fathers. */ public ShowSelectFoundingFatherSwingTask(List<FoundingFather> choices) { this.choices = choices; } protected Object doWork() { return getFreeColClient().getCanvas().showChooseFoundingFatherDialog(choices); } /** * Show dialog and wait for selection. * * @return selection. */ public FoundingFather select() { try { Object result = invokeAndWait(); return (FoundingFather) result; } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } } /** * This class displays a negotiation dialog. */ class ShowNegotiationDialogSwingTask extends SwingTask { /** * Constructor. * * @param unit The unit which init the negotiation. * @param settlement The settlement where the unit has made the proposal * @param proposal The proposal made by unit's owner. */ public ShowNegotiationDialogSwingTask(Unit unit, Settlement settlement, DiplomaticTrade proposal) { this.unit = unit; this.settlement = settlement; this.proposal = proposal; } /** * Show dialog and wait for selection. * * @return selection. */ public DiplomaticTrade select() { try { Object result = invokeAndWait(); return (DiplomaticTrade) result; } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { return getFreeColClient().getCanvas().showNegotiationDialog(unit, settlement, proposal); } private Unit unit; private Settlement settlement; private DiplomaticTrade proposal; } /** * This class shows the monarch panel. */ class ShowMonarchPanelSwingTask extends SwingTask { /** * Constructor. * * @param action The action key. * @param replace The replacement values. */ public ShowMonarchPanelSwingTask(MonarchAction action, String... replace) { _action = action; _replace = replace; } /** * Show dialog and wait for selection. * * @return true if OK, false if Cancel. */ public boolean confirm() { try { Object result = invokeAndWait(); return ((Boolean) result).booleanValue(); } catch (InvocationTargetException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new RuntimeException(e.getCause()); } } } protected Object doWork() { boolean choice = getFreeColClient().getCanvas().showMonarchPanel(_action, _replace); return Boolean.valueOf(choice); } private MonarchAction _action; private String[] _replace; } }
true
true
private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final MonarchAction action = Enum.valueOf(MonarchAction.class, element.getAttribute("action")); Element reply; switch (action) { case RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); if (new ShowMonarchPanelSwingTask(action, "%replace%", element.getAttribute("amount"), "%goods%", element.getAttribute("goods")).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case LOWER_TAX: final int newTax = new Integer(element.getAttribute("amount")).intValue(); final int difference = freeColClient.getMyPlayer().getTax() - newTax; freeColClient.getMyPlayer().setTax(newTax); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.lowerTax", "%difference%",String.valueOf(difference), "%newTax%", String.valueOf(newTax))); break; case ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); ArrayList<String> unitNames = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); unitNames.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.addToREF", "%addition%", Utils.join(" " + Messages.message("and") + " ", unitNames))); break; case DECLARE_WAR: Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("enemy")); player.changeRelationWithPlayer(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getNationAsString()}}, ModelMessage.MessageType.WARNING)); break; case SUPPORT_LAND: case SUPPORT_SEA: case ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } //player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == MonarchAction.ADD_UNITS || !canvas.showMonarchPanel(action))) { canvas.showEuropePanel(); } } }); break; case OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<String> mercenaries = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } if (new ShowMonarchPanelSwingTask(action, "%gold%", element.getAttribute("price"), "%mercenaries%", Utils.join(" " + Messages.message("and") + " ", mercenaries)).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; }
private Element monarchAction(Element element) { final FreeColClient freeColClient = getFreeColClient(); Player player = freeColClient.getMyPlayer(); Monarch monarch = player.getMonarch(); final MonarchAction action = Enum.valueOf(MonarchAction.class, element.getAttribute("action")); Element reply; switch (action) { case RAISE_TAX: boolean force = Boolean.parseBoolean(element.getAttribute("force")); final int amount = new Integer(element.getAttribute("amount")).intValue(); if (force) { freeColClient.getMyPlayer().setTax(amount); player.addModelMessage(new ModelMessage(player, "model.monarch.forceTaxRaise", new String[][] { {"%replace%", String.valueOf(amount) }}, ModelMessage.MessageType.WARNING)); reply = null; } else { reply = Message.createNewRootElement("acceptTax"); if (new ShowMonarchPanelSwingTask(action, "%replace%", element.getAttribute("amount"), "%goods%", element.getAttribute("goods")).confirm()) { freeColClient.getMyPlayer().setTax(amount); reply.setAttribute("accepted", String.valueOf(true)); new UpdateMenuBarSwingTask().invokeLater(); } else { reply.setAttribute("accepted", String.valueOf(false)); } } return reply; case LOWER_TAX: final int newTax = new Integer(element.getAttribute("amount")).intValue(); final int difference = freeColClient.getMyPlayer().getTax() - newTax; freeColClient.getMyPlayer().setTax(newTax); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.lowerTax", "%difference%",String.valueOf(difference), "%newTax%", String.valueOf(newTax))); break; case ADD_TO_REF: Element additionElement = Message.getChildElement(element, "addition"); NodeList childElements = additionElement.getChildNodes(); ArrayList<AbstractUnit> units = new ArrayList<AbstractUnit>(); ArrayList<String> unitNames = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); units.add(unit); unitNames.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } monarch.addToREF(units); player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.WARNING, null, "model.monarch.addToREF", "%addition%", Utils.join(" " + Messages.message("and") + " ", unitNames))); break; case DECLARE_WAR: Player enemy = (Player) getGame().getFreeColGameObject(element.getAttribute("enemy")); player.changeRelationWithPlayer(enemy, Stance.WAR); player.addModelMessage(new ModelMessage(player, "model.monarch.declareWar", new String[][] { {"%nation%", enemy.getNationAsString()}}, ModelMessage.MessageType.WARNING)); break; case SUPPORT_LAND: case SUPPORT_SEA: case ADD_UNITS: NodeList unitList = element.getChildNodes(); for (int i = 0; i < unitList.getLength(); i++) { Element unitElement = (Element) unitList.item(i); Unit newUnit = (Unit) getGame().getFreeColGameObject(unitElement.getAttribute("ID")); if (newUnit == null) { newUnit = new Unit(getGame(), unitElement); } else { newUnit.readFromXMLElement(unitElement); } player.getEurope().add(newUnit); } SwingUtilities.invokeLater(new Runnable() { public void run() { Canvas canvas = getFreeColClient().getCanvas(); if (!canvas.isShowingSubPanel() && (action == MonarchAction.ADD_UNITS || !canvas.showMonarchPanel(action))) { canvas.showEuropePanel(); } } }); break; case OFFER_MERCENARIES: reply = Message.createNewRootElement("hireMercenaries"); Element mercenaryElement = Message.getChildElement(element, "mercenaries"); childElements = mercenaryElement.getChildNodes(); ArrayList<String> mercenaries = new ArrayList<String>(); for (int index = 0; index < childElements.getLength(); index++) { AbstractUnit unit = new AbstractUnit(); unit.readFromXMLElement((Element) childElements.item(index)); mercenaries.add(unit.getNumber() + " " + Unit.getName(unit.getUnitType(), unit.getRole())); } if (new ShowMonarchPanelSwingTask(action, "%gold%", element.getAttribute("price"), "%mercenaries%", Utils.join(" " + Messages.message("and") + " ", mercenaries)).confirm()) { int price = new Integer(element.getAttribute("price")).intValue(); freeColClient.getMyPlayer().modifyGold(-price); SwingUtilities.invokeLater(new Runnable() { public void run() { freeColClient.getCanvas().updateGoldLabel(); } }); reply.setAttribute("accepted", String.valueOf(true)); } else { reply.setAttribute("accepted", String.valueOf(false)); } return reply; } return null; }
diff --git a/client/ui/src/main/java/de/objectcode/time4u/client/ui/CompactPerspective.java b/client/ui/src/main/java/de/objectcode/time4u/client/ui/CompactPerspective.java index 9544168e..68c30855 100644 --- a/client/ui/src/main/java/de/objectcode/time4u/client/ui/CompactPerspective.java +++ b/client/ui/src/main/java/de/objectcode/time4u/client/ui/CompactPerspective.java @@ -1,38 +1,42 @@ package de.objectcode.time4u.client.ui; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; import de.objectcode.time4u.client.ui.views.CalendarView; import de.objectcode.time4u.client.ui.views.ProjectTreeView; import de.objectcode.time4u.client.ui.views.PunchView; import de.objectcode.time4u.client.ui.views.StatisticsView; import de.objectcode.time4u.client.ui.views.TaskListView; import de.objectcode.time4u.client.ui.views.TodoTreeView; import de.objectcode.time4u.client.ui.views.WorkItemView; public class CompactPerspective implements IPerspectiveFactory { public static final String ID = "de.objectcode.client.ui.compactPerspective"; public void createInitialLayout(final IPageLayout layout) { final String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.addStandaloneView(CalendarView.ID, false, IPageLayout.LEFT, 0.25f, editorArea); layout.addStandaloneViewPlaceholder(TodoTreeView.ID, IPageLayout.RIGHT, 0.1f, editorArea, true); layout.addStandaloneView(TaskListView.ID, false, IPageLayout.TOP, 0.7f, CalendarView.ID); layout.addStandaloneView(ProjectTreeView.ID, false, IPageLayout.TOP, 0.6f, TaskListView.ID); layout.addStandaloneView(WorkItemView.ID, false, IPageLayout.TOP, 0.7f, editorArea); layout.addStandaloneView(StatisticsView.ID, false, IPageLayout.BOTTOM, 0.3f, editorArea); layout.addStandaloneView(PunchView.ID, false, IPageLayout.RIGHT, 0.7f, StatisticsView.ID); + layout.addStandaloneViewPlaceholder("de.objectcode.time4u.client.ui.view.todoTree", IPageLayout.RIGHT, 0.3f, + editorArea, false); + layout.addStandaloneViewPlaceholder("de.objectcode.time4u.client.connection.ui.syncrhonizeView", IPageLayout.RIGHT, + 0.7f, PunchView.ID, false); layout.getViewLayout(ProjectTreeView.ID).setCloseable(false); layout.getViewLayout(TaskListView.ID).setCloseable(false); layout.getViewLayout(CalendarView.ID).setCloseable(false); layout.getViewLayout(WorkItemView.ID).setCloseable(false); layout.getViewLayout(StatisticsView.ID).setCloseable(false); layout.getViewLayout(PunchView.ID).setCloseable(false); } }
true
true
public void createInitialLayout(final IPageLayout layout) { final String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.addStandaloneView(CalendarView.ID, false, IPageLayout.LEFT, 0.25f, editorArea); layout.addStandaloneViewPlaceholder(TodoTreeView.ID, IPageLayout.RIGHT, 0.1f, editorArea, true); layout.addStandaloneView(TaskListView.ID, false, IPageLayout.TOP, 0.7f, CalendarView.ID); layout.addStandaloneView(ProjectTreeView.ID, false, IPageLayout.TOP, 0.6f, TaskListView.ID); layout.addStandaloneView(WorkItemView.ID, false, IPageLayout.TOP, 0.7f, editorArea); layout.addStandaloneView(StatisticsView.ID, false, IPageLayout.BOTTOM, 0.3f, editorArea); layout.addStandaloneView(PunchView.ID, false, IPageLayout.RIGHT, 0.7f, StatisticsView.ID); layout.getViewLayout(ProjectTreeView.ID).setCloseable(false); layout.getViewLayout(TaskListView.ID).setCloseable(false); layout.getViewLayout(CalendarView.ID).setCloseable(false); layout.getViewLayout(WorkItemView.ID).setCloseable(false); layout.getViewLayout(StatisticsView.ID).setCloseable(false); layout.getViewLayout(PunchView.ID).setCloseable(false); }
public void createInitialLayout(final IPageLayout layout) { final String editorArea = layout.getEditorArea(); layout.setEditorAreaVisible(false); layout.addStandaloneView(CalendarView.ID, false, IPageLayout.LEFT, 0.25f, editorArea); layout.addStandaloneViewPlaceholder(TodoTreeView.ID, IPageLayout.RIGHT, 0.1f, editorArea, true); layout.addStandaloneView(TaskListView.ID, false, IPageLayout.TOP, 0.7f, CalendarView.ID); layout.addStandaloneView(ProjectTreeView.ID, false, IPageLayout.TOP, 0.6f, TaskListView.ID); layout.addStandaloneView(WorkItemView.ID, false, IPageLayout.TOP, 0.7f, editorArea); layout.addStandaloneView(StatisticsView.ID, false, IPageLayout.BOTTOM, 0.3f, editorArea); layout.addStandaloneView(PunchView.ID, false, IPageLayout.RIGHT, 0.7f, StatisticsView.ID); layout.addStandaloneViewPlaceholder("de.objectcode.time4u.client.ui.view.todoTree", IPageLayout.RIGHT, 0.3f, editorArea, false); layout.addStandaloneViewPlaceholder("de.objectcode.time4u.client.connection.ui.syncrhonizeView", IPageLayout.RIGHT, 0.7f, PunchView.ID, false); layout.getViewLayout(ProjectTreeView.ID).setCloseable(false); layout.getViewLayout(TaskListView.ID).setCloseable(false); layout.getViewLayout(CalendarView.ID).setCloseable(false); layout.getViewLayout(WorkItemView.ID).setCloseable(false); layout.getViewLayout(StatisticsView.ID).setCloseable(false); layout.getViewLayout(PunchView.ID).setCloseable(false); }
diff --git a/framework/src/nz/ac/otago/orest/RestServlet.java b/framework/src/nz/ac/otago/orest/RestServlet.java index adc13ca..a3bd203 100644 --- a/framework/src/nz/ac/otago/orest/RestServlet.java +++ b/framework/src/nz/ac/otago/orest/RestServlet.java @@ -1,125 +1,126 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nz.ac.otago.orest; import nz.ac.otago.orest.enums.HttpMethod; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import orest.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author mark */ public class RestServlet extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(RestServlet.class); /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) throws ServletException, IOException { logger.debug("Processing request."); String contentType = request.getContentType(); logger.debug("Request Content-Type is '{}'", contentType); - // strip any crap off the content-type (like charsets) - contentType = contentType.replaceFirst("[^(?:\\w*/\\w*)](.*)", ""); + if(contentType != null && !contentType.isEmpty()) { + // strip any crap off the content-type (like charsets) + contentType = contentType.replaceFirst("[^(?:\\w*/\\w*)](.*)", ""); + } logger.debug("Stripped Content-Type is '{}'", contentType); // see if we have a REST session yet - if not create one and add it to the standard session RestSession session = (RestSession) request.getSession().getAttribute("session"); if (session == null) { session = new RestSession(); RestConfiguration configuration = new Configuration(); session.setConfiguration(configuration); request.getSession().setAttribute("session", session); logger.debug("Created new REST session."); } else { logger.debug("Using existing REST session."); } String path = request.getPathInfo(); logger.debug("Path = '{}'", path); logger.debug("Method = '{}'", method); if (!path.equals("/")) { try { session.processRequest(path, method, request, response, contentType); } catch(ORestException ex) { response.sendError(ex.getHttpStatus(), ex.getMessage()); } catch (Exception ex) { - ex.printStackTrace(); // TODO: remove stacktrace logger.error("Exception occurred processing request", ex); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response, HttpMethod.GET); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response, HttpMethod.POST); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response, HttpMethod.DELETE); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response, HttpMethod.PUT); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Main OREST servlet"; }// </editor-fold> }
false
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) throws ServletException, IOException { logger.debug("Processing request."); String contentType = request.getContentType(); logger.debug("Request Content-Type is '{}'", contentType); // strip any crap off the content-type (like charsets) contentType = contentType.replaceFirst("[^(?:\\w*/\\w*)](.*)", ""); logger.debug("Stripped Content-Type is '{}'", contentType); // see if we have a REST session yet - if not create one and add it to the standard session RestSession session = (RestSession) request.getSession().getAttribute("session"); if (session == null) { session = new RestSession(); RestConfiguration configuration = new Configuration(); session.setConfiguration(configuration); request.getSession().setAttribute("session", session); logger.debug("Created new REST session."); } else { logger.debug("Using existing REST session."); } String path = request.getPathInfo(); logger.debug("Path = '{}'", path); logger.debug("Method = '{}'", method); if (!path.equals("/")) { try { session.processRequest(path, method, request, response, contentType); } catch(ORestException ex) { response.sendError(ex.getHttpStatus(), ex.getMessage()); } catch (Exception ex) { ex.printStackTrace(); // TODO: remove stacktrace logger.error("Exception occurred processing request", ex); } } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) throws ServletException, IOException { logger.debug("Processing request."); String contentType = request.getContentType(); logger.debug("Request Content-Type is '{}'", contentType); if(contentType != null && !contentType.isEmpty()) { // strip any crap off the content-type (like charsets) contentType = contentType.replaceFirst("[^(?:\\w*/\\w*)](.*)", ""); } logger.debug("Stripped Content-Type is '{}'", contentType); // see if we have a REST session yet - if not create one and add it to the standard session RestSession session = (RestSession) request.getSession().getAttribute("session"); if (session == null) { session = new RestSession(); RestConfiguration configuration = new Configuration(); session.setConfiguration(configuration); request.getSession().setAttribute("session", session); logger.debug("Created new REST session."); } else { logger.debug("Using existing REST session."); } String path = request.getPathInfo(); logger.debug("Path = '{}'", path); logger.debug("Method = '{}'", method); if (!path.equals("/")) { try { session.processRequest(path, method, request, response, contentType); } catch(ORestException ex) { response.sendError(ex.getHttpStatus(), ex.getMessage()); } catch (Exception ex) { logger.error("Exception occurred processing request", ex); } } }
diff --git a/android/src/org/coolreader/crengine/ReaderView.java b/android/src/org/coolreader/crengine/ReaderView.java index 8788f830..e69d9eca 100644 --- a/android/src/org/coolreader/crengine/ReaderView.java +++ b/android/src/org/coolreader/crengine/ReaderView.java @@ -1,3005 +1,3007 @@ package org.coolreader.crengine; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.Callable; import org.coolreader.CoolReader; import org.coolreader.R; import org.coolreader.crengine.Engine.HyphDict; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.text.ClipboardManager; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class ReaderView extends SurfaceView implements android.view.SurfaceHolder.Callback { // additional key codes for Nook public static final int NOOK_KEY_PREV_LEFT = 96; public static final int NOOK_KEY_PREV_RIGHT = 98; public static final int NOOK_KEY_NEXT_LEFT = 95; public static final int NOOK_KEY_NEXT_RIGHT = 97; public static final int NOOK_KEY_SHIFT_UP = 101; public static final int NOOK_KEY_SHIFT_DOWN = 100; public static final String PROP_PAGE_BACKGROUND_IMAGE ="background.image"; public static final String PROP_PAGE_BACKGROUND_IMAGE_DAY ="background.image.day"; public static final String PROP_PAGE_BACKGROUND_IMAGE_NIGHT ="background.image.night"; public static final String PROP_NIGHT_MODE ="crengine.night.mode"; public static final String PROP_FONT_COLOR_DAY ="font.color.day"; public static final String PROP_BACKGROUND_COLOR_DAY ="background.color.day"; public static final String PROP_FONT_COLOR_NIGHT ="font.color.night"; public static final String PROP_BACKGROUND_COLOR_NIGHT ="background.color.night"; public static final String PROP_FONT_COLOR ="font.color.default"; public static final String PROP_BACKGROUND_COLOR ="background.color.default"; public static final String PROP_FONT_ANTIALIASING ="font.antialiasing.mode"; public static final String PROP_FONT_FACE ="font.face.default"; public static final String PROP_FONT_WEIGHT_EMBOLDEN ="font.face.weight.embolden"; public static final String PROP_TXT_OPTION_PREFORMATTED ="crengine.file.txt.preformatted"; public static final String PROP_LOG_FILENAME ="crengine.log.filename"; public static final String PROP_LOG_LEVEL ="crengine.log.level"; public static final String PROP_LOG_AUTOFLUSH ="crengine.log.autoflush"; public static final String PROP_FONT_SIZE ="crengine.font.size"; public static final String PROP_STATUS_FONT_COLOR ="crengine.page.header.font.color"; public static final String PROP_STATUS_FONT_COLOR_DAY ="crengine.page.header.font.color.day"; public static final String PROP_STATUS_FONT_COLOR_NIGHT ="crengine.page.header.font.color.night"; public static final String PROP_STATUS_FONT_FACE ="crengine.page.header.font.face"; public static final String PROP_STATUS_FONT_SIZE ="crengine.page.header.font.size"; public static final String PROP_STATUS_CHAPTER_MARKS ="crengine.page.header.chapter.marks"; public static final String PROP_PAGE_MARGIN_TOP ="crengine.page.margin.top"; public static final String PROP_PAGE_MARGIN_BOTTOM ="crengine.page.margin.bottom"; public static final String PROP_PAGE_MARGIN_LEFT ="crengine.page.margin.left"; public static final String PROP_PAGE_MARGIN_RIGHT ="crengine.page.margin.right"; public static final String PROP_PAGE_VIEW_MODE ="crengine.page.view.mode"; // pages/scroll public static final String PROP_PAGE_ANIMATION ="crengine.page.animation"; public static final String PROP_INTERLINE_SPACE ="crengine.interline.space"; public static final String PROP_ROTATE_ANGLE ="window.rotate.angle"; public static final String PROP_EMBEDDED_STYLES ="crengine.doc.embedded.styles.enabled"; public static final String PROP_DISPLAY_INVERSE ="crengine.display.inverse"; // public static final String PROP_DISPLAY_FULL_UPDATE_INTERVAL ="crengine.display.full.update.interval"; // public static final String PROP_DISPLAY_TURBO_UPDATE_MODE ="crengine.display.turbo.update"; public static final String PROP_STATUS_LINE ="window.status.line"; public static final String PROP_BOOKMARK_ICONS ="crengine.bookmarks.icons"; public static final String PROP_FOOTNOTES ="crengine.footnotes"; public static final String PROP_SHOW_TIME ="window.status.clock"; public static final String PROP_SHOW_TITLE ="window.status.title"; public static final String PROP_SHOW_BATTERY ="window.status.battery"; public static final String PROP_SHOW_BATTERY_PERCENT ="window.status.battery.percent"; public static final String PROP_FONT_KERNING_ENABLED ="font.kerning.enabled"; public static final String PROP_LANDSCAPE_PAGES ="window.landscape.pages"; public static final String PROP_HYPHENATION_DICT ="crengine.hyphenation.dictionary.code"; // non-crengine public static final String PROP_AUTOSAVE_BOOKMARKS ="crengine.autosave.bookmarks"; public static final String PROP_MIN_FILE_SIZE_TO_CACHE ="crengine.cache.filesize.min"; public static final String PROP_FORCED_MIN_FILE_SIZE_TO_CACHE ="crengine.cache.forced.filesize.min"; public static final String PROP_PROGRESS_SHOW_FIRST_PAGE="crengine.progress.show.first.page"; public static final String PROP_CONTROLS_ENABLE_VOLUME_KEYS ="app.controls.volume.keys.enabled"; public static final String PROP_APP_FULLSCREEN ="app.fullscreen"; public static final String PROP_APP_BOOK_PROPERTY_SCAN_ENABLED ="app.browser.fileprops.scan.enabled"; public static final String PROP_APP_SHOW_COVERPAGES ="app.browser.coverpages"; public static final String PROP_APP_SCREEN_ORIENTATION ="app.screen.orientation"; public static final String PROP_APP_SCREEN_BACKLIGHT ="app.screen.backlight"; public static final String PROP_APP_SCREEN_BACKLIGHT_DAY ="app.screen.backlight.day"; public static final String PROP_APP_SCREEN_BACKLIGHT_NIGHT ="app.screen.backlight.night"; public static final String PROP_APP_TAP_ZONE_ACTIONS_TAP ="app.tapzone.action.tap"; public static final String PROP_APP_KEY_ACTIONS_PRESS ="app.key.action.press"; public static final String PROP_APP_TRACKBALL_DISABLED ="app.trackball.disabled"; public static final String PROP_APP_SCREEN_BACKLIGHT_LOCK ="app.screen.backlight.lock.enabled"; public static final String PROP_APP_TAP_ZONE_HILIGHT ="app.tapzone.hilight"; public static final int PAGE_ANIMATION_NONE = 0; public static final int PAGE_ANIMATION_PAPER = 1; public static final int PAGE_ANIMATION_SLIDE = 2; public enum ViewMode { PAGES, SCROLL } private ViewMode viewMode = ViewMode.PAGES; public enum ReaderCommand { DCMD_NONE(0), DCMD_REPEAT(1), // repeat last action //definitions from crengine/include/lvdocview.h DCMD_BEGIN(100), DCMD_LINEUP(101), DCMD_PAGEUP(102), DCMD_PAGEDOWN(103), DCMD_LINEDOWN(104), DCMD_LINK_FORWARD(105), DCMD_LINK_BACK(106), DCMD_LINK_NEXT(107), DCMD_LINK_PREV(108), DCMD_LINK_GO(109), DCMD_END(110), DCMD_GO_POS(111), DCMD_GO_PAGE(112), DCMD_ZOOM_IN(113), DCMD_ZOOM_OUT(114), DCMD_TOGGLE_TEXT_FORMAT(115), DCMD_BOOKMARK_SAVE_N(116), DCMD_BOOKMARK_GO_N(117), DCMD_MOVE_BY_CHAPTER(118), DCMD_GO_SCROLL_POS(119), DCMD_TOGGLE_PAGE_SCROLL_VIEW(120), DCMD_LINK_FIRST(121), DCMD_ROTATE_BY(122), DCMD_ROTATE_SET(123), DCMD_SAVE_HISTORY(124), DCMD_SAVE_TO_CACHE(125), DCMD_TOGGLE_BOLD(126), DCMD_SCROLL_BY(127), DCMD_REQUEST_RENDER(128), // definitions from android/jni/readerview.h DCMD_OPEN_RECENT_BOOK(2000), DCMD_CLOSE_BOOK(2001), DCMD_RESTORE_POSITION(2002), // application actions DCMD_RECENT_BOOKS_LIST(2003), DCMD_SEARCH(2004), DCMD_EXIT(2005), DCMD_BOOKMARKS(2005), DCMD_GO_PERCENT_DIALOG(2006), DCMD_GO_PAGE_DIALOG(2007), DCMD_TOC_DIALOG(2008), DCMD_FILE_BROWSER(2009), DCMD_OPTIONS_DIALOG(2010), DCMD_TOGGLE_DAY_NIGHT_MODE(2011), DCMD_READER_MENU(2012), DCMD_TOGGLE_TOUCH_SCREEN_LOCK(2013), ; private final int nativeId; private ReaderCommand( int nativeId ) { this.nativeId = nativeId; } } private void execute( Engine.EngineTask task ) { mEngine.execute(task); } private void post( Engine.EngineTask task ) { mEngine.post(task); } private abstract class Task implements Engine.EngineTask { public void done() { // override to do something useful } public void fail(Exception e) { // do nothing, just log exception // override to do custom action Log.e("cr3", "Task " + this.getClass().getSimpleName() + " is failed with exception " + e.getMessage(), e); } } static class Sync<T> extends Object { private T result = null; private boolean completed = false; public synchronized void set( T res ) { result = res; completed = true; notify(); } public synchronized T get() { while ( !completed ) { try { wait(); } catch (Exception e) { // ignore } } return result; } } private <T> T executeSync( final Callable<T> task ) { //Log.d("cr3", "executeSync called"); final Sync<T> sync = new Sync<T>(); post( new Runnable() { public void run() { try { sync.set( task.call() ); } catch ( Exception e ) { } } }); T res = sync.get(); //Log.d("cr3", "executeSync done"); return res; } // Native functions /* implementend by libcr3engine.so */ // get current page image private native void getPageImageInternal(Bitmap bitmap); // constructor's native part private native void createInternal(); private native void destroyInternal(); private native boolean loadDocumentInternal( String fileName ); private native java.util.Properties getSettingsInternal(); private native boolean applySettingsInternal( java.util.Properties settings ); private native void setStylesheetInternal( String stylesheet ); private native void resizeInternal( int dx, int dy ); private native boolean doCommandInternal( int command, int param ); private native Bookmark getCurrentPageBookmarkInternal(); private native boolean goToPositionInternal(String xPath); private native PositionProperties getPositionPropsInternal(String xPath); private native void updateBookInfoInternal( BookInfo info ); private native TOCItem getTOCInternal(); private native void clearSelectionInternal(); private native boolean findTextInternal( String pattern, int origin, int reverse, int caseInsensitive ); private native void setBatteryStateInternal( int state ); private native byte[] getCoverPageDataInternal(); private native void setPageBackgroundTextureInternal( byte[] imageBytes, int tileFlags ); private native void updateSelectionInternal( Selection sel ); protected int mNativeObject; // used from JNI private final CoolReader mActivity; private final Engine mEngine; private final BackgroundThread mBackThread; private BookInfo mBookInfo; private Properties mSettings = new Properties(); public Engine getEngine() { return mEngine; } public CoolReader getActivity() { return mActivity; } private int lastResizeTaskId = 0; @Override protected void onSizeChanged(final int w, final int h, int oldw, int oldh) { Log.d("cr3", "onSizeChanged("+w + ", " + h +")"); super.onSizeChanged(w, h, oldw, oldh); final int thisId = ++lastResizeTaskId; mActivity.getHistory().updateCoverPageSize(w, h); post(new Task() { public void work() { BackgroundThread.ensureBackground(); if ( thisId != lastResizeTaskId ) { Log.d("cr3", "skipping duplicate resize request"); return; } internalDX = w; internalDY = h; Log.d("cr3", "ResizeTask: resizeInternal("+w+","+h+")"); resizeInternal(w, h); // if ( mOpened ) { // Log.d("cr3", "ResizeTask: done, drawing page"); // drawPage(); // } } public void done() { clearImageCache(); invalidate(); } }); } public boolean isBookLoaded() { BackgroundThread.ensureGUI(); return mOpened; } public int getOrientation() { int angle = mSettings.getInt(PROP_APP_SCREEN_ORIENTATION, 0); if ( angle==4 ) angle = mActivity.getOrientationFromSensor(); return angle; } private int overrideKey( int keyCode ) { return keyCode; /* int angle = getOrientation(); int[] subst = new int[] { 1, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_LEFT, 1, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT, 1, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_DOWN, 1, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_UP, 1, KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, 1, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP, // 2, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, // 2, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_UP, // 2, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT, // 2, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_LEFT, // 2, KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, // 2, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_UP, // 3, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_RIGHT, // 3, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, // 3, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_UP, // 3, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN, }; for ( int i=0; i<subst.length; i+=3 ) { if ( angle==subst[i] && keyCode==subst[i+1] ) return subst[i+2]; } return keyCode; */ } public int getTapZone( int x, int y, int dx, int dy ) { int x1 = dx / 3; int x2 = dx * 2 / 3; int y1 = dy / 3; int y2 = dy * 2 / 3; int zone = 0; if ( y<y1 ) { if ( x<x1 ) zone = 1; else if ( x<x2 ) zone = 2; else zone = 3; } else if ( y<y2 ) { if ( x<x1 ) zone = 4; else if ( x<x2 ) zone = 5; else zone = 6; } else { if ( x<x1 ) zone = 7; else if ( x<x2 ) zone = 8; else zone = 9; } return zone; } public void onTapZone( int zone, boolean isLongPress ) { ReaderAction action; if ( !isLongPress ) action = ReaderAction.findForTap(zone, mSettings); else action = ReaderAction.findForLongTap(zone, mSettings); if ( action.isNone() ) return; Log.d("cr3", "onTapZone : action " + action.id + " is found for tap zone " + zone + (isLongPress ? " (long)":"")); onAction( action ); } public FileInfo getOpenedFileInfo() { if ( isBookLoaded() && mBookInfo!=null ) return mBookInfo.getFileInfo(); return null; } public final int LONG_KEYPRESS_TIME = 900; public final int AUTOREPEAT_KEYPRESS_TIME = 700; public final int DOUBLE_CLICK_INTERVAL = 400; private ReaderAction currentDoubleClickAction = null; private ReaderAction currentSingleClickAction = null; private long currentDoubleClickActionStart = 0; private int currentDoubleClickActionKeyCode = 0; @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { if ( keyCode==KeyEvent.KEYCODE_VOLUME_DOWN || keyCode==KeyEvent.KEYCODE_VOLUME_UP ) if ( !enableVolumeKeys ) return super.onKeyUp(keyCode, event); if ( keyCode==KeyEvent.KEYCODE_POWER || keyCode==KeyEvent.KEYCODE_ENDCALL ) { mActivity.releaseBacklightControl(); return false; } boolean tracked = isTracked(event); if ( keyCode!=KeyEvent.KEYCODE_BACK ) backKeyDownHere = false; mActivity.onUserActivity(); if ( keyCode==KeyEvent.KEYCODE_BACK && !tracked ) return true; backKeyDownHere = false; // apply orientation keyCode = overrideKey( keyCode ); boolean isLongPress = (event.getEventTime()-event.getDownTime())>=LONG_KEYPRESS_TIME; ReaderAction action = ReaderAction.findForKey( keyCode, mSettings ); ReaderAction longAction = ReaderAction.findForLongKey( keyCode, mSettings ); ReaderAction dblAction = ReaderAction.findForDoubleKey( keyCode, mSettings ); stopTracking(); if ( keyCode>=KeyEvent.KEYCODE_0 && keyCode<=KeyEvent.KEYCODE_9 && tracked ) { // goto/set shortcut bookmark int shortcut = keyCode - KeyEvent.KEYCODE_0; if ( shortcut==0 ) shortcut = 10; if ( isLongPress ) addBookmark(shortcut); else goToBookmark(shortcut); return true; } else if ( keyCode==KeyEvent.KEYCODE_VOLUME_DOWN || keyCode==KeyEvent.KEYCODE_VOLUME_UP ) return enableVolumeKeys; if ( action.isNone() || !tracked ) { return super.onKeyUp(keyCode, event); } if ( !action.isNone() && action.canRepeat() && longAction.isRepeat() ) { // already processed by onKeyDown() return true; } if ( isLongPress ) { action = longAction; } else { if ( !dblAction.isNone() ) { // wait for possible double click currentDoubleClickActionStart = android.os.SystemClock.uptimeMillis(); currentDoubleClickAction = dblAction; currentSingleClickAction = action; currentDoubleClickActionKeyCode = keyCode; final int myKeyCode = keyCode; BackgroundThread.instance().postGUI(new Runnable() { public void run() { if ( currentSingleClickAction!=null && currentDoubleClickActionKeyCode==myKeyCode ) { Log.d("cr3", "onKeyUp: single click action " + currentSingleClickAction.id + " found for key " + myKeyCode + " single click"); onAction( currentSingleClickAction ); } currentDoubleClickActionStart = 0; currentDoubleClickActionKeyCode = 0; currentDoubleClickAction = null; currentSingleClickAction = null; } }, DOUBLE_CLICK_INTERVAL); // posted return true; } } if ( !action.isNone() ) { Log.d("cr3", "onKeyUp: action " + action.id + " found for key " + keyCode + (isLongPress?" (long)" : "") ); onAction( action ); return true; } // not processed return super.onKeyUp(keyCode, event); } boolean VOLUME_KEYS_ZOOM = false; private boolean backKeyDownHere = false; @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { stopTracking(); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); } private boolean startTrackingKey( KeyEvent event ) { if ( event.getRepeatCount()==0 ) { stopTracking(); trackedKeyEvent = event; return true; } return false; } private void stopTracking() { trackedKeyEvent = null; actionToRepeat = null; repeatActionActive = false; } private boolean isTracked( KeyEvent event ) { if ( trackedKeyEvent!=null && trackedKeyEvent.getDownTime() == event.getDownTime() ) return true; stopTracking(); return false; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { Log.v("cr3", "onKeyMultiple( keyCode=" + keyCode + ", repeatCount=" + repeatCount + ", event=" + event); return super.onKeyMultiple(keyCode, repeatCount, event); } private KeyEvent trackedKeyEvent = null; private ReaderAction actionToRepeat = null; private boolean repeatActionActive = false; @Override public boolean onKeyDown(int keyCode, final KeyEvent event) { backKeyDownHere = false; if ( event.getRepeatCount()==0 ) Log.v("cr3", "onKeyDown("+keyCode + ", " + event +")"); if ( keyCode==KeyEvent.KEYCODE_POWER || keyCode==KeyEvent.KEYCODE_ENDCALL ) { mActivity.releaseBacklightControl(); return false; } mActivity.onUserActivity(); if ( keyCode==KeyEvent.KEYCODE_VOLUME_UP || keyCode==KeyEvent.KEYCODE_VOLUME_DOWN ) if (!enableVolumeKeys) return super.onKeyDown(keyCode, event); keyCode = overrideKey( keyCode ); ReaderAction action = ReaderAction.findForKey( keyCode, mSettings ); ReaderAction longAction = ReaderAction.findForLongKey( keyCode, mSettings ); ReaderAction dblAction = ReaderAction.findForDoubleKey( keyCode, mSettings ); if ( event.getRepeatCount()==0 ) { if ( keyCode==currentDoubleClickActionKeyCode && currentDoubleClickActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { if ( currentDoubleClickAction!=null ) { Log.d("cr3", "executing doubleclick action " + currentDoubleClickAction); onAction(currentDoubleClickAction); } currentDoubleClickActionStart = 0; currentDoubleClickActionKeyCode = 0; currentDoubleClickAction = null; currentSingleClickAction = null; return true; } else { if ( currentSingleClickAction!=null ) { onAction(currentSingleClickAction); } currentDoubleClickActionStart = 0; currentDoubleClickActionKeyCode = 0; currentDoubleClickAction = null; currentSingleClickAction = null; } } if ( event.getRepeatCount()>0 ) { if ( !isTracked(event) ) return true; // ignore // repeating key down boolean isLongPress = (event.getEventTime()-event.getDownTime())>=AUTOREPEAT_KEYPRESS_TIME; if ( isLongPress ) { if ( !repeatActionActive && actionToRepeat!=null ) { Log.v("cr3", "autorepeating action : " + actionToRepeat ); repeatActionActive = true; onAction(actionToRepeat, new Runnable() { public void run() { if ( trackedKeyEvent!=null && trackedKeyEvent.getDownTime()==event.getDownTime() ) { Log.v("cr3", "action is completed : " + actionToRepeat ); repeatActionActive = false; } } }); } else { stopTracking(); Log.v("cr3", "executing action on long press : " + longAction ); onAction(longAction); } } return true; } if ( !action.isNone() && action.canRepeat() && longAction.isRepeat() ) { // start tracking repeat startTrackingKey(event); actionToRepeat = action; Log.v("cr3", "running action with scheduled autorepeat : " + actionToRepeat ); repeatActionActive = true; onAction(actionToRepeat, new Runnable() { public void run() { if ( trackedKeyEvent==event ) { Log.v("cr3", "action is completed : " + actionToRepeat ); repeatActionActive = false; } } }); return true; } else { actionToRepeat = null; } if ( keyCode>=KeyEvent.KEYCODE_0 && keyCode<=KeyEvent.KEYCODE_9 ) { // will process in keyup handler startTrackingKey(event); return true; } if ( action.isNone() && longAction.isNone() ) return super.onKeyDown(keyCode, event); startTrackingKey(event); return true; } private int nextUpdateId = 0; private void updateSelection(int startX, int startY, int endX, int endY, final boolean isUpdateEnd ) { final Selection sel = new Selection(); final int myId = ++nextUpdateId; sel.startX = startX; sel.startY = startY; sel.endX = endX; sel.endY = endY; mEngine.execute(new Task() { @Override public void work() throws Exception { if ( myId != nextUpdateId && !isUpdateEnd ) return; updateSelectionInternal(sel); if ( !sel.isEmpty() ) { invalidImages = true; BitmapInfo bi = preparePageImage(0); if ( bi!=null ) { draw(); } } } @Override public void done() { if ( isUpdateEnd ) { String text = sel.text; if ( text!=null && text.length()>0 ) { ClipboardManager cm = mActivity.getClipboardmanager(); cm.setText(text); Log.i("cr3", "Setting clipboard text: " + text); mActivity.showToast("Selection text copied to clipboard"); } clearSelection(); } } }); } private void cancelSelection() { // selectionInProgress = false; clearSelection(); } private boolean isTouchScreenEnabled = true; private boolean isManualScrollActive = false; private int manualScrollStartPosX = 0; private int manualScrollStartPosY = 0; volatile private boolean touchEventIgnoreNextUp = false; volatile private int longTouchId = 0; volatile private long currentDoubleTapActionStart = 0; private boolean selectionInProgress = false; private int selectionStartX = 0; private int selectionStartY = 0; private int selectionEndX = 0; private int selectionEndY = 0; @Override public boolean onTouchEvent(MotionEvent event) { if ( !isTouchScreenEnabled ) { return true; } int x = (int)event.getX(); int y = (int)event.getY(); int dx = getWidth(); int dy = getHeight(); int START_DRAG_THRESHOLD = mActivity.getPalmTipPixels(); final int zone = getTapZone(x, y, dx, dy); if ( event.getAction()==MotionEvent.ACTION_UP ) { longTouchId++; if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_UP: selection finished"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, true ); selectionInProgress = false; return true; } if ( touchEventIgnoreNextUp ) return true; mActivity.onUserActivity(); unhiliteTapZone(); boolean isLongPress = (event.getEventTime()-event.getDownTime())>LONG_KEYPRESS_TIME; stopAnimation(x, y); if ( isManualScrollActive ) { isManualScrollActive = false; return true; } if ( isLongPress ) { onTapZone( zone, isLongPress ); currentDoubleTapActionStart = 0; } else { currentDoubleTapActionStart = android.os.SystemClock.uptimeMillis(); final long myStart = currentDoubleTapActionStart; BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { - if ( currentDoubleTapActionStart != myStart ) { + if ( currentDoubleTapActionStart == myStart ) { onTapZone( zone, false ); } currentDoubleTapActionStart = 0; } }, DOUBLE_CLICK_INTERVAL); } return true; } else if ( event.getAction()==MotionEvent.ACTION_DOWN ) { touchEventIgnoreNextUp = false; if ( currentDoubleTapActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { Log.v("cr3", "touch ACTION_DOWN: double tap: starting selection"); // double tap started selectionInProgress = true; longTouchId++; selectionStartX = x; selectionStartY = y; selectionEndX = x; selectionEndY = y; + currentDoubleTapActionStart = 0; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } + currentDoubleTapActionStart = 0; selectionInProgress = false; manualScrollStartPosX = x; manualScrollStartPosY = y; currentDoubleTapActionStart = 0; if ( hiliteTapZoneOnTap ) { hiliteTapZone( true, x, y, dx, dy ); scheduleUnhilite( LONG_KEYPRESS_TIME ); } final int myId = ++longTouchId; mBackThread.postGUI( new Runnable() { @Override public void run() { if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; onTapZone( zone, true ); } } }, LONG_KEYPRESS_TIME); return true; } else if ( event.getAction()==MotionEvent.ACTION_MOVE) { if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_MOVE: updating selection"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } // if ( viewMode==ViewMode.SCROLL ) { if ( !isManualScrollActive ) { int deltax = manualScrollStartPosX - x; int deltay = manualScrollStartPosY - y; deltax = deltax < 0 ? -deltax : deltax; deltay = deltay < 0 ? -deltay : deltay; if ( deltax + deltay > START_DRAG_THRESHOLD ) { longTouchId++; isManualScrollActive = true; startAnimation(manualScrollStartPosX, manualScrollStartPosY, dx, dy); updateAnimation(x, y); return true; } } // } if ( !isManualScrollActive ) return true; updateAnimation(x, y); } else if ( event.getAction()==MotionEvent.ACTION_OUTSIDE ) { if ( selectionInProgress ) { // cancel selection cancelSelection(); } isManualScrollActive = false; currentDoubleTapActionStart = 0; longTouchId++; stopAnimation(-1, -1); hiliteTapZone( false, x, y, dx, dy ); } return true; //return super.onTouchEvent(event); } @Override public boolean onTrackballEvent(MotionEvent event) { Log.d("cr3", "onTrackballEvent(" + event + ")"); if ( mSettings.getBool(PROP_APP_TRACKBALL_DISABLED, false) ) { Log.d("cr3", "trackball is disabled in settings"); return true; } return super.onTrackballEvent(event); } public void showTOC() { BackgroundThread.ensureGUI(); final ReaderView view = this; mEngine.post(new Task() { TOCItem toc; PositionProperties pos; public void work() { BackgroundThread.ensureBackground(); toc = getTOCInternal(); pos = getPositionPropsInternal(null); } public void done() { BackgroundThread.ensureGUI(); if ( toc!=null && pos!=null ) { TOCDlg dlg = new TOCDlg(mActivity, view, toc, pos.pageNumber); dlg.show(); } else { mActivity.showToast("No Table of Contents found"); } } }); } public void showSearchDialog() { BackgroundThread.ensureGUI(); SearchDlg dlg = new SearchDlg( mActivity, this ); dlg.show(); } public void findText( final String pattern, final boolean reverse, final boolean caseInsensitive ) { BackgroundThread.ensureGUI(); final ReaderView view = this; mEngine.execute(new Task() { public void work() throws Exception { BackgroundThread.ensureBackground(); boolean res = findTextInternal( pattern, 1, reverse?1:0, caseInsensitive?1:0); if ( !res ) res = findTextInternal( pattern, -1, reverse?1:0, caseInsensitive?1:0); if ( !res ) { clearSelectionInternal(); throw new Exception("pattern not found"); } } public void done() { BackgroundThread.ensureGUI(); drawPage(); FindNextDlg.showDialog( mActivity, view, pattern, caseInsensitive ); } public void fail(Exception e) { BackgroundThread.ensureGUI(); mActivity.showToast("Pattern not found"); } }); } public void findNext( final String pattern, final boolean reverse, final boolean caseInsensitive ) { BackgroundThread.ensureGUI(); mEngine.execute(new Task() { public void work() throws Exception { BackgroundThread.ensureBackground(); boolean res = findTextInternal( pattern, 1, reverse?1:0, caseInsensitive?1:0); if ( !res ) res = findTextInternal( pattern, -1, reverse?1:0, caseInsensitive?1:0); if ( !res ) { clearSelectionInternal(); throw new Exception("pattern not found"); } } public void done() { BackgroundThread.ensureGUI(); drawPage(); } }); } public void clearSelection() { BackgroundThread.ensureGUI(); mEngine.post(new Task() { public void work() throws Exception { BackgroundThread.ensureBackground(); clearSelectionInternal(); invalidImages = true; } public void done() { BackgroundThread.ensureGUI(); drawPage(); } }); } public void goToBookmark( Bookmark bm ) { BackgroundThread.ensureGUI(); final String pos = bm.getStartPos(); mEngine.execute(new Task() { public void work() { BackgroundThread.ensureBackground(); goToPositionInternal(pos); } public void done() { BackgroundThread.ensureGUI(); drawPage(); } }); } public boolean goToBookmark( final int shortcut ) { BackgroundThread.ensureGUI(); if ( mBookInfo!=null ) { Bookmark bm = mBookInfo.findShortcutBookmark(shortcut); if ( bm==null ) { addBookmark(shortcut); return true; } else { // go to bookmark goToBookmark( bm ); return false; } } return false; } public void addBookmark( final int shortcut ) { BackgroundThread.ensureGUI(); // set bookmark instead mEngine.execute(new Task() { Bookmark bm; public void work() { BackgroundThread.ensureBackground(); if ( mBookInfo!=null ) { bm = getCurrentPageBookmarkInternal(); bm.setShortcut(shortcut); } } public void done() { if ( mBookInfo!=null && bm!=null ) { mBookInfo.setShortcutBookmark(shortcut, bm); mActivity.getDB().save(mBookInfo); mActivity.showToast("Bookmark " + (shortcut==10?0:shortcut) + " is set."); } } }); } public boolean onMenuItem( final int itemId ) { BackgroundThread.ensureGUI(); ReaderAction action = ReaderAction.findByMenuId(itemId); if ( action.isNone() ) return false; onAction(action); return true; } public void onAction( final ReaderAction action ) { onAction(action, null); } public void onAction( final ReaderAction action, final Runnable onFinishHandler ) { BackgroundThread.ensureGUI(); if ( action.cmd!=ReaderCommand.DCMD_NONE ) onCommand( action.cmd, action.param, onFinishHandler ); } public void toggleDayNightMode() { Properties settings = getSettings(); OptionsDialog.toggleDayNightMode(settings); setSettings(settings, null); } public void onCommand( final ReaderCommand cmd, final int param ) { onCommand( cmd, param, null ); } public void onCommand( final ReaderCommand cmd, final int param, final Runnable onFinishHandler ) { BackgroundThread.ensureGUI(); Log.i("cr3", "On command " + cmd + (param!=0?" ("+param+")":" ")); switch ( cmd ) { case DCMD_TOGGLE_TOUCH_SCREEN_LOCK: isTouchScreenEnabled = !isTouchScreenEnabled; if ( isTouchScreenEnabled ) mActivity.showToast(R.string.action_touch_screen_enabled_toast); else mActivity.showToast(R.string.action_touch_screen_disabled_toast); break; case DCMD_ZOOM_OUT: doEngineCommand( ReaderCommand.DCMD_ZOOM_OUT, 1); syncViewSettings(getSettings()); break; case DCMD_ZOOM_IN: doEngineCommand( ReaderCommand.DCMD_ZOOM_IN, 1); syncViewSettings(getSettings()); break; case DCMD_PAGEDOWN: if ( param==1 ) animatePageFlip(1, onFinishHandler); else doEngineCommand(cmd, param, onFinishHandler); break; case DCMD_PAGEUP: if ( param==1 ) animatePageFlip(-1, onFinishHandler); else doEngineCommand(cmd, param, onFinishHandler); break; case DCMD_BEGIN: case DCMD_END: doEngineCommand(cmd, param); break; case DCMD_RECENT_BOOKS_LIST: mActivity.showBrowserRecentBooks(); break; case DCMD_SEARCH: showSearchDialog(); break; case DCMD_EXIT: mActivity.finish(); break; case DCMD_BOOKMARKS: mActivity.showBookmarksDialog(); break; case DCMD_GO_PERCENT_DIALOG: mActivity.showGoToPercentDialog(); break; case DCMD_GO_PAGE_DIALOG: mActivity.showGoToPageDialog(); break; case DCMD_TOC_DIALOG: showTOC(); break; case DCMD_FILE_BROWSER: mActivity.showBrowser(getOpenedFileInfo()); break; case DCMD_OPTIONS_DIALOG: mActivity.showOptionsDialog(); break; case DCMD_READER_MENU: mActivity.openOptionsMenu(); break; case DCMD_TOGGLE_DAY_NIGHT_MODE: toggleDayNightMode(); break; } } public void doEngineCommand( final ReaderCommand cmd, final int param ) { doEngineCommand( cmd, param, null ); } public void doEngineCommand( final ReaderCommand cmd, final int param, final Runnable doneHandler ) { BackgroundThread.ensureGUI(); Log.d("cr3", "doCommand("+cmd + ", " + param +")"); post(new Task() { boolean res; public void work() { BackgroundThread.ensureBackground(); res = doCommandInternal(cmd.nativeId, param); } public void done() { if ( res ) drawPage( doneHandler ); } }); } public void doCommandFromBackgroundThread( final ReaderCommand cmd, final int param ) { Log.d("cr3", "doCommandFromBackgroundThread("+cmd + ", " + param +")"); BackgroundThread.ensureBackground(); boolean res = doCommandInternal(cmd.nativeId, param); if ( res ) { BackgroundThread.guiExecutor.execute(new Runnable() { public void run() { drawPage(); } }); } } volatile private boolean mInitialized = false; volatile private boolean mOpened = false; //private File historyFile; private void updateLoadedBookInfo() { BackgroundThread.ensureBackground(); // get title, authors, etc. updateBookInfoInternal( mBookInfo ); } private void applySettings( Properties props ) { BackgroundThread.ensureBackground(); Log.v("cr3", "applySettings() " + props); boolean isFullScreen = props.getBool(PROP_APP_FULLSCREEN, false ); props.setBool(PROP_SHOW_BATTERY, isFullScreen); props.setBool(PROP_SHOW_TIME, isFullScreen); String backgroundImageId = props.getProperty(PROP_PAGE_BACKGROUND_IMAGE); if ( backgroundImageId!=null ) setBackgroundTexture(backgroundImageId); applySettingsInternal(props); syncViewSettings(props); drawPage(); } public static boolean eq(Object obj1, Object obj2) { if ( obj1==null && obj2==null ) return true; if ( obj1==null || obj2==null ) return false; return obj1.equals(obj2); } public void saveSettings( Properties settings ) { mActivity.saveSettings(settings); } /** * Read JNI view settings, update and save if changed */ private void syncViewSettings( final Properties currSettings ) { post( new Task() { Properties props; public void work() { BackgroundThread.ensureBackground(); java.util.Properties internalProps = getSettingsInternal(); props = new Properties(internalProps); } public void done() { Properties changedSettings = props.diff(currSettings); for ( Map.Entry<Object, Object> entry : changedSettings.entrySet() ) { currSettings.setProperty((String)entry.getKey(), (String)entry.getValue()); } mSettings = currSettings; saveSettings(currSettings); } }); } public Properties getSettings() { return new Properties(mSettings); } private boolean hiliteTapZoneOnTap = false; private boolean enableVolumeKeys = true; static private final int DEF_PAGE_FLIP_MS = 500; public void applyAppSetting( String key, String value ) { boolean flg = "1".equals(value); if ( key.equals(PROP_APP_FULLSCREEN) ) { this.mActivity.setFullscreen( "1".equals(value) ); } else if ( key.equals(PROP_APP_SHOW_COVERPAGES) ) { mActivity.getHistory().setCoverPagesEnabled(flg); } else if ( key.equals(PROP_APP_BOOK_PROPERTY_SCAN_ENABLED) ) { mActivity.getScanner().setDirScanEnabled(flg); } else if ( key.equals(PROP_APP_SCREEN_BACKLIGHT_LOCK) ) { mActivity.setWakeLockEnabled(flg); } else if ( key.equals(PROP_NIGHT_MODE) ) { mActivity.setNightMode(flg); } else if ( key.equals(PROP_APP_TAP_ZONE_HILIGHT) ) { hiliteTapZoneOnTap = flg; } else if ( key.equals(PROP_APP_SCREEN_ORIENTATION) ) { int orientation = "1".equals(value) ? 1 : ("4".equals(value) ? 4 : 0); mActivity.setScreenOrientation(orientation); } else if ( PROP_PAGE_ANIMATION.equals(key) ) { try { int n = Integer.valueOf(value); if ( n<0 || n>2 ) n = 1; pageFlipAnimationMode = n; } catch ( Exception e ) { // ignore } pageFlipAnimationSpeedMs = pageFlipAnimationMode!=PAGE_ANIMATION_NONE ? DEF_PAGE_FLIP_MS : 0; } else if ( PROP_CONTROLS_ENABLE_VOLUME_KEYS.equals(key) ) { enableVolumeKeys = flg; } else if ( PROP_APP_SCREEN_BACKLIGHT.equals(key) ) { try { int n = Integer.valueOf(value); mActivity.setScreenBacklightLevel(n); } catch ( Exception e ) { // ignore } } } public void setAppSettings( Properties newSettings, Properties oldSettings ) { Log.v("cr3", "setAppSettings() " + newSettings.toString()); BackgroundThread.ensureGUI(); if ( oldSettings==null ) oldSettings = mSettings; Properties changedSettings = newSettings.diff(oldSettings); for ( Map.Entry<Object, Object> entry : changedSettings.entrySet() ) { String key = (String)entry.getKey(); String value = (String)entry.getValue(); applyAppSetting( key, value ); if ( PROP_APP_FULLSCREEN.equals(key) ) { boolean flg = mSettings.getBool(PROP_APP_FULLSCREEN, false); newSettings.setBool(PROP_SHOW_BATTERY, flg); newSettings.setBool(PROP_SHOW_TIME, flg); } else if ( PROP_PAGE_VIEW_MODE.equals(key) ) { boolean flg = "1".equals(value); viewMode = flg ? ViewMode.PAGES : ViewMode.SCROLL; } else if ( PROP_APP_SCREEN_ORIENTATION.equals(key) || PROP_PAGE_ANIMATION.equals(key) || PROP_CONTROLS_ENABLE_VOLUME_KEYS.equals(key) || PROP_APP_SHOW_COVERPAGES.equals(key) || PROP_APP_SCREEN_BACKLIGHT.equals(key) || PROP_APP_BOOK_PROPERTY_SCAN_ENABLED.equals(key) || PROP_APP_SCREEN_BACKLIGHT_LOCK.equals(key) || PROP_APP_TAP_ZONE_HILIGHT.equals(key) ) { newSettings.setProperty(key, value); } else if ( PROP_HYPHENATION_DICT.equals(key) ) { Engine.HyphDict dict = HyphDict.byCode(value); //mEngine.setHyphenationDictionary(); if ( mEngine.setHyphenationDictionary(dict) ) { if ( isBookLoaded() ) { doEngineCommand( ReaderCommand.DCMD_REQUEST_RENDER, 0); //drawPage(); } } newSettings.setProperty(key, value); } } } public ViewMode getViewMode() { return viewMode; } /** * Change settings. * @param newSettings are new settings * @param oldSettings are old settings, null to use mSettings */ public void setSettings(Properties newSettings, Properties oldSettings) { Log.v("cr3", "setSettings() " + newSettings.toString()); BackgroundThread.ensureGUI(); if ( oldSettings==null ) oldSettings = mSettings; final Properties currSettings = new Properties(oldSettings); setAppSettings( newSettings, currSettings ); Properties changedSettings = newSettings.diff(currSettings); currSettings.setAll(changedSettings); mBackThread.executeBackground(new Runnable() { public void run() { applySettings(currSettings); } }); // } } private void setBackgroundTexture( String textureId ) { BackgroundTextureInfo[] textures = mEngine.getAvailableTextures(); for ( BackgroundTextureInfo item : textures ) { if ( item.id.equals(textureId) ) { setBackgroundTexture( item ); return; } } setBackgroundTexture( Engine.NO_TEXTURE ); } private void setBackgroundTexture( BackgroundTextureInfo texture ) { if ( !currentBackgroundTexture.equals(texture) ) { Log.d("cr3", "setBackgroundTexture( " + texture + " )"); currentBackgroundTexture = texture; byte[] data = mEngine.getImageData(currentBackgroundTexture); setPageBackgroundTextureInternal(data, texture.tiled ? 1 : 0); } } BackgroundTextureInfo currentBackgroundTexture = Engine.NO_TEXTURE; class CreateViewTask extends Task { Properties props = new Properties(); public CreateViewTask( Properties props ) { this.props = props; Properties oldSettings = new Properties(); // may be changed by setAppSettings setAppSettings(props, oldSettings); props.setAll(oldSettings); mSettings = props; } public void work() throws Exception { BackgroundThread.ensureBackground(); Log.d("cr3", "CreateViewTask - in background thread"); // BackgroundTextureInfo[] textures = mEngine.getAvailableTextures(); // byte[] data = mEngine.getImageData(textures[3]); byte[] data = mEngine.getImageData(currentBackgroundTexture); setPageBackgroundTextureInternal(data, currentBackgroundTexture.tiled?1:0); //File historyDir = activity.getDir("settings", Context.MODE_PRIVATE); //File historyDir = new File(Environment.getExternalStorageDirectory(), ".cr3"); //historyDir.mkdirs(); //File historyFile = new File(historyDir, "cr3hist.ini"); //File historyFile = new File(activity.getDir("settings", Context.MODE_PRIVATE), "cr3hist.ini"); //if ( historyFile.exists() ) { //Log.d("cr3", "Reading history from file " + historyFile.getAbsolutePath()); //readHistoryInternal(historyFile.getAbsolutePath()); //} String css = mEngine.loadResourceUtf8(R.raw.fb2); if ( css!=null && css.length()>0 ) setStylesheetInternal(css); applySettings(props); mInitialized = true; } public void done() { Log.d("cr3", "InitializationFinishedEvent"); BackgroundThread.ensureGUI(); //setSettings(props, new Properties()); } public void fail( Exception e ) { Log.e("cr3", "CoolReader engine initialization failed. Exiting.", e); mEngine.fatalError("Failed to init CoolReader engine"); } } public void closeIfOpened( final FileInfo fileInfo ) { if ( this.mBookInfo!=null && this.mBookInfo.getFileInfo().pathname.equals(fileInfo.pathname) && mOpened ) { close(); } } public void loadDocument( final FileInfo fileInfo ) { if ( this.mBookInfo!=null && this.mBookInfo.getFileInfo().pathname.equals(fileInfo.pathname) && mOpened ) { Log.d("cr3", "trying to load already opened document"); mActivity.showReader(); drawPage(); return; } post(new LoadDocumentTask(fileInfo, null)); } public boolean loadLastDocument( final Runnable errorHandler ) { BackgroundThread.ensureGUI(); //BookInfo book = mActivity.getHistory().getLastBook(); String lastBookName = mActivity.getLastSuccessfullyOpenedBook(); Log.i("cr3", "loadLastDocument() is called, lastBookName = " + lastBookName); return loadDocument( lastBookName, errorHandler ); } public boolean loadDocument( String fileName, final Runnable errorHandler ) { BackgroundThread.ensureGUI(); Log.i("cr3", "loadDocument(" + fileName + ")"); if ( fileName==null ) { Log.v("cr3", "loadDocument() : no filename specified"); errorHandler.run(); return false; } BookInfo book = fileName!=null ? mActivity.getHistory().getBookInfo(fileName) : null; if ( book!=null ) Log.v("cr3", "loadDocument() : found book in history : " + book); FileInfo fi = null; if ( book==null ) { Log.v("cr3", "loadDocument() : book not found in history, looking for location directory"); FileInfo dir = mActivity.getScanner().findParent(new FileInfo(fileName), mActivity.getScanner().getRoot()); if ( dir!=null ) { Log.v("cr3", "loadDocument() : document location found : " + dir); fi = dir.findItemByPathName(fileName); Log.v("cr3", "loadDocument() : item inside location : " + fi); } if ( fi==null ) { Log.v("cr3", "loadDocument() : no file item " + fileName + " found inside " + dir); errorHandler.run(); return false; } if ( fi.isDirectory ) { Log.v("cr3", "loadDocument() : is a directory, opening browser"); mActivity.showBrowser(fi); return true; } } else { fi = book.getFileInfo(); Log.v("cr3", "loadDocument() : item from history : " + fi); } post( new LoadDocumentTask(fi, errorHandler) ); Log.v("cr3", "loadDocument: LoadDocumentTask(" + fi + ") is posted"); return true; } public BookInfo getBookInfo() { BackgroundThread.ensureGUI(); return mBookInfo; } private int mBatteryState = 100; public void setBatteryState( int state ) { mBatteryState = state; drawPage(); } private static class BitmapFactory { public static final int MAX_FREE_LIST_SIZE=2; ArrayList<Bitmap> freeList = new ArrayList<Bitmap>(); ArrayList<Bitmap> usedList = new ArrayList<Bitmap>(); public synchronized Bitmap get( int dx, int dy ) { for ( int i=0; i<freeList.size(); i++ ) { Bitmap bmp = freeList.get(i); if ( bmp.getWidth()==dx && bmp.getHeight()==dy ) { // found bitmap of proper size freeList.remove(i); usedList.add(bmp); //Log.d("cr3", "BitmapFactory: reused free bitmap, used list = " + usedList.size() + ", free list=" + freeList.size()); return bmp; } } for ( int i=freeList.size()-1; i>=0; i-- ) { Bitmap bmp = freeList.remove(i); //Log.d("cr3", "Recycling free bitmap "+bmp.getWidth()+"x"+bmp.getHeight()); bmp.recycle(); } Bitmap bmp = Bitmap.createBitmap(dx, dy, Bitmap.Config.RGB_565); //bmp.setDensity(0); usedList.add(bmp); //Log.d("cr3", "Created new bitmap "+dx+"x"+dy+". New bitmap list size = " + usedList.size()); return bmp; } public synchronized void compact() { while ( freeList.size()>0 ) { freeList.get(0).recycle(); freeList.remove(0); } } public synchronized void release( Bitmap bmp ) { for ( int i=0; i<usedList.size(); i++ ) { if ( usedList.get(i)==bmp ) { freeList.add(bmp); usedList.remove(i); while ( freeList.size()>MAX_FREE_LIST_SIZE ) { freeList.get(0).recycle(); freeList.remove(0); } Log.d("cr3", "BitmapFactory: bitmap released, used size = " + usedList.size() + ", free size=" + freeList.size()); return; } } // unknown bitmap, just recycle bmp.recycle(); } }; BitmapFactory factory = new BitmapFactory(); class BitmapInfo { Bitmap bitmap; PositionProperties position; void recycle() { factory.release(bitmap); bitmap = null; position = null; } @Override public String toString() { return "BitmapInfo [position=" + position + "]"; } } private BitmapInfo mCurrentPageInfo; private BitmapInfo mNextPageInfo; /** * Prepare and cache page image. * Cache is represented by two slots: mCurrentPageInfo and mNextPageInfo. * If page already exists in cache, returns it (if current page requested, * ensures that it became stored as mCurrentPageInfo; if another page requested, * no mCurrentPageInfo/mNextPageInfo reordering made). * @param offset is kind of page: 0==current, -1=previous, 1=next page * @return page image and properties, null if requested page is unavailable (e.g. requested next/prev page is out of document range) */ private BitmapInfo preparePageImage( int offset ) { BackgroundThread.ensureBackground(); Log.v("cr3", "preparePageImage( "+offset+")"); if ( invalidImages ) { if ( mCurrentPageInfo!=null ) mCurrentPageInfo.recycle(); mCurrentPageInfo = null; if ( mNextPageInfo!=null ) mNextPageInfo.recycle(); mNextPageInfo = null; invalidImages = false; } if ( internalDX==0 || internalDY==0 ) { internalDX=200; internalDY=300; resizeInternal(internalDX, internalDY); } PositionProperties currpos = getPositionPropsInternal(null); boolean isPageView = currpos.pageMode!=0; BitmapInfo currposBitmap = null; if ( mCurrentPageInfo!=null && mCurrentPageInfo.position.equals(currpos) ) currposBitmap = mCurrentPageInfo; else if ( mNextPageInfo!=null && mNextPageInfo.position.equals(currpos) ) currposBitmap = mNextPageInfo; if ( offset==0 ) { // Current page requested if ( currposBitmap!=null ) { if ( mNextPageInfo==currposBitmap ) { // reorder pages BitmapInfo tmp = mNextPageInfo; mNextPageInfo = mCurrentPageInfo; mCurrentPageInfo = tmp; } // found ready page image return mCurrentPageInfo; } if ( mCurrentPageInfo!=null ) { mCurrentPageInfo.recycle(); mCurrentPageInfo = null; } BitmapInfo bi = new BitmapInfo(); bi.position = currpos; bi.bitmap = factory.get(internalDX, internalDY); setBatteryStateInternal(mBatteryState); getPageImageInternal(bi.bitmap); mCurrentPageInfo = bi; //Log.v("cr3", "Prepared new current page image " + mCurrentPageInfo); return mCurrentPageInfo; } if ( isPageView ) { // PAGES: one of next or prev pages requested, offset is specified as param int cmd1 = offset > 0 ? ReaderCommand.DCMD_PAGEDOWN.nativeId : ReaderCommand.DCMD_PAGEUP.nativeId; int cmd2 = offset > 0 ? ReaderCommand.DCMD_PAGEUP.nativeId : ReaderCommand.DCMD_PAGEDOWN.nativeId; if ( offset<0 ) offset = -offset; if ( doCommandInternal(cmd1, offset) ) { // can move to next page PositionProperties nextpos = getPositionPropsInternal(null); BitmapInfo nextposBitmap = null; if ( mCurrentPageInfo!=null && mCurrentPageInfo.position.equals(nextpos) ) nextposBitmap = mCurrentPageInfo; else if ( mNextPageInfo!=null && mNextPageInfo.position.equals(nextpos) ) nextposBitmap = mNextPageInfo; if ( nextposBitmap==null ) { // existing image not found in cache, overriding mNextPageInfo if ( mNextPageInfo!=null ) mNextPageInfo.recycle(); mNextPageInfo = null; BitmapInfo bi = new BitmapInfo(); bi.position = nextpos; bi.bitmap = factory.get(internalDX, internalDY); setBatteryStateInternal(mBatteryState); getPageImageInternal(bi.bitmap); mNextPageInfo = bi; nextposBitmap = bi; //Log.v("cr3", "Prepared new current page image " + mNextPageInfo); } // return back to previous page doCommandInternal(cmd2, offset); return nextposBitmap; } else { // cannot move to page: out of document range return null; } } else { // SCROLL next or prev page requested, with pixel offset specified int y = currpos.y + offset; if ( doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, y) ) { PositionProperties nextpos = getPositionPropsInternal(null); BitmapInfo nextposBitmap = null; if ( mCurrentPageInfo!=null && mCurrentPageInfo.position.equals(nextpos) ) nextposBitmap = mCurrentPageInfo; else if ( mNextPageInfo!=null && mNextPageInfo.position.equals(nextpos) ) nextposBitmap = mNextPageInfo; if ( nextposBitmap==null ) { // existing image not found in cache, overriding mNextPageInfo if ( mNextPageInfo!=null ) mNextPageInfo.recycle(); mNextPageInfo = null; BitmapInfo bi = new BitmapInfo(); bi.position = nextpos; bi.bitmap = factory.get(internalDX, internalDY); setBatteryStateInternal(mBatteryState); getPageImageInternal(bi.bitmap); mNextPageInfo = bi; nextposBitmap = bi; } // return back to prev position doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, currpos.y); return nextposBitmap; } else { return null; } } } private int lastDrawTaskId = 0; private class DrawPageTask extends Task { final int id; BitmapInfo bi; Runnable doneHandler; DrawPageTask(Runnable doneHandler) { this.id = ++lastDrawTaskId; this.doneHandler = doneHandler; } public void work() { BackgroundThread.ensureBackground(); if ( this.id!=lastDrawTaskId ) { Log.d("cr3", "skipping duplicate drawPage request"); return; } nextHiliteId++; if ( currentAnimation!=null ) { Log.d("cr3", "skipping drawPage request while scroll animation is in progress"); return; } Log.e("cr3", "DrawPageTask.work("+internalDX+","+internalDY+")"); bi = preparePageImage(0); if ( bi!=null ) { draw(); } } @Override public void done() { BackgroundThread.ensureGUI(); // Log.d("cr3", "drawPage : bitmap is ready, invalidating view to draw new bitmap"); // if ( bi!=null ) { // setBitmap( bi.bitmap ); // invalidate(); // } // if (mOpened) mEngine.hideProgress(); if ( doneHandler!=null ) doneHandler.run(); } @Override public void fail(Exception e) { mEngine.hideProgress(); } }; class ReaderSurfaceView extends SurfaceView { public ReaderSurfaceView( Context context ) { super(context); } } // SurfaceView callbacks @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.i("cr3", "surfaceChanged(" + width + ", " + height + ")"); drawPage(); } boolean mSurfaceCreated = false; @Override public void surfaceCreated(SurfaceHolder holder) { Log.i("cr3", "surfaceCreated()"); mSurfaceCreated = true; drawPage(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.i("cr3", "surfaceDestroyed()"); mSurfaceCreated = false; } enum AnimationType { SCROLL, // for scroll mode PAGE_SHIFT, // for simple page shift } private ViewAnimationControl currentAnimation = null; private int pageFlipAnimationSpeedMs = DEF_PAGE_FLIP_MS; // if 0 : no animation private int pageFlipAnimationMode = PAGE_ANIMATION_PAPER; // if 0 : no animation private void animatePageFlip( final int dir ) { animatePageFlip(dir, null); } private void animatePageFlip( final int dir, final Runnable onFinishHandler ) { BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { BackgroundThread.ensureBackground(); if ( currentAnimation==null ) { PositionProperties currPos = getPositionPropsInternal(null); if ( currPos==null ) return; int w = currPos.pageWidth; int h = currPos.pageHeight; int dir2 = dir; // if ( currPos.pageMode==2 ) // if ( dir2==1 ) // dir2 = 2; // else if ( dir2==-1 ) // dir2 = -2; int speed = pageFlipAnimationSpeedMs; if ( onFinishHandler!=null ) speed = pageFlipAnimationSpeedMs / 2; if ( currPos.pageMode!=0 ) { int fromX = dir2>0 ? w : 0; int toX = dir2>0 ? 0 : w; new PageViewAnimation(fromX, w, dir2); if ( currentAnimation!=null ) { if ( currentAnimation!=null ) { nextHiliteId++; hiliteRect = null; } currentAnimation.update(toX, h/2); currentAnimation.move(speed, true); currentAnimation.stop(-1, -1); if ( onFinishHandler!=null ) BackgroundThread.guiExecutor.execute(onFinishHandler); } } else { //new ScrollViewAnimation(startY, maxY); int fromY = dir>0 ? h*7/8 : 0; int toY = dir>0 ? 0 : h*7/8; new ScrollViewAnimation(fromY, h); if ( currentAnimation!=null ) { if ( currentAnimation!=null ) { nextHiliteId++; hiliteRect = null; } currentAnimation.update(w/2, toY); currentAnimation.move(speed, true); currentAnimation.stop(-1, -1); if ( onFinishHandler!=null ) BackgroundThread.guiExecutor.execute(onFinishHandler); } } } } }); } static private Rect tapZoneBounds( int startX, int startY, int maxX, int maxY ) { if ( startX<0 ) startX=0; if ( startY<0 ) startY = 0; if ( startX>maxX ) startX = maxX; if ( startY>maxY) startY = maxY; int dx = (maxX + 2) / 3; int dy = (maxY + 2) / 3; int x0 = startX / dx * dx; int y0 = startY / dy * dy; return new Rect(x0, y0, x0+dx, y0+dy); } volatile private int nextHiliteId = 0; private final static int HILITE_RECT_ALPHA = 32; private Rect hiliteRect = null; private void unhiliteTapZone() { hiliteTapZone( false, 0, 0, getWidth(), getHeight() ); } private void hiliteTapZone( final boolean hilite, final int startX, final int startY, final int maxX, final int maxY ) { if (DEBUG_ANIMATION) Log.d("cr3", "highliteTapZone("+startX + ", " + startY+")"); final int myHiliteId = ++nextHiliteId; int txcolor = mSettings.getColor(PROP_FONT_COLOR, Color.BLACK); final int color = (txcolor & 0xFFFFFF) | (HILITE_RECT_ALPHA<<24); BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { if ( myHiliteId != nextHiliteId || (!hilite && hiliteRect==null) ) return; BackgroundThread.ensureBackground(); final BitmapInfo pageImage = preparePageImage(0); if ( pageImage!=null && pageImage.bitmap!=null && pageImage.position!=null ) { //PositionProperties currPos = pageImage.position; final Rect rc = hilite ? tapZoneBounds( startX, startY, maxX, maxY ) : hiliteRect; if ( hilite ) hiliteRect = rc; else hiliteRect = null; if ( rc!=null ) drawCallback( new DrawCanvasCallback() { @Override public void drawTo(Canvas canvas) { if ( mInitialized && mCurrentPageInfo!=null ) { Log.d("cr3", "onDraw() -- drawing page image"); canvas.drawBitmap(mCurrentPageInfo.bitmap, rc, rc, null); if ( hilite ) { Paint p = new Paint(); p.setColor(color); if ( true ) { canvas.drawRect(new Rect(rc.left, rc.top, rc.right-2, rc.top+2), p); canvas.drawRect(new Rect(rc.left, rc.top+2, rc.left+2, rc.bottom-2), p); canvas.drawRect(new Rect(rc.right-2-2, rc.top+2, rc.right-2, rc.bottom-2), p); canvas.drawRect(new Rect(rc.left+2, rc.bottom-2-2, rc.right-2-2, rc.bottom-2), p); } else { canvas.drawRect(rc, p); } } } } }, rc); } } }); } private void scheduleUnhilite( int delay ) { final int myHiliteId = nextHiliteId; mBackThread.postGUI(new Runnable() { @Override public void run() { if ( myHiliteId == nextHiliteId && hiliteRect!=null ) unhiliteTapZone(); } }, delay); } private void startAnimation( final int startX, final int startY, final int maxX, final int maxY ) { if (DEBUG_ANIMATION) Log.d("cr3", "startAnimation("+startX + ", " + startY+")"); BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { BackgroundThread.ensureBackground(); PositionProperties currPos = getPositionPropsInternal(null); if ( currPos.pageMode!=0 ) { //int dir = startX > maxX/2 ? currPos.pageMode : -currPos.pageMode; int dir = startX > maxX/2 ? 1 : -1; int sx = startX; if ( dir<0 ) sx = 0; new PageViewAnimation(sx, maxX, dir); } else { new ScrollViewAnimation(startY, maxY); } if ( currentAnimation!=null ) { nextHiliteId++; hiliteRect = null; } } }); } private final static boolean DEBUG_ANIMATION = false; private int updateSerialNumber = 0; private void updateAnimation( final int x, final int y ) { if (DEBUG_ANIMATION) Log.d("cr3", "updateAnimation("+x + ", " + y+")"); final int serial = ++updateSerialNumber; BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { if ( currentAnimation!=null ) { currentAnimation.update(x, y); if ( serial==updateSerialNumber ) //|| serial==updateSerialNumber-1 currentAnimation.animate(); } } }); try { // give a chance to background thread to process event faster Thread.sleep(0); } catch ( InterruptedException e ) { // ignore } } private void stopAnimation( final int x, final int y ) { if (DEBUG_ANIMATION) Log.d("cr3", "stopAnimation("+x+", "+y+")"); BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { if ( currentAnimation!=null ) { currentAnimation.stop(x, y); } } }); } private int animationSerialNumber = 0; private void scheduleAnimation() { final int serial = ++animationSerialNumber; BackgroundThread.backgroundExecutor.execute(new Runnable() { @Override public void run() { if ( serial!=animationSerialNumber ) return; if ( currentAnimation!=null ) { currentAnimation.animate(); } } }); } interface ViewAnimationControl { public void update( int x, int y ); public void stop( int x, int y ); public void animate(); public void move( int duration, boolean accelerated ); public boolean isStarted(); } private Object surfaceLock = new Object(); private static final int[] accelerationShape = new int[] { 0, 6, 24, 54, 95, 146, 206, 273, 345, 421, 500, 578, 654, 726, 793, 853, 904, 945, 975, 993, 1000 }; static public int accelerate( int x0, int x1, int x ) { if ( x<x0 ) x = x0; if (x>x1) x = x1; int intervals = accelerationShape.length - 1; int pos = 100 * intervals * (x - x0) / (x1-x0); int interval = pos / 100; int part = pos % 100; if ( interval<0 ) interval = 0; else if ( interval>intervals ) interval = intervals; int y = interval==intervals ? 100000 : accelerationShape[interval]*100 + (accelerationShape[interval+1]-accelerationShape[interval]) * part; return x0 + (x1 - x0) * y / 100000; } private interface DrawCanvasCallback { public void drawTo( Canvas c ); } private void drawCallback( DrawCanvasCallback callback, Rect rc ) { if ( !mSurfaceCreated ) return; //synchronized(surfaceLock) { } //Log.v("cr3", "draw() - in thread " + Thread.currentThread().getName()); final SurfaceHolder holder = getHolder(); //Log.v("cr3", "before synchronized(surfaceLock)"); if ( holder!=null ) //synchronized(surfaceLock) { Canvas canvas = null; try { long startTs = android.os.SystemClock.uptimeMillis(); canvas = holder.lockCanvas(rc); //Log.v("cr3", "before draw(canvas)"); if ( canvas!=null ) { callback.drawTo(canvas); if ( rc==null ) { long endTs = android.os.SystemClock.uptimeMillis(); updateAnimationDurationStats(endTs - startTs); } } } finally { //Log.v("cr3", "exiting finally"); if ( canvas!=null && getHolder()!=null ) { //Log.v("cr3", "before unlockCanvasAndPost"); if ( canvas!=null && holder!=null ) holder.unlockCanvasAndPost(canvas); //Log.v("cr3", "after unlockCanvasAndPost"); } } } //Log.v("cr3", "exiting draw()"); } abstract class ViewAnimationBase implements ViewAnimationControl { long startTimeStamp; boolean started; public boolean isStarted() { return started; } ViewAnimationBase() { startTimeStamp = android.os.SystemClock.uptimeMillis(); } public void close() { currentAnimation = null; } public void draw() { drawCallback( new DrawCanvasCallback() { @Override public void drawTo(Canvas c) { draw(c); } }, null); } abstract void draw( Canvas canvas ); } class ScrollViewAnimation extends ViewAnimationBase { int startY; int maxY; int pointerStartPos; int pointerDestPos; int pointerCurrPos; ScrollViewAnimation( int startY, int maxY ) { super(); this.startY = startY; this.maxY = maxY; long start = android.os.SystemClock.uptimeMillis(); Log.v("cr3", "ScrollViewAnimation -- creating: drawing two pages to buffer"); PositionProperties currPos = getPositionPropsInternal(null); int pos = currPos.y; int pos0 = pos - (maxY - startY); if ( pos0<0 ) pos0 = 0; pointerStartPos = pos; pointerCurrPos = pos; pointerDestPos = startY; BitmapInfo image1; BitmapInfo image2; doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, pos0); image1 = preparePageImage(0); image2 = preparePageImage(image1.position.pageHeight); // doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, pos0 + image1.position.pageHeight); // image2 = preparePageImage(0); doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, pos); if ( image1==null || image2==null ) { Log.v("cr3", "ScrollViewAnimation -- not started: image is null"); return; } long duration = android.os.SystemClock.uptimeMillis() - start; Log.v("cr3", "ScrollViewAnimation -- created in " + duration + " millis"); currentAnimation = this; } @Override public void stop(int x, int y) { //if ( started ) { if ( y!=-1 ) { int delta = startY - y; pointerCurrPos = pointerStartPos + delta; } pointerDestPos = pointerCurrPos; draw(); doCommandInternal(ReaderCommand.DCMD_GO_POS.nativeId, pointerDestPos); //} close(); } @Override public void move( int duration, boolean accelerated ) { if ( duration>0 ) { int steps = (int)(duration / getAvgAnimationDrawDuration()) + 2; int x0 = pointerCurrPos; int x1 = pointerDestPos; if ( (x0-x1)<10 && (x0-x1)>-10 ) steps = 2; for ( int i=1; i<steps; i++ ) { int x = x0 + (x1-x0) * i / steps; pointerCurrPos = accelerated ? accelerate( x0, x1, x ) : x; draw(); } } pointerCurrPos = pointerDestPos; draw(); } @Override public void update(int x, int y) { int delta = startY - y; pointerDestPos = pointerStartPos + delta; } public void animate() { //Log.d("cr3", "animate() is called"); if ( pointerDestPos != pointerCurrPos ) { if ( !started ) started = true; // TODO int delta = pointerCurrPos-pointerDestPos; if ( delta<0 ) delta = -delta; long avgDraw = getAvgAnimationDrawDuration(); int maxStep = (int)(maxY * 1500 / avgDraw); int step; if ( delta > maxStep * 2 ) step = maxStep; else step = (delta + 3) / 4; //int step = delta<3 ? 1 : (delta<5 ? 2 : (delta<10 ? 3 : (delta<15 ? 6 : (delta<25 ? 10 : (delta<50 ? 15 : 30))))); if ( pointerCurrPos<pointerDestPos ) pointerCurrPos+=step; else if ( pointerCurrPos>pointerDestPos ) pointerCurrPos-=step; Log.d("cr3", "animate("+pointerCurrPos + " => " + pointerDestPos + " step=" + step + ")"); //pointerCurrPos = pointerDestPos; draw(); if ( pointerDestPos != pointerCurrPos ) scheduleAnimation(); } } public void draw(Canvas canvas) { BitmapInfo image1 = mCurrentPageInfo; BitmapInfo image2 = mNextPageInfo; int h = image1.position.pageHeight; int rowsFromImg1 = image1.position.y + h - pointerCurrPos; int rowsFromImg2 = h - rowsFromImg1; Rect src1 = new Rect(0, h-rowsFromImg1, mCurrentPageInfo.bitmap.getWidth(), h); Rect dst1 = new Rect(0, 0, mCurrentPageInfo.bitmap.getWidth(), rowsFromImg1); canvas.drawBitmap(image1.bitmap, src1, dst1, null); if (image2!=null) { Rect src2 = new Rect(0, 0, mCurrentPageInfo.bitmap.getWidth(), rowsFromImg2); Rect dst2 = new Rect(0, rowsFromImg1, mCurrentPageInfo.bitmap.getWidth(), h); canvas.drawBitmap(image2.bitmap, src2, dst2, null); } //Log.v("cr3", "anim.drawScroll( pos=" + pointerCurrPos + ", " + src1 + "=>" + dst1 + ", " + src2 + "=>" + dst2 + " )"); } } class PageViewAnimation extends ViewAnimationBase { int startX; int maxX; int page1; int page2; int direction; int currShift; int destShift; int pageCount; private final boolean naturalPageFlip; PageViewAnimation( int startX, int maxX, int direction ) { super(); this.startX = startX; this.maxX = maxX; this.direction = direction; this.currShift = 0; this.destShift = 0; this.naturalPageFlip = (pageFlipAnimationMode==PAGE_ANIMATION_PAPER); long start = android.os.SystemClock.uptimeMillis(); Log.v("cr3", "PageViewAnimation -- creating: drawing two pages to buffer"); PositionProperties currPos = mCurrentPageInfo.position; if ( currPos==null ) currPos = getPositionPropsInternal(null); page1 = currPos.pageNumber; page2 = currPos.pageNumber + direction; if ( page2<0 || page2>=currPos.pageCount) { currentAnimation = null; return; } this.pageCount = currPos.pageMode; BitmapInfo image1 = preparePageImage(0); BitmapInfo image2 = preparePageImage(direction); if ( image1==null || image2==null ) { Log.v("cr3", "PageViewAnimation -- cannot start animation: page image is null"); return; } if ( page1==page2 ) { Log.v("cr3", "PageViewAnimation -- cannot start animation: not moved"); return; } page2 = image2.position.pageNumber; currentAnimation = this; divPaint = new Paint(); divPaint.setColor(Color.argb(128, 128, 128, 128)); long duration = android.os.SystemClock.uptimeMillis() - start; Log.d("cr3", "PageViewAnimation -- created in " + duration + " millis"); } @Override public void move( int duration, boolean accelerated ) { if ( duration > 0 ) { int steps = (int)(duration / getAvgAnimationDrawDuration()) + 2; int x0 = currShift; int x1 = destShift; if ( (x0-x1)<10 && (x0-x1)>-10 ) steps = 2; for ( int i=1; i<steps; i++ ) { int x = x0 + (x1-x0) * i / steps; currShift = accelerated ? accelerate( x0, x1, x ) : x; draw(); } } currShift = destShift; draw(); } @Override public void stop(int x, int y) { if (DEBUG_ANIMATION) Log.v("cr3", "PageViewAnimation.stop(" + x + ", " + y + ")"); //if ( started ) { boolean moved = false; if ( x!=-1 ) { int threshold = mActivity.getPalmTipPixels() * 7/8; if ( direction>0 ) { // | <===== | int dx = startX - x; if ( dx>threshold ) moved = true; } else { // | =====> | int dx = x - startX; if ( dx>threshold ) moved = true; } int duration; if ( moved ) { destShift = maxX; duration = 500; // 500 ms forward } else { destShift = 0; duration = 200; // 200 ms cancel } move( duration, false ); } else { moved = true; } doCommandInternal(ReaderCommand.DCMD_GO_PAGE.nativeId, moved ? page2 : page1); //} close(); // preparing images for next page flip preparePageImage(0); preparePageImage(direction); //if ( started ) // drawPage(); } @Override public void update(int x, int y) { if (DEBUG_ANIMATION) Log.v("cr3", "PageViewAnimation.update(" + x + ", " + y + ")"); int delta = direction>0 ? startX - x : x - startX; if ( delta<=0 ) destShift = 0; else if ( delta<maxX ) destShift = delta; else destShift = maxX; } public void animate() { if (DEBUG_ANIMATION) Log.v("cr3", "PageViewAnimation.animate("+currShift + " => " + currShift + ")"); //Log.d("cr3", "animate() is called"); if ( currShift != destShift ) { started = true; int delta = currShift - destShift; if ( delta<0 ) delta = -delta; long avgDraw = getAvgAnimationDrawDuration(); int maxStep = (int)(maxX * 1500 / avgDraw); int step; if ( delta > maxStep * 2 ) step = maxStep; else step = (delta + 3) / 4; //int step = delta<3 ? 1 : (delta<5 ? 2 : (delta<10 ? 3 : (delta<15 ? 6 : (delta<25 ? 10 : (delta<50 ? 15 : 30))))); if ( currShift < destShift ) currShift+=step; else if ( currShift > destShift ) currShift-=step; if (DEBUG_ANIMATION) Log.v("cr3", "PageViewAnimation.animate("+currShift + " => " + destShift + " step=" + step + ")"); //pointerCurrPos = pointerDestPos; draw(); if ( currShift != destShift ) scheduleAnimation(); } } public void draw(Canvas canvas) { if (DEBUG_ANIMATION) Log.v("cr3", "PageViewAnimation.draw("+currShift + ")"); BitmapInfo image1 = mCurrentPageInfo; BitmapInfo image2 = mNextPageInfo; int w = image1.bitmap.getWidth(); int h = image1.bitmap.getHeight(); int div; if ( direction > 0 ) { // FORWARD div = w-currShift; if ( naturalPageFlip ) { if ( this.pageCount==2 ) { int w2 = w/2; if ( div<w2 ) { // left - part of old page Rect src1 = new Rect(0, 0, div, h); Rect dst1 = new Rect(0, 0, div, h); canvas.drawBitmap(image1.bitmap, src1, dst1, null); // left, resized part of new page Rect src2 = new Rect(0, 0, w2, h); Rect dst2 = new Rect(div, 0, w2, h); canvas.drawBitmap(image2.bitmap, src2, dst2, null); // right, new page Rect src3 = new Rect(w2, 0, w, h); Rect dst3 = new Rect(w2, 0, w, h); canvas.drawBitmap(image2.bitmap, src3, dst3, null); } else { // left - old page Rect src1 = new Rect(0, 0, w2, h); Rect dst1 = new Rect(0, 0, w2, h); canvas.drawBitmap(image1.bitmap, src1, dst1, null); // right, resized old page Rect src2 = new Rect(w2, 0, w, h); Rect dst2 = new Rect(w2, 0, div, h); canvas.drawBitmap(image1.bitmap, src2, dst2, null); // right, new page Rect src3 = new Rect(div, 0, w, h); Rect dst3 = new Rect(div, 0, w, h); canvas.drawBitmap(image2.bitmap, src3, dst3, null); } } else { Rect src1 = new Rect(0, 0, w, h); Rect dst1 = new Rect(0, 0, w-currShift, h); //Log.v("cr3", "drawing " + image1); canvas.drawBitmap(image1.bitmap, src1, dst1, null); Rect src2 = new Rect(w-currShift, 0, w, h); Rect dst2 = new Rect(w-currShift, 0, w, h); //Log.v("cr3", "drawing " + image1); canvas.drawBitmap(image2.bitmap, src2, dst2, null); } } else { Rect src1 = new Rect(currShift, 0, w, h); Rect dst1 = new Rect(0, 0, w-currShift, h); //Log.v("cr3", "drawing " + image1); canvas.drawBitmap(image1.bitmap, src1, dst1, null); Rect src2 = new Rect(w-currShift, 0, w, h); Rect dst2 = new Rect(w-currShift, 0, w, h); //Log.v("cr3", "drawing " + image1); canvas.drawBitmap(image2.bitmap, src2, dst2, null); } } else { // BACK div = currShift; if ( naturalPageFlip ) { if ( this.pageCount==2 ) { int w2 = w/2; if ( div<w2 ) { // left - part of old page Rect src1 = new Rect(0, 0, div, h); Rect dst1 = new Rect(0, 0, div, h); canvas.drawBitmap(image2.bitmap, src1, dst1, null); // left, resized part of new page Rect src2 = new Rect(0, 0, w2, h); Rect dst2 = new Rect(div, 0, w2, h); canvas.drawBitmap(image1.bitmap, src2, dst2, null); // right, new page Rect src3 = new Rect(w2, 0, w, h); Rect dst3 = new Rect(w2, 0, w, h); canvas.drawBitmap(image1.bitmap, src3, dst3, null); } else { // left - old page Rect src1 = new Rect(0, 0, w2, h); Rect dst1 = new Rect(0, 0, w2, h); canvas.drawBitmap(image2.bitmap, src1, dst1, null); // right, resized old page Rect src2 = new Rect(w2, 0, w, h); Rect dst2 = new Rect(w2, 0, div, h); canvas.drawBitmap(image2.bitmap, src2, dst2, null); // right, new page Rect src3 = new Rect(div, 0, w, h); Rect dst3 = new Rect(div, 0, w, h); canvas.drawBitmap(image1.bitmap, src3, dst3, null); } } else { Rect src1 = new Rect(currShift, 0, w, h); Rect dst1 = new Rect(currShift, 0, w, h); canvas.drawBitmap(image1.bitmap, src1, dst1, null); Rect src2 = new Rect(0, 0, w, h); Rect dst2 = new Rect(0, 0, currShift, h); canvas.drawBitmap(image2.bitmap, src2, dst2, null); } } else { Rect src1 = new Rect(currShift, 0, w, h); Rect dst1 = new Rect(currShift, 0, w, h); canvas.drawBitmap(image1.bitmap, src1, dst1, null); Rect src2 = new Rect(w-currShift, 0, w, h); Rect dst2 = new Rect(0, 0, currShift, h); canvas.drawBitmap(image2.bitmap, src2, dst2, null); } } if ( div>0 && div<w ) canvas.drawLine(div, 0, div, h, divPaint); } Paint divPaint; } private long sumAnimationDrawDuration = 1000; private int drawAnimationCount = 10; private long getAvgAnimationDrawDuration() { return sumAnimationDrawDuration / drawAnimationCount; } private void updateAnimationDurationStats( long duration ) { if ( duration<=0 ) duration = 1; else if ( duration>1500 ) return; sumAnimationDrawDuration += duration; if ( ++drawAnimationCount>100 ) { drawAnimationCount /= 2; sumAnimationDrawDuration /= 2; } } private void drawPage() { drawPage(null); } private void drawPage( Runnable doneHandler ) { if ( !mInitialized || !mOpened ) return; Log.v("cr3", "drawPage() : submitting DrawPageTask"); post( new DrawPageTask(doneHandler) ); } private int internalDX = 0; private int internalDY = 0; private byte[] coverPageBytes = null; private BitmapDrawable coverPageDrawable = null; private void findCoverPage() { Log.d("cr3", "document is loaded succesfull, checking coverpage data"); if ( mActivity.getHistory().getCoverPagesEnabled() ) { byte[] coverpageBytes = getCoverPageDataInternal(); if ( coverpageBytes!=null ) { Log.d("cr3", "Found cover page data: " + coverpageBytes.length + " bytes"); BitmapDrawable drawable = mActivity.getHistory().decodeCoverPage(coverpageBytes); if ( drawable!=null ) { coverPageBytes = coverpageBytes; coverPageDrawable = drawable; } } } } private class LoadDocumentTask extends Task { String filename; Runnable errorHandler; String pos; LoadDocumentTask( FileInfo fileInfo, Runnable errorHandler ) { Log.v("cr3", "LoadDocumentTask for " + fileInfo); BackgroundThread.ensureGUI(); this.filename = fileInfo.getPathName(); this.errorHandler = errorHandler; //FileInfo fileInfo = new FileInfo(filename); mBookInfo = mActivity.getHistory().getOrCreateBookInfo( fileInfo ); if ( mBookInfo!=null && mBookInfo.getLastPosition()!=null ) pos = mBookInfo.getLastPosition().getStartPos(); Log.v("cr3", "LoadDocumentTask : book info " + mBookInfo); //mBitmap = null; mEngine.showProgress( 1000, R.string.progress_loading ); //init(); } public void work() throws IOException { BackgroundThread.ensureBackground(); coverPageBytes = null; coverPageDrawable = null; Log.i("cr3", "Loading document " + filename); boolean success = loadDocumentInternal(filename); if ( success ) { Log.v("cr3", "loadDocumentInternal completed successfully"); findCoverPage(); Log.v("cr3", "requesting page image, to render"); preparePageImage(0); Log.v("cr3", "updating loaded book info"); updateLoadedBookInfo(); Log.i("cr3", "Document " + filename + " is loaded successfully"); restorePositionBackground(pos); CoolReader.dumpHeapAllocation(); } else { Log.e("cr3", "Error occured while trying to load document " + filename); throw new IOException("Cannot read document"); } } public void done() { BackgroundThread.ensureGUI(); Log.d("cr3", "LoadDocumentTask, GUI thread is finished successfully"); mActivity.getHistory().updateBookAccess(mBookInfo); mActivity.getHistory().saveToDB(); if ( coverPageBytes!=null && coverPageDrawable!=null ) { mActivity.getHistory().setBookCoverpageData( mBookInfo.getFileInfo().id, coverPageBytes ); //mEngine.setProgressDrawable(coverPageDrawable); } mOpened = true; drawPage(); mBackThread.postGUI(new Runnable() { public void run() { mActivity.showReader(); } }); mActivity.setLastSuccessfullyOpenedBook(filename); } public void fail( Exception e ) { BackgroundThread.ensureGUI(); Log.e("cr3", "LoadDocumentTask failed for " + mBookInfo); mActivity.getHistory().removeBookInfo( mBookInfo.getFileInfo(), true, false ); mBookInfo = null; Log.d("cr3", "LoadDocumentTask is finished with exception " + e.getMessage()); mOpened = false; drawPage(); mEngine.hideProgress(); mActivity.showToast("Error while loading document"); if ( errorHandler!=null ) { Log.e("cr3", "LoadDocumentTask: Calling error handler"); errorHandler.run(); } } } protected void doDraw(Canvas canvas) { try { Log.d("cr3", "doDraw() called"); if ( mInitialized && mCurrentPageInfo!=null ) { Log.d("cr3", "onDraw() -- drawing page image"); Rect dst = new Rect(0, 0, canvas.getWidth(), canvas.getHeight()); Rect src = new Rect(0, 0, mCurrentPageInfo.bitmap.getWidth(), mCurrentPageInfo.bitmap.getHeight()); canvas.drawBitmap(mCurrentPageInfo.bitmap, src, dst, null); } else { Log.d("cr3", "onDraw() -- drawing empty screen"); canvas.drawColor(Color.rgb(192, 192, 192)); } } catch ( Exception e ) { Log.e("cr3", "exception while drawing", e); } } protected void draw() { drawCallback(new DrawCanvasCallback() { @Override public void drawTo(Canvas c) { doDraw(c); } }, null); } @Override protected void onDraw(Canvas canvas) { try { Log.d("cr3", "onDraw() called"); draw(); // if ( mInitialized && mBitmap!=null ) { // Log.d("cr3", "onDraw() -- drawing page image"); // Rect rc = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight()); // canvas.drawBitmap(mBitmap, rc, rc, null); // } else { // Log.d("cr3", "onDraw() -- drawing empty screen"); // canvas.drawColor(Color.rgb(192, 192, 192)); // } } catch ( Exception e ) { Log.e("cr3", "exception while drawing", e); } } private void restorePositionBackground( String pos ) { BackgroundThread.ensureBackground(); if ( pos!=null ) { BackgroundThread.ensureBackground(); goToPositionInternal( pos ); preparePageImage(0); } } // private void restorePosition() // { // BackgroundThread.ensureGUI(); // if ( mBookInfo!=null ) { // if ( mBookInfo.getLastPosition()!=null ) { // final String pos = mBookInfo.getLastPosition().getStartPos(); // post( new Task() { // public void work() { // BackgroundThread.ensureBackground(); // goToPositionInternal( pos ); // preparePageImage(0); // } // }); // mActivity.getHistory().updateBookAccess(mBookInfo); // } // mActivity.getHistory().saveToDB(); // } // } // private void savePosition() // { // BackgroundThread.ensureBackground(); // if ( !mOpened ) // return; // Bookmark bmk = getCurrentPageBookmarkInternal(); // if ( bmk!=null ) // Log.d("cr3", "saving position, bmk=" + bmk.getStartPos()); // else // Log.d("cr3", "saving position: no current page bookmark obtained"); // if ( bmk!=null && mBookInfo!=null ) { // bmk.setTimeStamp(System.currentTimeMillis()); // bmk.setType(Bookmark.TYPE_LAST_POSITION); // mBookInfo.setLastPosition(bmk); // mActivity.getHistory().updateRecentDir(); // mActivity.getHistory().saveToDB(); // saveSettings(); // } // } private class SavePositionTask extends Task { Bookmark bmk; @Override public void done() { if ( bmk!=null && mBookInfo!=null ) { bmk.setTimeStamp(System.currentTimeMillis()); bmk.setType(Bookmark.TYPE_LAST_POSITION); mBookInfo.setLastPosition(bmk); mActivity.getHistory().updateRecentDir(); mActivity.getHistory().saveToDB(); } } public void work() throws Exception { BackgroundThread.ensureBackground(); if ( !mOpened ) return; bmk = getCurrentPageBookmarkInternal(); if ( bmk!=null ) Log.d("cr3", "saving position, bmk=" + bmk.getStartPos()); else Log.d("cr3", "saving position: no current page bookmark obtained"); } } public void save() { BackgroundThread.ensureGUI(); post( new SavePositionTask() ); } public void close() { BackgroundThread.ensureGUI(); Log.i("cr3", "ReaderView.close() is called"); if ( !mOpened ) return; //save(); post( new Task() { public void work() { BackgroundThread.ensureBackground(); if ( mOpened ) { mOpened = false; Log.i("cr3", "ReaderView().close() : closing current document"); doCommandInternal(ReaderCommand.DCMD_CLOSE_BOOK.nativeId, 0); } } public void done() { BackgroundThread.ensureGUI(); if ( currentAnimation==null ) { if ( mCurrentPageInfo!=null ) { mCurrentPageInfo.recycle(); mCurrentPageInfo = null; } if ( mNextPageInfo!=null ) { mNextPageInfo.recycle(); mNextPageInfo = null; } } else invalidImages = true; factory.compact(); mCurrentPageInfo = null; } }); } public void destroy() { Log.i("cr3", "ReaderView.destroy() is called"); BackgroundThread.ensureGUI(); if ( mInitialized ) { //close(); BackgroundThread.backgroundExecutor.execute( new Runnable() { public void run() { BackgroundThread.ensureBackground(); if ( mInitialized ) { Log.i("cr3", "ReaderView.destroyInternal() calling"); destroyInternal(); mInitialized = false; currentBackgroundTexture = Engine.NO_TEXTURE; } } }); //engine.waitTasksCompletion(); } } @Override protected void onDetachedFromWindow() { // TODO Auto-generated method stub super.onDetachedFromWindow(); Log.d("cr3", "View.onDetachedFromWindow() is called"); } private String getCSSForFormat( DocumentFormat fileFormat ) { if ( fileFormat==null ) fileFormat = DocumentFormat.FB2; File[] dataDirs = Engine.getDataDirectories(null, false, false); for ( File dir : dataDirs ) { File file = new File( dir, fileFormat.getCssName() ); if ( file.exists() ) { String css = mEngine.loadFileUtf8(file); if ( css!=null ) return css; } } String s = mEngine.loadResourceUtf8(fileFormat.getCSSResourceId()); return s; } boolean enable_progress_callback = true; ReaderCallback readerCallback = new ReaderCallback() { public boolean OnExportProgress(int percent) { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnExportProgress " + percent); return true; } public void OnExternalLink(String url, String nodeXPath) { BackgroundThread.ensureBackground(); } public void OnFormatEnd() { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnFormatEnd"); //mEngine.hideProgress(); drawPage(); } public boolean OnFormatProgress(final int percent) { BackgroundThread.ensureBackground(); if ( enable_progress_callback ) { Log.d("cr3", "readerCallback.OnFormatProgress " + percent); mEngine.showProgress( percent*4/10 + 5000, R.string.progress_formatting); } // executeSync( new Callable<Object>() { // public Object call() { // BackgroundThread.ensureGUI(); // Log.d("cr3", "readerCallback.OnFormatProgress " + percent); // mEngine.showProgress( percent*4/10 + 5000, R.string.progress_formatting); // return null; // } // }); return true; } public void OnFormatStart() { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnFormatStart"); } public void OnLoadFileEnd() { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnLoadFileEnd"); } public void OnLoadFileError(String message) { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnLoadFileError(" + message + ")"); } public void OnLoadFileFirstPagesReady() { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnLoadFileFirstPagesReady"); } public String OnLoadFileFormatDetected(final DocumentFormat fileFormat) { BackgroundThread.ensureBackground(); String res = executeSync( new Callable<String>() { public String call() { BackgroundThread.ensureGUI(); Log.i("cr3", "readerCallback.OnLoadFileFormatDetected " + fileFormat); if ( fileFormat!=null ) { String s = getCSSForFormat(fileFormat); Log.i("cr3", "setting .css for file format " + fileFormat + " from resource " + (fileFormat!=null?fileFormat.getCssName():"[NONE]")); return s; } return null; } }); return res; } public boolean OnLoadFileProgress(final int percent) { BackgroundThread.ensureBackground(); if ( enable_progress_callback ) { Log.d("cr3", "readerCallback.OnLoadFileProgress " + percent); mEngine.showProgress( percent*4/10 + 1000, R.string.progress_loading); } // executeSync( new Callable<Object>() { // public Object call() { // BackgroundThread.ensureGUI(); // Log.d("cr3", "readerCallback.OnLoadFileProgress " + percent); // mEngine.showProgress( percent*4/10 + 1000, R.string.progress_loading); // return null; // } // }); return true; } public void OnLoadFileStart(String filename) { BackgroundThread.ensureBackground(); Log.d("cr3", "readerCallback.OnLoadFileStart " + filename); } /// Override to handle external links public void OnImageCacheClear() { //Log.d("cr3", "readerCallback.OnImageCacheClear"); clearImageCache(); } }; private boolean invalidImages = true; private void clearImageCache() { BackgroundThread.instance().postBackground( new Runnable() { public void run() { invalidImages = true; } }); } public void setStyleSheet( final String css ) { BackgroundThread.ensureGUI(); if ( css!=null && css.length()>0 ) { post(new Task() { public void work() { setStylesheetInternal(css); } }); } } public void goToPosition( int position ) { BackgroundThread.ensureGUI(); doEngineCommand(ReaderView.ReaderCommand.DCMD_GO_POS, position); } public void moveBy( final int delta ) { BackgroundThread.ensureGUI(); Log.d("cr3", "moveBy(" + delta + ")"); post(new Task() { public void work() { BackgroundThread.ensureBackground(); doCommandInternal(ReaderCommand.DCMD_SCROLL_BY.nativeId, delta); } public void done() { drawPage(); } }); } public void goToPage( int pageNumber ) { BackgroundThread.ensureGUI(); doEngineCommand(ReaderView.ReaderCommand.DCMD_GO_PAGE, pageNumber-1); } public void goToPercent( final int percent ) { BackgroundThread.ensureGUI(); if ( percent>=0 && percent<=100 ) post( new Task() { public void work() { PositionProperties pos = getPositionPropsInternal(null); if ( pos!=null && pos.pageCount>0) { int pageNumber = pos.pageCount * percent / 100; doCommandFromBackgroundThread(ReaderView.ReaderCommand.DCMD_GO_PAGE, pageNumber); } } }); } @Override public void finalize() { Log.w("cr3", "ReaderView.finalize() is called"); //destroyInternal(); } public ReaderView(CoolReader activity, Engine engine, BackgroundThread backThread, Properties props ) { super(activity); SurfaceHolder holder = getHolder(); holder.addCallback(this); BackgroundThread.ensureGUI(); this.mActivity = activity; this.mEngine = engine; this.mBackThread = backThread; setFocusable(true); setFocusableInTouchMode(true); mBackThread.postBackground(new Runnable() { @Override public void run() { Log.d("cr3", "ReaderView - in background thread: calling createInternal()"); createInternal(); mInitialized = true; } }); post(new CreateViewTask( props )); } }
false
true
public boolean onTouchEvent(MotionEvent event) { if ( !isTouchScreenEnabled ) { return true; } int x = (int)event.getX(); int y = (int)event.getY(); int dx = getWidth(); int dy = getHeight(); int START_DRAG_THRESHOLD = mActivity.getPalmTipPixels(); final int zone = getTapZone(x, y, dx, dy); if ( event.getAction()==MotionEvent.ACTION_UP ) { longTouchId++; if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_UP: selection finished"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, true ); selectionInProgress = false; return true; } if ( touchEventIgnoreNextUp ) return true; mActivity.onUserActivity(); unhiliteTapZone(); boolean isLongPress = (event.getEventTime()-event.getDownTime())>LONG_KEYPRESS_TIME; stopAnimation(x, y); if ( isManualScrollActive ) { isManualScrollActive = false; return true; } if ( isLongPress ) { onTapZone( zone, isLongPress ); currentDoubleTapActionStart = 0; } else { currentDoubleTapActionStart = android.os.SystemClock.uptimeMillis(); final long myStart = currentDoubleTapActionStart; BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { if ( currentDoubleTapActionStart != myStart ) { onTapZone( zone, false ); } currentDoubleTapActionStart = 0; } }, DOUBLE_CLICK_INTERVAL); } return true; } else if ( event.getAction()==MotionEvent.ACTION_DOWN ) { touchEventIgnoreNextUp = false; if ( currentDoubleTapActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { Log.v("cr3", "touch ACTION_DOWN: double tap: starting selection"); // double tap started selectionInProgress = true; longTouchId++; selectionStartX = x; selectionStartY = y; selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } selectionInProgress = false; manualScrollStartPosX = x; manualScrollStartPosY = y; currentDoubleTapActionStart = 0; if ( hiliteTapZoneOnTap ) { hiliteTapZone( true, x, y, dx, dy ); scheduleUnhilite( LONG_KEYPRESS_TIME ); } final int myId = ++longTouchId; mBackThread.postGUI( new Runnable() { @Override public void run() { if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; onTapZone( zone, true ); } } }, LONG_KEYPRESS_TIME); return true; } else if ( event.getAction()==MotionEvent.ACTION_MOVE) { if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_MOVE: updating selection"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } // if ( viewMode==ViewMode.SCROLL ) { if ( !isManualScrollActive ) { int deltax = manualScrollStartPosX - x; int deltay = manualScrollStartPosY - y; deltax = deltax < 0 ? -deltax : deltax; deltay = deltay < 0 ? -deltay : deltay; if ( deltax + deltay > START_DRAG_THRESHOLD ) { longTouchId++; isManualScrollActive = true; startAnimation(manualScrollStartPosX, manualScrollStartPosY, dx, dy); updateAnimation(x, y); return true; } } // } if ( !isManualScrollActive ) return true; updateAnimation(x, y); } else if ( event.getAction()==MotionEvent.ACTION_OUTSIDE ) { if ( selectionInProgress ) { // cancel selection cancelSelection(); } isManualScrollActive = false; currentDoubleTapActionStart = 0; longTouchId++; stopAnimation(-1, -1); hiliteTapZone( false, x, y, dx, dy ); } return true; //return super.onTouchEvent(event); }
public boolean onTouchEvent(MotionEvent event) { if ( !isTouchScreenEnabled ) { return true; } int x = (int)event.getX(); int y = (int)event.getY(); int dx = getWidth(); int dy = getHeight(); int START_DRAG_THRESHOLD = mActivity.getPalmTipPixels(); final int zone = getTapZone(x, y, dx, dy); if ( event.getAction()==MotionEvent.ACTION_UP ) { longTouchId++; if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_UP: selection finished"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, true ); selectionInProgress = false; return true; } if ( touchEventIgnoreNextUp ) return true; mActivity.onUserActivity(); unhiliteTapZone(); boolean isLongPress = (event.getEventTime()-event.getDownTime())>LONG_KEYPRESS_TIME; stopAnimation(x, y); if ( isManualScrollActive ) { isManualScrollActive = false; return true; } if ( isLongPress ) { onTapZone( zone, isLongPress ); currentDoubleTapActionStart = 0; } else { currentDoubleTapActionStart = android.os.SystemClock.uptimeMillis(); final long myStart = currentDoubleTapActionStart; BackgroundThread.instance().postGUI(new Runnable() { @Override public void run() { if ( currentDoubleTapActionStart == myStart ) { onTapZone( zone, false ); } currentDoubleTapActionStart = 0; } }, DOUBLE_CLICK_INTERVAL); } return true; } else if ( event.getAction()==MotionEvent.ACTION_DOWN ) { touchEventIgnoreNextUp = false; if ( currentDoubleTapActionStart + DOUBLE_CLICK_INTERVAL > android.os.SystemClock.uptimeMillis() ) { Log.v("cr3", "touch ACTION_DOWN: double tap: starting selection"); // double tap started selectionInProgress = true; longTouchId++; selectionStartX = x; selectionStartY = y; selectionEndX = x; selectionEndY = y; currentDoubleTapActionStart = 0; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } currentDoubleTapActionStart = 0; selectionInProgress = false; manualScrollStartPosX = x; manualScrollStartPosY = y; currentDoubleTapActionStart = 0; if ( hiliteTapZoneOnTap ) { hiliteTapZone( true, x, y, dx, dy ); scheduleUnhilite( LONG_KEYPRESS_TIME ); } final int myId = ++longTouchId; mBackThread.postGUI( new Runnable() { @Override public void run() { if ( myId==longTouchId ) { touchEventIgnoreNextUp = true; onTapZone( zone, true ); } } }, LONG_KEYPRESS_TIME); return true; } else if ( event.getAction()==MotionEvent.ACTION_MOVE) { if ( selectionInProgress ) { Log.v("cr3", "touch ACTION_MOVE: updating selection"); selectionEndX = x; selectionEndY = y; updateSelection( selectionStartX, selectionStartY, selectionEndX, selectionEndY, false ); return true; } // if ( viewMode==ViewMode.SCROLL ) { if ( !isManualScrollActive ) { int deltax = manualScrollStartPosX - x; int deltay = manualScrollStartPosY - y; deltax = deltax < 0 ? -deltax : deltax; deltay = deltay < 0 ? -deltay : deltay; if ( deltax + deltay > START_DRAG_THRESHOLD ) { longTouchId++; isManualScrollActive = true; startAnimation(manualScrollStartPosX, manualScrollStartPosY, dx, dy); updateAnimation(x, y); return true; } } // } if ( !isManualScrollActive ) return true; updateAnimation(x, y); } else if ( event.getAction()==MotionEvent.ACTION_OUTSIDE ) { if ( selectionInProgress ) { // cancel selection cancelSelection(); } isManualScrollActive = false; currentDoubleTapActionStart = 0; longTouchId++; stopAnimation(-1, -1); hiliteTapZone( false, x, y, dx, dy ); } return true; //return super.onTouchEvent(event); }
diff --git a/emailcommon/src/com/android/emailcommon/Device.java b/emailcommon/src/com/android/emailcommon/Device.java index a93a17a2..8cd7d561 100644 --- a/emailcommon/src/com/android/emailcommon/Device.java +++ b/emailcommon/src/com/android/emailcommon/Device.java @@ -1,109 +1,114 @@ /* /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.emailcommon; import com.android.emailcommon.utility.Utility; import android.content.Context; import android.telephony.TelephonyManager; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Device { private static String sDeviceId = null; /** * EAS requires a unique device id, so that sync is possible from a variety of different * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other * device that doesn't provide one, we can create it as android<n> where <n> is system time. * This would work on a real device as well, but it would be better to use the "real" id if * it's available */ static public synchronized String getDeviceId(Context context) throws IOException { if (sDeviceId == null) { sDeviceId = getDeviceIdInternal(context); } return sDeviceId; } static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); - // STOPSHIP Remove logging - Log.w(Logging.LOG_TAG, "deviceId read as: " + id); - return id; + if (id == null) { + // It's very bad if we read a null device id; let's delete that file + if (!f.delete()) { + Log.e(Logging.LOG_TAG, "Can't delete null deviceName file; try overwrite."); + } + } else { + return id; + } } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); // STOPSHIP Remove logging Log.w(Logging.LOG_TAG, "deviceId written as: " + id); return id; } /** * @return Device's unique ID if available. null if the device has no unique ID. */ public static String getConsistentDeviceId(Context context) { final String deviceId; try { TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (tm == null) { return null; } deviceId = tm.getDeviceId(); if (deviceId == null) { return null; } } catch (Exception e) { Log.d(Logging.LOG_TAG, "Error in TelephonyManager.getDeviceId(): " + e.getMessage()); return null; } return Utility.getSmallHash(deviceId); } }
true
true
static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); // STOPSHIP Remove logging Log.w(Logging.LOG_TAG, "deviceId read as: " + id); return id; } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); // STOPSHIP Remove logging Log.w(Logging.LOG_TAG, "deviceId written as: " + id); return id; }
static private String getDeviceIdInternal(Context context) throws IOException { if (context == null) { throw new IllegalStateException("getDeviceId requires a Context"); } File f = context.getFileStreamPath("deviceName"); BufferedReader rdr = null; String id; if (f.exists()) { if (f.canRead()) { rdr = new BufferedReader(new FileReader(f), 128); id = rdr.readLine(); rdr.close(); if (id == null) { // It's very bad if we read a null device id; let's delete that file if (!f.delete()) { Log.e(Logging.LOG_TAG, "Can't delete null deviceName file; try overwrite."); } } else { return id; } } else { Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" + " Trying to remove."); if (!f.delete()) { Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite."); } } } BufferedWriter w = new BufferedWriter(new FileWriter(f), 128); final String consistentDeviceId = getConsistentDeviceId(context); if (consistentDeviceId != null) { // Use different prefix from random IDs. id = "androidc" + consistentDeviceId; } else { id = "android" + System.currentTimeMillis(); } w.write(id); w.close(); // STOPSHIP Remove logging Log.w(Logging.LOG_TAG, "deviceId written as: " + id); return id; }
diff --git a/JavaLib/src/com/punchline/javalib/entities/components/MultiComponent.java b/JavaLib/src/com/punchline/javalib/entities/components/MultiComponent.java index 023fe57..1c82601 100644 --- a/JavaLib/src/com/punchline/javalib/entities/components/MultiComponent.java +++ b/JavaLib/src/com/punchline/javalib/entities/components/MultiComponent.java @@ -1,124 +1,124 @@ package com.punchline.javalib.entities.components; import java.util.HashSet; import com.badlogic.gdx.utils.Array; /** * Component wrapper for multiple Components of the same type. For instance, an entity requiring multiple sprites could contain a MultiComponent<Sprite>. * MultiComponents contain a LibGDX array of contained components, but also a single base Component. Whenever information is needed from the MultiComponent, and each * Component's information is different, the accessor from base will be used. * @author Natman64 * @created Aug 21, 2013 * @param <T> The type of Component that will be stored in the MultiComponent. */ public class MultiComponent<T extends Component> implements Component { //region Fields/Initialization /** * This MultiComponent's base component. */ protected T base; /** * This MultiComponent's child components, including the base. */ protected Array<T> children = new Array<T>(); /** * Constructs a MultiComponent. * @param base The base Component. * @param children The child components. */ public MultiComponent(T base, T... children) { this.base = base; this.children.add(base); for (T child : children) { this.children.add(child); } } //endregion //region Events @Override public void onAdd(ComponentManager container) { for (T child : children) { child.onAdd(container); } } @Override public void onRemove(ComponentManager container) { for (T child : children) { child.onRemove(container); } } //endregion //region Reordering /** * Reorders the MultiComponent's children. * @param order An Array of integers, specifying the new order. Example: {0, 4, 1, 3, 2} */ public void reorder(Array<Integer> order) { //Check for the proper size if (order.size != children.size) throw new IllegalArgumentException("The order array's size does not match the size of the children array."); //Check for duplicates HashSet<Integer> duplicateSet = new HashSet<Integer>(); for (Integer i : order) { duplicateSet.add(i); } if (duplicateSet.size() != order.size) throw new IllegalArgumentException("The order array contained duplicate indices."); //Now it should be safe to reorder. Array<T> children = new Array<T>(); for (Integer i : order) { - T child = children.get(i); + T child = this.children.get(i); children.add(child); } this.children = children; } //endregion //region Accessors /** * @return This MultiComponent's base Component. */ public T getBase() { return base; } /** * @param index The index of one of this MultiComponent's children. * @return The desired child Component. */ public T getChild(int index) { return children.get(index); } /** * @return A copy of this MultiComponent's children list. */ public Array<T> getComponents() { return new Array<T>(children); } //endregion }
true
true
public void reorder(Array<Integer> order) { //Check for the proper size if (order.size != children.size) throw new IllegalArgumentException("The order array's size does not match the size of the children array."); //Check for duplicates HashSet<Integer> duplicateSet = new HashSet<Integer>(); for (Integer i : order) { duplicateSet.add(i); } if (duplicateSet.size() != order.size) throw new IllegalArgumentException("The order array contained duplicate indices."); //Now it should be safe to reorder. Array<T> children = new Array<T>(); for (Integer i : order) { T child = children.get(i); children.add(child); } this.children = children; }
public void reorder(Array<Integer> order) { //Check for the proper size if (order.size != children.size) throw new IllegalArgumentException("The order array's size does not match the size of the children array."); //Check for duplicates HashSet<Integer> duplicateSet = new HashSet<Integer>(); for (Integer i : order) { duplicateSet.add(i); } if (duplicateSet.size() != order.size) throw new IllegalArgumentException("The order array contained duplicate indices."); //Now it should be safe to reorder. Array<T> children = new Array<T>(); for (Integer i : order) { T child = this.children.get(i); children.add(child); } this.children = children; }
diff --git a/src/com/pilot51/voicenotify/Service.java b/src/com/pilot51/voicenotify/Service.java index a8e54d1..c908b26 100644 --- a/src/com/pilot51/voicenotify/Service.java +++ b/src/com/pilot51/voicenotify/Service.java @@ -1,332 +1,332 @@ package com.pilot51.voicenotify; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.IllegalFormatException; import java.util.Timer; import java.util.TimerTask; import android.accessibilityservice.AccessibilityService; import android.accessibilityservice.AccessibilityServiceInfo; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.media.AudioManager; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.speech.tts.TextToSpeech; import android.telephony.TelephonyManager; import android.util.Log; import android.view.accessibility.AccessibilityEvent; public class Service extends AccessibilityService { private String lastMsg = ""; private static final int SPEAK = 1, STOP_SPEAK = 2, START_TTS = 3, STOP_TTS = 4; private long lastMsgTime; private TextToSpeech mTts; private AudioManager audioMan; private TelephonyManager telephony; private HeadsetReceiver headsetReceiver = new HeadsetReceiver(); private RepeatTimer repeater; private Shake shake; private boolean isInitialized, isScreenOn, isHeadsetPlugged, isBluetoothConnected; private HashMap<String, String> ttsParams = new HashMap<String, String>(); private ArrayList<String> ignoreReasons = new ArrayList<String>(), repeatList = new ArrayList<String>(); private Handler ttsHandler = new Handler() { @Override public void handleMessage(Message message) { switch (message.what) { case SPEAK: shake.enable(); boolean isNotificationStream = Common.prefs.getString("ttsStream", null).contentEquals("notification"); if (isNotificationStream) ttsParams.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION)); mTts.speak((String)message.obj, TextToSpeech.QUEUE_ADD, ttsParams); if (isNotificationStream) { ttsParams.clear(); mTts.speak(" ", TextToSpeech.QUEUE_ADD, null); } break; case STOP_SPEAK: shake.disable(); mTts.stop(); break; case START_TTS: mTts = new TextToSpeech(Service.this, null); break; case STOP_TTS: mTts.shutdown(); break; } } }; @Override public void onAccessibilityEvent(AccessibilityEvent event) { long newMsgTime = System.currentTimeMillis(); PackageManager packMan = getPackageManager(); ApplicationInfo appInfo = new ApplicationInfo(); String pkgName = String.valueOf(event.getPackageName()); try { appInfo = packMan.getApplicationInfo(pkgName, 0); } catch (NameNotFoundException e) { e.printStackTrace(); } StringBuilder notifyMsg = new StringBuilder(); if (!event.getText().isEmpty()) for (CharSequence subText : event.getText()) notifyMsg.append(subText); final String label = String.valueOf(appInfo.loadLabel(packMan)), ttsStringPref = Common.prefs.getString("ttsString", null); NotifyList.addNotification(label, notifyMsg.toString()); String newMsg; try { newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " ")); } catch(IllegalFormatException e) { Log.w(Common.TAG, "Error formatting custom TTS string!"); e.printStackTrace(); newMsg = ttsStringPref; } - final String[] ignoreStrings = Common.prefs.getString("ignore_strings", "").split("\n"); + final String[] ignoreStrings = Common.prefs.getString("ignore_strings", "").toLowerCase().split("\n"); boolean stringIgnored = false; if (ignoreStrings != null) { for (int i = 0; i < ignoreStrings.length; i++) { if (ignoreStrings[i].length() != 0 && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) { stringIgnored = true; break; } } } if (!AppList.getIsEnabled(pkgName)) ignoreReasons.add("ignored app (pref.)"); if (stringIgnored) ignoreReasons.add("ignored string (pref.)"); if (event.getText().isEmpty()) ignoreReasons.add("empty message"); int ignoreRepeat; try { ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null)); } catch (NumberFormatException e) { ignoreRepeat = -1; } if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000)) ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)"); if (ignoreReasons.isEmpty()) { int delay = 0; try { delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null)); } catch (NumberFormatException e) {} if (!isScreenOn()) { int interval; try { interval = Integer.parseInt(Common.prefs.getString("tts_repeat", "0")); } catch (NumberFormatException e) { interval = 0; } if (interval > 0) { repeatList.add(newMsg); if (repeater == null) repeater = new RepeatTimer(interval); else repeater.checkInterval(interval); } } if (delay > 0) { final String msg = newMsg; new Timer().schedule(new TimerTask() { @Override public void run() { speak(msg, false); } }, delay * 1000); } else speak(newMsg, false); } else { String reasons = ignoreReasons.toString().replaceAll("\\[|\\]", ""); Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + reasons); NotifyList.setLastIgnore(reasons); ignoreReasons.clear(); } lastMsg = newMsg; lastMsgTime = newMsgTime; } /** * Sends msg to TTS if ignore condition is not met. * @param msg The string to be spoken. */ private void speak(String msg, boolean isNew) { if (ignore(isNew)) return; ttsHandler.obtainMessage(SPEAK, msg).sendToTarget(); } /** * Checks for any notification-independent ignore states. * @returns True if an ignore condition is met, false otherwise. */ private boolean ignore(boolean isNew) { Calendar c = Calendar.getInstance(); int calTime = c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE), quietStart = Common.prefs.getInt("quietStart", 0), quietEnd = Common.prefs.getInt("quietEnd", 0); if ((quietStart < quietEnd & quietStart <= calTime & calTime < quietEnd) | (quietEnd < quietStart & (quietStart <= calTime | calTime < quietEnd))) { ignoreReasons.add("quiet time (pref.)"); } if ((audioMan.getRingerMode() == AudioManager.RINGER_MODE_SILENT || audioMan.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE) && !Common.prefs.getBoolean(Common.SPEAK_SILENT_ON, false)) { ignoreReasons.add("silent or vibrate mode (pref.)"); } if (telephony.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK | telephony.getCallState() == TelephonyManager.CALL_STATE_RINGING) { ignoreReasons.add("active or ringing call"); } if (!isScreenOn() & !Common.prefs.getBoolean(Common.SPEAK_SCREEN_OFF, true)) { ignoreReasons.add("screen off (pref.)"); } if (isScreenOn() & !Common.prefs.getBoolean(Common.SPEAK_SCREEN_ON, true)) { ignoreReasons.add("screen on (pref.)"); } if (!(isHeadsetPlugged | isBluetoothConnected) & !Common.prefs.getBoolean(Common.SPEAK_HEADSET_OFF, true)) { ignoreReasons.add("headset off (pref.)"); } if ((isHeadsetPlugged | isBluetoothConnected) & !Common.prefs.getBoolean(Common.SPEAK_HEADSET_ON, true)) { ignoreReasons.add("headset on (pref.)"); } if (!ignoreReasons.isEmpty()) { String reasons = ignoreReasons.toString().replaceAll("\\[|\\]", ""); Log.i(Common.TAG, "Notification ignored for reason(s): " + reasons); if (isNew) NotifyList.setLastIgnore(reasons); ignoreReasons.clear(); return true; } return false; } private class RepeatTimer extends TimerTask { private int interval; private RepeatTimer(int interval) { this.interval = interval; if (interval <= 0) return; new Timer().schedule(this, interval * 60000, interval * 60000); } /** * If passed interval is different from current timer interval, * cancels current timer and, if interval > 0, creates new instance with passed interval. * @param interval The interval to check against. */ private void checkInterval(int interval) { if (this.interval != interval) { cancel(); if (interval > 0) repeater = new RepeatTimer(interval); } } @Override public void run() { if (isScreenOn()) { repeatList.clear(); cancel(); } for (int i = 0; i < repeatList.size(); i++) { speak(repeatList.get(i), true); } } @Override public boolean cancel() { repeater = null; return super.cancel(); } } @Override public void onInterrupt() { ttsHandler.sendEmptyMessage(STOP_SPEAK); } @Override public void onServiceConnected() { if (isInitialized) return; new Common(this); ttsHandler.sendEmptyMessage(START_TTS); AccessibilityServiceInfo info = new AccessibilityServiceInfo(); info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED; info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN; setServiceInfo(info); audioMan = (AudioManager)getSystemService(Context.AUDIO_SERVICE); telephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(headsetReceiver, filter); shake = new Shake(this); shake.setOnShakeListener(new Shake.OnShakeListener() { @Override public void onShake() { ttsHandler.sendEmptyMessage(STOP_SPEAK); } }); isInitialized = true; } @Override public boolean onUnbind(Intent intent) { if (isInitialized) { ttsHandler.sendEmptyMessage(STOP_TTS); unregisterReceiver(headsetReceiver); isInitialized = false; } return false; } private boolean isScreenOn() { if (android.os.Build.VERSION.SDK_INT >= 7) isScreenOn = CheckScreen.isScreenOn(this); return isScreenOn; } private static class CheckScreen { private static PowerManager powerMan; private static boolean isScreenOn(Context c) { if (powerMan == null) powerMan = (PowerManager)c.getSystemService(Context.POWER_SERVICE); return powerMan.isScreenOn(); } } private class HeadsetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_HEADSET_PLUG)) isHeadsetPlugged = intent.getIntExtra("state", 0) == 1; else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) isBluetoothConnected = true; else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) isBluetoothConnected = false; else if (action.equals(Intent.ACTION_SCREEN_ON)) isScreenOn = true; else if (action.equals(Intent.ACTION_SCREEN_OFF)) isScreenOn = false; if (mTts.isSpeaking() && ignore(false)) ttsHandler.sendEmptyMessage(STOP_SPEAK); } } }
true
true
public void onAccessibilityEvent(AccessibilityEvent event) { long newMsgTime = System.currentTimeMillis(); PackageManager packMan = getPackageManager(); ApplicationInfo appInfo = new ApplicationInfo(); String pkgName = String.valueOf(event.getPackageName()); try { appInfo = packMan.getApplicationInfo(pkgName, 0); } catch (NameNotFoundException e) { e.printStackTrace(); } StringBuilder notifyMsg = new StringBuilder(); if (!event.getText().isEmpty()) for (CharSequence subText : event.getText()) notifyMsg.append(subText); final String label = String.valueOf(appInfo.loadLabel(packMan)), ttsStringPref = Common.prefs.getString("ttsString", null); NotifyList.addNotification(label, notifyMsg.toString()); String newMsg; try { newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " ")); } catch(IllegalFormatException e) { Log.w(Common.TAG, "Error formatting custom TTS string!"); e.printStackTrace(); newMsg = ttsStringPref; } final String[] ignoreStrings = Common.prefs.getString("ignore_strings", "").split("\n"); boolean stringIgnored = false; if (ignoreStrings != null) { for (int i = 0; i < ignoreStrings.length; i++) { if (ignoreStrings[i].length() != 0 && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) { stringIgnored = true; break; } } } if (!AppList.getIsEnabled(pkgName)) ignoreReasons.add("ignored app (pref.)"); if (stringIgnored) ignoreReasons.add("ignored string (pref.)"); if (event.getText().isEmpty()) ignoreReasons.add("empty message"); int ignoreRepeat; try { ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null)); } catch (NumberFormatException e) { ignoreRepeat = -1; } if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000)) ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)"); if (ignoreReasons.isEmpty()) { int delay = 0; try { delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null)); } catch (NumberFormatException e) {} if (!isScreenOn()) { int interval; try { interval = Integer.parseInt(Common.prefs.getString("tts_repeat", "0")); } catch (NumberFormatException e) { interval = 0; } if (interval > 0) { repeatList.add(newMsg); if (repeater == null) repeater = new RepeatTimer(interval); else repeater.checkInterval(interval); } } if (delay > 0) { final String msg = newMsg; new Timer().schedule(new TimerTask() { @Override public void run() { speak(msg, false); } }, delay * 1000); } else speak(newMsg, false); } else { String reasons = ignoreReasons.toString().replaceAll("\\[|\\]", ""); Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + reasons); NotifyList.setLastIgnore(reasons); ignoreReasons.clear(); } lastMsg = newMsg; lastMsgTime = newMsgTime; }
public void onAccessibilityEvent(AccessibilityEvent event) { long newMsgTime = System.currentTimeMillis(); PackageManager packMan = getPackageManager(); ApplicationInfo appInfo = new ApplicationInfo(); String pkgName = String.valueOf(event.getPackageName()); try { appInfo = packMan.getApplicationInfo(pkgName, 0); } catch (NameNotFoundException e) { e.printStackTrace(); } StringBuilder notifyMsg = new StringBuilder(); if (!event.getText().isEmpty()) for (CharSequence subText : event.getText()) notifyMsg.append(subText); final String label = String.valueOf(appInfo.loadLabel(packMan)), ttsStringPref = Common.prefs.getString("ttsString", null); NotifyList.addNotification(label, notifyMsg.toString()); String newMsg; try { newMsg = String.format(ttsStringPref.replace("%t", "%1$s").replace("%m", "%2$s"), label, notifyMsg.toString().replaceAll("[\\|\\[\\]\\{\\}\\*<>]+", " ")); } catch(IllegalFormatException e) { Log.w(Common.TAG, "Error formatting custom TTS string!"); e.printStackTrace(); newMsg = ttsStringPref; } final String[] ignoreStrings = Common.prefs.getString("ignore_strings", "").toLowerCase().split("\n"); boolean stringIgnored = false; if (ignoreStrings != null) { for (int i = 0; i < ignoreStrings.length; i++) { if (ignoreStrings[i].length() != 0 && notifyMsg.toString().toLowerCase().contains(ignoreStrings[i])) { stringIgnored = true; break; } } } if (!AppList.getIsEnabled(pkgName)) ignoreReasons.add("ignored app (pref.)"); if (stringIgnored) ignoreReasons.add("ignored string (pref.)"); if (event.getText().isEmpty()) ignoreReasons.add("empty message"); int ignoreRepeat; try { ignoreRepeat = Integer.parseInt(Common.prefs.getString("ignore_repeat", null)); } catch (NumberFormatException e) { ignoreRepeat = -1; } if (lastMsg.contentEquals(newMsg) && (ignoreRepeat == -1 || newMsgTime - lastMsgTime < ignoreRepeat * 1000)) ignoreReasons.add("identical message within " + (ignoreRepeat == -1 ? "infinite" : ignoreRepeat) + " seconds (pref.)"); if (ignoreReasons.isEmpty()) { int delay = 0; try { delay = Integer.parseInt(Common.prefs.getString("ttsDelay", null)); } catch (NumberFormatException e) {} if (!isScreenOn()) { int interval; try { interval = Integer.parseInt(Common.prefs.getString("tts_repeat", "0")); } catch (NumberFormatException e) { interval = 0; } if (interval > 0) { repeatList.add(newMsg); if (repeater == null) repeater = new RepeatTimer(interval); else repeater.checkInterval(interval); } } if (delay > 0) { final String msg = newMsg; new Timer().schedule(new TimerTask() { @Override public void run() { speak(msg, false); } }, delay * 1000); } else speak(newMsg, false); } else { String reasons = ignoreReasons.toString().replaceAll("\\[|\\]", ""); Log.i(Common.TAG, "Notification from " + label + " ignored for reason(s): " + reasons); NotifyList.setLastIgnore(reasons); ignoreReasons.clear(); } lastMsg = newMsg; lastMsgTime = newMsgTime; }
diff --git a/src/com/dmdirc/ui/swing/dialogs/wizard/firstrun/CommunicationStep.java b/src/com/dmdirc/ui/swing/dialogs/wizard/firstrun/CommunicationStep.java index ea16fe574..203f16d73 100644 --- a/src/com/dmdirc/ui/swing/dialogs/wizard/firstrun/CommunicationStep.java +++ b/src/com/dmdirc/ui/swing/dialogs/wizard/firstrun/CommunicationStep.java @@ -1,111 +1,111 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.ui.swing.dialogs.wizard.firstrun; import com.dmdirc.ui.swing.JWrappingLabel; import com.dmdirc.ui.swing.dialogs.wizard.Step; import java.awt.Dimension; import javax.swing.JCheckBox; import net.miginfocom.swing.MigLayout; /** * Sets communication options. */ public final class CommunicationStep extends Step { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 1; /** Update info. */ private JWrappingLabel updatesInfo; /** Update checker. */ private JCheckBox updates; /** Error reports info. */ private JWrappingLabel errorsInfo; /** Error reports. */ private JCheckBox errors; /** * Creates a new instance of SetupStep. */ public CommunicationStep() { super(); initComponents(); layoutComponents(); } /** * Initialises the components. */ protected void initComponents() { updatesInfo = new JWrappingLabel("DMDirc can automatically check for " + "updates for various parts of the client, you can globally " + "disable that behaviour here, you can also fine tune the " + "behaviour in the preferences dialog once the client is running."); - updates = new JCheckBox("Enabled update checks?", true); + updates = new JCheckBox("Enable update checks?", true); errorsInfo = new JWrappingLabel("DMDirc will automatically report application " + "errors to the developers, whilst this is of great help to the developers " + "you may disable this behaviour here."); errors = new JCheckBox("Enable error reporting?", true); } /** * Lays out the components. */ private void layoutComponents() { setLayout(new MigLayout("fillx, wrap 1")); updatesInfo.setMaximumSize(new Dimension(400, Integer.MAX_VALUE)); errorsInfo.setMaximumSize(new Dimension(400, Integer.MAX_VALUE)); add(updatesInfo, "growx, pushx"); add(updates, ""); add(errorsInfo, "growx, pushx"); add(errors, ""); } /** * Checks if updates are enabled. * * @return true iif updates are enabled */ public boolean checkUpdates() { return updates.isSelected(); } /** * Checks if error reports are enabled. * * @return true iif error reports are enabled */ public boolean checkErrors() { return updates.isSelected(); } }
true
true
protected void initComponents() { updatesInfo = new JWrappingLabel("DMDirc can automatically check for " + "updates for various parts of the client, you can globally " + "disable that behaviour here, you can also fine tune the " + "behaviour in the preferences dialog once the client is running."); updates = new JCheckBox("Enabled update checks?", true); errorsInfo = new JWrappingLabel("DMDirc will automatically report application " + "errors to the developers, whilst this is of great help to the developers " + "you may disable this behaviour here."); errors = new JCheckBox("Enable error reporting?", true); }
protected void initComponents() { updatesInfo = new JWrappingLabel("DMDirc can automatically check for " + "updates for various parts of the client, you can globally " + "disable that behaviour here, you can also fine tune the " + "behaviour in the preferences dialog once the client is running."); updates = new JCheckBox("Enable update checks?", true); errorsInfo = new JWrappingLabel("DMDirc will automatically report application " + "errors to the developers, whilst this is of great help to the developers " + "you may disable this behaviour here."); errors = new JCheckBox("Enable error reporting?", true); }
diff --git a/jnalib/src/com/sun/jna/win32/W32APITypeMapper.java b/jnalib/src/com/sun/jna/win32/W32APITypeMapper.java index 5370ac39..f18eff19 100644 --- a/jnalib/src/com/sun/jna/win32/W32APITypeMapper.java +++ b/jnalib/src/com/sun/jna/win32/W32APITypeMapper.java @@ -1,74 +1,74 @@ /* Copyright (c) 2007 Timothy Wall, All Rights Reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package com.sun.jna.win32; import com.sun.jna.DefaultTypeMapper; import com.sun.jna.FromNativeContext; import com.sun.jna.Pointer; import com.sun.jna.StringArray; import com.sun.jna.ToNativeContext; import com.sun.jna.TypeConverter; import com.sun.jna.TypeMapper; import com.sun.jna.WString; /** Provide standard conversion for W32 API types. This comprises the * following native types: * <ul> * <li>Unicode or ASCII/MBCS strings and arrays of string, as appropriate * <li>BOOL * </ul> * @author twall */ public class W32APITypeMapper extends DefaultTypeMapper { public static final TypeMapper UNICODE = new W32APITypeMapper(true); public static final TypeMapper ASCII = new W32APITypeMapper(false); protected W32APITypeMapper(boolean unicode) { if (unicode) { TypeConverter stringConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { if (value == null) return null; if (value instanceof String[]) { return new StringArray((String[])value, true); } return new WString(value.toString()); } public Object fromNative(Object value, FromNativeContext context) { if (value == null) return null; - return ((Pointer)value).getString(0, true); + return value.toString(); } public Class nativeType() { - return Pointer.class; + return WString.class; } }; addTypeConverter(String.class, stringConverter); addToNativeConverter(String[].class, stringConverter); } TypeConverter booleanConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { return new Integer(Boolean.TRUE.equals(value) ? 1 : 0); } public Object fromNative(Object value, FromNativeContext context) { return ((Integer)value).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; } public Class nativeType() { // BOOL is 32-bit int return Integer.class; } }; addTypeConverter(Boolean.class, booleanConverter); } }
false
true
protected W32APITypeMapper(boolean unicode) { if (unicode) { TypeConverter stringConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { if (value == null) return null; if (value instanceof String[]) { return new StringArray((String[])value, true); } return new WString(value.toString()); } public Object fromNative(Object value, FromNativeContext context) { if (value == null) return null; return ((Pointer)value).getString(0, true); } public Class nativeType() { return Pointer.class; } }; addTypeConverter(String.class, stringConverter); addToNativeConverter(String[].class, stringConverter); } TypeConverter booleanConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { return new Integer(Boolean.TRUE.equals(value) ? 1 : 0); } public Object fromNative(Object value, FromNativeContext context) { return ((Integer)value).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; } public Class nativeType() { // BOOL is 32-bit int return Integer.class; } }; addTypeConverter(Boolean.class, booleanConverter); }
protected W32APITypeMapper(boolean unicode) { if (unicode) { TypeConverter stringConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { if (value == null) return null; if (value instanceof String[]) { return new StringArray((String[])value, true); } return new WString(value.toString()); } public Object fromNative(Object value, FromNativeContext context) { if (value == null) return null; return value.toString(); } public Class nativeType() { return WString.class; } }; addTypeConverter(String.class, stringConverter); addToNativeConverter(String[].class, stringConverter); } TypeConverter booleanConverter = new TypeConverter() { public Object toNative(Object value, ToNativeContext context) { return new Integer(Boolean.TRUE.equals(value) ? 1 : 0); } public Object fromNative(Object value, FromNativeContext context) { return ((Integer)value).intValue() != 0 ? Boolean.TRUE : Boolean.FALSE; } public Class nativeType() { // BOOL is 32-bit int return Integer.class; } }; addTypeConverter(Boolean.class, booleanConverter); }
diff --git a/src/main/java/com/kurtraschke/wmatagtfsrealtime/GTFSRealtimeProviderImpl.java b/src/main/java/com/kurtraschke/wmatagtfsrealtime/GTFSRealtimeProviderImpl.java index d59a4b0..1b927f8 100644 --- a/src/main/java/com/kurtraschke/wmatagtfsrealtime/GTFSRealtimeProviderImpl.java +++ b/src/main/java/com/kurtraschke/wmatagtfsrealtime/GTFSRealtimeProviderImpl.java @@ -1,468 +1,465 @@ /* * Copyright (C) 2012 Google, Inc. * Copyright (C) 2012 Kurt Raschke * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.kurtraschke.wmatagtfsrealtime; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.transit.realtime.GtfsRealtime.Alert; import com.google.transit.realtime.GtfsRealtime.EntitySelector; import com.google.transit.realtime.GtfsRealtime.FeedEntity; import com.google.transit.realtime.GtfsRealtime.FeedMessage; import com.google.transit.realtime.GtfsRealtime.Position; import com.google.transit.realtime.GtfsRealtime.TripDescriptor; import com.google.transit.realtime.GtfsRealtime.TripUpdate; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeEvent; import com.google.transit.realtime.GtfsRealtime.TripUpdate.StopTimeUpdate; import com.google.transit.realtime.GtfsRealtime.VehicleDescriptor; import com.google.transit.realtime.GtfsRealtime.VehiclePosition; import com.kurtraschke.wmatagtfsrealtime.api.WMATAAlert; import com.kurtraschke.wmatagtfsrealtime.api.WMATABusPosition; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.onebusaway.transit_data.model.ListBean; import org.onebusaway.transit_data.model.trips.TripDetailsBean; import org.onebusaway.transit_data.model.trips.TripDetailsInclusionBean; import org.onebusaway.transit_data.model.trips.TripDetailsQueryBean; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeLibrary; import org.onebusway.gtfs_realtime.exporter.GtfsRealtimeMutableProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; /** * This class produces GTFS-realtime trip updates and vehicle positions by * periodically polling the custom WMATA vehicle data API and converting the * resulting vehicle data into the GTFS-realtime format. * * * @author bdferris * */ @Singleton public class GTFSRealtimeProviderImpl { private static final Logger _log = LoggerFactory.getLogger(GTFSRealtimeProviderImpl.class); private ScheduledExecutorService _executor; private GtfsRealtimeMutableProvider _gtfsRealtimeProvider; private WMATAAPIService _api; private WMATARouteMapperService _routeMapperService; private WMATATripMapperService _tripMapperService; private TransitDataServiceService _tds; private CacheManager _cacheManager; private Cache _lastStopForTripCache; private Cache _alertIDCache; /** * How often vehicle data will be downloaded, in seconds. FIXME: move this * into the configuration file. */ private int _refreshInterval = 30; @Inject public void setGtfsRealtimeProvider(GtfsRealtimeMutableProvider gtfsRealtimeProvider) { _gtfsRealtimeProvider = gtfsRealtimeProvider; } @Inject public void setWMATAAPIService(WMATAAPIService api) { _api = api; } @Inject public void setWMATARouteMapperService(WMATARouteMapperService mapperService) { _routeMapperService = mapperService; } @Inject public void setWMATATripMapperService(WMATATripMapperService tripMapperService) { _tripMapperService = tripMapperService; } @Inject public void setTransitDataServiceService(TransitDataServiceService tds) { _tds = tds; } @Inject public void setCacheManager(CacheManager cacheManager) { _cacheManager = cacheManager; } @Inject public void setLastStopForTripCache(@Named("caches.lastStopForTrip") Cache lastStopForTripCache) { _lastStopForTripCache = lastStopForTripCache; } @Inject public void setAlertIDCache(@Named("caches.alertID") Cache alertIDCache) { _alertIDCache = alertIDCache; } /** * @param refreshInterval how often vehicle data will be downloaded, in * seconds. */ public void setRefreshInterval(int refreshInterval) { _refreshInterval = refreshInterval; } /** * The start method automatically starts up a recurring task that * periodically downloads the latest vehicle data from the SEPTA vehicle * stream and processes them. */ @PostConstruct public void start() { _log.info("starting GTFS-realtime service"); _executor = Executors.newSingleThreadScheduledExecutor(); _executor.scheduleWithFixedDelay(new VehiclesRefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS); _executor.scheduleWithFixedDelay(new AlertsRefreshTask(), 0, 2 * _refreshInterval, TimeUnit.SECONDS); } /** * The stop method cancels the recurring vehicle data downloader task. */ @PreDestroy public void stop() { _log.info("stopping GTFS-realtime service"); _executor.shutdownNow(); _cacheManager.shutdown(); } /** * ** * Private Methods - Here is where the real work happens ** */ /** * This method downloads the latest vehicle data, processes each vehicle in * turn, and create a GTFS-realtime feed of trip updates and vehicle * positions as a result. */ private void refreshVehicles() throws IOException, SAXException { /** * We download the vehicle details as an array of JSON objects. */ List<WMATABusPosition> busPositions = _api.downloadBusPositions(); /** * The FeedMessage.Builder is what we will use to build up our * GTFS-realtime feeds. We create a feed for both trip updates and * vehicle positions. */ FeedMessage.Builder tripUpdates = GtfsRealtimeLibrary.createFeedMessageBuilder(); FeedMessage.Builder vehiclePositions = GtfsRealtimeLibrary.createFeedMessageBuilder(); /** * We iterate over every JSON vehicle object. */ for (WMATABusPosition bp : busPositions) { try { ProcessedVehicleResponse pvr = processVehicle(bp); tripUpdates.addEntity(pvr.tripUpdateEntity); vehiclePositions.addEntity(pvr.vehiclePositionEntity); } catch (Exception e) { _log.warn("Error constructing update for vehicle " + bp.getVehicleID(), e); } } /** * Build out the final GTFS-realtime feed messagse and save them. */ _gtfsRealtimeProvider.setTripUpdates(tripUpdates.build()); _gtfsRealtimeProvider.setVehiclePositions(vehiclePositions.build()); _log.info("vehicles extracted: " + tripUpdates.getEntityCount()); } private ProcessedVehicleResponse processVehicle(WMATABusPosition bp) throws IOException, SAXException { ProcessedVehicleResponse pvr = new ProcessedVehicleResponse(); String route = bp.getRouteID(); String vehicle = bp.getVehicleID(); String trip = bp.getTripID(); Date dateTime = bp.getDateTime(); float lat = bp.getLat(); float lon = bp.getLon(); float deviation = bp.getDeviation(); String gtfsRouteID; String gtfsTripID = null; gtfsRouteID = _routeMapperService.getBusRouteMapping(route); if (gtfsRouteID != null) { GregorianCalendar serviceDate = new GregorianCalendar(); serviceDate.setTime(bp.getTripStartTime()); serviceDate.set(Calendar.HOUR_OF_DAY, 0); serviceDate.set(Calendar.MINUTE, 0); serviceDate.set(Calendar.SECOND, 0); serviceDate.set(Calendar.MILLISECOND, 0); gtfsTripID = _tripMapperService.getTripMapping(serviceDate.getTime(), trip, route); } /** * We construct a TripDescriptor and VehicleDescriptor, which will be * used in both trip updates and vehicle positions to identify the trip * and vehicle. */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); if (gtfsRouteID != null) { - /* FIXME: OBA wrongly rejects TripUpdates which have a route ID set. - * Fix OBA then come back here and fix this. - */ - //tripDescriptor.setRouteId(stripID(gtfsRouteID)); + tripDescriptor.setRouteId(stripID(gtfsRouteID)); } if (gtfsTripID != null) { tripDescriptor.setTripId(stripID(gtfsTripID)); } VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(vehicle); /** * To construct our TripUpdate, we create a stop-time arrival event for * the last stop for the vehicle, with the specified arrival delay. We * add the stop-time update to a TripUpdate builder, along with the trip * and vehicle descriptors. */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(Math.round(deviation * -60)); StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); stopTimeUpdate.setArrival(arrival); if (gtfsTripID != null) { stopTimeUpdate.setStopId(stripID(getLastStopForTrip(gtfsTripID))); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addStopTimeUpdate(stopTimeUpdate); tripUpdate.setTrip(tripDescriptor); tripUpdate.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the trip update and add it to the * GTFS-realtime trip updates feed. */ FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(vehicle); tripUpdateEntity.setTripUpdate(tripUpdate); pvr.tripUpdateEntity = tripUpdateEntity; /** * To construct our VehiclePosition, we create a position for the * vehicle. We add the position to a VehiclePosition builder, along with * the trip and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude((float) lat); position.setLongitude((float) lon); VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setTimestamp(dateTime.getTime() / 1000L); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the vehicle position and add it to * the GTFS-realtime vehicle positions feed. */ FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(vehicle); vehiclePositionEntity.setVehicle(vehiclePosition); pvr.vehiclePositionEntity = vehiclePositionEntity; return pvr; } private String getLastStopForTrip(String tripID) { Element e = _lastStopForTripCache.get(tripID); if (e == null) { TripDetailsQueryBean tdqb = new TripDetailsQueryBean(); tdqb.setTripId(tripID); tdqb.setInclusion(new TripDetailsInclusionBean(true, true, false)); ListBean<TripDetailsBean> b = _tds.getService().getTripDetails(tdqb); String lastStopID = Iterables.getLast(Iterables.getOnlyElement(b.getList()).getSchedule().getStopTimes()).getStop().getId(); _lastStopForTripCache.put(new Element(tripID, lastStopID)); return lastStopID; } else { return (String) e.getObjectValue(); } } private String stripID(String id) { return id.split("_", 2)[1]; } private void refreshAlerts() throws IOException, SAXException { List<WMATAAlert> busAlerts = _api.downloadBusAlerts(); List<WMATAAlert> railAlerts = _api.downloadRailAlerts(); Set<String> alertsInUpdate = new HashSet<String>(); FeedMessage.Builder alerts = GtfsRealtimeLibrary.createFeedMessageBuilder(); for (WMATAAlert busAlert : busAlerts) { Alert.Builder alert = Alert.newBuilder(); alert.setDescriptionText(GtfsRealtimeLibrary.getTextAsTranslatedString(busAlert.getDescription())); String[] routes = busAlert.getTitle().split(", "); for (String route : routes) { EntitySelector.Builder entity = EntitySelector.newBuilder(); String gtfsRoute = _routeMapperService.getBusRouteMapping(route); if (gtfsRoute != null) { entity.setRouteId(stripID(gtfsRoute)); alert.addInformedEntity(entity); } } if (alert.getInformedEntityCount() > 0) { FeedEntity.Builder alertEntity = FeedEntity.newBuilder(); alertEntity.setId(busAlert.getGuid().toString()); alertEntity.setAlert(alert); alerts.addEntity(alertEntity); _alertIDCache.put(new Element(busAlert.getGuid().toString(), null)); } } for (WMATAAlert railAlert : railAlerts) { Alert.Builder alert = Alert.newBuilder(); alert.setDescriptionText(GtfsRealtimeLibrary.getTextAsTranslatedString(railAlert.getDescription())); String[] routes = railAlert.getTitle().split(", "); for (String route : routes) { String mappedRoute = _routeMapperService.getRailRouteMapping(route); if (mappedRoute != null) { EntitySelector.Builder entity = EntitySelector.newBuilder(); entity.setRouteId(stripID(mappedRoute)); alert.addInformedEntity(entity); } } if (alert.getInformedEntityCount() > 0) { FeedEntity.Builder alertEntity = FeedEntity.newBuilder(); alertEntity.setId(railAlert.getGuid().toString()); alertEntity.setAlert(alert); alerts.addEntity(alertEntity); _alertIDCache.put(new Element(railAlert.getGuid().toString(), null)); } } Set<String> currentAlertIDs = new HashSet<String>(); for (FeedEntity e : alerts.getEntityList()) { currentAlertIDs.add(e.getId()); } ImmutableSet<String> allAlertIDs = ImmutableSet.copyOf(_alertIDCache.getKeysWithExpiryCheck()); /* * If an alert was in the feed previously, and is not now, * then add it back to the feed with the isDeleted flag set, so * clients will remove it from their UI. */ for (String removedAlert : Sets.difference(allAlertIDs, currentAlertIDs)) { FeedEntity.Builder alertEntity = FeedEntity.newBuilder(); alertEntity.setId(removedAlert); alertEntity.setIsDeleted(true); alerts.addEntity(alertEntity); } _gtfsRealtimeProvider.setAlerts(alerts.build()); _log.info("alerts extracted: " + alerts.getEntityCount()); } /** * Task that will download new vehicle data from the remote data source when * executed. */ private class VehiclesRefreshTask implements Runnable { @Override public void run() { try { _log.info("refreshing vehicles"); refreshVehicles(); } catch (Exception ex) { _log.warn("Error in vehicle refresh task", ex); } } } /** * Task that will download new alert data from the remote data source when * executed. */ private class AlertsRefreshTask implements Runnable { @Override public void run() { try { _log.info("refreshing alerts"); refreshAlerts(); } catch (Exception ex) { _log.warn("Error in alert refresh task", ex); } } } private class ProcessedVehicleResponse { FeedEntity.Builder tripUpdateEntity; FeedEntity.Builder vehiclePositionEntity; } }
true
true
private ProcessedVehicleResponse processVehicle(WMATABusPosition bp) throws IOException, SAXException { ProcessedVehicleResponse pvr = new ProcessedVehicleResponse(); String route = bp.getRouteID(); String vehicle = bp.getVehicleID(); String trip = bp.getTripID(); Date dateTime = bp.getDateTime(); float lat = bp.getLat(); float lon = bp.getLon(); float deviation = bp.getDeviation(); String gtfsRouteID; String gtfsTripID = null; gtfsRouteID = _routeMapperService.getBusRouteMapping(route); if (gtfsRouteID != null) { GregorianCalendar serviceDate = new GregorianCalendar(); serviceDate.setTime(bp.getTripStartTime()); serviceDate.set(Calendar.HOUR_OF_DAY, 0); serviceDate.set(Calendar.MINUTE, 0); serviceDate.set(Calendar.SECOND, 0); serviceDate.set(Calendar.MILLISECOND, 0); gtfsTripID = _tripMapperService.getTripMapping(serviceDate.getTime(), trip, route); } /** * We construct a TripDescriptor and VehicleDescriptor, which will be * used in both trip updates and vehicle positions to identify the trip * and vehicle. */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); if (gtfsRouteID != null) { /* FIXME: OBA wrongly rejects TripUpdates which have a route ID set. * Fix OBA then come back here and fix this. */ //tripDescriptor.setRouteId(stripID(gtfsRouteID)); } if (gtfsTripID != null) { tripDescriptor.setTripId(stripID(gtfsTripID)); } VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(vehicle); /** * To construct our TripUpdate, we create a stop-time arrival event for * the last stop for the vehicle, with the specified arrival delay. We * add the stop-time update to a TripUpdate builder, along with the trip * and vehicle descriptors. */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(Math.round(deviation * -60)); StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); stopTimeUpdate.setArrival(arrival); if (gtfsTripID != null) { stopTimeUpdate.setStopId(stripID(getLastStopForTrip(gtfsTripID))); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addStopTimeUpdate(stopTimeUpdate); tripUpdate.setTrip(tripDescriptor); tripUpdate.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the trip update and add it to the * GTFS-realtime trip updates feed. */ FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(vehicle); tripUpdateEntity.setTripUpdate(tripUpdate); pvr.tripUpdateEntity = tripUpdateEntity; /** * To construct our VehiclePosition, we create a position for the * vehicle. We add the position to a VehiclePosition builder, along with * the trip and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude((float) lat); position.setLongitude((float) lon); VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setTimestamp(dateTime.getTime() / 1000L); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the vehicle position and add it to * the GTFS-realtime vehicle positions feed. */ FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(vehicle); vehiclePositionEntity.setVehicle(vehiclePosition); pvr.vehiclePositionEntity = vehiclePositionEntity; return pvr; }
private ProcessedVehicleResponse processVehicle(WMATABusPosition bp) throws IOException, SAXException { ProcessedVehicleResponse pvr = new ProcessedVehicleResponse(); String route = bp.getRouteID(); String vehicle = bp.getVehicleID(); String trip = bp.getTripID(); Date dateTime = bp.getDateTime(); float lat = bp.getLat(); float lon = bp.getLon(); float deviation = bp.getDeviation(); String gtfsRouteID; String gtfsTripID = null; gtfsRouteID = _routeMapperService.getBusRouteMapping(route); if (gtfsRouteID != null) { GregorianCalendar serviceDate = new GregorianCalendar(); serviceDate.setTime(bp.getTripStartTime()); serviceDate.set(Calendar.HOUR_OF_DAY, 0); serviceDate.set(Calendar.MINUTE, 0); serviceDate.set(Calendar.SECOND, 0); serviceDate.set(Calendar.MILLISECOND, 0); gtfsTripID = _tripMapperService.getTripMapping(serviceDate.getTime(), trip, route); } /** * We construct a TripDescriptor and VehicleDescriptor, which will be * used in both trip updates and vehicle positions to identify the trip * and vehicle. */ TripDescriptor.Builder tripDescriptor = TripDescriptor.newBuilder(); if (gtfsRouteID != null) { tripDescriptor.setRouteId(stripID(gtfsRouteID)); } if (gtfsTripID != null) { tripDescriptor.setTripId(stripID(gtfsTripID)); } VehicleDescriptor.Builder vehicleDescriptor = VehicleDescriptor.newBuilder(); vehicleDescriptor.setId(vehicle); /** * To construct our TripUpdate, we create a stop-time arrival event for * the last stop for the vehicle, with the specified arrival delay. We * add the stop-time update to a TripUpdate builder, along with the trip * and vehicle descriptors. */ StopTimeEvent.Builder arrival = StopTimeEvent.newBuilder(); arrival.setDelay(Math.round(deviation * -60)); StopTimeUpdate.Builder stopTimeUpdate = StopTimeUpdate.newBuilder(); stopTimeUpdate.setArrival(arrival); if (gtfsTripID != null) { stopTimeUpdate.setStopId(stripID(getLastStopForTrip(gtfsTripID))); } TripUpdate.Builder tripUpdate = TripUpdate.newBuilder(); tripUpdate.addStopTimeUpdate(stopTimeUpdate); tripUpdate.setTrip(tripDescriptor); tripUpdate.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the trip update and add it to the * GTFS-realtime trip updates feed. */ FeedEntity.Builder tripUpdateEntity = FeedEntity.newBuilder(); tripUpdateEntity.setId(vehicle); tripUpdateEntity.setTripUpdate(tripUpdate); pvr.tripUpdateEntity = tripUpdateEntity; /** * To construct our VehiclePosition, we create a position for the * vehicle. We add the position to a VehiclePosition builder, along with * the trip and vehicle descriptors. */ Position.Builder position = Position.newBuilder(); position.setLatitude((float) lat); position.setLongitude((float) lon); VehiclePosition.Builder vehiclePosition = VehiclePosition.newBuilder(); vehiclePosition.setTimestamp(dateTime.getTime() / 1000L); vehiclePosition.setPosition(position); vehiclePosition.setTrip(tripDescriptor); vehiclePosition.setVehicle(vehicleDescriptor); /** * Create a new feed entity to wrap the vehicle position and add it to * the GTFS-realtime vehicle positions feed. */ FeedEntity.Builder vehiclePositionEntity = FeedEntity.newBuilder(); vehiclePositionEntity.setId(vehicle); vehiclePositionEntity.setVehicle(vehiclePosition); pvr.vehiclePositionEntity = vehiclePositionEntity; return pvr; }
diff --git a/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java b/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java index 28c83ec77..0ad2121a0 100644 --- a/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +++ b/driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java @@ -1,410 +1,412 @@ /* * Copyright (C) 2012 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.core; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.*; import org.apache.cassandra.transport.Event; import org.apache.cassandra.transport.messages.RegisterMessage; import org.apache.cassandra.transport.messages.QueryMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.policies.*; import com.datastax.driver.core.exceptions.DriverInternalError; import com.datastax.driver.core.exceptions.NoHostAvailableException; class ControlConnection implements Host.StateListener { private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class); // TODO: we might want to make that configurable private static final long MAX_SCHEMA_AGREEMENT_WAIT_MS = 10000; private static final InetAddress bindAllAddress; static { try { bindAllAddress = InetAddress.getByAddress(new byte[4]); } catch (UnknownHostException e) { throw new RuntimeException(e); } } private static final String SELECT_KEYSPACES = "SELECT * FROM system.schema_keyspaces"; private static final String SELECT_COLUMN_FAMILIES = "SELECT * FROM system.schema_columnfamilies"; private static final String SELECT_COLUMNS = "SELECT * FROM system.schema_columns"; private static final String SELECT_PEERS = "SELECT peer, data_center, rack, tokens, rpc_address FROM system.peers"; private static final String SELECT_LOCAL = "SELECT cluster_name, data_center, rack, tokens, partitioner FROM system.local WHERE key='local'"; private static final String SELECT_SCHEMA_PEERS = "SELECT rpc_address, schema_version FROM system.peers"; private static final String SELECT_SCHEMA_LOCAL = "SELECT schema_version FROM system.local WHERE key='local'"; private final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>(); private final Cluster.Manager cluster; private final LoadBalancingPolicy balancingPolicy; private final ReconnectionPolicy reconnectionPolicy = new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000); private final AtomicReference<ScheduledFuture> reconnectionAttempt = new AtomicReference<ScheduledFuture>(); private volatile boolean isShutdown; public ControlConnection(Cluster.Manager manager, Metadata metadata) { this.cluster = manager; this.balancingPolicy = new RoundRobinPolicy(); this.balancingPolicy.init(manager.getCluster(), metadata.allHosts()); } // Only for the initial connection. Does not schedule retries if it fails public void connect() { if (isShutdown) return; setNewConnection(reconnectInternal()); } public void shutdown() { isShutdown = true; Connection connection = connectionRef.get(); if (connection != null) connection.close(); } private void reconnect() { if (isShutdown) return; try { setNewConnection(reconnectInternal()); } catch (NoHostAvailableException e) { logger.error("[Control connection] Cannot connect to any host, scheduling retry"); new AbstractReconnectionHandler(cluster.reconnectionExecutor, reconnectionPolicy.newSchedule(), reconnectionAttempt) { protected Connection tryReconnect() throws ConnectionException { try { return reconnectInternal(); } catch (NoHostAvailableException e) { throw new ConnectionException(null, e.getMessage()); } } protected void onReconnection(Connection connection) { setNewConnection(connection); } protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs); return true; } protected boolean onUnknownException(Exception e, long nextDelayMs) { logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e); return true; } }.start(); } } private void setNewConnection(Connection newConnection) { logger.debug("[Control connection] Successfully connected to {}", newConnection.address); Connection old = connectionRef.getAndSet(newConnection); if (old != null && !old.isClosed()) old.close(); } private Connection reconnectInternal() { Iterator<Host> iter = balancingPolicy.newQueryPlan(Query.DEFAULT); Map<InetAddress, String> errors = null; Host host = null; try { while (iter.hasNext()) { host = iter.next(); try { return tryConnect(host); } catch (ConnectionException e) { errors = logError(host, e.getMessage(), errors, iter); host.getMonitor().signalConnectionFailure(e); } catch (ExecutionException e) { errors = logError(host, e.getMessage(), errors, iter); } } } catch (InterruptedException e) { // Sets interrupted status Thread.currentThread().interrupt(); // Indicates that all remaining hosts are skipped due to the interruption if (host != null) errors = logError(host, "Connection thread interrupted", errors, iter); while (iter.hasNext()) errors = logError(iter.next(), "Connection thread interrupted", errors, iter); } throw new NoHostAvailableException(errors == null ? Collections.<InetAddress, String>emptyMap() : errors); } private static Map<InetAddress, String> logError(Host host, String msg, Map<InetAddress, String> errors, Iterator<Host> iter) { if (errors == null) errors = new HashMap<InetAddress, String>(); errors.put(host.getAddress(), msg); if (logger.isDebugEnabled()) { if (iter.hasNext()) { logger.debug("[Control connection] error on {} connection ({}), trying next host", host, msg); } else { logger.debug("[Control connection] error on {} connection ({}), no more host to try", host, msg); } } return errors; } private Connection tryConnect(Host host) throws ConnectionException, ExecutionException, InterruptedException { Connection connection = cluster.connectionFactory.open(host); try { logger.trace("[Control connection] Registering for events"); List<Event.Type> evs = Arrays.asList(new Event.Type[]{ Event.Type.TOPOLOGY_CHANGE, Event.Type.STATUS_CHANGE, Event.Type.SCHEMA_CHANGE, }); connection.write(new RegisterMessage(evs)); logger.debug(String.format("[Control connection] Refreshing node list and token map")); refreshNodeListAndTokenMap(connection); logger.debug("[Control connection] Refreshing schema"); refreshSchema(connection, null, null, cluster); return connection; } catch (BusyConnectionException e) { throw new DriverInternalError("Newly created connection should not be busy"); } } public void refreshSchema(String keyspace, String table) throws InterruptedException { logger.debug("[Control connection] Refreshing schema for {}.{}", keyspace, table); try { refreshSchema(connectionRef.get(), keyspace, table, cluster); } catch (ConnectionException e) { logger.debug("[Control connection] Connection error while refeshing schema ({})", e.getMessage()); reconnect(); } catch (ExecutionException e) { logger.error("[Control connection] Unexpected error while refeshing schema", e); reconnect(); } catch (BusyConnectionException e) { logger.debug("[Control connection] Connection is busy, reconnecting"); reconnect(); } } static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on schema String whereClause = ""; if (keyspace != null) { whereClause = " WHERE keyspace_name = '" + keyspace + "'"; if (table != null) whereClause += " AND columnfamily_name = '" + table + "'"; } ResultSetFuture ksFuture = table == null ? new ResultSetFuture(null, new QueryMessage(SELECT_KEYSPACES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)) : null; ResultSetFuture cfFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMN_FAMILIES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture colsFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMNS + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); if (ksFuture != null) connection.write(ksFuture.callback); connection.write(cfFuture.callback); connection.write(colsFuture.callback); cluster.metadata.rebuildSchema(keyspace, table, ksFuture == null ? null : ksFuture.get(), cfFuture.get(), colsFuture.get()); } public void refreshNodeListAndTokenMap() { Connection c = connectionRef.get(); // At startup, when we add the initial nodes, this will be null, which is ok if (c == null) return; logger.debug(String.format("[Control connection] Refreshing node list and token map")); try { refreshNodeListAndTokenMap(c); } catch (ConnectionException e) { logger.debug("[Control connection] Connection error while refeshing node list and token map ({})", e.getMessage()); reconnect(); } catch (ExecutionException e) { logger.error("[Control connection] Unexpected error while refeshing node list and token map", e); reconnect(); } catch (BusyConnectionException e) { logger.debug("[Control connection] Connection is busy, reconnecting"); reconnect(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.debug("[Control connection] Interrupted while refreshing node list and token map, skipping it."); } } private void refreshNodeListAndTokenMap(Connection connection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on nodes and tokens ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); String partitioner = null; Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>(); // Update cluster name, DC and rack for the one node we are connected to Row localRow = localFuture.get().one(); if (localRow != null) { String clusterName = localRow.getString("cluster_name"); if (clusterName != null) cluster.metadata.clusterName = clusterName; Host host = cluster.metadata.getHost(connection.address); // In theory host can't be null. However there is no point in risking a NPE in case we // have a race between a node removal and this. if (host != null) host.setLocationInfo(localRow.getString("data_center"), localRow.getString("rack")); + else + logger.warn("Found the host metadata for {} to be null. Perhaps the node was recently removed?", connection.address); partitioner = localRow.getString("partitioner"); Set<String> tokens = localRow.getSet("tokens", String.class); if (partitioner != null && !tokens.isEmpty()) tokenMap.put(host, tokens); } List<InetAddress> foundHosts = new ArrayList<InetAddress>(); List<String> dcs = new ArrayList<String>(); List<String> racks = new ArrayList<String>(); List<Set<String>> allTokens = new ArrayList<Set<String>>(); for (Row row : peersFuture.get()) { InetAddress addr = row.getInet("rpc_address"); if (addr == null) { addr = row.getInet("peer"); logger.error("No rpc_address found for host {} in {}'s peers system table. That should not happen but using address {} instead", addr, connection.address, addr); } else if (addr.equals(bindAllAddress)) { addr = row.getInet("peer"); } foundHosts.add(addr); dcs.add(row.getString("data_center")); racks.add(row.getString("rack")); allTokens.add(row.getSet("tokens", String.class)); } for (int i = 0; i < foundHosts.size(); i++) { Host host = cluster.metadata.getHost(foundHosts.get(i)); if (host == null) { // We don't know that node, add it. host = cluster.addHost(foundHosts.get(i), true); } host.setLocationInfo(dcs.get(i), racks.get(i)); if (partitioner != null && !allTokens.get(i).isEmpty()) tokenMap.put(host, allTokens.get(i)); } // Removes all those that seems to have been removed (since we lost the control connection) Set<InetAddress> foundHostsSet = new HashSet<InetAddress>(foundHosts); for (Host host : cluster.metadata.allHosts()) if (!host.getAddress().equals(connection.address) && !foundHostsSet.contains(host.getAddress())) cluster.removeHost(host); if (partitioner != null) cluster.metadata.rebuildTokenMap(partitioner, tokenMap); } static boolean waitForSchemaAgreement(Connection connection, Metadata metadata) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { long start = System.currentTimeMillis(); long elapsed = 0; while (elapsed < MAX_SCHEMA_AGREEMENT_WAIT_MS) { ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); Set<UUID> versions = new HashSet<UUID>(); Row localRow = localFuture.get().one(); if (localRow != null && !localRow.isNull("schema_version")) versions.add(localRow.getUUID("schema_version")); for (Row row : peersFuture.get()) { if (row.isNull("rpc_address") || row.isNull("schema_version")) continue; InetAddress rpc = row.getInet("rpc_address"); if (rpc.equals(bindAllAddress)) rpc = row.getInet("peer"); Host peer = metadata.getHost(rpc); if (peer != null && peer.getMonitor().isUp()) versions.add(row.getUUID("schema_version")); } if (versions.size() <= 1) return true; // let's not flood the node too much Thread.sleep(200); elapsed = System.currentTimeMillis() - start; } return false; } boolean isOpen() { Connection c = connectionRef.get(); return c != null && !c.isClosed(); } public void onUp(Host host) { balancingPolicy.onUp(host); } public void onDown(Host host) { balancingPolicy.onDown(host); // If that's the host we're connected to, and we haven't yet schedul a reconnection, pre-emptively start one Connection current = connectionRef.get(); if (logger.isTraceEnabled()) logger.trace("[Control connection] {} is down, currently connected to {}", host, current == null ? "nobody" : current.address); if (current != null && current.address.equals(host.getAddress()) && reconnectionAttempt.get() == null) reconnect(); } public void onAdd(Host host) { balancingPolicy.onAdd(host); refreshNodeListAndTokenMap(); } public void onRemove(Host host) { balancingPolicy.onRemove(host); refreshNodeListAndTokenMap(); } }
true
true
private void refreshNodeListAndTokenMap(Connection connection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on nodes and tokens ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); String partitioner = null; Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>(); // Update cluster name, DC and rack for the one node we are connected to Row localRow = localFuture.get().one(); if (localRow != null) { String clusterName = localRow.getString("cluster_name"); if (clusterName != null) cluster.metadata.clusterName = clusterName; Host host = cluster.metadata.getHost(connection.address); // In theory host can't be null. However there is no point in risking a NPE in case we // have a race between a node removal and this. if (host != null) host.setLocationInfo(localRow.getString("data_center"), localRow.getString("rack")); partitioner = localRow.getString("partitioner"); Set<String> tokens = localRow.getSet("tokens", String.class); if (partitioner != null && !tokens.isEmpty()) tokenMap.put(host, tokens); } List<InetAddress> foundHosts = new ArrayList<InetAddress>(); List<String> dcs = new ArrayList<String>(); List<String> racks = new ArrayList<String>(); List<Set<String>> allTokens = new ArrayList<Set<String>>(); for (Row row : peersFuture.get()) { InetAddress addr = row.getInet("rpc_address"); if (addr == null) { addr = row.getInet("peer"); logger.error("No rpc_address found for host {} in {}'s peers system table. That should not happen but using address {} instead", addr, connection.address, addr); } else if (addr.equals(bindAllAddress)) { addr = row.getInet("peer"); } foundHosts.add(addr); dcs.add(row.getString("data_center")); racks.add(row.getString("rack")); allTokens.add(row.getSet("tokens", String.class)); } for (int i = 0; i < foundHosts.size(); i++) { Host host = cluster.metadata.getHost(foundHosts.get(i)); if (host == null) { // We don't know that node, add it. host = cluster.addHost(foundHosts.get(i), true); } host.setLocationInfo(dcs.get(i), racks.get(i)); if (partitioner != null && !allTokens.get(i).isEmpty()) tokenMap.put(host, allTokens.get(i)); } // Removes all those that seems to have been removed (since we lost the control connection) Set<InetAddress> foundHostsSet = new HashSet<InetAddress>(foundHosts); for (Host host : cluster.metadata.allHosts()) if (!host.getAddress().equals(connection.address) && !foundHostsSet.contains(host.getAddress())) cluster.removeHost(host); if (partitioner != null) cluster.metadata.rebuildTokenMap(partitioner, tokenMap); }
private void refreshNodeListAndTokenMap(Connection connection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on nodes and tokens ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); String partitioner = null; Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>(); // Update cluster name, DC and rack for the one node we are connected to Row localRow = localFuture.get().one(); if (localRow != null) { String clusterName = localRow.getString("cluster_name"); if (clusterName != null) cluster.metadata.clusterName = clusterName; Host host = cluster.metadata.getHost(connection.address); // In theory host can't be null. However there is no point in risking a NPE in case we // have a race between a node removal and this. if (host != null) host.setLocationInfo(localRow.getString("data_center"), localRow.getString("rack")); else logger.warn("Found the host metadata for {} to be null. Perhaps the node was recently removed?", connection.address); partitioner = localRow.getString("partitioner"); Set<String> tokens = localRow.getSet("tokens", String.class); if (partitioner != null && !tokens.isEmpty()) tokenMap.put(host, tokens); } List<InetAddress> foundHosts = new ArrayList<InetAddress>(); List<String> dcs = new ArrayList<String>(); List<String> racks = new ArrayList<String>(); List<Set<String>> allTokens = new ArrayList<Set<String>>(); for (Row row : peersFuture.get()) { InetAddress addr = row.getInet("rpc_address"); if (addr == null) { addr = row.getInet("peer"); logger.error("No rpc_address found for host {} in {}'s peers system table. That should not happen but using address {} instead", addr, connection.address, addr); } else if (addr.equals(bindAllAddress)) { addr = row.getInet("peer"); } foundHosts.add(addr); dcs.add(row.getString("data_center")); racks.add(row.getString("rack")); allTokens.add(row.getSet("tokens", String.class)); } for (int i = 0; i < foundHosts.size(); i++) { Host host = cluster.metadata.getHost(foundHosts.get(i)); if (host == null) { // We don't know that node, add it. host = cluster.addHost(foundHosts.get(i), true); } host.setLocationInfo(dcs.get(i), racks.get(i)); if (partitioner != null && !allTokens.get(i).isEmpty()) tokenMap.put(host, allTokens.get(i)); } // Removes all those that seems to have been removed (since we lost the control connection) Set<InetAddress> foundHostsSet = new HashSet<InetAddress>(foundHosts); for (Host host : cluster.metadata.allHosts()) if (!host.getAddress().equals(connection.address) && !foundHostsSet.contains(host.getAddress())) cluster.removeHost(host); if (partitioner != null) cluster.metadata.rebuildTokenMap(partitioner, tokenMap); }
diff --git a/src/main/java/com/ffbit/maven/solr/extract/BootstrapStrategy.java b/src/main/java/com/ffbit/maven/solr/extract/BootstrapStrategy.java index 0132ac4..e1ea1a3 100644 --- a/src/main/java/com/ffbit/maven/solr/extract/BootstrapStrategy.java +++ b/src/main/java/com/ffbit/maven/solr/extract/BootstrapStrategy.java @@ -1,13 +1,13 @@ package com.ffbit.maven.solr.extract; /** * Represents Configuration Bootstrapping Strategy hierarchy. */ public interface BootstrapStrategy { /** * Configuration Bootstrap. */ - public void bootstrap(); + void bootstrap(); }
true
true
public void bootstrap();
void bootstrap();
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/support/RestXContentBuilder.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/support/RestXContentBuilder.java index 0d4fb286f23..3b0c9c3f4db 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/support/RestXContentBuilder.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/action/support/RestXContentBuilder.java @@ -1,98 +1,97 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.rest.action.support; import org.elasticsearch.common.compress.lzf.LZFDecoder; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.CachedStreamInput; import org.elasticsearch.common.io.stream.LZFStreamInput; import org.elasticsearch.common.xcontent.*; import org.elasticsearch.rest.RestRequest; import java.io.IOException; /** * @author kimchy (shay.banon) */ public class RestXContentBuilder { public static XContentBuilder restContentBuilder(RestRequest request) throws IOException { XContentType contentType = XContentType.fromRestContentType(request.header("Content-Type")); if (contentType == null) { // try and guess it from the body, if exists if (request.hasContent()) { contentType = XContentFactory.xContentType(request.contentByteArray(), request.contentByteArrayOffset(), request.contentLength()); } } if (contentType == null) { // default to JSON contentType = XContentType.JSON; } XContentBuilder builder = XContentFactory.contentBuilder(contentType); if (request.paramAsBoolean("pretty", false)) { builder.prettyPrint(); } String casing = request.param("case"); if (casing != null && "camelCase".equals(casing)) { builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.CAMELCASE); } else { // we expect all REST interfaces to write results in underscore casing, so // no need for double casing builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.NONE); } return builder; } public static void restDocumentSource(byte[] source, XContentBuilder builder, ToXContent.Params params) throws IOException { if (LZFDecoder.isCompressed(source)) { BytesStreamInput siBytes = new BytesStreamInput(source); LZFStreamInput siLzf = CachedStreamInput.cachedLzf(siBytes); XContentType contentType = XContentFactory.xContentType(siLzf); siLzf.resetToBufferStart(); if (contentType == builder.contentType()) { builder.rawField("_source", siLzf); } else { - // TODO, should we just return it as binary and not auto convert it? - XContentParser parser = XContentFactory.xContent(builder.contentType()).createParser(siLzf); + XContentParser parser = XContentFactory.xContent(contentType).createParser(siLzf); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } else { - if (XContentFactory.xContentType(source) == builder.contentType()) { + XContentType contentType = XContentFactory.xContentType(source); + if (contentType == builder.contentType()) { builder.rawField("_source", source); } else { - // TODO, should we just return it as binary and not auto convert it? - XContentParser parser = XContentFactory.xContent(builder.contentType()).createParser(source); + XContentParser parser = XContentFactory.xContent(contentType).createParser(source); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } } }
false
true
public static void restDocumentSource(byte[] source, XContentBuilder builder, ToXContent.Params params) throws IOException { if (LZFDecoder.isCompressed(source)) { BytesStreamInput siBytes = new BytesStreamInput(source); LZFStreamInput siLzf = CachedStreamInput.cachedLzf(siBytes); XContentType contentType = XContentFactory.xContentType(siLzf); siLzf.resetToBufferStart(); if (contentType == builder.contentType()) { builder.rawField("_source", siLzf); } else { // TODO, should we just return it as binary and not auto convert it? XContentParser parser = XContentFactory.xContent(builder.contentType()).createParser(siLzf); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } else { if (XContentFactory.xContentType(source) == builder.contentType()) { builder.rawField("_source", source); } else { // TODO, should we just return it as binary and not auto convert it? XContentParser parser = XContentFactory.xContent(builder.contentType()).createParser(source); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } }
public static void restDocumentSource(byte[] source, XContentBuilder builder, ToXContent.Params params) throws IOException { if (LZFDecoder.isCompressed(source)) { BytesStreamInput siBytes = new BytesStreamInput(source); LZFStreamInput siLzf = CachedStreamInput.cachedLzf(siBytes); XContentType contentType = XContentFactory.xContentType(siLzf); siLzf.resetToBufferStart(); if (contentType == builder.contentType()) { builder.rawField("_source", siLzf); } else { XContentParser parser = XContentFactory.xContent(contentType).createParser(siLzf); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } else { XContentType contentType = XContentFactory.xContentType(source); if (contentType == builder.contentType()) { builder.rawField("_source", source); } else { XContentParser parser = XContentFactory.xContent(contentType).createParser(source); try { parser.nextToken(); builder.field("_source"); builder.copyCurrentStructure(parser); } finally { parser.close(); } } } }
diff --git a/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java b/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java index 4f06f4d7..c3a1f498 100644 --- a/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java +++ b/src/main/java/org/bukkit/event/player/PlayerInteractEvent.java @@ -1,171 +1,171 @@ package org.bukkit.event.player; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.inventory.ItemStack; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event.Result; import org.bukkit.event.block.Action; /** * * @author durron597 * */ public class PlayerInteractEvent extends PlayerEvent implements Cancellable { protected ItemStack item; protected Action action; protected Block blockClicked; protected BlockFace blockFace; private Result useClickedBlock; private Result useItemInHand; public PlayerInteractEvent(Player who, Action action, ItemStack item, Block clickedBlock, BlockFace clickedFace) { super(Type.PLAYER_INTERACT, who); this.action = action; this.item = item; this.blockClicked = clickedBlock; this.blockFace = clickedFace; - useItemInHand = item == null ? Result.DENY : Result.ALLOW; + useItemInHand = item == null ? Result.DENY : Result.DEFAULT; useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; } /** * Returns the action type * * @return Action returns the type of interaction */ public Action getAction() { return action; } /** * Gets the cancellation state of this event. Set to true if you * want to prevent buckets from placing water and so forth * * @return boolean cancellation state */ public boolean isCancelled() { return useInteractedBlock() == Result.DENY; } /** * Sets the cancellation state of this event. A canceled event will not * be executed in the server, but will still pass to other plugins * * Canceling this event will prevent use of food (player won't lose the * food item), prevent bows/snowballs/eggs from firing, etc. (player won't * lose the ammo) * * @param cancel true if you wish to cancel this event */ public void setCancelled(boolean cancel) { setUseInteractedBlock(cancel ? Result.DENY : useInteractedBlock() == Result.DENY ? Result.DEFAULT : useInteractedBlock()); } /** * Returns the item in hand represented by this event * * @return ItemStack the item used */ public ItemStack getItem() { return this.item; } /** * Convenience method. Returns the material of the item represented by this * event * * @return Material the material of the item used */ public Material getMaterial() { if (!hasItem()) return Material.AIR; return item.getType(); } /** * Check if this event involved a block * * return boolean true if it did */ public boolean hasBlock() { return this.blockClicked != null; } /** * Check if this event involved an item * * return boolean true if it did */ public boolean hasItem() { return this.item != null; } /** * Convenience method to inform the user whether this was a block placement * event. * * @return boolean true if the item in hand was a block */ public boolean isBlockInHand() { if (!hasItem()) return false; return item.getType().isBlock(); } /** * Returns the clicked block * * @return Block returns the block clicked with this item. */ public Block getClickedBlock() { return blockClicked; } /** * Returns the face of the block that was clicked * * @return BlockFace returns the face of the block that was clicked */ public BlockFace getBlockFace() { return blockFace; } /** * This controls the action to take with the block (if any) that was clicked on * This event gets processed for all blocks, but most don't have a default action * @return the action to take with the interacted block */ public Result useInteractedBlock() { return useClickedBlock; } /** * @param useInteractedBlock the action to take with the interacted block */ public void setUseInteractedBlock(Result useInteractedBlock) { this.useClickedBlock = useInteractedBlock; } /** * This controls the action to take with the item the player is holding * This includes both blocks and items (such as flint and steel or records) * When this is set to default, it will be allowed if no action is taken on the interacted block * @return the action to take with the item in hand */ public Result useItemInHand() { return useItemInHand; } /** * @param useItemInHand the action to take with the item in hand */ public void setUseItemInHand(Result useItemInHand) { this.useItemInHand = useItemInHand; } }
true
true
public PlayerInteractEvent(Player who, Action action, ItemStack item, Block clickedBlock, BlockFace clickedFace) { super(Type.PLAYER_INTERACT, who); this.action = action; this.item = item; this.blockClicked = clickedBlock; this.blockFace = clickedFace; useItemInHand = item == null ? Result.DENY : Result.ALLOW; useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; }
public PlayerInteractEvent(Player who, Action action, ItemStack item, Block clickedBlock, BlockFace clickedFace) { super(Type.PLAYER_INTERACT, who); this.action = action; this.item = item; this.blockClicked = clickedBlock; this.blockFace = clickedFace; useItemInHand = item == null ? Result.DENY : Result.DEFAULT; useClickedBlock = clickedBlock == null ? Result.DENY : Result.ALLOW; }
diff --git a/src/com/tiwun/tiwunandroidapp/FullscreenActivity.java b/src/com/tiwun/tiwunandroidapp/FullscreenActivity.java index 3d48cbd..d6635a6 100644 --- a/src/com/tiwun/tiwunandroidapp/FullscreenActivity.java +++ b/src/com/tiwun/tiwunandroidapp/FullscreenActivity.java @@ -1,168 +1,168 @@ package com.tiwun.tiwunandroidapp; import com.tiwun.tiwunandoridapp.R; import com.tiwun.tiwunandroidapp.util.SystemUiHider; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity { /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View contentView = findViewById(R.id.tiwunWebView); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. // int mControlsHeight; // int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // // If the ViewPropertyAnimator API is available // // (Honeycomb MR2 and later), use it to animate the // // in-layout UI controls at the bottom of the // // screen. // if (mControlsHeight == 0) { // mControlsHeight = controlsView.getHeight(); // } // if (mShortAnimTime == 0) { // mShortAnimTime = getResources().getInteger( // android.R.integer.config_shortAnimTime); // } // controlsView.animate() // .translationY(visible ? 0 : mControlsHeight) // .setDuration(mShortAnimTime); // } else { // // If the ViewPropertyAnimator APIs aren't // // available, simply show or hide the in-layout UI // // controls. // controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); // } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.tiwunWebView).setOnTouchListener(mDelayHideTouchListener); webView = (WebView) findViewById(R.id.tiwunWebView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); - webView.loadUrl("http://www.tiwun.com"); + webView.loadUrl("http://www.tiwun.com/?device=android"); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View contentView = findViewById(R.id.tiwunWebView); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. // int mControlsHeight; // int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // // If the ViewPropertyAnimator API is available // // (Honeycomb MR2 and later), use it to animate the // // in-layout UI controls at the bottom of the // // screen. // if (mControlsHeight == 0) { // mControlsHeight = controlsView.getHeight(); // } // if (mShortAnimTime == 0) { // mShortAnimTime = getResources().getInteger( // android.R.integer.config_shortAnimTime); // } // controlsView.animate() // .translationY(visible ? 0 : mControlsHeight) // .setDuration(mShortAnimTime); // } else { // // If the ViewPropertyAnimator APIs aren't // // available, simply show or hide the in-layout UI // // controls. // controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); // } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.tiwunWebView).setOnTouchListener(mDelayHideTouchListener); webView = (WebView) findViewById(R.id.tiwunWebView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl("http://www.tiwun.com"); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen); final View contentView = findViewById(R.id.tiwunWebView); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. // int mControlsHeight; // int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // // If the ViewPropertyAnimator API is available // // (Honeycomb MR2 and later), use it to animate the // // in-layout UI controls at the bottom of the // // screen. // if (mControlsHeight == 0) { // mControlsHeight = controlsView.getHeight(); // } // if (mShortAnimTime == 0) { // mShortAnimTime = getResources().getInteger( // android.R.integer.config_shortAnimTime); // } // controlsView.animate() // .translationY(visible ? 0 : mControlsHeight) // .setDuration(mShortAnimTime); // } else { // // If the ViewPropertyAnimator APIs aren't // // available, simply show or hide the in-layout UI // // controls. // controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); // } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.tiwunWebView).setOnTouchListener(mDelayHideTouchListener); webView = (WebView) findViewById(R.id.tiwunWebView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl("http://www.tiwun.com/?device=android"); }
diff --git a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java index e679d0fa..61f1f3ec 100644 --- a/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java +++ b/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java @@ -1,85 +1,86 @@ /* * Cxdopyright (C) 2010 Evgeny Mandrikov, Jérémie Lagarde * * Sonar-IDE is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar-IDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar-IDE; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ide.eclipse.internal.ui.texteditor.coverage; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; /** * Action to toggle the coverage bar's and color information in the editor. When * turned on, sonar ide plugin shows the coverage informations form sonar server * in the editor . * * @author Jérémie Lagarde * @since 0.2.0 */ public class CoverageToggleAction implements IEditorActionDelegate, IUpdate { /** The editor we are working on. */ ITextEditor editor = null; IAction action = null; public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; + update(); } else { editor = null; } } public void run(IAction action) { if (editor == null) { return; } toggleCoverageRuler(); } public void selectionChanged(IAction action, ISelection selection) { } public void update() { if (action != null) { action.setChecked(isCoverageRulerVisible()); } } /** * Toggles the coverage global preference and shows the sonar coverage ruler * accordingly. */ private void toggleCoverageRuler() { IPreferenceStore store = EditorsUI.getPreferenceStore(); store.setValue(CoverageColumn.SONAR_COVERAGE_RULER, !isCoverageRulerVisible()); } /** * Returns whether the sonar coverage ruler column should be visible according * to the preference store settings. */ private boolean isCoverageRulerVisible() { IPreferenceStore store = EditorsUI.getPreferenceStore(); return store != null ? store.getBoolean(CoverageColumn.SONAR_COVERAGE_RULER) : false; } }
true
true
public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; } else { editor = null; } }
public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; update(); } else { editor = null; } }
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/ui/editors/table/TableComponent.java b/orbisgis-core/src/main/java/org/orbisgis/core/ui/editors/table/TableComponent.java index dac8afa93..272c20e01 100644 --- a/orbisgis-core/src/main/java/org/orbisgis/core/ui/editors/table/TableComponent.java +++ b/orbisgis-core/src/main/java/org/orbisgis/core/ui/editors/table/TableComponent.java @@ -1,1221 +1,1221 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488. * * * Team leader Erwan BOCHER, scientific researcher, * * * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * Copyright (C) 2010 Erwan BOCHER, Alexis GUEGANNO, Antoine GOURLAY, Adelin PIAU, Gwendall PETIT * * This file is part of OrbisGIS. * * OrbisGIS is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.core.ui.editors.table; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.TreeSet; import java.util.regex.Pattern; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.gdms.data.DataSource; import org.gdms.data.FilterDataSourceDecorator; import org.gdms.data.edition.EditionEvent; import org.gdms.data.edition.EditionListener; import org.gdms.data.edition.FieldEditionEvent; import org.gdms.data.edition.MetadataEditionListener; import org.gdms.data.edition.MultipleEditionEvent; import org.gdms.data.metadata.Metadata; import org.gdms.data.types.Constraint; import org.gdms.data.types.Type; import org.gdms.data.values.Value; import org.gdms.data.values.ValueFactory; import org.gdms.driver.DriverException; import org.gdms.sql.strategies.SortComparator; import org.orbisgis.core.Services; import org.orbisgis.core.background.BackgroundJob; import org.orbisgis.core.background.BackgroundManager; import org.orbisgis.core.errorManager.ErrorManager; import org.orbisgis.core.sif.SQLUIPanel; import org.orbisgis.core.sif.UIFactory; import org.orbisgis.core.ui.components.sif.AskValue; import org.orbisgis.core.ui.components.text.JButtonTextField; import org.orbisgis.core.ui.pluginSystem.workbench.WorkbenchContext; import org.orbisgis.core.ui.pluginSystem.workbench.WorkbenchFrame; import org.orbisgis.core.ui.plugins.views.TableEditorPlugIn; import org.orbisgis.core.ui.plugins.views.sqlConsole.syntax.SQLCompletionProvider; import org.orbisgis.core.ui.preferences.lookandfeel.OrbisGISIcon; import org.orbisgis.core.ui.preferences.lookandfeel.UIColorPreferences; import org.orbisgis.core.ui.preferences.lookandfeel.images.IconLoader; import org.orbisgis.progress.IProgressMonitor; import org.orbisgis.progress.NullProgressMonitor; import org.orbisgis.utils.I18N; public class TableComponent extends JPanel implements WorkbenchFrame { private static final String OPTIMALWIDTH = "OPTIMALWIDTH"; private static final String SETWIDTH = "SETWIDTH"; private static final String SORTUP = "SORTUP"; private static final String SORTDOWN = "SORTDOWN"; private static final String NOSORT = "NOSORT"; private static final Color NUMERIC_COLOR = new Color(205, 197, 191); private static final Color DEFAULT_COLOR = new Color(238, 229, 222); // Swing components private javax.swing.JScrollPane jScrollPane = null; private JTable table = null; private JLabel nbRowsSelectedLabel = null; private SQLCompletionProvider cpl; // Model private int selectedColumn = -1; private DataSourceDataModel tableModel; private DataSource dataSource; private ArrayList<Integer> indexes = null; private Selection selection; private TableEditableElement element; private int selectedRowsCount; // listeners private ActionListener menuListener = new PopupActionListener(); private ModificationListener listener = new ModificationListener(); private SelectionListener selectionListener = new SyncSelectionListener(); // flags private boolean managingSelection; private TableEditorPlugIn editor; private org.orbisgis.core.ui.pluginSystem.menu.MenuTree menuTree; private int patternCaseOption = Pattern.CASE_INSENSITIVE; @Override public org.orbisgis.core.ui.pluginSystem.menu.MenuTree getMenuTreePopup() { return menuTree; } /** * This is the default constructor * * @throws DriverException */ public TableComponent(TableEditorPlugIn editor) { this.editor = editor; initialize(); } /** * This method initializes this */ private void initialize() { menuTree = new org.orbisgis.core.ui.pluginSystem.menu.MenuTree(); this.setLayout(new BorderLayout()); add(getJScrollPane(), BorderLayout.CENTER); add(getTableToolBar(), BorderLayout.NORTH); add(getWhereTextField(), BorderLayout.SOUTH); } /** * This method initializes table * * @return javax.swing.JTable */ public javax.swing.JTable getTable() { if (table == null) { table = new JTable(); table .setSelectionBackground(UIColorPreferences.TABLE_EDITOR_SELECTION_BACKGROUND); table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); table.getSelectionModel().setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); table.setDragEnabled(true); table.getSelectionModel().addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (!managingSelection && (selection != null)) { managingSelection = true; int[] selectedRows = table .getSelectedRows(); if (indexes != null) { for (int i = 0; i < selectedRows.length; i++) { selectedRows[i] = indexes .get(selectedRows[i]); } } selectedRowsCount = selectedRows.length; selection.setSelectedRows(selectedRows); managingSelection = false; updateRowsMessage(); } } } }); table.getTableHeader().setReorderingAllowed(false); table.getTableHeader().addMouseListener( new HeaderPopupMouseAdapter()); table.addMouseListener(new CellPopupMouseAdapter()); table.setColumnSelectionAllowed(true); table.getColumnModel().setSelectionModel( new DefaultListSelectionModel()); } return table; } private Component getTableToolBar() { JToolBar toolBar = new JToolBar(); toolBar.setFloatable(false); toolBar.add(getPanelInformation(), BorderLayout.NORTH); toolBar.add(getRegexTextField(), BorderLayout.SOUTH); return toolBar; } public JPanel getPanelInformation() { final JPanel informationPanel = new JPanel(); final FlowLayout flowLayout = new FlowLayout(); flowLayout.setAlignment(FlowLayout.LEFT); informationPanel.setLayout(flowLayout); informationPanel.add(getNbRowsInformation()); return informationPanel; } private JPanel getRegexTextField() { final JPanel regexPanel = new JPanel(); final FlowLayout flowLayout = new FlowLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); regexPanel.setLayout(flowLayout); JLabel label = new JLabel( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.search")); final JButtonTextField regexTxtFilter = new JButtonTextField(20); regexTxtFilter.setBackground(Color.WHITE); regexTxtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_text")); regexTxtFilter .setToolTipText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.searchEnter")); regexTxtFilter.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { final String whereText = regexTxtFilter.getText(); if (whereText.length() == 0) { if (selectedRowsCount > 0) { selection.clearSelection(); updateRowsMessage(); } } else { findTextPattern(whereText); } } } }); regexTxtFilter.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (regexTxtFilter .getText() .equals( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_text"))) regexTxtFilter.setText(""); } public void mouseExited(MouseEvent e) { if (regexTxtFilter.getText().equals("")) regexTxtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_text")); } }); regexPanel.add(label); regexPanel.add(regexTxtFilter); return regexPanel; } public void findTextPattern(final String text) { String quote = "\\Q"; String endQuote = "\\E"; String regex = quote + text + endQuote; final Pattern pattern = Pattern.compile(regex, patternCaseOption); BackgroundManager bm = Services.getService(BackgroundManager.class); bm.backgroundOperation(new BackgroundJob() { @Override public void run(IProgressMonitor pm) { try { ArrayList<Integer> filtered = new ArrayList<Integer>(); pm.startTask("Searching..."); for (int i = 0; i < tableModel.getRowCount(); i++) { if (i / 100 == i / 100.0) { if (pm.isCancelled()) { break; } else { pm.progressTo((int) (100 * i / tableModel .getRowCount())); } } Value[] values = dataSource.getRow(i); boolean select = false; for (int j = 0; j < values.length; j++) { Value value = values[j]; if (value.getType() == Type.GEOMETRY) { continue; } String valueString = value.toString(); pattern.matcher(valueString).reset(); select = select || (pattern.matcher(valueString).find()); } pm.endTask(); if (select) { filtered.add(i); } } int[] sel = new int[filtered.size()]; for (int i = 0; i < sel.length; i++) { sel[i] = filtered.get(i); } selection.setSelectedRows(sel); updateTableSelection(); } catch (DriverException e1) { e1.printStackTrace(); } } @Override public String getTaskName() { return I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.searching"); } }); } private JLabel getNbRowsInformation() { JLabel nbRowsMessage = new JLabel(); nbRowsMessage .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.rowNumber")); nbRowsSelectedLabel = nbRowsMessage; return nbRowsMessage; } private JTextField getWhereTextField() { final JButtonTextField txtFilter = new JButtonTextField(20); cpl = new SQLCompletionProvider(txtFilter); cpl.install(); txtFilter.setBackground(Color.WHITE); txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); txtFilter .setToolTipText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.searchEnter")); txtFilter.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { + if ((e.getKeyCode() == KeyEvent.VK_ENTER) && e.isControlDown()) { final String whereText = txtFilter.getText(); if (whereText.length() == 0) { if (selectedRowsCount > 0) { selection.clearSelection(); updateRowsMessage(); } } else { try { FilterDataSourceDecorator filterDataSourceDecorator = new FilterDataSourceDecorator( dataSource); filterDataSourceDecorator.setFilter(whereText); long dsRowCount = filterDataSourceDecorator .getRowCount(); List<Integer> map = filterDataSourceDecorator .getIndexMap(); int[] sel = new int[map.size()]; for (int i = 0; i < dsRowCount; i++) { sel[i] = (int) filterDataSourceDecorator .getOriginalIndex(i); } selection.setSelectedRows(sel); } catch (DriverException e1) { e1.printStackTrace(); } } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }); txtFilter.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (txtFilter .getText() .equals( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere"))) txtFilter.setText(""); } public void mouseExited(MouseEvent e) { if (txtFilter.getText().equals("")) txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); } }); return txtFilter; } /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private javax.swing.JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new javax.swing.JScrollPane(); jScrollPane.setViewportView(getTable()); } return jScrollPane; } /** * Shows a dialog with the error type * * @param msg */ private void inputError(String msg, Exception e) { Services.getService(ErrorManager.class).error(msg, e); getTable().requestFocus(); } public boolean tableHasFocus() { return table.hasFocus() || table.isEditing(); } public String[] getSelectedFieldNames() { int[] selected = table.getSelectedColumns(); String[] ret = new String[selected.length]; for (int i = 0; i < ret.length; i++) { ret[i] = tableModel.getColumnName(selected[i]); } return ret; } public void setElement(TableEditableElement element) { if (this.dataSource != null) { this.dataSource.removeEditionListener(listener); this.dataSource.removeMetadataEditionListener(listener); this.selection.removeSelectionListener(selectionListener); } this.element = element; if (this.element == null) { this.dataSource = null; this.selection = null; table.setModel(new DefaultTableModel()); } else { this.dataSource = element.getDataSource(); this.dataSource.addEditionListener(listener); this.dataSource.addMetadataEditionListener(listener); this.cpl.setRootText("SELECT * FROM " + dataSource.getName() + " WHERE"); tableModel = new DataSourceDataModel(); table.setModel(tableModel); table.setBackground(DEFAULT_COLOR); autoResizeColWidth(Math.min(5, tableModel.getRowCount()), new HashMap<String, Integer>(), new HashMap<String, TableCellRenderer>()); this.selection = element.getSelection(); this.selection.setSelectionListener(selectionListener); selectedRowsCount = selection.getSelectedRows().length; updateTableSelection(); updateRowsMessage(); } } private void autoResizeColWidth(int rowsToCheck, HashMap<String, Integer> widths, HashMap<String, TableCellRenderer> renderers) { DefaultTableColumnModel colModel = new DefaultTableColumnModel(); int maxWidth = 200; for (int i = 0; i < tableModel.getColumnCount(); i++) { TableColumn col = new TableColumn(i); String columnName = tableModel.getColumnName(i); int columnType = tableModel.getColumnType(i).getTypeCode(); col.setHeaderValue(columnName); TableCellRenderer tableCellRenderer = renderers.get(columnName); if (tableCellRenderer == null) { tableCellRenderer = new ButtonHeaderRenderer(); } col.setHeaderRenderer(tableCellRenderer); Integer width = widths.get(columnName); if (width == null) { width = getColumnOptimalWidth(rowsToCheck, maxWidth, i, new NullProgressMonitor()); } col.setPreferredWidth(width); colModel.addColumn(col); switch (columnType) { case Type.DOUBLE: case Type.INT: case Type.LONG: NumberFormat formatter = NumberFormat.getCurrencyInstance(); FormatRenderer formatRenderer = new FormatRenderer(formatter); formatRenderer.setHorizontalAlignment(SwingConstants.RIGHT); formatRenderer.setBackground(NUMERIC_COLOR); col.setCellRenderer(formatRenderer); break; default: break; } } table.setColumnModel(colModel); } private int getColumnOptimalWidth(int rowsToCheck, int maxWidth, int column, IProgressMonitor pm) { TableColumn col = table.getColumnModel().getColumn(column); int margin = 5; int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = table.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, col .getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // Check header comp = renderer.getTableCellRendererComponent(table, col .getHeaderValue(), false, false, 0, column); width = Math.max(width, comp.getPreferredSize().width); // Get maximum width of column data for (int r = 0; r < rowsToCheck; r++) { if (r / 100 == r / 100.0) { if (pm.isCancelled()) { break; } else { pm.progressTo(100 * r / rowsToCheck); } } renderer = table.getCellRenderer(r, column); comp = renderer.getTableCellRendererComponent(table, table .getValueAt(r, column), false, false, r, column); width = Math.max(width, comp.getPreferredSize().width); } // limit width = Math.min(width, maxWidth); // Add margin width += 2 * margin; return width; } private void refreshTableStructure() { TableColumnModel columnModel = table.getColumnModel(); HashMap<String, Integer> widths = new HashMap<String, Integer>(); HashMap<String, TableCellRenderer> renderers = new HashMap<String, TableCellRenderer>(); try { for (int i = 0; i < dataSource.getMetadata().getFieldCount(); i++) { String columnName = null; try { columnName = dataSource.getMetadata().getFieldName(i); } catch (DriverException e) { } int columnIndex = -1; if (columnName != null) { try { columnIndex = columnModel.getColumnIndex(columnName); } catch (IllegalArgumentException e) { columnIndex = -1; } if (columnIndex != -1) { TableColumn column = columnModel.getColumn(columnIndex); widths.put(columnName, column.getPreferredWidth()); renderers.put(columnName, column.getHeaderRenderer()); } } } } catch (DriverException e) { Services .getService(ErrorManager.class) .warning( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.refreshTableStructure"), e); } tableModel.fireTableStructureChanged(); autoResizeColWidth(Math.min(5, tableModel.getRowCount()), widths, renderers); } private int getRowIndex(int row) { if (indexes != null) { row = indexes.get(row); } return row; } private void updateTableSelection() { if (!managingSelection) { managingSelection = true; ListSelectionModel model = table.getSelectionModel(); model.setValueIsAdjusting(true); model.clearSelection(); for (int i : selection.getSelectedRows()) { if (indexes != null) { Integer sortedIndex = indexes.indexOf(i); model.addSelectionInterval(sortedIndex, sortedIndex); } else { model.addSelectionInterval(i, i); } } selectedRowsCount = selection.getSelectedRows().length; model.setValueIsAdjusting(false); managingSelection = false; updateRowsMessage(); } } private void fireTableDataChanged() { Rectangle r = table.getVisibleRect(); // to avoid losing the selection managingSelection = true; tableModel.fireTableDataChanged(); managingSelection = false; updateTableSelection(); table.scrollRectToVisible(r); } public void updateRowsMessage() { if (selectedRowsCount > 0) { nbRowsSelectedLabel .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.rowSelected") + selectedRowsCount + " / " + table.getRowCount()); } else { nbRowsSelectedLabel .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.rowNumber") + tableModel.getRowCount()); } } public void moveSelectionUp() { int[] selectedRows = selection.getSelectedRows(); HashSet<Integer> selectedRowSet = new HashSet<Integer>(); indexes = new ArrayList<Integer>(); for (int i : selectedRows) { indexes.add(i); selectedRowSet.add(i); } for (int i = 0; i < tableModel.getRowCount(); i++) { if (!selectedRowSet.contains(i)) { indexes.add(i); } } fireTableDataChanged(); } private class SyncSelectionListener implements SelectionListener { @Override public void selectionChanged() { updateTableSelection(); } } private final class PopupActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (OPTIMALWIDTH.equals(e.getActionCommand())) { BackgroundManager bm = Services .getService(BackgroundManager.class); bm.backgroundOperation(new BackgroundJob() { @Override public void run(IProgressMonitor pm) { final int width = getColumnOptimalWidth(table .getRowCount(), Integer.MAX_VALUE, selectedColumn, pm); final TableColumn col = table.getColumnModel() .getColumn(selectedColumn); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { col.setPreferredWidth(width); } }); } @Override public String getTaskName() { return I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.columnOptimalWidth"); } }); } else if (SETWIDTH.equals(e.getActionCommand())) { TableColumn selectedTableColumn = table.getTableHeader() .getColumnModel().getColumn(selectedColumn); AskValue av = new AskValue( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.newColumnWidth"), null, null, Integer.toString(selectedTableColumn .getPreferredWidth())); av.setType(SQLUIPanel.INT); if (UIFactory.showDialog(av)) { selectedTableColumn.setPreferredWidth(Integer.parseInt(av .getValue())); } } else if (SORTUP.equals(e.getActionCommand())) { BackgroundManager bm = Services .getService(BackgroundManager.class); bm.backgroundOperation(new SortJob(true)); } else if (SORTDOWN.equals(e.getActionCommand())) { BackgroundManager bm = Services .getService(BackgroundManager.class); bm.backgroundOperation(new SortJob(false)); } else if (NOSORT.equals(e.getActionCommand())) { indexes = null; fireTableDataChanged(); } table.getTableHeader().repaint(); } } private abstract class PopupMouseAdapter extends MouseAdapter { WorkbenchContext wbContext = Services .getService(WorkbenchContext.class); @Override public void mousePressed(MouseEvent e) { updateContext(e); popup(e); } @Override public void mouseReleased(MouseEvent e) { popup(e); } /** * This method is used to update the popup context. Used by plugins to * determine when it's showing. * * @param e */ private void updateContext(MouseEvent e) { boolean oneColumnHeaderIsSelected = table.getTableHeader() .contains(e.getPoint()); selectedColumn = table.columnAtPoint(e.getPoint()); int clickedRow = table.rowAtPoint(e.getPoint()); if (oneColumnHeaderIsSelected) { if ("ColumnAction".equals(getExtensionPointId())) { wbContext.setHeaderSelected(selectedColumn); } else { wbContext.setRowSelected(e); if (!table.isRowSelected(clickedRow)) { selection.setSelectedRows(new int[] { clickedRow }); updateTableSelection(); } } } else { wbContext.setRowSelected(e); if (!table.isRowSelected(clickedRow)) { selection.setSelectedRows(new int[] { clickedRow }); updateTableSelection(); } } } private void popup(final MouseEvent e) { final Component component = getComponent(); component.repaint(); if (e.isPopupTrigger()) { JComponent[] menus = null; final JPopupMenu pop = getPopupMenu(); menus = wbContext.getWorkbench().getFrame() .getMenuTableTreePopup().getJMenus(); for (JComponent menu : menus) { pop.add(menu); } pop.show(component, e.getX(), e.getY()); } } protected void addMenu(JPopupMenu pop, String text, Icon icon, String actionCommand) { JMenuItem menu = new JMenuItem(text); menu.setIcon(icon); menu.setActionCommand(actionCommand); menu.addActionListener(menuListener); pop.add(menu); } protected abstract Component getComponent(); protected abstract String getExtensionPointId(); protected abstract JPopupMenu getPopupMenu(); } private class HeaderPopupMouseAdapter extends PopupMouseAdapter { @Override protected Component getComponent() { return table.getTableHeader(); } @Override protected String getExtensionPointId() { return "ColumnAction"; } @Override protected JPopupMenu getPopupMenu() { JPopupMenu pop = new JPopupMenu(); addMenu( pop, I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.optimalWidth"), IconLoader.getIcon("text_letterspacing.png"), OPTIMALWIDTH); addMenu( pop, I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.setWidth"), null, SETWIDTH); pop.addSeparator(); if (tableModel.getColumnType(selectedColumn).getTypeCode() != Type.GEOMETRY) { addMenu( pop, I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.sortAscending"), IconLoader.getIcon("thumb_up.png"), SORTUP); addMenu( pop, I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.sortDescending"), IconLoader.getIcon("thumb_down.png"), SORTDOWN); addMenu( pop, I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.noSort"), OrbisGISIcon.TABLE_REFRESH, NOSORT); } return pop; } } private class CellPopupMouseAdapter extends PopupMouseAdapter { @Override protected Component getComponent() { return table; } @Override protected String getExtensionPointId() { return "CellAction"; } @Override protected JPopupMenu getPopupMenu() { return new JPopupMenu(); } } private class ModificationListener implements EditionListener, MetadataEditionListener { @Override public void multipleModification(MultipleEditionEvent e) { tableModel.fireTableDataChanged(); } @Override public void singleModification(EditionEvent e) { if (e.getType() != EditionEvent.RESYNC) { int row = (int) e.getRowIndex(); if (indexes != null) { row = indexes.indexOf(new Integer(row)); } int column = e.getFieldIndex(); if ((e.getType() == EditionEvent.DELETE) || (e.getType() == EditionEvent.INSERT)) { refreshTableStructure(); } else { tableModel.fireTableCellUpdated(row, column); } if (row != -1) { table.scrollRectToVisible(table.getCellRect(row, column, true)); } } else { refreshTableStructure(); } } @Override public void fieldAdded(FieldEditionEvent event) { fieldRemoved(null); } @Override public void fieldModified(FieldEditionEvent event) { fieldRemoved(null); } @Override public void fieldRemoved(FieldEditionEvent event) { refreshTableStructure(); } } public class DataSourceDataModel extends AbstractTableModel { private Metadata metadata; private Metadata getMetadata() throws DriverException { if (metadata == null) { metadata = dataSource.getMetadata(); } return metadata; } /** * Returns the name of the field. * * @param col * index of field * * @return Name of field */ @Override public String getColumnName(int col) { try { return getMetadata().getFieldName(col); } catch (DriverException e) { return null; } } /** * Returns the type of field * * @param col * index of field * @return Type of field */ public Type getColumnType(int col) { try { return getMetadata().getFieldType(col); } catch (DriverException e) { return null; } } /** * Returns the number of fields. * * @return number of fields */ @Override public int getColumnCount() { try { return getMetadata().getFieldCount(); } catch (DriverException e) { return 0; } } /** * Returns number of rows. * * @return number of rows. */ @Override public int getRowCount() { try { return (int) dataSource.getRowCount(); } catch (DriverException e) { return 0; } } /** * @see javax.swing.table.TableModel#getValueAt(int, int) */ @Override public Object getValueAt(int row, int col) { try { return dataSource.getFieldValue(getRowIndex(row), col) .toString(); } catch (DriverException e) { return ""; } } /** * @see javax.swing.table.TableModel#isCellEditable(int, int) */ @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (element.isEditable()) { try { Type fieldType = getMetadata().getFieldType(columnIndex); Constraint c = fieldType.getConstraint(Constraint.READONLY); return (fieldType.getTypeCode() != Type.RASTER) && (c == null); } catch (DriverException e) { return false; } } else { return false; } } /** * @see javax.swing.table.TableModel#setValueAt(java.lang.Object, int, * int) */ @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { try { Type type = getMetadata().getFieldType(columnIndex); String strValue = aValue.toString().trim(); Value v = ValueFactory.createValueByType(strValue, type .getTypeCode()); dataSource.setFieldValue(getRowIndex(rowIndex), columnIndex, v); } catch (DriverException e1) { throw new RuntimeException(e1); } catch (NumberFormatException e) { inputError("Cannot parse number: " + e.getMessage(), e); } catch (ParseException e) { inputError(e.getMessage(), e); } } } private final class SortJob implements BackgroundJob { private boolean ascending; public SortJob(boolean ascending) { this.ascending = ascending; } @Override public void run(IProgressMonitor pm) { try { int rowCount = (int) dataSource.getRowCount(); Value[][] cache = new Value[rowCount][1]; for (int i = 0; i < rowCount; i++) { cache[i][0] = dataSource.getFieldValue(i, selectedColumn); } ArrayList<Boolean> order = new ArrayList<Boolean>(); order.add(ascending); TreeSet<Integer> sortset = new TreeSet<Integer>( new SortComparator(cache, order)); for (int i = 0; i < rowCount; i++) { if (i / 100 == i / 100.0) { if (pm.isCancelled()) { break; } else { pm.progressTo(100 * i / rowCount); } } sortset.add(new Integer(i)); } ArrayList<Integer> indexes = new ArrayList<Integer>(); Iterator<Integer> it = sortset.iterator(); while (it.hasNext()) { Integer integer = (Integer) it.next(); indexes.add(integer); } TableComponent.this.indexes = indexes; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { fireTableDataChanged(); } }); } catch (DriverException e) { Services.getService(ErrorManager.class).error("Cannot sort", e); } } @Override public String getTaskName() { return I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.sorting"); } } public class ButtonHeaderRenderer extends JButton implements TableCellRenderer { public ButtonHeaderRenderer() { setMargin(new Insets(0, 0, 0, 0)); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText((value == null) ? "" : value.toString()); boolean isPressed = (column == selectedColumn); if (isPressed) { setPressedColumn(column); } getModel().setPressed(isPressed); getModel().setArmed(isPressed); return this; } public void setPressedColumn(int col) { selectedColumn = col; } } public int getSelectedColumn() { return selectedColumn; } }
true
true
private JTextField getWhereTextField() { final JButtonTextField txtFilter = new JButtonTextField(20); cpl = new SQLCompletionProvider(txtFilter); cpl.install(); txtFilter.setBackground(Color.WHITE); txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); txtFilter .setToolTipText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.searchEnter")); txtFilter.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { final String whereText = txtFilter.getText(); if (whereText.length() == 0) { if (selectedRowsCount > 0) { selection.clearSelection(); updateRowsMessage(); } } else { try { FilterDataSourceDecorator filterDataSourceDecorator = new FilterDataSourceDecorator( dataSource); filterDataSourceDecorator.setFilter(whereText); long dsRowCount = filterDataSourceDecorator .getRowCount(); List<Integer> map = filterDataSourceDecorator .getIndexMap(); int[] sel = new int[map.size()]; for (int i = 0; i < dsRowCount; i++) { sel[i] = (int) filterDataSourceDecorator .getOriginalIndex(i); } selection.setSelectedRows(sel); } catch (DriverException e1) { e1.printStackTrace(); } } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }); txtFilter.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (txtFilter .getText() .equals( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere"))) txtFilter.setText(""); } public void mouseExited(MouseEvent e) { if (txtFilter.getText().equals("")) txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); } }); return txtFilter; }
private JTextField getWhereTextField() { final JButtonTextField txtFilter = new JButtonTextField(20); cpl = new SQLCompletionProvider(txtFilter); cpl.install(); txtFilter.setBackground(Color.WHITE); txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); txtFilter .setToolTipText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.searchEnter")); txtFilter.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { if ((e.getKeyCode() == KeyEvent.VK_ENTER) && e.isControlDown()) { final String whereText = txtFilter.getText(); if (whereText.length() == 0) { if (selectedRowsCount > 0) { selection.clearSelection(); updateRowsMessage(); } } else { try { FilterDataSourceDecorator filterDataSourceDecorator = new FilterDataSourceDecorator( dataSource); filterDataSourceDecorator.setFilter(whereText); long dsRowCount = filterDataSourceDecorator .getRowCount(); List<Integer> map = filterDataSourceDecorator .getIndexMap(); int[] sel = new int[map.size()]; for (int i = 0; i < dsRowCount; i++) { sel[i] = (int) filterDataSourceDecorator .getOriginalIndex(i); } selection.setSelectedRows(sel); } catch (DriverException e1) { e1.printStackTrace(); } } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } }); txtFilter.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (txtFilter .getText() .equals( I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere"))) txtFilter.setText(""); } public void mouseExited(MouseEvent e) { if (txtFilter.getText().equals("")) txtFilter .setText(I18N .getText("orbisgis.org.orbisgis.core.ui.editors.table.TableComponent.put_a_sqlwhere")); } }); return txtFilter; }
diff --git a/src/main/java/net/pms/encoders/FFmpegVideo.java b/src/main/java/net/pms/encoders/FFmpegVideo.java index 25504308c..63a0c5ba7 100644 --- a/src/main/java/net/pms/encoders/FFmpegVideo.java +++ b/src/main/java/net/pms/encoders/FFmpegVideo.java @@ -1,756 +1,756 @@ /* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License only. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.pms.encoders; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.factories.Borders; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.Font; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JComponent; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAMediaSubtitle; import net.pms.dlna.DLNAResource; import net.pms.formats.Format; import net.pms.io.OutputParams; import net.pms.io.PipeIPCProcess; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.io.StreamModifier; import net.pms.network.HTTPResource; import net.pms.util.ProcessUtil; import org.apache.commons.lang.StringUtils; import static org.apache.commons.lang.StringUtils.isBlank; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Pure FFmpeg video player. * * Design note: * * Helper methods that return lists of <code>String</code>s representing options are public * to facilitate composition e.g. a custom engine (plugin) that uses tsMuxeR for videos without * subtitles and FFmpeg otherwise needs to compose and call methods on both players. * * To avoid API churn, and to provide wiggle room for future functionality, all of these methods * take RendererConfiguration (renderer) and DLNAMediaInfo (media) parameters, even if one or * both of these parameters are unused. */ public class FFmpegVideo extends Player { private static final Logger LOGGER = LoggerFactory.getLogger(FFmpegVideo.class); private static final String DEFAULT_QSCALE = "3"; private static final PmsConfiguration configuration = PMS.getConfiguration(); // FIXME we have an id() accessor for this; no need for the field to be public @Deprecated public static final String ID = "ffmpegvideo"; /** * Returns a list of strings representing the rescale options for this transcode i.e. the ffmpeg -vf * options used to resize a video that's too wide and/or high for the specified renderer. * If the renderer has no size limits, or there's no media metadata, or the video is within the renderer's * size limits, an empty list is returned. * * @param renderer the DLNA renderer the video is being streamed to * @param media metadata for the DLNA resource which is being transcoded * @return a {@link List} of <code>String</code>s representing the rescale options for this video, * or an empty list if the video doesn't need to be resized. */ public List<String> getRescaleOptions(RendererConfiguration renderer, DLNAMediaInfo media) { List<String> rescaleOptions = new ArrayList<String>(); boolean isResolutionTooHighForRenderer = renderer.isVideoRescale() && // renderer defines a max width/height (media != null) && ( (media.getWidth() > renderer.getMaxVideoWidth()) || (media.getHeight() > renderer.getMaxVideoHeight()) ); if (isResolutionTooHighForRenderer) { String rescaleSpec = String.format( // http://stackoverflow.com/a/8351875 "scale=iw*min(%1$d/iw\\,%2$d/ih):ih*min(%1$d/iw\\,%2$d/ih),pad=%1$d:%2$d:(%1$d-iw)/2:(%2$d-ih)/2", renderer.getMaxVideoWidth(), renderer.getMaxVideoHeight() ); rescaleOptions.add("-vf"); rescaleOptions.add(rescaleSpec); } return rescaleOptions; } /** * Takes a renderer and returns a list of <code>String</code>s representing ffmpeg output options * (i.e. options that define the output file's video codec, audio codec and container) * compatible with the renderer's <code>TranscodeVideo</code> profile. * * @param renderer The {@link RendererConfiguration} instance whose <code>TranscodeVideo</code> profile is to be processed. * @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos). * @return a {@link List} of <code>String</code>s representing the ffmpeg output parameters for the renderer according * to its <code>TranscodeVideo</code> profile. */ public List<String> getTranscodeVideoOptions(RendererConfiguration renderer, DLNAMediaInfo media, OutputParams params) { List<String> transcodeOptions = new ArrayList<String>(); if (renderer.isTranscodeToWMV()) { // WMV transcodeOptions.add("-c:v"); transcodeOptions.add("wmv2"); transcodeOptions.add("-c:a"); transcodeOptions.add("wmav2"); transcodeOptions.add("-f"); transcodeOptions.add("asf"); } else { // MPEGPSAC3 or MPEGTSAC3 final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID); // Output audio codec dtsRemux = isTsMuxeRVideoEngineEnabled && configuration.isDTSEmbedInPCM() && params.aid != null && params.aid.isDTS() && !avisynth() && renderer.isDTSPlayable(); if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && renderer.isTranscodeToAC3()) { // AC-3 remux transcodeOptions.add("-c:a"); transcodeOptions.add("copy"); } else { if (dtsRemux) { // Audio is added in a separate process later transcodeOptions.add("-an"); } else if (type() == Format.AUDIO) { // Skip } else { transcodeOptions.add("-c:a"); transcodeOptions.add("ac3"); } } // Output file format transcodeOptions.add("-f"); if (dtsRemux) { transcodeOptions.add("mpeg2video"); } else if (renderer.isTranscodeToMPEGTSAC3()) { // MPEGTSAC3 transcodeOptions.add("mpegts"); } else { // default: MPEGPSAC3 transcodeOptions.add("vob"); } // Output video codec if (!dtsRemux) { transcodeOptions.add("-c:v"); transcodeOptions.add("mpeg2video"); } } return transcodeOptions; } /** * Takes a renderer and metadata for the current video and returns the video bitrate spec for the current transcode according to * the limits/requirements of the renderer. * * @param renderer a {@link RendererConfiguration} instance representing the renderer being streamed to * @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos). * @return a {@link List} of <code>String</code>s representing the video bitrate options for this transcode */ public List<String> getVideoBitrateOptions(RendererConfiguration renderer, DLNAMediaInfo media) { // media is currently unused List<String> videoBitrateOptions = new ArrayList<String>(); String sMaxVideoBitrate = renderer.getMaxVideoBitrate(); // currently Mbit/s int iMaxVideoBitrate = 0; if (sMaxVideoBitrate != null) { try { iMaxVideoBitrate = Integer.parseInt(sMaxVideoBitrate); } catch (NumberFormatException nfe) { LOGGER.error("Can't parse max video bitrate", nfe); // XXX this should be handled in RendererConfiguration } } if (iMaxVideoBitrate == 0) { // unlimited: try to preserve the bitrate videoBitrateOptions.add("-q:v"); // video qscale videoBitrateOptions.add(DEFAULT_QSCALE); } else { // limit the bitrate FIXME untested // convert megabits-per-second (as per the current option name: MaxVideoBitrateMbps) to bps // FIXME rather than dealing with megabit vs mebibit issues here, this should be left up to the client i.e. // the renderer.conf unit should be bits-per-second (and the option should be renamed: MaxVideoBitrateMbps -> MaxVideoBitrate) videoBitrateOptions.add("-maxrate"); videoBitrateOptions.add("" + iMaxVideoBitrate * 1000 * 1000); } return videoBitrateOptions; } /** * Takes a renderer and metadata for the current video and returns the audio bitrate spec for the current transcode according to * the limits/requirements of the renderer. * * @param renderer a {@link RendererConfiguration} instance representing the renderer being streamed to * @param media the media metadata for the video being streamed. May contain unset/null values (e.g. for web videos). * @return a {@link List} of <code>String</code>s representing the audio bitrate options for this transcode */ public List<String> getAudioBitrateOptions(RendererConfiguration renderer, DLNAMediaInfo media) { List<String> audioBitrateOptions = new ArrayList<String>(); audioBitrateOptions.add("-q:a"); audioBitrateOptions.add(DEFAULT_QSCALE); return audioBitrateOptions; } protected boolean dtsRemux; protected boolean ac3Remux; @Override public int purpose() { return VIDEO_SIMPLEFILE_PLAYER; } @Override // TODO make this static so it can replace ID, instead of having both public String id() { return ID; } @Override public boolean isTimeSeekable() { return true; } @Override public boolean avisynth() { return false; } public String initialString() { String threads = ""; if (configuration.isFfmpegMultithreading()) { threads = " -threads " + configuration.getNumberOfCpuCores(); } return configuration.getFfmpegSettings() + threads; } @Override public String name() { return "FFmpeg"; } @Override public int type() { return Format.VIDEO; } // unused; return this array for backwards-compatibility @Deprecated protected String[] getDefaultArgs() { List<String> defaultArgsList = new ArrayList<String>(); defaultArgsList.add("-loglevel"); defaultArgsList.add("fatal"); String[] defaultArgsArray = new String[defaultArgsList.size()]; defaultArgsList.toArray(defaultArgsArray); return defaultArgsArray; } private int[] getVideoBitrateConfig(String bitrate) { int bitrates[] = new int[2]; if (bitrate.contains("(") && bitrate.contains(")")) { bitrates[1] = Integer.parseInt(bitrate.substring(bitrate.indexOf("(") + 1, bitrate.indexOf(")"))); } if (bitrate.contains("(")) { bitrate = bitrate.substring(0, bitrate.indexOf("(")).trim(); } if (isBlank(bitrate)) { bitrate = "0"; } bitrates[0] = (int) Double.parseDouble(bitrate); return bitrates; } @Override @Deprecated public String[] args() { return getDefaultArgs(); // unused; return this array for for backwards compatibility } private List<String> getCustomArgs() { String customOptionsString = configuration.getFfmpegSettings(); if (StringUtils.isNotBlank(customOptionsString)) { LOGGER.debug("Custom ffmpeg output options: {}", customOptionsString); } String[] customOptions = StringUtils.split(customOptionsString); return new ArrayList<String>(Arrays.asList(customOptions)); } // XXX hardwired to false and not referenced anywhere else in the codebase @Deprecated public boolean mplayer() { return false; } @Override public String mimeType() { return HTTPResource.VIDEO_TRANSCODE; } @Override public String executable() { return configuration.getFfmpegPath(); } @Override public ProcessWrapper launchTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params ) throws IOException { return getFFMpegTranscode(fileName, dlna, media, params, null); } // XXX pointless redirection of launchTranscode // TODO remove this method and move its body into launchTranscode // TODO call setAudioAndSubs to populate params with audio track/subtitles metadata @Deprecated protected ProcessWrapperImpl getFFMpegTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params, String args[] ) throws IOException { int nThreads = configuration.getNumberOfCpuCores(); List<String> cmdList = new ArrayList<String>(); RendererConfiguration renderer = params.mediaRenderer; boolean avisynth = avisynth(); cmdList.add(executable()); // Prevent FFmpeg timeout cmdList.add("-y"); cmdList.add("-loglevel"); cmdList.add("warning"); if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + params.timeseek); } // decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID); ac3Remux = false; dtsRemux = false; if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) { // AC-3 remux takes priority ac3Remux = true; } else { // Now check for DTS remux and LPCM streaming dtsRemux = isTsMuxeRVideoEngineEnabled && configuration.isDTSEmbedInPCM() && params.aid != null && params.aid.isDTS() && !avisynth() && params.mediaRenderer.isDTSPlayable(); } String frameRateRatio = null; String frameRateNumber = null; if (media != null) { frameRateRatio = media.getValidFps(true); frameRateNumber = media.getValidFps(false); } // Input filename cmdList.add("-i"); if (avisynth && !fileName.toLowerCase().endsWith(".iso")) { File avsFile = AviSynthFFmpeg.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber); cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath())); } else { cmdList.add(fileName); } // encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); if (params.timeend > 0) { cmdList.add("-t"); cmdList.add("" + params.timeend); } // add video bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getVideoBitrateOptions(renderer, media)); // add audio bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getAudioBitrateOptions(renderer, media)); // if the source is too large for the renderer, resize it cmdList.addAll(getRescaleOptions(renderer, media)); int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate()); int rendererMaxBitrates[] = new int[2]; if (renderer.getMaxVideoBitrate() != null) { rendererMaxBitrates = getVideoBitrateConfig(renderer.getMaxVideoBitrate()); } if ((defaultMaxBitrates[0] == 0 && rendererMaxBitrates[0] > 0) || rendererMaxBitrates[0] < defaultMaxBitrates[0] && rendererMaxBitrates[0] > 0) { defaultMaxBitrates = rendererMaxBitrates; } if (params.mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0) { // Convert value from Mb to Kb defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0]; // Halve it since it seems to send up to 1 second of video in advance defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2; int bufSize = 1835; if (media.isHDVideo()) { bufSize = defaultMaxBitrates[0] / 3; } if (bufSize > 7000) { bufSize = 7000; } if (defaultMaxBitrates[1] > 0) { bufSize = defaultMaxBitrates[1]; } if (params.mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) { bufSize = 1835; } // Audio is always AC3 right now, so subtract the configured amount (usually 640) defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate(); // Round down to the nearest Mb defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000; // FFmpeg uses bytes for inputs instead of kbytes like MEncoder bufSize = bufSize * 1000; defaultMaxBitrates[0] = defaultMaxBitrates[0] * 1000; cmdList.add("-bufsize"); cmdList.add("" + bufSize); cmdList.add("-maxrate"); cmdList.add("" + defaultMaxBitrates[0]); } int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux) { channels = 2; } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } LOGGER.trace("channels=" + channels); // Audio bitrate - if (!(params.aid.isAC3() && !ac3Remux) && !(type() == Format.AUDIO)) { + if (!(params.aid != null && params.aid.isAC3() && !ac3Remux) && !(type() == Format.AUDIO)) { cmdList.add("-ab"); cmdList.add(configuration.getAudioBitrate() + "k"); } // add custom args cmdList.addAll(getCustomArgs()); // add the output options (-f, -acodec, -vcodec) cmdList.addAll(getTranscodeVideoOptions(renderer, media, params)); if (!dtsRemux) { cmdList.add("pipe:"); } String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs( fileName, dlna, media, params, cmdArray ); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); if (dtsRemux) { PipeProcess pipe; pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); TsMuxeRVideo ts = new TsMuxeRVideo(configuration); File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() }; pw = new ProcessWrapperImpl(cmd, params); PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); cmdList.add(ffVideoPipe.getInputPipe()); OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; String[] cmdArrayDts = new String[cmdList.size()]; cmdList.toArray(cmdArrayDts); cmdArrayDts = finalizeTranscoderArgs( this, fileName, dlna, media, params, cmdArrayDts ); ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArrayDts, ffparams); ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess(); pw.attachProcess(ff_video_pipe_process); ff_video_pipe_process.runInNewThread(); ffVideoPipe.deleteLater(); pw.attachProcess(ffVideo); ffVideo.runInNewThread(); PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); StreamModifier sm = new StreamModifier(); sm.setPcm(false); sm.setDtsembed(dtsRemux); sm.setSampleFrequency(48000); sm.setBitspersample(16); sm.setNbchannels(channels); String ffmpegLPCMextract[] = new String[]{ executable(), "-y", "-ss", "0", "-i", fileName, "-ac", "" + channels, "-f", "dts", "-c:a", "copy", ffAudioPipe.getInputPipe() }; if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS ffAudioPipe.setModifier(sm); } if (params.stdin != null) { ffmpegLPCMextract[4] = "-"; } if (params.timeseek > 0) { ffmpegLPCMextract[3] = "" + params.timeseek; } OutputParams ffaudioparams = new OutputParams(configuration); ffaudioparams.maxBufferSize = 1; ffaudioparams.stdin = params.stdin; ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams); params.stdin = null; PrintWriter pwMux = new PrintWriter(f); pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500"); String videoType = "V_MPEG-2"; if (params.no_videoencode && params.forceType != null) { videoType = params.forceType; } String fps = ""; if (params.forceFps != null) { fps = "fps=" + params.forceFps + ", "; } String audioType = "A_AC3"; if (dtsRemux) { if (params.mediaRenderer.isMuxDTSToMpeg()) { // Renderer can play proper DTS track audioType = "A_DTS"; } else { // DTS padded in LPCM trick audioType = "A_LPCM"; } } pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1"); pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2"); pwMux.close(); ProcessWrapper pipe_process = pipe.getPipeProcess(); pw.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } pipe.deleteLater(); params.input_pipes[0] = pipe; ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess(); pw.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffAudioPipe.deleteLater(); pw.attachProcess(ffAudio); ffAudio.runInNewThread(); } pw.runInNewThread(); return pw; } private JCheckBox multithreading; @Override public JComponent config() { return config("NetworkTab.5"); } protected JComponent config(String languageLabel) { FormLayout layout = new FormLayout( "left:pref, 0:grow", "p, 3dlu, p, 3dlu" ); PanelBuilder builder = new PanelBuilder(layout); builder.setBorder(Borders.EMPTY_BORDER); builder.setOpaque(false); CellConstraints cc = new CellConstraints(); JComponent cmp = builder.addSeparator(Messages.getString(languageLabel), cc.xyw(2, 1, 1)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); multithreading = new JCheckBox(Messages.getString("MEncoderVideo.35")); multithreading.setContentAreaFilled(false); if (configuration.isFfmpegMultithreading()) { multithreading.setSelected(true); } multithreading.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setFfmpegMultithreading(e.getStateChange() == ItemEvent.SELECTED); } }); builder.add(multithreading, cc.xy(2, 3)); return builder.getPanel(); } /** * {@inheritDoc} */ @Override public boolean isCompatible(DLNAResource resource) { if (resource == null || resource.getFormat().getType() != Format.VIDEO) { return false; } DLNAMediaSubtitle subtitle = resource.getMediaSubtitle(); // Check whether the subtitle actually has a language defined, // uninitialized DLNAMediaSubtitle objects have a null language. if (subtitle != null && subtitle.getLang() != null) { // The resource needs a subtitle, but this engine implementation does not support subtitles yet return false; } try { String audioTrackName = resource.getMediaAudio().toString(); String defaultAudioTrackName = resource.getMedia().getAudioTracksList().get(0).toString(); if (!audioTrackName.equals(defaultAudioTrackName)) { // This engine implementation only supports playback of the default audio track at this time return false; } } catch (NullPointerException e) { LOGGER.trace("FFmpeg cannot determine compatibility based on audio track for " + resource.getSystemName()); } catch (IndexOutOfBoundsException e) { LOGGER.trace("FFmpeg cannot determine compatibility based on default audio track for " + resource.getSystemName()); } Format format = resource.getFormat(); if (format != null) { Format.Identifier id = format.getIdentifier(); if (id.equals(Format.Identifier.MKV) || id.equals(Format.Identifier.MPG)) { return true; } } return false; } }
true
true
protected ProcessWrapperImpl getFFMpegTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params, String args[] ) throws IOException { int nThreads = configuration.getNumberOfCpuCores(); List<String> cmdList = new ArrayList<String>(); RendererConfiguration renderer = params.mediaRenderer; boolean avisynth = avisynth(); cmdList.add(executable()); // Prevent FFmpeg timeout cmdList.add("-y"); cmdList.add("-loglevel"); cmdList.add("warning"); if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + params.timeseek); } // decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID); ac3Remux = false; dtsRemux = false; if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) { // AC-3 remux takes priority ac3Remux = true; } else { // Now check for DTS remux and LPCM streaming dtsRemux = isTsMuxeRVideoEngineEnabled && configuration.isDTSEmbedInPCM() && params.aid != null && params.aid.isDTS() && !avisynth() && params.mediaRenderer.isDTSPlayable(); } String frameRateRatio = null; String frameRateNumber = null; if (media != null) { frameRateRatio = media.getValidFps(true); frameRateNumber = media.getValidFps(false); } // Input filename cmdList.add("-i"); if (avisynth && !fileName.toLowerCase().endsWith(".iso")) { File avsFile = AviSynthFFmpeg.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber); cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath())); } else { cmdList.add(fileName); } // encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); if (params.timeend > 0) { cmdList.add("-t"); cmdList.add("" + params.timeend); } // add video bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getVideoBitrateOptions(renderer, media)); // add audio bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getAudioBitrateOptions(renderer, media)); // if the source is too large for the renderer, resize it cmdList.addAll(getRescaleOptions(renderer, media)); int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate()); int rendererMaxBitrates[] = new int[2]; if (renderer.getMaxVideoBitrate() != null) { rendererMaxBitrates = getVideoBitrateConfig(renderer.getMaxVideoBitrate()); } if ((defaultMaxBitrates[0] == 0 && rendererMaxBitrates[0] > 0) || rendererMaxBitrates[0] < defaultMaxBitrates[0] && rendererMaxBitrates[0] > 0) { defaultMaxBitrates = rendererMaxBitrates; } if (params.mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0) { // Convert value from Mb to Kb defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0]; // Halve it since it seems to send up to 1 second of video in advance defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2; int bufSize = 1835; if (media.isHDVideo()) { bufSize = defaultMaxBitrates[0] / 3; } if (bufSize > 7000) { bufSize = 7000; } if (defaultMaxBitrates[1] > 0) { bufSize = defaultMaxBitrates[1]; } if (params.mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) { bufSize = 1835; } // Audio is always AC3 right now, so subtract the configured amount (usually 640) defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate(); // Round down to the nearest Mb defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000; // FFmpeg uses bytes for inputs instead of kbytes like MEncoder bufSize = bufSize * 1000; defaultMaxBitrates[0] = defaultMaxBitrates[0] * 1000; cmdList.add("-bufsize"); cmdList.add("" + bufSize); cmdList.add("-maxrate"); cmdList.add("" + defaultMaxBitrates[0]); } int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux) { channels = 2; } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } LOGGER.trace("channels=" + channels); // Audio bitrate if (!(params.aid.isAC3() && !ac3Remux) && !(type() == Format.AUDIO)) { cmdList.add("-ab"); cmdList.add(configuration.getAudioBitrate() + "k"); } // add custom args cmdList.addAll(getCustomArgs()); // add the output options (-f, -acodec, -vcodec) cmdList.addAll(getTranscodeVideoOptions(renderer, media, params)); if (!dtsRemux) { cmdList.add("pipe:"); } String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs( fileName, dlna, media, params, cmdArray ); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); if (dtsRemux) { PipeProcess pipe; pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); TsMuxeRVideo ts = new TsMuxeRVideo(configuration); File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() }; pw = new ProcessWrapperImpl(cmd, params); PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); cmdList.add(ffVideoPipe.getInputPipe()); OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; String[] cmdArrayDts = new String[cmdList.size()]; cmdList.toArray(cmdArrayDts); cmdArrayDts = finalizeTranscoderArgs( this, fileName, dlna, media, params, cmdArrayDts ); ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArrayDts, ffparams); ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess(); pw.attachProcess(ff_video_pipe_process); ff_video_pipe_process.runInNewThread(); ffVideoPipe.deleteLater(); pw.attachProcess(ffVideo); ffVideo.runInNewThread(); PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); StreamModifier sm = new StreamModifier(); sm.setPcm(false); sm.setDtsembed(dtsRemux); sm.setSampleFrequency(48000); sm.setBitspersample(16); sm.setNbchannels(channels); String ffmpegLPCMextract[] = new String[]{ executable(), "-y", "-ss", "0", "-i", fileName, "-ac", "" + channels, "-f", "dts", "-c:a", "copy", ffAudioPipe.getInputPipe() }; if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS ffAudioPipe.setModifier(sm); } if (params.stdin != null) { ffmpegLPCMextract[4] = "-"; } if (params.timeseek > 0) { ffmpegLPCMextract[3] = "" + params.timeseek; } OutputParams ffaudioparams = new OutputParams(configuration); ffaudioparams.maxBufferSize = 1; ffaudioparams.stdin = params.stdin; ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams); params.stdin = null; PrintWriter pwMux = new PrintWriter(f); pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500"); String videoType = "V_MPEG-2"; if (params.no_videoencode && params.forceType != null) { videoType = params.forceType; } String fps = ""; if (params.forceFps != null) { fps = "fps=" + params.forceFps + ", "; } String audioType = "A_AC3"; if (dtsRemux) { if (params.mediaRenderer.isMuxDTSToMpeg()) { // Renderer can play proper DTS track audioType = "A_DTS"; } else { // DTS padded in LPCM trick audioType = "A_LPCM"; } } pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1"); pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2"); pwMux.close(); ProcessWrapper pipe_process = pipe.getPipeProcess(); pw.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } pipe.deleteLater(); params.input_pipes[0] = pipe; ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess(); pw.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffAudioPipe.deleteLater(); pw.attachProcess(ffAudio); ffAudio.runInNewThread(); } pw.runInNewThread(); return pw; }
protected ProcessWrapperImpl getFFMpegTranscode( String fileName, DLNAResource dlna, DLNAMediaInfo media, OutputParams params, String args[] ) throws IOException { int nThreads = configuration.getNumberOfCpuCores(); List<String> cmdList = new ArrayList<String>(); RendererConfiguration renderer = params.mediaRenderer; boolean avisynth = avisynth(); cmdList.add(executable()); // Prevent FFmpeg timeout cmdList.add("-y"); cmdList.add("-loglevel"); cmdList.add("warning"); if (params.timeseek > 0) { cmdList.add("-ss"); cmdList.add("" + params.timeseek); } // decoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); final boolean isTsMuxeRVideoEngineEnabled = configuration.getEnginesAsList(PMS.get().getRegistry()).contains(TsMuxeRVideo.ID); ac3Remux = false; dtsRemux = false; if (configuration.isRemuxAC3() && params.aid != null && params.aid.isAC3() && !avisynth() && params.mediaRenderer.isTranscodeToAC3()) { // AC-3 remux takes priority ac3Remux = true; } else { // Now check for DTS remux and LPCM streaming dtsRemux = isTsMuxeRVideoEngineEnabled && configuration.isDTSEmbedInPCM() && params.aid != null && params.aid.isDTS() && !avisynth() && params.mediaRenderer.isDTSPlayable(); } String frameRateRatio = null; String frameRateNumber = null; if (media != null) { frameRateRatio = media.getValidFps(true); frameRateNumber = media.getValidFps(false); } // Input filename cmdList.add("-i"); if (avisynth && !fileName.toLowerCase().endsWith(".iso")) { File avsFile = AviSynthFFmpeg.getAVSScript(fileName, params.sid, params.fromFrame, params.toFrame, frameRateRatio, frameRateNumber); cmdList.add(ProcessUtil.getShortFileNameIfWideChars(avsFile.getAbsolutePath())); } else { cmdList.add(fileName); } // encoder threads cmdList.add("-threads"); cmdList.add("" + nThreads); if (params.timeend > 0) { cmdList.add("-t"); cmdList.add("" + params.timeend); } // add video bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getVideoBitrateOptions(renderer, media)); // add audio bitrate options // TODO: Integrate our (more comprehensive) code with this function // from PMS to make keeping synchronised easier. // Until then, leave the following line commented out. // cmdList.addAll(getAudioBitrateOptions(renderer, media)); // if the source is too large for the renderer, resize it cmdList.addAll(getRescaleOptions(renderer, media)); int defaultMaxBitrates[] = getVideoBitrateConfig(configuration.getMaximumBitrate()); int rendererMaxBitrates[] = new int[2]; if (renderer.getMaxVideoBitrate() != null) { rendererMaxBitrates = getVideoBitrateConfig(renderer.getMaxVideoBitrate()); } if ((defaultMaxBitrates[0] == 0 && rendererMaxBitrates[0] > 0) || rendererMaxBitrates[0] < defaultMaxBitrates[0] && rendererMaxBitrates[0] > 0) { defaultMaxBitrates = rendererMaxBitrates; } if (params.mediaRenderer.getCBRVideoBitrate() == 0 && defaultMaxBitrates[0] > 0) { // Convert value from Mb to Kb defaultMaxBitrates[0] = 1000 * defaultMaxBitrates[0]; // Halve it since it seems to send up to 1 second of video in advance defaultMaxBitrates[0] = defaultMaxBitrates[0] / 2; int bufSize = 1835; if (media.isHDVideo()) { bufSize = defaultMaxBitrates[0] / 3; } if (bufSize > 7000) { bufSize = 7000; } if (defaultMaxBitrates[1] > 0) { bufSize = defaultMaxBitrates[1]; } if (params.mediaRenderer.isDefaultVBVSize() && rendererMaxBitrates[1] == 0) { bufSize = 1835; } // Audio is always AC3 right now, so subtract the configured amount (usually 640) defaultMaxBitrates[0] = defaultMaxBitrates[0] - configuration.getAudioBitrate(); // Round down to the nearest Mb defaultMaxBitrates[0] = defaultMaxBitrates[0] / 1000 * 1000; // FFmpeg uses bytes for inputs instead of kbytes like MEncoder bufSize = bufSize * 1000; defaultMaxBitrates[0] = defaultMaxBitrates[0] * 1000; cmdList.add("-bufsize"); cmdList.add("" + bufSize); cmdList.add("-maxrate"); cmdList.add("" + defaultMaxBitrates[0]); } int channels; if (ac3Remux) { channels = params.aid.getAudioProperties().getNumberOfChannels(); // AC-3 remux } else if (dtsRemux) { channels = 2; } else { channels = configuration.getAudioChannelCount(); // 5.1 max for AC-3 encoding } LOGGER.trace("channels=" + channels); // Audio bitrate if (!(params.aid != null && params.aid.isAC3() && !ac3Remux) && !(type() == Format.AUDIO)) { cmdList.add("-ab"); cmdList.add(configuration.getAudioBitrate() + "k"); } // add custom args cmdList.addAll(getCustomArgs()); // add the output options (-f, -acodec, -vcodec) cmdList.addAll(getTranscodeVideoOptions(renderer, media, params)); if (!dtsRemux) { cmdList.add("pipe:"); } String[] cmdArray = new String[cmdList.size()]; cmdList.toArray(cmdArray); cmdArray = finalizeTranscoderArgs( fileName, dlna, media, params, cmdArray ); ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); if (dtsRemux) { PipeProcess pipe; pipe = new PipeProcess(System.currentTimeMillis() + "tsmuxerout.ts"); TsMuxeRVideo ts = new TsMuxeRVideo(configuration); File f = new File(configuration.getTempFolder(), "pms-tsmuxer.meta"); String cmd[] = new String[]{ ts.executable(), f.getAbsolutePath(), pipe.getInputPipe() }; pw = new ProcessWrapperImpl(cmd, params); PipeIPCProcess ffVideoPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegvideo", System.currentTimeMillis() + "videoout", false, true); cmdList.add(ffVideoPipe.getInputPipe()); OutputParams ffparams = new OutputParams(configuration); ffparams.maxBufferSize = 1; ffparams.stdin = params.stdin; String[] cmdArrayDts = new String[cmdList.size()]; cmdList.toArray(cmdArrayDts); cmdArrayDts = finalizeTranscoderArgs( this, fileName, dlna, media, params, cmdArrayDts ); ProcessWrapperImpl ffVideo = new ProcessWrapperImpl(cmdArrayDts, ffparams); ProcessWrapper ff_video_pipe_process = ffVideoPipe.getPipeProcess(); pw.attachProcess(ff_video_pipe_process); ff_video_pipe_process.runInNewThread(); ffVideoPipe.deleteLater(); pw.attachProcess(ffVideo); ffVideo.runInNewThread(); PipeIPCProcess ffAudioPipe = new PipeIPCProcess(System.currentTimeMillis() + "ffmpegaudio01", System.currentTimeMillis() + "audioout", false, true); StreamModifier sm = new StreamModifier(); sm.setPcm(false); sm.setDtsembed(dtsRemux); sm.setSampleFrequency(48000); sm.setBitspersample(16); sm.setNbchannels(channels); String ffmpegLPCMextract[] = new String[]{ executable(), "-y", "-ss", "0", "-i", fileName, "-ac", "" + channels, "-f", "dts", "-c:a", "copy", ffAudioPipe.getInputPipe() }; if (!params.mediaRenderer.isMuxDTSToMpeg()) { // No need to use the PCM trick when media renderer supports DTS ffAudioPipe.setModifier(sm); } if (params.stdin != null) { ffmpegLPCMextract[4] = "-"; } if (params.timeseek > 0) { ffmpegLPCMextract[3] = "" + params.timeseek; } OutputParams ffaudioparams = new OutputParams(configuration); ffaudioparams.maxBufferSize = 1; ffaudioparams.stdin = params.stdin; ProcessWrapperImpl ffAudio = new ProcessWrapperImpl(ffmpegLPCMextract, ffaudioparams); params.stdin = null; PrintWriter pwMux = new PrintWriter(f); pwMux.println("MUXOPT --no-pcr-on-video-pid --no-asyncio --new-audio-pes --vbr --vbv-len=500"); String videoType = "V_MPEG-2"; if (params.no_videoencode && params.forceType != null) { videoType = params.forceType; } String fps = ""; if (params.forceFps != null) { fps = "fps=" + params.forceFps + ", "; } String audioType = "A_AC3"; if (dtsRemux) { if (params.mediaRenderer.isMuxDTSToMpeg()) { // Renderer can play proper DTS track audioType = "A_DTS"; } else { // DTS padded in LPCM trick audioType = "A_LPCM"; } } pwMux.println(videoType + ", \"" + ffVideoPipe.getOutputPipe() + "\", " + fps + "level=4.1, insertSEI, contSPS, track=1"); pwMux.println(audioType + ", \"" + ffAudioPipe.getOutputPipe() + "\", track=2"); pwMux.close(); ProcessWrapper pipe_process = pipe.getPipeProcess(); pw.attachProcess(pipe_process); pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } pipe.deleteLater(); params.input_pipes[0] = pipe; ProcessWrapper ff_pipe_process = ffAudioPipe.getPipeProcess(); pw.attachProcess(ff_pipe_process); ff_pipe_process.runInNewThread(); try { Thread.sleep(50); } catch (InterruptedException e) { } ffAudioPipe.deleteLater(); pw.attachProcess(ffAudio); ffAudio.runInNewThread(); } pw.runInNewThread(); return pw; }
diff --git a/Application/src/mvhsbandinventory/Display.java b/Application/src/mvhsbandinventory/Display.java index c0a7464..4332710 100644 --- a/Application/src/mvhsbandinventory/Display.java +++ b/Application/src/mvhsbandinventory/Display.java @@ -1,708 +1,708 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mvhsbandinventory; /** * * @author nicholson */ public class Display extends javax.swing.JPanel implements java.beans.Customizer { private Object bean; /** Creates new customizer DispTest */ public Display() { initComponents(); } public void setObject(Object bean) { this.bean = bean; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); infoTabs = new javax.swing.JTabbedPane(); detailPanel = new javax.swing.JPanel(); statusLabel = new javax.swing.JLabel(); statusCombo = new javax.swing.JComboBox(); instrumentLabel = new javax.swing.JLabel(); instruBox = new javax.swing.JTextField(); brandLabel = new javax.swing.JLabel(); brandBox = new javax.swing.JTextField(); serialLabel = new javax.swing.JLabel(); serialBox = new javax.swing.JTextField(); rankLabel = new javax.swing.JLabel(); rankBox = new javax.swing.JTextField(); valueLabel = new javax.swing.JLabel(); valueBox = new javax.swing.JTextField(); strapLabel = new javax.swing.JLabel(); strapCombo = new javax.swing.JComboBox(); ligatureLabel = new javax.swing.JLabel(); ligCombo = new javax.swing.JComboBox(); mpieceLabel = new javax.swing.JLabel(); mpieceCombo = new javax.swing.JComboBox(); capLabel = new javax.swing.JLabel(); capCombo = new javax.swing.JComboBox(); bowLabel = new javax.swing.JLabel(); bowCombo = new javax.swing.JComboBox(); noteLabel = new javax.swing.JLabel(); jScrollPane5 = new javax.swing.JScrollPane(); notesTPane = new javax.swing.JTextPane(); historyPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); checkoutPanel = new javax.swing.JPanel(); instrumentLabel1 = new javax.swing.JLabel(); instruBox1 = new javax.swing.JTextField(); brandLabel1 = new javax.swing.JLabel(); brandBox1 = new javax.swing.JTextField(); serialLabel1 = new javax.swing.JLabel(); serialBox1 = new javax.swing.JTextField(); strapLabel1 = new javax.swing.JLabel(); strapCombo1 = new javax.swing.JComboBox(); ligatureLabel1 = new javax.swing.JLabel(); ligCombo1 = new javax.swing.JComboBox(); noteLabel1 = new javax.swing.JLabel(); otherBox = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); formButton = new javax.swing.JButton(); outButton = new javax.swing.JButton(); inButton = new javax.swing.JButton(); lostButton = new javax.swing.JButton(); buffer = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); jPanel8 = new javax.swing.JPanel(); searchCombo = new javax.swing.JComboBox(); searchBar = new javax.swing.JTextField(); jScrollPane4 = new javax.swing.JScrollPane(); instrumentTable = new javax.swing.JTable(); searchButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); advSearchButton = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); jSplitPane1.setAutoscrolls(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setName(""); // NOI18N jPanel1.setLayout(new java.awt.BorderLayout()); detailPanel.setLayout(new java.awt.GridBagLayout()); statusLabel.setText("Status:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(statusLabel, gridBagConstraints); statusCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "In Storage", "At Shop", "On Loan", "Missing" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(statusCombo, gridBagConstraints); instrumentLabel.setText("Instrument:"); instrumentLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(instrumentLabel, gridBagConstraints); instruBox.setEditable(false); instruBox.setAutoscrolls(false); instruBox.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox.setPreferredSize(null); instruBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(instruBox, gridBagConstraints); brandLabel.setText("Brand:"); brandLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(brandLabel, gridBagConstraints); brandBox.setEditable(false); brandBox.setAutoscrolls(false); brandBox.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(brandBox, gridBagConstraints); serialLabel.setText("Serial Number:"); serialLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(serialLabel, gridBagConstraints); serialBox.setEditable(false); serialBox.setAutoscrolls(false); serialBox.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(serialBox, gridBagConstraints); rankLabel.setText("Rank:"); rankLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(rankLabel, gridBagConstraints); rankBox.setHorizontalAlignment(javax.swing.JTextField.CENTER); rankBox.setText("3"); rankBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(rankBox, gridBagConstraints); valueLabel.setText("Value: $"); valueLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(valueLabel, gridBagConstraints); valueBox.setHorizontalAlignment(javax.swing.JTextField.RIGHT); valueBox.setText("0"); valueBox.setAutoscrolls(false); valueBox.setMinimumSize(new java.awt.Dimension(200, 20)); valueBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 95; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(valueBox, gridBagConstraints); strapLabel.setText("Neck Strap:"); strapLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(strapLabel, gridBagConstraints); strapCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); strapCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(strapCombo, gridBagConstraints); ligatureLabel.setText("Ligature:"); ligatureLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(ligatureLabel, gridBagConstraints); ligCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); ligCombo.setPreferredSize(null); ligCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(ligCombo, gridBagConstraints); mpieceLabel.setText("Mouthpiece:"); mpieceLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(mpieceLabel, gridBagConstraints); mpieceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); mpieceCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(mpieceCombo, gridBagConstraints); capLabel.setText("Mouthpiece Cap:"); capLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(capLabel, gridBagConstraints); capCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); capCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(capCombo, gridBagConstraints); bowLabel.setText("Bow:"); bowLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(bowLabel, gridBagConstraints); bowCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); bowCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(bowCombo, gridBagConstraints); noteLabel.setText("Notes:"); noteLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; detailPanel.add(noteLabel, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(25, 25)); jScrollPane5.setPreferredSize(null); notesTPane.setMinimumSize(new java.awt.Dimension(25, 25)); notesTPane.setPreferredSize(null); jScrollPane5.setViewportView(notesTPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; detailPanel.add(jScrollPane5, gridBagConstraints); infoTabs.addTab("Details", detailPanel); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Date", "Event" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable1.setPreferredSize(new java.awt.Dimension(100, 64)); jScrollPane1.setViewportView(jTable1); org.jdesktop.layout.GroupLayout historyPanelLayout = new org.jdesktop.layout.GroupLayout(historyPanel); historyPanel.setLayout(historyPanelLayout); historyPanelLayout.setHorizontalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(historyPanelLayout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 935, Short.MAX_VALUE) .addContainerGap()) ); historyPanelLayout.setVerticalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) - .add(org.jdesktop.layout.GroupLayout.TRAILING, historyPanelLayout.createSequentialGroup() + .add(historyPanelLayout.createSequentialGroup() .addContainerGap() - .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE) - .add(342, 342, 342)) + .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE) + .addContainerGap()) ); infoTabs.addTab("History", historyPanel); checkoutPanel.setLayout(new java.awt.GridBagLayout()); instrumentLabel1.setText("Owner:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(instrumentLabel1, gridBagConstraints); instruBox1.setAutoscrolls(false); instruBox1.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox1.setPreferredSize(null); instruBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBox1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(instruBox1, gridBagConstraints); brandLabel1.setText("School Year:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(brandLabel1, gridBagConstraints); brandBox1.setAutoscrolls(false); brandBox1.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(brandBox1, gridBagConstraints); serialLabel1.setText("Date Out:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(serialLabel1, gridBagConstraints); serialBox1.setAutoscrolls(false); serialBox1.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(serialBox1, gridBagConstraints); strapLabel1.setText("Fee Paid:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(strapLabel1, gridBagConstraints); strapCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Paid", "Unpaid", "Waived", " " })); strapCombo1.setSelectedIndex(1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(strapCombo1, gridBagConstraints); ligatureLabel1.setText("For Use In:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(ligatureLabel1, gridBagConstraints); ligCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" })); ligCombo1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligCombo1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(ligCombo1, gridBagConstraints); noteLabel1.setText("Other:"); noteLabel1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(noteLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkoutPanel.add(otherBox, gridBagConstraints); jPanel3.setPreferredSize(new java.awt.Dimension(107, 23)); formButton.setText("Generate Form"); jPanel3.add(formButton); outButton.setText("Check Out"); jPanel3.add(outButton); inButton.setText("Check In"); jPanel3.add(inButton); lostButton.setText("Lost"); jPanel3.add(lostButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.ipady = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; checkoutPanel.add(jPanel3, gridBagConstraints); org.jdesktop.layout.GroupLayout bufferLayout = new org.jdesktop.layout.GroupLayout(buffer); buffer.setLayout(bufferLayout); bufferLayout.setHorizontalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); bufferLayout.setVerticalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.weighty = 2.0; checkoutPanel.add(buffer, gridBagConstraints); infoTabs.addTab("Check In/Out", checkoutPanel); jPanel1.add(infoTabs, java.awt.BorderLayout.CENTER); jPanel2.setLayout(new java.awt.GridBagLayout()); saveButton.setText("SAVE CHANGES"); saveButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(saveButton, gridBagConstraints); cancelButton.setText("CANCEL CHANGES"); cancelButton.setPreferredSize(null); jPanel2.add(cancelButton, new java.awt.GridBagConstraints()); deleteButton.setText("DELETE INSTRUMENT"); deleteButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; jPanel2.add(deleteButton, gridBagConstraints); jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH); jSplitPane1.setRightComponent(jPanel1); searchCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Brand", "Serial #", "Rank", "Value", "Status", "Ligature", "Mouthpiece", "Mouthpiece Cap", "Bow" })); searchCombo.setPreferredSize(null); searchCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchComboActionPerformed(evt); } }); searchBar.setText("Search Bar"); searchBar.setPreferredSize(null); searchBar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchBarActionPerformed(evt); } }); jScrollPane4.setPreferredSize(null); instrumentTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Instrument", "Brand", "Serial #" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); instrumentTable.setPreferredSize(null); jScrollPane4.setViewportView(instrumentTable); searchButton.setText("Search"); searchButton.setPreferredSize(null); addButton.setText("Add New Instrument"); addButton.setPreferredSize(null); advSearchButton.setText("ADVANCED SEARCH"); advSearchButton.setPreferredSize(null); org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .add(jPanel8Layout.createSequentialGroup() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jPanel8Layout.createSequentialGroup() .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(searchBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 745, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane1.setLeftComponent(jPanel8); add(jSplitPane1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void searchComboActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_searchComboActionPerformed {//GEN-HEADEREND:event_searchComboActionPerformed // TODO add your handling code here: }//GEN-LAST:event_searchComboActionPerformed private void searchBarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_searchBarActionPerformed {//GEN-HEADEREND:event_searchBarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_searchBarActionPerformed private void instruBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_instruBoxActionPerformed {//GEN-HEADEREND:event_instruBoxActionPerformed // TODO add your handling code here: }//GEN-LAST:event_instruBoxActionPerformed private void ligComboActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ligComboActionPerformed {//GEN-HEADEREND:event_ligComboActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ligComboActionPerformed private void instruBox1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_instruBox1ActionPerformed {//GEN-HEADEREND:event_instruBox1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_instruBox1ActionPerformed private void ligCombo1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_ligCombo1ActionPerformed {//GEN-HEADEREND:event_ligCombo1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ligCombo1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JButton advSearchButton; private javax.swing.JComboBox bowCombo; private javax.swing.JLabel bowLabel; private javax.swing.JTextField brandBox; private javax.swing.JTextField brandBox1; private javax.swing.JLabel brandLabel; private javax.swing.JLabel brandLabel1; private javax.swing.JPanel buffer; private javax.swing.JButton cancelButton; private javax.swing.JComboBox capCombo; private javax.swing.JLabel capLabel; private javax.swing.JPanel checkoutPanel; private javax.swing.JButton deleteButton; private javax.swing.JPanel detailPanel; private javax.swing.JButton formButton; private javax.swing.JPanel historyPanel; private javax.swing.JButton inButton; private javax.swing.JTabbedPane infoTabs; private javax.swing.JTextField instruBox; private javax.swing.JTextField instruBox1; private javax.swing.JLabel instrumentLabel; private javax.swing.JLabel instrumentLabel1; private javax.swing.JTable instrumentTable; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTable jTable1; private javax.swing.JComboBox ligCombo; private javax.swing.JComboBox ligCombo1; private javax.swing.JLabel ligatureLabel; private javax.swing.JLabel ligatureLabel1; private javax.swing.JButton lostButton; private javax.swing.JComboBox mpieceCombo; private javax.swing.JLabel mpieceLabel; private javax.swing.JLabel noteLabel; private javax.swing.JLabel noteLabel1; private javax.swing.JTextPane notesTPane; private javax.swing.JTextField otherBox; private javax.swing.JButton outButton; private javax.swing.JTextField rankBox; private javax.swing.JLabel rankLabel; private javax.swing.JButton saveButton; private javax.swing.JTextField searchBar; private javax.swing.JButton searchButton; private javax.swing.JComboBox searchCombo; private javax.swing.JTextField serialBox; private javax.swing.JTextField serialBox1; private javax.swing.JLabel serialLabel; private javax.swing.JLabel serialLabel1; private javax.swing.JComboBox statusCombo; private javax.swing.JLabel statusLabel; private javax.swing.JComboBox strapCombo; private javax.swing.JComboBox strapCombo1; private javax.swing.JLabel strapLabel; private javax.swing.JLabel strapLabel1; private javax.swing.JTextField valueBox; private javax.swing.JLabel valueLabel; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); infoTabs = new javax.swing.JTabbedPane(); detailPanel = new javax.swing.JPanel(); statusLabel = new javax.swing.JLabel(); statusCombo = new javax.swing.JComboBox(); instrumentLabel = new javax.swing.JLabel(); instruBox = new javax.swing.JTextField(); brandLabel = new javax.swing.JLabel(); brandBox = new javax.swing.JTextField(); serialLabel = new javax.swing.JLabel(); serialBox = new javax.swing.JTextField(); rankLabel = new javax.swing.JLabel(); rankBox = new javax.swing.JTextField(); valueLabel = new javax.swing.JLabel(); valueBox = new javax.swing.JTextField(); strapLabel = new javax.swing.JLabel(); strapCombo = new javax.swing.JComboBox(); ligatureLabel = new javax.swing.JLabel(); ligCombo = new javax.swing.JComboBox(); mpieceLabel = new javax.swing.JLabel(); mpieceCombo = new javax.swing.JComboBox(); capLabel = new javax.swing.JLabel(); capCombo = new javax.swing.JComboBox(); bowLabel = new javax.swing.JLabel(); bowCombo = new javax.swing.JComboBox(); noteLabel = new javax.swing.JLabel(); jScrollPane5 = new javax.swing.JScrollPane(); notesTPane = new javax.swing.JTextPane(); historyPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); checkoutPanel = new javax.swing.JPanel(); instrumentLabel1 = new javax.swing.JLabel(); instruBox1 = new javax.swing.JTextField(); brandLabel1 = new javax.swing.JLabel(); brandBox1 = new javax.swing.JTextField(); serialLabel1 = new javax.swing.JLabel(); serialBox1 = new javax.swing.JTextField(); strapLabel1 = new javax.swing.JLabel(); strapCombo1 = new javax.swing.JComboBox(); ligatureLabel1 = new javax.swing.JLabel(); ligCombo1 = new javax.swing.JComboBox(); noteLabel1 = new javax.swing.JLabel(); otherBox = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); formButton = new javax.swing.JButton(); outButton = new javax.swing.JButton(); inButton = new javax.swing.JButton(); lostButton = new javax.swing.JButton(); buffer = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); jPanel8 = new javax.swing.JPanel(); searchCombo = new javax.swing.JComboBox(); searchBar = new javax.swing.JTextField(); jScrollPane4 = new javax.swing.JScrollPane(); instrumentTable = new javax.swing.JTable(); searchButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); advSearchButton = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); jSplitPane1.setAutoscrolls(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setName(""); // NOI18N jPanel1.setLayout(new java.awt.BorderLayout()); detailPanel.setLayout(new java.awt.GridBagLayout()); statusLabel.setText("Status:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(statusLabel, gridBagConstraints); statusCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "In Storage", "At Shop", "On Loan", "Missing" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(statusCombo, gridBagConstraints); instrumentLabel.setText("Instrument:"); instrumentLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(instrumentLabel, gridBagConstraints); instruBox.setEditable(false); instruBox.setAutoscrolls(false); instruBox.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox.setPreferredSize(null); instruBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(instruBox, gridBagConstraints); brandLabel.setText("Brand:"); brandLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(brandLabel, gridBagConstraints); brandBox.setEditable(false); brandBox.setAutoscrolls(false); brandBox.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(brandBox, gridBagConstraints); serialLabel.setText("Serial Number:"); serialLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(serialLabel, gridBagConstraints); serialBox.setEditable(false); serialBox.setAutoscrolls(false); serialBox.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(serialBox, gridBagConstraints); rankLabel.setText("Rank:"); rankLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(rankLabel, gridBagConstraints); rankBox.setHorizontalAlignment(javax.swing.JTextField.CENTER); rankBox.setText("3"); rankBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(rankBox, gridBagConstraints); valueLabel.setText("Value: $"); valueLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(valueLabel, gridBagConstraints); valueBox.setHorizontalAlignment(javax.swing.JTextField.RIGHT); valueBox.setText("0"); valueBox.setAutoscrolls(false); valueBox.setMinimumSize(new java.awt.Dimension(200, 20)); valueBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 95; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(valueBox, gridBagConstraints); strapLabel.setText("Neck Strap:"); strapLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(strapLabel, gridBagConstraints); strapCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); strapCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(strapCombo, gridBagConstraints); ligatureLabel.setText("Ligature:"); ligatureLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(ligatureLabel, gridBagConstraints); ligCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); ligCombo.setPreferredSize(null); ligCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(ligCombo, gridBagConstraints); mpieceLabel.setText("Mouthpiece:"); mpieceLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(mpieceLabel, gridBagConstraints); mpieceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); mpieceCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(mpieceCombo, gridBagConstraints); capLabel.setText("Mouthpiece Cap:"); capLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(capLabel, gridBagConstraints); capCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); capCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(capCombo, gridBagConstraints); bowLabel.setText("Bow:"); bowLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(bowLabel, gridBagConstraints); bowCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); bowCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(bowCombo, gridBagConstraints); noteLabel.setText("Notes:"); noteLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; detailPanel.add(noteLabel, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(25, 25)); jScrollPane5.setPreferredSize(null); notesTPane.setMinimumSize(new java.awt.Dimension(25, 25)); notesTPane.setPreferredSize(null); jScrollPane5.setViewportView(notesTPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; detailPanel.add(jScrollPane5, gridBagConstraints); infoTabs.addTab("Details", detailPanel); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Date", "Event" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable1.setPreferredSize(new java.awt.Dimension(100, 64)); jScrollPane1.setViewportView(jTable1); org.jdesktop.layout.GroupLayout historyPanelLayout = new org.jdesktop.layout.GroupLayout(historyPanel); historyPanel.setLayout(historyPanelLayout); historyPanelLayout.setHorizontalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(historyPanelLayout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 935, Short.MAX_VALUE) .addContainerGap()) ); historyPanelLayout.setVerticalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, historyPanelLayout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE) .add(342, 342, 342)) ); infoTabs.addTab("History", historyPanel); checkoutPanel.setLayout(new java.awt.GridBagLayout()); instrumentLabel1.setText("Owner:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(instrumentLabel1, gridBagConstraints); instruBox1.setAutoscrolls(false); instruBox1.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox1.setPreferredSize(null); instruBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBox1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(instruBox1, gridBagConstraints); brandLabel1.setText("School Year:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(brandLabel1, gridBagConstraints); brandBox1.setAutoscrolls(false); brandBox1.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(brandBox1, gridBagConstraints); serialLabel1.setText("Date Out:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(serialLabel1, gridBagConstraints); serialBox1.setAutoscrolls(false); serialBox1.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(serialBox1, gridBagConstraints); strapLabel1.setText("Fee Paid:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(strapLabel1, gridBagConstraints); strapCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Paid", "Unpaid", "Waived", " " })); strapCombo1.setSelectedIndex(1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(strapCombo1, gridBagConstraints); ligatureLabel1.setText("For Use In:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(ligatureLabel1, gridBagConstraints); ligCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" })); ligCombo1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligCombo1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(ligCombo1, gridBagConstraints); noteLabel1.setText("Other:"); noteLabel1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(noteLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkoutPanel.add(otherBox, gridBagConstraints); jPanel3.setPreferredSize(new java.awt.Dimension(107, 23)); formButton.setText("Generate Form"); jPanel3.add(formButton); outButton.setText("Check Out"); jPanel3.add(outButton); inButton.setText("Check In"); jPanel3.add(inButton); lostButton.setText("Lost"); jPanel3.add(lostButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.ipady = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; checkoutPanel.add(jPanel3, gridBagConstraints); org.jdesktop.layout.GroupLayout bufferLayout = new org.jdesktop.layout.GroupLayout(buffer); buffer.setLayout(bufferLayout); bufferLayout.setHorizontalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); bufferLayout.setVerticalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.weighty = 2.0; checkoutPanel.add(buffer, gridBagConstraints); infoTabs.addTab("Check In/Out", checkoutPanel); jPanel1.add(infoTabs, java.awt.BorderLayout.CENTER); jPanel2.setLayout(new java.awt.GridBagLayout()); saveButton.setText("SAVE CHANGES"); saveButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(saveButton, gridBagConstraints); cancelButton.setText("CANCEL CHANGES"); cancelButton.setPreferredSize(null); jPanel2.add(cancelButton, new java.awt.GridBagConstraints()); deleteButton.setText("DELETE INSTRUMENT"); deleteButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; jPanel2.add(deleteButton, gridBagConstraints); jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH); jSplitPane1.setRightComponent(jPanel1); searchCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Brand", "Serial #", "Rank", "Value", "Status", "Ligature", "Mouthpiece", "Mouthpiece Cap", "Bow" })); searchCombo.setPreferredSize(null); searchCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchComboActionPerformed(evt); } }); searchBar.setText("Search Bar"); searchBar.setPreferredSize(null); searchBar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchBarActionPerformed(evt); } }); jScrollPane4.setPreferredSize(null); instrumentTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Instrument", "Brand", "Serial #" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); instrumentTable.setPreferredSize(null); jScrollPane4.setViewportView(instrumentTable); searchButton.setText("Search"); searchButton.setPreferredSize(null); addButton.setText("Add New Instrument"); addButton.setPreferredSize(null); advSearchButton.setText("ADVANCED SEARCH"); advSearchButton.setPreferredSize(null); org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .add(jPanel8Layout.createSequentialGroup() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jPanel8Layout.createSequentialGroup() .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(searchBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 745, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane1.setLeftComponent(jPanel8); add(jSplitPane1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); infoTabs = new javax.swing.JTabbedPane(); detailPanel = new javax.swing.JPanel(); statusLabel = new javax.swing.JLabel(); statusCombo = new javax.swing.JComboBox(); instrumentLabel = new javax.swing.JLabel(); instruBox = new javax.swing.JTextField(); brandLabel = new javax.swing.JLabel(); brandBox = new javax.swing.JTextField(); serialLabel = new javax.swing.JLabel(); serialBox = new javax.swing.JTextField(); rankLabel = new javax.swing.JLabel(); rankBox = new javax.swing.JTextField(); valueLabel = new javax.swing.JLabel(); valueBox = new javax.swing.JTextField(); strapLabel = new javax.swing.JLabel(); strapCombo = new javax.swing.JComboBox(); ligatureLabel = new javax.swing.JLabel(); ligCombo = new javax.swing.JComboBox(); mpieceLabel = new javax.swing.JLabel(); mpieceCombo = new javax.swing.JComboBox(); capLabel = new javax.swing.JLabel(); capCombo = new javax.swing.JComboBox(); bowLabel = new javax.swing.JLabel(); bowCombo = new javax.swing.JComboBox(); noteLabel = new javax.swing.JLabel(); jScrollPane5 = new javax.swing.JScrollPane(); notesTPane = new javax.swing.JTextPane(); historyPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); checkoutPanel = new javax.swing.JPanel(); instrumentLabel1 = new javax.swing.JLabel(); instruBox1 = new javax.swing.JTextField(); brandLabel1 = new javax.swing.JLabel(); brandBox1 = new javax.swing.JTextField(); serialLabel1 = new javax.swing.JLabel(); serialBox1 = new javax.swing.JTextField(); strapLabel1 = new javax.swing.JLabel(); strapCombo1 = new javax.swing.JComboBox(); ligatureLabel1 = new javax.swing.JLabel(); ligCombo1 = new javax.swing.JComboBox(); noteLabel1 = new javax.swing.JLabel(); otherBox = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); formButton = new javax.swing.JButton(); outButton = new javax.swing.JButton(); inButton = new javax.swing.JButton(); lostButton = new javax.swing.JButton(); buffer = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); saveButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); jPanel8 = new javax.swing.JPanel(); searchCombo = new javax.swing.JComboBox(); searchBar = new javax.swing.JTextField(); jScrollPane4 = new javax.swing.JScrollPane(); instrumentTable = new javax.swing.JTable(); searchButton = new javax.swing.JButton(); addButton = new javax.swing.JButton(); advSearchButton = new javax.swing.JButton(); setLayout(new java.awt.BorderLayout()); jSplitPane1.setAutoscrolls(true); jSplitPane1.setContinuousLayout(true); jSplitPane1.setName(""); // NOI18N jPanel1.setLayout(new java.awt.BorderLayout()); detailPanel.setLayout(new java.awt.GridBagLayout()); statusLabel.setText("Status:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(statusLabel, gridBagConstraints); statusCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "In Storage", "At Shop", "On Loan", "Missing" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(statusCombo, gridBagConstraints); instrumentLabel.setText("Instrument:"); instrumentLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(instrumentLabel, gridBagConstraints); instruBox.setEditable(false); instruBox.setAutoscrolls(false); instruBox.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox.setPreferredSize(null); instruBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(instruBox, gridBagConstraints); brandLabel.setText("Brand:"); brandLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(brandLabel, gridBagConstraints); brandBox.setEditable(false); brandBox.setAutoscrolls(false); brandBox.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(brandBox, gridBagConstraints); serialLabel.setText("Serial Number:"); serialLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(serialLabel, gridBagConstraints); serialBox.setEditable(false); serialBox.setAutoscrolls(false); serialBox.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(serialBox, gridBagConstraints); rankLabel.setText("Rank:"); rankLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(rankLabel, gridBagConstraints); rankBox.setHorizontalAlignment(javax.swing.JTextField.CENTER); rankBox.setText("3"); rankBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(rankBox, gridBagConstraints); valueLabel.setText("Value: $"); valueLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(valueLabel, gridBagConstraints); valueBox.setHorizontalAlignment(javax.swing.JTextField.RIGHT); valueBox.setText("0"); valueBox.setAutoscrolls(false); valueBox.setMinimumSize(new java.awt.Dimension(200, 20)); valueBox.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 95; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(valueBox, gridBagConstraints); strapLabel.setText("Neck Strap:"); strapLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(strapLabel, gridBagConstraints); strapCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); strapCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(strapCombo, gridBagConstraints); ligatureLabel.setText("Ligature:"); ligatureLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(ligatureLabel, gridBagConstraints); ligCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); ligCombo.setPreferredSize(null); ligCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(ligCombo, gridBagConstraints); mpieceLabel.setText("Mouthpiece:"); mpieceLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(mpieceLabel, gridBagConstraints); mpieceCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); mpieceCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(mpieceCombo, gridBagConstraints); capLabel.setText("Mouthpiece Cap:"); capLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(capLabel, gridBagConstraints); capCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); capCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(capCombo, gridBagConstraints); bowLabel.setText("Bow:"); bowLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; detailPanel.add(bowLabel, gridBagConstraints); bowCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Yes", "No", "n/a" })); bowCombo.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; detailPanel.add(bowCombo, gridBagConstraints); noteLabel.setText("Notes:"); noteLabel.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; detailPanel.add(noteLabel, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(25, 25)); jScrollPane5.setPreferredSize(null); notesTPane.setMinimumSize(new java.awt.Dimension(25, 25)); notesTPane.setPreferredSize(null); jScrollPane5.setViewportView(notesTPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; detailPanel.add(jScrollPane5, gridBagConstraints); infoTabs.addTab("Details", detailPanel); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Date", "Event" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jTable1.setPreferredSize(new java.awt.Dimension(100, 64)); jScrollPane1.setViewportView(jTable1); org.jdesktop.layout.GroupLayout historyPanelLayout = new org.jdesktop.layout.GroupLayout(historyPanel); historyPanel.setLayout(historyPanelLayout); historyPanelLayout.setHorizontalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(historyPanelLayout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 935, Short.MAX_VALUE) .addContainerGap()) ); historyPanelLayout.setVerticalGroup( historyPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(historyPanelLayout.createSequentialGroup() .addContainerGap() .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 755, Short.MAX_VALUE) .addContainerGap()) ); infoTabs.addTab("History", historyPanel); checkoutPanel.setLayout(new java.awt.GridBagLayout()); instrumentLabel1.setText("Owner:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(instrumentLabel1, gridBagConstraints); instruBox1.setAutoscrolls(false); instruBox1.setMinimumSize(new java.awt.Dimension(200, 20)); instruBox1.setPreferredSize(null); instruBox1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { instruBox1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(instruBox1, gridBagConstraints); brandLabel1.setText("School Year:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(brandLabel1, gridBagConstraints); brandBox1.setAutoscrolls(false); brandBox1.setMinimumSize(new java.awt.Dimension(200, 20)); brandBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(brandBox1, gridBagConstraints); serialLabel1.setText("Date Out:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(serialLabel1, gridBagConstraints); serialBox1.setAutoscrolls(false); serialBox1.setMinimumSize(new java.awt.Dimension(200, 20)); serialBox1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 100; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(serialBox1, gridBagConstraints); strapLabel1.setText("Fee Paid:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(strapLabel1, gridBagConstraints); strapCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Paid", "Unpaid", "Waived", " " })); strapCombo1.setSelectedIndex(1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(strapCombo1, gridBagConstraints); ligatureLabel1.setText("For Use In:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(ligatureLabel1, gridBagConstraints); ligCombo1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "0", "1", "2", "3", "4", "5", "6", "7" })); ligCombo1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ligCombo1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; checkoutPanel.add(ligCombo1, gridBagConstraints); noteLabel1.setText("Other:"); noteLabel1.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; checkoutPanel.add(noteLabel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; checkoutPanel.add(otherBox, gridBagConstraints); jPanel3.setPreferredSize(new java.awt.Dimension(107, 23)); formButton.setText("Generate Form"); jPanel3.add(formButton); outButton.setText("Check Out"); jPanel3.add(outButton); inButton.setText("Check In"); jPanel3.add(inButton); lostButton.setText("Lost"); jPanel3.add(lostButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.ipadx = 300; gridBagConstraints.ipady = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHWEST; checkoutPanel.add(jPanel3, gridBagConstraints); org.jdesktop.layout.GroupLayout bufferLayout = new org.jdesktop.layout.GroupLayout(buffer); buffer.setLayout(bufferLayout); bufferLayout.setHorizontalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); bufferLayout.setVerticalGroup( bufferLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 100, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; gridBagConstraints.weighty = 2.0; checkoutPanel.add(buffer, gridBagConstraints); infoTabs.addTab("Check In/Out", checkoutPanel); jPanel1.add(infoTabs, java.awt.BorderLayout.CENTER); jPanel2.setLayout(new java.awt.GridBagLayout()); saveButton.setText("SAVE CHANGES"); saveButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(saveButton, gridBagConstraints); cancelButton.setText("CANCEL CHANGES"); cancelButton.setPreferredSize(null); jPanel2.add(cancelButton, new java.awt.GridBagConstraints()); deleteButton.setText("DELETE INSTRUMENT"); deleteButton.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; jPanel2.add(deleteButton, gridBagConstraints); jPanel1.add(jPanel2, java.awt.BorderLayout.SOUTH); jSplitPane1.setRightComponent(jPanel1); searchCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Name", "Brand", "Serial #", "Rank", "Value", "Status", "Ligature", "Mouthpiece", "Mouthpiece Cap", "Bow" })); searchCombo.setPreferredSize(null); searchCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchComboActionPerformed(evt); } }); searchBar.setText("Search Bar"); searchBar.setPreferredSize(null); searchBar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchBarActionPerformed(evt); } }); jScrollPane4.setPreferredSize(null); instrumentTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Instrument", "Brand", "Serial #" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); instrumentTable.setPreferredSize(null); jScrollPane4.setViewportView(instrumentTable); searchButton.setText("Search"); searchButton.setPreferredSize(null); addButton.setText("Add New Instrument"); addButton.setPreferredSize(null); advSearchButton.setText("ADVANCED SEARCH"); advSearchButton.setPreferredSize(null); org.jdesktop.layout.GroupLayout jPanel8Layout = new org.jdesktop.layout.GroupLayout(jPanel8); jPanel8.setLayout(jPanel8Layout); jPanel8Layout.setHorizontalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .add(jPanel8Layout.createSequentialGroup() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(jPanel8Layout.createSequentialGroup() .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 72, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); jPanel8Layout.setVerticalGroup( jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel8Layout.createSequentialGroup() .addContainerGap() .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(searchBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(searchCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanel8Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(advSearchButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 745, Short.MAX_VALUE) .addContainerGap()) ); jSplitPane1.setLeftComponent(jPanel8); add(jSplitPane1, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java b/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java index b0b79d1b5..8553bbc02 100644 --- a/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java +++ b/GAE/src/org/waterforpeople/mapping/app/web/rest/security/GoogleAccountsAuthenticationProvider.java @@ -1,107 +1,107 @@ package org.waterforpeople.mapping.app.web.rest.security; import java.util.EnumSet; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.inject.Inject; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.DisabledException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; import org.waterforpeople.mapping.app.web.rest.security.user.GaeUser; import com.gallatinsystems.user.dao.UserDao; import com.google.appengine.api.users.User; /** * A simple authentication provider which interacts with {@code User} returned by the GAE {@code UserService}, * and also the local persistent {@code UserRegistry} to build an application user principal. * <p> * If the user has been authenticated through google accounts, it will check if they are already registered * and either load the existing user information or assign them a temporary identity with limited access until they * have registered. * <p> * If the account has been disabled, a {@code DisabledException} will be raised. * * @author Luke Taylor */ public class GoogleAccountsAuthenticationProvider implements AuthenticationProvider, MessageSourceAware { protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor(); private static final Logger log = Logger.getLogger(GoogleAccountsAuthenticationProvider.class.getName()); @Inject UserDao userDao; public Authentication authenticate(Authentication authentication) throws AuthenticationException { User googleUser = (User) authentication.getPrincipal(); GaeUser user = findUser(googleUser.getEmail()); if (user == null) { // User not in registry. Needs to register user = new GaeUser(googleUser.getNickname(), googleUser.getEmail()); } if (!user.isEnabled()) { throw new DisabledException("Account is disabled"); } return new GaeUserAuthentication(user, authentication.getDetails()); } private GaeUser findUser(String email) { - final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email); + final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email.toLowerCase()); if (user == null) { return null; } final int authority = getAuthorityLevel(user); final Set<AppRole> roles = EnumSet.noneOf(AppRole.class); if (authority == AppRole.NEW_USER.getLevel()) { roles.add(AppRole.NEW_USER); } else { for (AppRole r : AppRole.values()) { if (authority <= r.getLevel()) { roles.add(r); } } } return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true); } private int getAuthorityLevel(com.gallatinsystems.user.domain.User user) { if(user.isSuperAdmin() != null && user.isSuperAdmin()) { return AppRole.SUPER_ADMIN.getLevel(); } try { final int level = Integer.parseInt(user.getPermissionList()); return level; } catch (Exception e) { log.log(Level.WARNING, "Error getting role level, setting NEW_USER role", e); } return AppRole.NEW_USER.getLevel(); } /** * Indicate that this provider only supports PreAuthenticatedAuthenticationToken (sub)classes. */ public final boolean supports(Class<?> authentication) { return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication); } public void setMessageSource(MessageSource messageSource) { this.messages = new MessageSourceAccessor(messageSource); } }
true
true
private GaeUser findUser(String email) { final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email); if (user == null) { return null; } final int authority = getAuthorityLevel(user); final Set<AppRole> roles = EnumSet.noneOf(AppRole.class); if (authority == AppRole.NEW_USER.getLevel()) { roles.add(AppRole.NEW_USER); } else { for (AppRole r : AppRole.values()) { if (authority <= r.getLevel()) { roles.add(r); } } } return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true); }
private GaeUser findUser(String email) { final com.gallatinsystems.user.domain.User user = userDao.findUserByEmail(email.toLowerCase()); if (user == null) { return null; } final int authority = getAuthorityLevel(user); final Set<AppRole> roles = EnumSet.noneOf(AppRole.class); if (authority == AppRole.NEW_USER.getLevel()) { roles.add(AppRole.NEW_USER); } else { for (AppRole r : AppRole.values()) { if (authority <= r.getLevel()) { roles.add(r); } } } return new GaeUser(user.getUserName(), user.getEmailAddress(), roles, true); }
diff --git a/poem/src/main/java/org/melati/poem/GroupTable.java b/poem/src/main/java/org/melati/poem/GroupTable.java index f870a0ef2..c798269e9 100644 --- a/poem/src/main/java/org/melati/poem/GroupTable.java +++ b/poem/src/main/java/org/melati/poem/GroupTable.java @@ -1,76 +1,76 @@ /* * $Source$ * $Revision$ * * Part of Melati (http://melati.org), a framework for the rapid * development of clean, maintainable web applications. * * ------------------------------------- * Copyright (C) 2000 William Chesters * ------------------------------------- * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * A copy of the GPL should be in the file org/melati/COPYING in this tree. * Or see http://melati.org/License.html. * * Contact details for copyright holder: * * William Chesters <[email protected]> * http://paneris.org/~williamc * Obrechtstraat 114, 2517VX Den Haag, The Netherlands * * * ------ * Note * ------ * * I will assign copyright to PanEris (http://paneris.org) as soon as * we have sorted out what sort of legal existence we need to have for * that to make sense. When WebMacro's "Simple Public License" is * finalised, we'll offer it as an alternative license for Melati. * In the meantime, if you want to use Melati on non-GPL terms, * contact me! */ package org.melati.poem; public class GroupTable extends GroupTableBase { private Group administratorsGroup = new Group("Melati database administrators"); public GroupTable(Database database, String name) throws PoemException { super(database, name); } public GroupTable(Database database, String name, DefinitionSource definitionSource) throws PoemException { super(database, name, definitionSource); } Group administratorsGroup() { return administratorsGroup; } void postInitialise() { super.postInitialise(); - getNameColumn().ensure(administratorsGroup); + administratorsGroup = (Group)getNameColumn().ensure(administratorsGroup); if (info.getDefaultcanwrite() == null) info.setDefaultcanwrite(getDatabase().administerCapability()); if (info.getCancreate() == null) info.setCancreate(getDatabase().administerCapability()); } }
true
true
void postInitialise() { super.postInitialise(); getNameColumn().ensure(administratorsGroup); if (info.getDefaultcanwrite() == null) info.setDefaultcanwrite(getDatabase().administerCapability()); if (info.getCancreate() == null) info.setCancreate(getDatabase().administerCapability()); }
void postInitialise() { super.postInitialise(); administratorsGroup = (Group)getNameColumn().ensure(administratorsGroup); if (info.getDefaultcanwrite() == null) info.setDefaultcanwrite(getDatabase().administerCapability()); if (info.getCancreate() == null) info.setCancreate(getDatabase().administerCapability()); }
diff --git a/works-net/src/test/java/com/worksnet/model/UserServiceTest.java b/works-net/src/test/java/com/worksnet/model/UserServiceTest.java index 4c7eebd..0a6a621 100644 --- a/works-net/src/test/java/com/worksnet/model/UserServiceTest.java +++ b/works-net/src/test/java/com/worksnet/model/UserServiceTest.java @@ -1,36 +1,37 @@ package com.worksnet.model; import com.worksnet.service.UserService; import junit.framework.TestCase; import org.junit.Test; /** * @author maxim.levicky * Date: 3/11/13 * Time: 1:11 PM */ public class UserServiceTest extends TestCase { private UserService service; public UserServiceTest() { } @Override public void setUp() throws Exception { super.setUp(); service = new UserService(); } @Test public void testAddUser() throws Exception { + if (true) return; //TODO: fix text User user = new User(); user.setUserName("TestUser"); int userId = service.add(user); user.setId(userId); User dbUser = service.getById(userId); assertEquals(user, dbUser); } }
true
true
public void testAddUser() throws Exception { User user = new User(); user.setUserName("TestUser"); int userId = service.add(user); user.setId(userId); User dbUser = service.getById(userId); assertEquals(user, dbUser); }
public void testAddUser() throws Exception { if (true) return; //TODO: fix text User user = new User(); user.setUserName("TestUser"); int userId = service.add(user); user.setId(userId); User dbUser = service.getById(userId); assertEquals(user, dbUser); }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java index 4d4e7963c..84a353ed8 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java @@ -1,397 +1,399 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.ui; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.team.internal.ccvs.core.CVSAnnotateBlock; import org.eclipse.team.internal.ccvs.core.CVSException; import org.eclipse.team.internal.ccvs.core.ICVSRemoteFile; import org.eclipse.team.internal.ccvs.core.ICVSResource; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorRegistry; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IReusableEditor; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.registry.EditorDescriptor; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; /** * A view showing the results of the CVS Annotate Command. A linked * combination of a View of annotations, a source editor and the * Resource History View */ public class AnnotateView extends ViewPart implements ISelectionChangedListener { ITextEditor editor; HistoryView historyView; IWorkbenchPage page; ListViewer viewer; IDocument document; Collection cvsAnnotateBlocks; ICVSResource cvsResource; InputStream contents; IStructuredSelection previousListSelection; ITextSelection previousTextSelection; boolean lastSelectionWasText = false; public static final String VIEW_ID = "org.eclipse.team.ccvs.ui.AnnotateView"; //$NON-NLS-1$ private Composite top; private IPartListener partListener = new IPartListener() { public void partActivated(IWorkbenchPart part) { } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { if (editor != null && part == editor) { disconnect(); } } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; public AnnotateView() { super(); } public void createPartControl(Composite parent) { this.top = parent; // Create default contents Label label = new Label(top, SWT.WRAP); label.setText(CVSUIMessages.CVSAnnotateView_viewInstructions); //$NON-NLS-1$ label.setLayoutData(new GridData(GridData.FILL_BOTH)); top.layout(); } /** * Show the annotation view. * @param cvsResource * @param cvsAnnotateBlocks * @param contents * @throws PartInitException, CVSException */ public void showAnnotations(ICVSResource cvsResource, Collection cvsAnnotateBlocks, InputStream contents) throws PartInitException, CVSException { showAnnotations(cvsResource, cvsAnnotateBlocks, contents, true); } /** * Show the annotation view. * @param cvsResource * @param cvsAnnotateBlocks * @param contents * @param useHistoryView * @throws PartInitException, CVSException */ public void showAnnotations(ICVSResource cvsResource, Collection cvsAnnotateBlocks, InputStream contents, boolean useHistoryView) throws PartInitException, CVSException { // Disconnect from old annotation editor disconnect(); // Remove old viewer Control[] oldChildren = top.getChildren(); if (oldChildren != null) { for (int i = 0; i < oldChildren.length; i++) { oldChildren[i].dispose(); } } viewer = new ListViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new ArrayContentProvider()); viewer.setLabelProvider(new LabelProvider()); viewer.addSelectionChangedListener(this); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); WorkbenchHelp.setHelp(viewer.getControl(), IHelpContextIds.ANNOTATE_VIEW); top.layout(); this.cvsResource = cvsResource; this.contents = contents; this.cvsAnnotateBlocks = cvsAnnotateBlocks; page = CVSUIPlugin.getActivePage(); viewer.setInput(cvsAnnotateBlocks); editor = (ITextEditor) openEditor(); IDocumentProvider provider = editor.getDocumentProvider(); document = provider.getDocument(editor.getEditorInput()); setPartName(NLS.bind(CVSUIMessages.CVSAnnotateView_showFileAnnotation, (new Object[] {cvsResource.getName()}))); //$NON-NLS-1$ try { IResource localResource = cvsResource.getIResource(); if (localResource != null) { setTitleToolTip(localResource.getFullPath().toString()); } else { setTitleToolTip(cvsResource.getName()); } } catch (CVSException e) { setTitleToolTip(cvsResource.getName()); } if (!useHistoryView) { return; } // Get hook to the HistoryView historyView = (HistoryView) page.showView(HistoryView.VIEW_ID); historyView.showHistory((ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(cvsResource), false /* don't refetch */); } protected void disconnect() { if(editor != null) { if (editor.getSelectionProvider() instanceof IPostSelectionProvider) { ((IPostSelectionProvider) editor.getSelectionProvider()).removePostSelectionChangedListener(this); } editor.getSite().getPage().removePartListener(partListener); editor = null; document = null; } } /** * Makes the view visible in the active perspective. If there * isn't a view registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static AnnotateView openInActivePerspective() throws PartInitException { return (AnnotateView) CVSUIPlugin.getActivePage().showView(VIEW_ID); } /** * Selection changed in either the Annotate List View or the * Source editor. */ public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection() instanceof IStructuredSelection) { listSelectionChanged((IStructuredSelection) event.getSelection()); } else if (event.getSelection() instanceof ITextSelection) { textSelectionChanged((ITextSelection) event.getSelection()); } } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ public void dispose() { disconnect(); } /** * A selection event in the Annotate Source Editor * @param event */ private void textSelectionChanged(ITextSelection selection) { // Track where the last selection event came from to avoid // a selection event loop. lastSelectionWasText = true; // Locate the annotate block containing the selected line number. CVSAnnotateBlock match = null; for (Iterator iterator = cvsAnnotateBlocks.iterator(); iterator.hasNext();) { CVSAnnotateBlock block = (CVSAnnotateBlock) iterator.next(); if (block.contains(selection.getStartLine())) { match = block; break; } } // Select the annotate block in the List View. if (match == null) { return; } StructuredSelection listSelection = new StructuredSelection(match); viewer.setSelection(listSelection, true); } /** * A selection event in the Annotate List View * @param selection */ private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); + if (textSelection == null) return; CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); + if (listSelection == null) return; /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { historyView.selectRevision(listSelection.getRevision()); } lastSelectionWasText = false; } /** * Try and open the correct registered editor type for the file. * @throws CVSException, PartInitException */ private IEditorPart openEditor() throws CVSException, PartInitException { ICVSRemoteFile file = (ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(cvsResource); // Determine if the registered editor is an ITextEditor. // There is currently no support from UI to determine this information. This // problem has been logged in: https://bugs.eclipse.org/bugs/show_bug.cgi?id=47362 // For now, use internal classes. String id = getEditorId(file); ITextEditor editor = getEditor(id, file); // Hook Editor post selection listener. if (editor.getSelectionProvider() instanceof IPostSelectionProvider) { ((IPostSelectionProvider) editor.getSelectionProvider()).addPostSelectionChangedListener(this); } editor.getSite().getPage().addPartListener(partListener); return editor; } private ITextEditor getEditor(String id, ICVSRemoteFile file) throws PartInitException { // Either reuse an existing editor or open a new editor of the correct type. if (editor != null && editor instanceof IReusableEditor && page.isPartVisible(editor) && editor.getSite().getId().equals(id)) { // We can reuse the editor ((IReusableEditor) editor).setInput(new RemoteAnnotationEditorInput(file, contents)); return editor; } else { // We can not reuse the editor so close the existing one and open a new one. if (editor != null) { page.closeEditor(editor, false); editor = null; } IEditorPart part = page.openEditor(new RemoteAnnotationEditorInput(file, contents), id); if (part instanceof ITextEditor) { return (ITextEditor)part; } else { // We asked for a text editor but didn't get one // so open a vanilla text editor page.closeEditor(part, false); part = page.openEditor(new RemoteAnnotationEditorInput(file, contents), IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID); if (part instanceof ITextEditor) { return (ITextEditor)part; } else { // There is something really wrong so just bail throw new PartInitException(CVSUIMessages.AnnotateView_0); //$NON-NLS-1$ } } } } private String getEditorId(ICVSRemoteFile file) { String id; IEditorRegistry registry = CVSUIPlugin.getPlugin().getWorkbench().getEditorRegistry(); IEditorDescriptor descriptor = registry.getDefaultEditor(file.getName()); if (descriptor == null || !(descriptor instanceof EditorDescriptor) || !(((EditorDescriptor)descriptor).isInternal())) { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; //$NON-NLS-1$ } else { try { Object obj = IDEWorkbenchPlugin.createExtension(((EditorDescriptor) descriptor).getConfigurationElement(), "class"); //$NON-NLS-1$ if (obj instanceof ITextEditor) { id = descriptor.getId(); } else { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; } } catch (CoreException e) { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; } } return id; } // This method implemented to be an ISelectionChangeListener but we // don't really care when the List or Editor get focus. public void setFocus() { return; } }
false
true
private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { historyView.selectRevision(listSelection.getRevision()); } lastSelectionWasText = false; }
private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); if (textSelection == null) return; CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); if (listSelection == null) return; /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { historyView.selectRevision(listSelection.getRevision()); } lastSelectionWasText = false; }
diff --git a/api/src/main/java/org/openmrs/api/impl/CohortServiceImpl.java b/api/src/main/java/org/openmrs/api/impl/CohortServiceImpl.java index e39e356b..3f5ecb79 100644 --- a/api/src/main/java/org/openmrs/api/impl/CohortServiceImpl.java +++ b/api/src/main/java/org/openmrs/api/impl/CohortServiceImpl.java @@ -1,366 +1,371 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.api.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Cohort; import org.openmrs.Patient; import org.openmrs.api.APIException; import org.openmrs.api.CohortService; import org.openmrs.api.context.Context; import org.openmrs.api.db.CohortDAO; import org.openmrs.cohort.CohortDefinition; import org.openmrs.cohort.CohortDefinitionItemHolder; import org.openmrs.cohort.CohortDefinitionProvider; import org.openmrs.report.EvaluationContext; import org.openmrs.reporting.PatientCharacteristicFilter; import org.openmrs.reporting.PatientSearch; import org.openmrs.util.PrivilegeConstants; import org.springframework.util.StringUtils; /** * API functions related to Cohorts */ public class CohortServiceImpl extends BaseOpenmrsService implements CohortService { private Log log = LogFactory.getLog(this.getClass()); private CohortDAO dao; private static Map<Class<? extends CohortDefinition>, CohortDefinitionProvider> cohortDefinitionProviders = null; /** * @see org.openmrs.api.CohortService#setCohortDAO(org.openmrs.api.db.CohortDAO) */ public void setCohortDAO(CohortDAO dao) { this.dao = dao; } /** * Clean up after this class. Set the static var to null so that the classloader can reclaim the * space. * * @see org.openmrs.api.impl.BaseOpenmrsService#onShutdown() */ public void onShutdown() { cohortDefinitionProviders = null; } /** * @see org.openmrs.api.CohortService#saveCohort(org.openmrs.Cohort) */ public Cohort saveCohort(Cohort cohort) throws APIException { if (cohort.getCohortId() == null) { Context.requirePrivilege(PrivilegeConstants.ADD_COHORTS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_COHORTS); } if (cohort.getName() == null) { - throw new APIException("Cohort name is required"); + throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.nameRequired", null, + "Cohort name is required", Context.getLocale())); + } + if (cohort.getDescription() == null) { + throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.descriptionRequired", null, + "Cohort description is required", Context.getLocale())); } if (log.isInfoEnabled()) log.info("Saving cohort " + cohort); return dao.saveCohort(cohort); } /** * @see org.openmrs.api.CohortService#createCohort(org.openmrs.Cohort) * @deprecated */ public Cohort createCohort(Cohort cohort) { return Context.getCohortService().saveCohort(cohort); } /** * @see org.openmrs.api.CohortService#getCohort(java.lang.Integer) */ public Cohort getCohort(Integer id) { return dao.getCohort(id); } /** * @see org.openmrs.api.CohortService#getCohorts() * @deprecated */ public List<Cohort> getCohorts() { return getAllCohorts(); } /** * @see org.openmrs.api.CohortService#voidCohort(org.openmrs.Cohort, java.lang.String) */ public Cohort voidCohort(Cohort cohort, String reason) { // other setters done by the save handlers return saveCohort(cohort); } /** * @see org.openmrs.api.CohortService#getCohortByUuid(java.lang.String) */ public Cohort getCohortByUuid(String uuid) { return dao.getCohortByUuid(uuid); } /** * @see org.openmrs.api.CohortService#addPatientToCohort(org.openmrs.Cohort, * org.openmrs.Patient) */ public Cohort addPatientToCohort(Cohort cohort, Patient patient) { if (!cohort.contains(patient)) { cohort.getMemberIds().add(patient.getPatientId()); saveCohort(cohort); } return cohort; } /** * @see org.openmrs.api.CohortService#removePatientFromCohort(org.openmrs.Cohort, * org.openmrs.Patient) */ public Cohort removePatientFromCohort(Cohort cohort, Patient patient) { if (cohort.contains(patient)) { cohort.getMemberIds().remove(patient.getPatientId()); saveCohort(cohort); } return cohort; } /** * @see org.openmrs.api.CohortService#updateCohort(org.openmrs.Cohort) * @deprecated */ public Cohort updateCohort(Cohort cohort) { return Context.getCohortService().saveCohort(cohort); } /** * @see org.openmrs.api.CohortService#getCohortsContainingPatient(org.openmrs.Patient) */ public List<Cohort> getCohortsContainingPatient(Patient patient) { return dao.getCohortsContainingPatientId(patient.getPatientId()); } public List<Cohort> getCohortsContainingPatientId(Integer patientId) { return dao.getCohortsContainingPatientId(patientId); } /** * @see org.openmrs.api.CohortService#getCohorts(java.lang.String) */ public List<Cohort> getCohorts(String nameFragment) throws APIException { return dao.getCohorts(nameFragment); } /** * @see org.openmrs.api.CohortService#getAllCohorts() */ public List<Cohort> getAllCohorts() throws APIException { return getAllCohorts(false); } /** * @see org.openmrs.api.CohortService#getAllCohorts(boolean) */ public List<Cohort> getAllCohorts(boolean includeVoided) throws APIException { return dao.getAllCohorts(includeVoided); } /** * @see org.openmrs.api.CohortService#getCohort(java.lang.String) */ public Cohort getCohort(String name) throws APIException { return dao.getCohort(name); } /** * @see org.openmrs.api.CohortService#purgeCohort(org.openmrs.Cohort) */ public Cohort purgeCohort(Cohort cohort) throws APIException { return dao.deleteCohort(cohort); } /** * Auto generated method comment * * @param definitionClass * @return * @deprecated see reportingcompatibility module * @throws APIException */ @Deprecated private CohortDefinitionProvider getCohortDefinitionProvider(Class<? extends CohortDefinition> definitionClass) throws APIException { CohortDefinitionProvider ret = cohortDefinitionProviders.get(definitionClass); if (ret == null) throw new APIException("No CohortDefinitionProvider registered for " + definitionClass); else return ret; } /** * @see org.openmrs.api.CohortService#evaluate(org.openmrs.cohort.CohortDefinition, * org.openmrs.report.EvaluationContext) * @deprecated see reportingcompatibility module */ @Deprecated public Cohort evaluate(CohortDefinition definition, EvaluationContext evalContext) throws APIException { CohortDefinitionProvider provider = getCohortDefinitionProvider(definition.getClass()); return provider.evaluate(definition, evalContext); } /** * @see org.openmrs.api.CohortService#getAllPatientsCohortDefinition() * @deprecated see reportingcompatibility module */ @Deprecated public CohortDefinition getAllPatientsCohortDefinition() { PatientSearch ps = new PatientSearch(); ps.setFilterClass(PatientCharacteristicFilter.class); return ps; } /** * @see org.openmrs.api.CohortService#getCohortDefinition(java.lang.Class, java.lang.Integer) * @deprecated see reportingcompatibility module */ @Deprecated public CohortDefinition getCohortDefinition(Class<CohortDefinition> clazz, Integer id) { CohortDefinitionProvider provider = getCohortDefinitionProvider(clazz); return provider.getCohortDefinition(id); } /** * @see org.openmrs.api.CohortService#getCohortDefinition(java.lang.String) * @deprecated see reportingcompatibility module */ @SuppressWarnings("unchecked") @Deprecated public CohortDefinition getCohortDefinition(String key) { try { String[] keyValues = key.split(":"); Integer id = Integer.parseInt((keyValues[0] != null) ? keyValues[0] : "0"); String className = (keyValues[1] != null) ? keyValues[1] : ""; Class clazz = Class.forName(className); return getCohortDefinition(clazz, id); } catch (ClassNotFoundException e) { throw new APIException(e); } } /** * @see org.openmrs.api.CohortService#getAllCohortDefinitions() * @deprecated see reportingcompatibility module */ @Deprecated public List<CohortDefinitionItemHolder> getAllCohortDefinitions() { List<CohortDefinitionItemHolder> ret = new ArrayList<CohortDefinitionItemHolder>(); for (CohortDefinitionProvider provider : cohortDefinitionProviders.values()) { log.info("Getting cohort definitions from " + provider.getClass()); ret.addAll(provider.getAllCohortDefinitions()); } return ret; } /** * @see org.openmrs.api.CohortService#purgeCohortDefinition(org.openmrs.cohort.CohortDefinition) * @deprecated see reportingcompatibility module */ @Deprecated public void purgeCohortDefinition(CohortDefinition definition) { CohortDefinitionProvider provider = getCohortDefinitionProvider(definition.getClass()); provider.purgeCohortDefinition(definition); } /** * @see org.openmrs.api.CohortService#setCohortDefinitionProviders(Map) * @deprecated see reportingcompatibility module */ @Deprecated public void setCohortDefinitionProviders( Map<Class<? extends CohortDefinition>, CohortDefinitionProvider> providerClassMap) { for (Map.Entry<Class<? extends CohortDefinition>, CohortDefinitionProvider> entry : providerClassMap.entrySet()) { registerCohortDefinitionProvider(entry.getKey(), entry.getValue()); } } /** * @see org.openmrs.api.CohortService#getCohortDefinitionProviders() * @deprecated see reportingcompatibility module */ @Deprecated public Map<Class<? extends CohortDefinition>, CohortDefinitionProvider> getCohortDefinitionProviders() { if (cohortDefinitionProviders == null) cohortDefinitionProviders = new LinkedHashMap<Class<? extends CohortDefinition>, CohortDefinitionProvider>(); return cohortDefinitionProviders; } /** * @see org.openmrs.api.CohortService#registerCohortDefinitionProvider(Class, * CohortDefinitionProvider) * @deprecated see reportingcompatibility module */ @Deprecated public void registerCohortDefinitionProvider(Class<? extends CohortDefinition> defClass, CohortDefinitionProvider cohortDefProvider) throws APIException { getCohortDefinitionProviders().put(defClass, cohortDefProvider); } /** * @see org.openmrs.api.CohortService#removeCohortDefinitionProvider(java.lang.Class) * @deprecated see reportingcompatibility module */ @Deprecated public void removeCohortDefinitionProvider(Class<? extends CohortDefinitionProvider> providerClass) { // TODO: should this be looking through the values or the keys? for (Iterator<CohortDefinitionProvider> i = cohortDefinitionProviders.values().iterator(); i.hasNext();) { if (i.next().getClass().equals(providerClass)) i.remove(); } } /** * @see org.openmrs.api.CohortService#saveCohortDefinition(org.openmrs.cohort.CohortDefinition) * @deprecated see reportingcompatibility module */ @Deprecated public CohortDefinition saveCohortDefinition(CohortDefinition definition) throws APIException { CohortDefinitionProvider provider = getCohortDefinitionProvider(definition.getClass()); return provider.saveCohortDefinition(definition); } /** * @see org.openmrs.api.CohortService#getCohortDefinitions(java.lang.Class) * @deprecated see reportingcompatibility module */ @SuppressWarnings("unchecked") @Deprecated public List<CohortDefinitionItemHolder> getCohortDefinitions(Class providerClass) { CohortDefinitionProvider provider = getCohortDefinitionProvider(providerClass); return provider.getAllCohortDefinitions(); } }
true
true
public Cohort saveCohort(Cohort cohort) throws APIException { if (cohort.getCohortId() == null) { Context.requirePrivilege(PrivilegeConstants.ADD_COHORTS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_COHORTS); } if (cohort.getName() == null) { throw new APIException("Cohort name is required"); } if (log.isInfoEnabled()) log.info("Saving cohort " + cohort); return dao.saveCohort(cohort); }
public Cohort saveCohort(Cohort cohort) throws APIException { if (cohort.getCohortId() == null) { Context.requirePrivilege(PrivilegeConstants.ADD_COHORTS); } else { Context.requirePrivilege(PrivilegeConstants.EDIT_COHORTS); } if (cohort.getName() == null) { throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.nameRequired", null, "Cohort name is required", Context.getLocale())); } if (cohort.getDescription() == null) { throw new APIException(Context.getMessageSourceService().getMessage("Cohort.save.descriptionRequired", null, "Cohort description is required", Context.getLocale())); } if (log.isInfoEnabled()) log.info("Saving cohort " + cohort); return dao.saveCohort(cohort); }
diff --git a/dk.brics.lightrefactor.eclipse/src/dk/brics/lightrefactor/eclipse/handlers/RenameHandler.java b/dk.brics.lightrefactor.eclipse/src/dk/brics/lightrefactor/eclipse/handlers/RenameHandler.java index 8ec9f4a..fbd8a2a 100644 --- a/dk.brics.lightrefactor.eclipse/src/dk/brics/lightrefactor/eclipse/handlers/RenameHandler.java +++ b/dk.brics.lightrefactor.eclipse/src/dk/brics/lightrefactor/eclipse/handlers/RenameHandler.java @@ -1,497 +1,498 @@ package dk.brics.lightrefactor.eclipse.handlers; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.window.Window; import org.eclipse.ltk.core.refactoring.CompositeChange; import org.eclipse.ltk.core.refactoring.DocumentChange; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.ltk.core.refactoring.TextFileChange; import org.eclipse.swt.SWT; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.texteditor.ITextEditor; import org.mozilla.javascript.ast.AstNode; import dk.brics.jshtml.Html; import dk.brics.jshtml.HtmlJs; import dk.brics.jshtml.InlineJs; import dk.brics.lightrefactor.Asts; import dk.brics.lightrefactor.ISource; import dk.brics.lightrefactor.Loader; import dk.brics.lightrefactor.NameRef; import dk.brics.lightrefactor.NodeFinder; import dk.brics.lightrefactor.Renaming; import dk.brics.lightrefactor.eclipse.FileSource; import dk.brics.lightrefactor.eclipse.RefactoringScope; import dk.brics.lightrefactor.eclipse.ui.EnterNameDialog; import dk.brics.lightrefactor.eclipse.ui.RefactoringUtil; /** * Semi-automatic rename refactoring for JavaScript based on same-type inference. */ public class RenameHandler extends AbstractHandler { // TODO: Possible performance issue: AstNode.getAbsolutePosition() and Asts.source() costs are linear in tree depth // XXX: Undo label will be "Typing" if only modifying a single file // TODO: closed automatically opened editors afterwards? class JavaScriptResources { List<IFile> javascriptFiles = new ArrayList<IFile>(); List<IFile> htmlFiles = new ArrayList<IFile>(); } private boolean isJavaScript(IFile file) { return "js".equalsIgnoreCase(file.getFileExtension()); } private boolean isHtml(IFile file) { return "html".equalsIgnoreCase(file.getFileExtension()) || "htm".equalsIgnoreCase(file.getFileExtension()); } /** * Finds all JavaScript resources in the given project, folder, or workspace. * A JavaScript resource is a resource with the file extension "<tt>js</tt>" or "<tt>html</tt>" or "<tt>htm</tt>". * @param container resource container, such as a project, folder, or workspace * @return new list */ private JavaScriptResources getJavaScriptResources(IContainer container) { final JavaScriptResources result = new JavaScriptResources(); try { container.accept(new IResourceVisitor() { @Override public boolean visit(IResource resource) throws CoreException { IFile file = (IFile)resource.getAdapter(IFile.class); if (file == null) return true; if (isJavaScript(file)) { result.javascriptFiles.add(file); } else if (isHtml(file)) { result.htmlFiles.add(file); } return true; } }); } catch (CoreException e1) { throw new RuntimeException(e1); } return result; } /** * Every dirty editor that edits one of the given resources is saved. * Must be called in the UI thread. * @param window the workbench window whose editors should be saved * @param resources only editors that edit one of these resources will be saved */ private void saveOpenResources(IWorkbenchWindow window, Set<? extends IResource> resources) throws InterruptedException { final List<IEditorPart> editorsToSave = new ArrayList<IEditorPart>(); for (IWorkbenchPage page : window.getPages()) { for (IEditorReference ref : page.getEditorReferences()) { IEditorPart editor = ref.getEditor(false); if (editor == null) continue; if (!editor.isDirty()) continue; IResource editorResource = (IResource) editor.getEditorInput().getAdapter(IResource.class); if (editorResource == null) continue; if (!resources.contains(editorResource)) continue; editorsToSave.add(editor); } } if (editorsToSave.size() == 0) return; try { window.run(false, true, new IRunnableWithProgress() { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask("Saving open files", editorsToSave.size()); for (IEditorPart editor : editorsToSave) { monitor.subTask(editor.getTitle()); editor.doSave(monitor); monitor.worked(1); if (monitor.isCanceled()) { throw new InterruptedException(); } } monitor.done(); } }); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } /** * Map elements in a list to their index. */ private <E> Map<E,Integer> indexMap(List<E> list) { int i=0; Map<E,Integer> map = new HashMap<E,Integer>(); for (E x : list) { map.put(x, i++); } return map; } public Object execute(ExecutionEvent event) throws ExecutionException { final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); ITextEditor currentEditor = (ITextEditor) HandlerUtil.getActiveEditor(event); executeWith(window,currentEditor); return null; } public void executeWith(final IWorkbenchWindow window, ITextEditor currentEditor) throws ExecutionException { // Pull some useful objects out of the void ITextSelection sel = (ITextSelection) currentEditor.getEditorSite().getSelectionProvider().getSelection(); IDocument doc = currentEditor.getDocumentProvider().getDocument(currentEditor.getEditorInput()); IFile currentResource = (IFile) currentEditor.getEditorInput().getAdapter(IFile.class); // ===================== CLASSIFY REFACTORING REQUEST ================= // Load the AST FileSource currentSource; final Loader loader = new Loader(); if (isJavaScript(currentResource)) { currentSource = new FileSource(currentResource); loader.addSource(currentSource, doc.get()); } else if (isHtml(currentResource)) { currentSource = null; List<HtmlJs> frags = Html.extract(doc.get()); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs) frag; FileSource src = new FileSource(currentResource, inl.getOffset()); loader.addSource(src, inl.getCode()); if (sel.getOffset() >= inl.getOffset() && sel.getOffset() <= inl.getOffset() + inl.getCode().length()) { currentSource = src; } } } if (currentSource == null) { return; // not inside JavaScript fragment } } else { return; // does not apply to this file type } final Asts asts = loader.getAsts(); // Find the selected name token AstNode targetName = NodeFinder.find(asts.get(currentSource), sel.getOffset() - currentSource.getOffset()); String originalName = NameRef.name(targetName); boolean showScope; String thingType; if (NameRef.isPrty(targetName)) { thingType = "property"; showScope = true; } else if (NameRef.isGlobalVar(targetName)) { thingType = "variable"; showScope = true; } else if (NameRef.isVar(targetName)) { thingType = "variable"; showScope = false; } else if (NameRef.isLabel(targetName)) { thingType = "label"; showScope = false; } else { return; // cannot rename this type of thing } // ===================== INITIAL USER PROMPT ================= // Prompt the new name currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); EnterNameDialog newNameDialog = new EnterNameDialog(window.getShell(), thingType, originalName); newNameDialog.setShowScope(showScope); newNameDialog.open(); if (newNameDialog.getReturnCode() != Window.OK) { return; // we got cancelled } String newName = newNameDialog.getNewName(); RefactoringScope scope = showScope ? newNameDialog.getSelectedScope() : RefactoringScope.File; // ===================== FIND/SAVE AFFECTED RESOURCES ================= // Find affected resources and save them if they are open in a dirty editor final List<IFile> affectedResources = new ArrayList<IFile>(); affectedResources.add(currentResource); switch (scope) { case File: break; case Project: case Workspace: IContainer container = scope == RefactoringScope.Project ? currentResource.getProject() : currentResource.getWorkspace().getRoot(); JavaScriptResources resources = getJavaScriptResources(container); resources.javascriptFiles.remove(currentResource); resources.htmlFiles.remove(currentResource); affectedResources.addAll(resources.javascriptFiles); affectedResources.addAll(resources.htmlFiles); try { saveOpenResources(window, new HashSet<IFile>(affectedResources)); } catch (InterruptedException e1) { return; // operation was cancelled } break; } // Load all ASTs for (IFile file : affectedResources) { if (file.equals(currentResource)) continue; try { InputStream stream = file.getContents(); try { Reader reader = new InputStreamReader(stream, file.getCharset()); if (isJavaScript(file)) { loader.addSource(new FileSource(file), reader); } else if (isHtml(file)) { List<HtmlJs> frags = Html.extract(reader); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs)frag; loader.addSource(new FileSource(file, inl.getOffset()), inl.getCode()); } } } else { // ?? } } finally { stream.close(); } } catch (CoreException e) { throw new ExecutionException("Could not load file: " + file, e); } catch (IOException e) { throw new ExecutionException("Could not load file: " + file, e); } } // ===================== COMPUTE RENAMING INFO ===================== - Renaming renaming = new Renaming(asts, targetName); + Renaming renaming = new Renaming(asts); + List<ArrayList<AstNode>> questions = renaming.renameNode(targetName); // ===================== ORDERING OF QUESTIONS ===================== // Order questions such that all questions are visited in a forward manner (no jumping back and forth). // Also ensure that the current file is visited first (note: it is always the first entry in affectedResources) final Map<IFile,Integer> file2index = indexMap(affectedResources); final Comparator<ISource> sourceOrd = new Comparator<ISource>() { @Override public int compare(ISource o1, ISource o2) { FileSource fs1 = (FileSource)o1; FileSource fs2 = (FileSource)o2; int deltaIndex = file2index.get(fs1.getFileResource()) - file2index.get(fs2.getFileResource()); if (deltaIndex != 0) return deltaIndex; // if same file, compare by offset in that file return fs1.getOffset() - fs2.getOffset(); } }; final Comparator<AstNode> tokenOrd = new Comparator<AstNode>() { @Override public int compare(AstNode o1, AstNode o2) { int src = sourceOrd.compare(asts.source(o1), asts.source(o2)); if (src != 0) return src; return o1.getAbsolutePosition() - o2.getAbsolutePosition(); } }; // Order questions within each group - for (List<AstNode> list : renaming.getQuestions()) { + for (List<AstNode> list : questions) { Collections.sort(list, tokenOrd); } // Order questions by their first token - Collections.sort(renaming.getQuestions(), new Comparator<ArrayList<AstNode>>() { + Collections.sort(questions, new Comparator<ArrayList<AstNode>>() { @Override public int compare(ArrayList<AstNode> o1, ArrayList<AstNode> o2) { return tokenOrd.compare(o1.get(0), o2.get(0)); } }); // ===================== ASK EVERY QUESTION ===================== // Prompt user for each group of tokens List<AstNode> autoTokens = new ArrayList<AstNode>(); // automatically selected tokens // Automatically answer the question concerning the selected token // (Handling this here makes it easier to implement the back button in the question loop) - for (int i=0; i<renaming.getQuestions().size(); i++) { - if (renaming.getQuestions().get(i).contains(targetName)) { - autoTokens.addAll(renaming.getQuestions().get(i)); - renaming.getQuestions().remove(i); + for (int i=0; i<questions.size(); i++) { + if (questions.get(i).contains(targetName)) { + autoTokens.addAll(questions.get(i)); + questions.remove(i); break; } } // Ask the questions int questionIndex = 0; List<Integer> yesQuestions = new ArrayList<Integer>(); - while (questionIndex < renaming.getQuestions().size()) { - List<AstNode> names = renaming.getQuestions().get(questionIndex); + while (questionIndex < questions.size()) { + List<AstNode> names = questions.get(questionIndex); // select the first token in the editor AstNode name = names.get(0); FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); ITextEditor editor; try { // TODO: what if result is not an ITextEditor? editor = (ITextEditor) IDE.openEditor(currentEditor.getEditorSite().getPage(), file); } catch (PartInitException e) { throw new ExecutionException("Could not initialize editor", e); } // reveal token in the editor editor.selectAndReveal(src.getOffset() + NameRef.startPos(name), originalName.length()); // if more than one token is in this group, let the user know somehow String msgSuffix = ""; if (names.size() == 2) { msgSuffix = " (and 1 other)"; } else if (names.size() > 2) { msgSuffix = " (and " + (names.size()-1) + " others)"; } // prompt the user: should this token be renamed? int BACK; // index of the BACK button in the string array below int YES; // index of the YES button in the string array below String[] btns; if (questionIndex > 0) { BACK = 0; YES = 2; btns = new String[] {"< Back", "No", "Yes" }; } else { BACK = 3; YES = 1; btns = new String[] {"No", "Yes" }; } MessageDialog msg = new MessageDialog( window.getShell(), "Rename " + thingType, null, // no title image "Rename this token?" + msgSuffix, MessageDialog.NONE, // no image type btns, YES); int dialogReturnCode = msg.open(); // can be DEFAULT, BACK, YES, or NO // if the dialog was called (e.g. user pressed ESC) then cancel the entire refactoring if (dialogReturnCode == SWT.DEFAULT) return; if (dialogReturnCode == BACK) { // undo last answer if it was yes if (yesQuestions.size() > 0 && yesQuestions.get(yesQuestions.size()-1) == questionIndex-1) { yesQuestions.remove(yesQuestions.size()-1); } questionIndex--; // back to previous question continue; } if (dialogReturnCode == YES) { yesQuestions.add(questionIndex); } questionIndex++; // advance to next question } Set<IFile> modifiedFiles = new HashSet<IFile>(); List<AstNode> tokensToRename = new ArrayList<AstNode>(); tokensToRename.addAll(autoTokens); modifiedFiles.add(currentResource); for (int q : yesQuestions) { - tokensToRename.addAll(renaming.getQuestions().get(q)); - for (AstNode tok : renaming.getQuestions().get(q)) { + tokensToRename.addAll(questions.get(q)); + for (AstNode tok : questions.get(q)) { FileSource rsrc = (FileSource)asts.source(tok); modifiedFiles.add(rsrc.getFileResource()); } } // ===================== CLEAN UP UI ===================== // jump back to where the refactoring started // hack: we do this by selecting the original token again // do this before performing the changes, so the offset is still correct currentEditor.getEditorSite().getPage().activate(currentEditor); currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); // ===================== PERFORM CHANGES ===================== // Prepare the change set // In the following be aware of the following differences between TextFileChange and DocumentChange: // TextFileChange: changes are saved automatically, open editors will reload // DocumentChange: changes are not automatically saved, open editors will be marked dirty CompositeChange changeSet = new CompositeChange("Rename " + originalName + " to " + newName); Map<IFile,TextChange> file2changes = new HashMap<IFile,TextChange>(); if (modifiedFiles.size() == 1) { TextChange change = new DocumentChange(changeSet.getName(), doc); change.setEdit(new MultiTextEdit()); file2changes.put(currentResource, change); changeSet.add(change); } Collections.sort(tokensToRename); for (AstNode name : tokensToRename) { FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); TextChange change = file2changes.get(file); if (change == null) { change = new TextFileChange(changeSet.getName(), file); change.setEdit(new MultiTextEdit()); file2changes.put(file, change); changeSet.add(change); } change.addEdit(new ReplaceEdit(src.getOffset() + NameRef.startPos(name), originalName.length(), newName)); } // Execute the change if (newNameDialog.isPreviewSelected()) { RefactoringUtil.previewAndPerform(changeSet, changeSet.getName(), window.getShell(), changeSet.getName()); } else { RefactoringUtil.perform(changeSet, window, modifiedFiles.size() > 1); } } }
false
true
public void executeWith(final IWorkbenchWindow window, ITextEditor currentEditor) throws ExecutionException { // Pull some useful objects out of the void ITextSelection sel = (ITextSelection) currentEditor.getEditorSite().getSelectionProvider().getSelection(); IDocument doc = currentEditor.getDocumentProvider().getDocument(currentEditor.getEditorInput()); IFile currentResource = (IFile) currentEditor.getEditorInput().getAdapter(IFile.class); // ===================== CLASSIFY REFACTORING REQUEST ================= // Load the AST FileSource currentSource; final Loader loader = new Loader(); if (isJavaScript(currentResource)) { currentSource = new FileSource(currentResource); loader.addSource(currentSource, doc.get()); } else if (isHtml(currentResource)) { currentSource = null; List<HtmlJs> frags = Html.extract(doc.get()); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs) frag; FileSource src = new FileSource(currentResource, inl.getOffset()); loader.addSource(src, inl.getCode()); if (sel.getOffset() >= inl.getOffset() && sel.getOffset() <= inl.getOffset() + inl.getCode().length()) { currentSource = src; } } } if (currentSource == null) { return; // not inside JavaScript fragment } } else { return; // does not apply to this file type } final Asts asts = loader.getAsts(); // Find the selected name token AstNode targetName = NodeFinder.find(asts.get(currentSource), sel.getOffset() - currentSource.getOffset()); String originalName = NameRef.name(targetName); boolean showScope; String thingType; if (NameRef.isPrty(targetName)) { thingType = "property"; showScope = true; } else if (NameRef.isGlobalVar(targetName)) { thingType = "variable"; showScope = true; } else if (NameRef.isVar(targetName)) { thingType = "variable"; showScope = false; } else if (NameRef.isLabel(targetName)) { thingType = "label"; showScope = false; } else { return; // cannot rename this type of thing } // ===================== INITIAL USER PROMPT ================= // Prompt the new name currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); EnterNameDialog newNameDialog = new EnterNameDialog(window.getShell(), thingType, originalName); newNameDialog.setShowScope(showScope); newNameDialog.open(); if (newNameDialog.getReturnCode() != Window.OK) { return; // we got cancelled } String newName = newNameDialog.getNewName(); RefactoringScope scope = showScope ? newNameDialog.getSelectedScope() : RefactoringScope.File; // ===================== FIND/SAVE AFFECTED RESOURCES ================= // Find affected resources and save them if they are open in a dirty editor final List<IFile> affectedResources = new ArrayList<IFile>(); affectedResources.add(currentResource); switch (scope) { case File: break; case Project: case Workspace: IContainer container = scope == RefactoringScope.Project ? currentResource.getProject() : currentResource.getWorkspace().getRoot(); JavaScriptResources resources = getJavaScriptResources(container); resources.javascriptFiles.remove(currentResource); resources.htmlFiles.remove(currentResource); affectedResources.addAll(resources.javascriptFiles); affectedResources.addAll(resources.htmlFiles); try { saveOpenResources(window, new HashSet<IFile>(affectedResources)); } catch (InterruptedException e1) { return; // operation was cancelled } break; } // Load all ASTs for (IFile file : affectedResources) { if (file.equals(currentResource)) continue; try { InputStream stream = file.getContents(); try { Reader reader = new InputStreamReader(stream, file.getCharset()); if (isJavaScript(file)) { loader.addSource(new FileSource(file), reader); } else if (isHtml(file)) { List<HtmlJs> frags = Html.extract(reader); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs)frag; loader.addSource(new FileSource(file, inl.getOffset()), inl.getCode()); } } } else { // ?? } } finally { stream.close(); } } catch (CoreException e) { throw new ExecutionException("Could not load file: " + file, e); } catch (IOException e) { throw new ExecutionException("Could not load file: " + file, e); } } // ===================== COMPUTE RENAMING INFO ===================== Renaming renaming = new Renaming(asts, targetName); // ===================== ORDERING OF QUESTIONS ===================== // Order questions such that all questions are visited in a forward manner (no jumping back and forth). // Also ensure that the current file is visited first (note: it is always the first entry in affectedResources) final Map<IFile,Integer> file2index = indexMap(affectedResources); final Comparator<ISource> sourceOrd = new Comparator<ISource>() { @Override public int compare(ISource o1, ISource o2) { FileSource fs1 = (FileSource)o1; FileSource fs2 = (FileSource)o2; int deltaIndex = file2index.get(fs1.getFileResource()) - file2index.get(fs2.getFileResource()); if (deltaIndex != 0) return deltaIndex; // if same file, compare by offset in that file return fs1.getOffset() - fs2.getOffset(); } }; final Comparator<AstNode> tokenOrd = new Comparator<AstNode>() { @Override public int compare(AstNode o1, AstNode o2) { int src = sourceOrd.compare(asts.source(o1), asts.source(o2)); if (src != 0) return src; return o1.getAbsolutePosition() - o2.getAbsolutePosition(); } }; // Order questions within each group for (List<AstNode> list : renaming.getQuestions()) { Collections.sort(list, tokenOrd); } // Order questions by their first token Collections.sort(renaming.getQuestions(), new Comparator<ArrayList<AstNode>>() { @Override public int compare(ArrayList<AstNode> o1, ArrayList<AstNode> o2) { return tokenOrd.compare(o1.get(0), o2.get(0)); } }); // ===================== ASK EVERY QUESTION ===================== // Prompt user for each group of tokens List<AstNode> autoTokens = new ArrayList<AstNode>(); // automatically selected tokens // Automatically answer the question concerning the selected token // (Handling this here makes it easier to implement the back button in the question loop) for (int i=0; i<renaming.getQuestions().size(); i++) { if (renaming.getQuestions().get(i).contains(targetName)) { autoTokens.addAll(renaming.getQuestions().get(i)); renaming.getQuestions().remove(i); break; } } // Ask the questions int questionIndex = 0; List<Integer> yesQuestions = new ArrayList<Integer>(); while (questionIndex < renaming.getQuestions().size()) { List<AstNode> names = renaming.getQuestions().get(questionIndex); // select the first token in the editor AstNode name = names.get(0); FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); ITextEditor editor; try { // TODO: what if result is not an ITextEditor? editor = (ITextEditor) IDE.openEditor(currentEditor.getEditorSite().getPage(), file); } catch (PartInitException e) { throw new ExecutionException("Could not initialize editor", e); } // reveal token in the editor editor.selectAndReveal(src.getOffset() + NameRef.startPos(name), originalName.length()); // if more than one token is in this group, let the user know somehow String msgSuffix = ""; if (names.size() == 2) { msgSuffix = " (and 1 other)"; } else if (names.size() > 2) { msgSuffix = " (and " + (names.size()-1) + " others)"; } // prompt the user: should this token be renamed? int BACK; // index of the BACK button in the string array below int YES; // index of the YES button in the string array below String[] btns; if (questionIndex > 0) { BACK = 0; YES = 2; btns = new String[] {"< Back", "No", "Yes" }; } else { BACK = 3; YES = 1; btns = new String[] {"No", "Yes" }; } MessageDialog msg = new MessageDialog( window.getShell(), "Rename " + thingType, null, // no title image "Rename this token?" + msgSuffix, MessageDialog.NONE, // no image type btns, YES); int dialogReturnCode = msg.open(); // can be DEFAULT, BACK, YES, or NO // if the dialog was called (e.g. user pressed ESC) then cancel the entire refactoring if (dialogReturnCode == SWT.DEFAULT) return; if (dialogReturnCode == BACK) { // undo last answer if it was yes if (yesQuestions.size() > 0 && yesQuestions.get(yesQuestions.size()-1) == questionIndex-1) { yesQuestions.remove(yesQuestions.size()-1); } questionIndex--; // back to previous question continue; } if (dialogReturnCode == YES) { yesQuestions.add(questionIndex); } questionIndex++; // advance to next question } Set<IFile> modifiedFiles = new HashSet<IFile>(); List<AstNode> tokensToRename = new ArrayList<AstNode>(); tokensToRename.addAll(autoTokens); modifiedFiles.add(currentResource); for (int q : yesQuestions) { tokensToRename.addAll(renaming.getQuestions().get(q)); for (AstNode tok : renaming.getQuestions().get(q)) { FileSource rsrc = (FileSource)asts.source(tok); modifiedFiles.add(rsrc.getFileResource()); } } // ===================== CLEAN UP UI ===================== // jump back to where the refactoring started // hack: we do this by selecting the original token again // do this before performing the changes, so the offset is still correct currentEditor.getEditorSite().getPage().activate(currentEditor); currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); // ===================== PERFORM CHANGES ===================== // Prepare the change set // In the following be aware of the following differences between TextFileChange and DocumentChange: // TextFileChange: changes are saved automatically, open editors will reload // DocumentChange: changes are not automatically saved, open editors will be marked dirty CompositeChange changeSet = new CompositeChange("Rename " + originalName + " to " + newName); Map<IFile,TextChange> file2changes = new HashMap<IFile,TextChange>(); if (modifiedFiles.size() == 1) { TextChange change = new DocumentChange(changeSet.getName(), doc); change.setEdit(new MultiTextEdit()); file2changes.put(currentResource, change); changeSet.add(change); } Collections.sort(tokensToRename); for (AstNode name : tokensToRename) { FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); TextChange change = file2changes.get(file); if (change == null) { change = new TextFileChange(changeSet.getName(), file); change.setEdit(new MultiTextEdit()); file2changes.put(file, change); changeSet.add(change); } change.addEdit(new ReplaceEdit(src.getOffset() + NameRef.startPos(name), originalName.length(), newName)); } // Execute the change if (newNameDialog.isPreviewSelected()) { RefactoringUtil.previewAndPerform(changeSet, changeSet.getName(), window.getShell(), changeSet.getName()); } else { RefactoringUtil.perform(changeSet, window, modifiedFiles.size() > 1); } }
public void executeWith(final IWorkbenchWindow window, ITextEditor currentEditor) throws ExecutionException { // Pull some useful objects out of the void ITextSelection sel = (ITextSelection) currentEditor.getEditorSite().getSelectionProvider().getSelection(); IDocument doc = currentEditor.getDocumentProvider().getDocument(currentEditor.getEditorInput()); IFile currentResource = (IFile) currentEditor.getEditorInput().getAdapter(IFile.class); // ===================== CLASSIFY REFACTORING REQUEST ================= // Load the AST FileSource currentSource; final Loader loader = new Loader(); if (isJavaScript(currentResource)) { currentSource = new FileSource(currentResource); loader.addSource(currentSource, doc.get()); } else if (isHtml(currentResource)) { currentSource = null; List<HtmlJs> frags = Html.extract(doc.get()); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs) frag; FileSource src = new FileSource(currentResource, inl.getOffset()); loader.addSource(src, inl.getCode()); if (sel.getOffset() >= inl.getOffset() && sel.getOffset() <= inl.getOffset() + inl.getCode().length()) { currentSource = src; } } } if (currentSource == null) { return; // not inside JavaScript fragment } } else { return; // does not apply to this file type } final Asts asts = loader.getAsts(); // Find the selected name token AstNode targetName = NodeFinder.find(asts.get(currentSource), sel.getOffset() - currentSource.getOffset()); String originalName = NameRef.name(targetName); boolean showScope; String thingType; if (NameRef.isPrty(targetName)) { thingType = "property"; showScope = true; } else if (NameRef.isGlobalVar(targetName)) { thingType = "variable"; showScope = true; } else if (NameRef.isVar(targetName)) { thingType = "variable"; showScope = false; } else if (NameRef.isLabel(targetName)) { thingType = "label"; showScope = false; } else { return; // cannot rename this type of thing } // ===================== INITIAL USER PROMPT ================= // Prompt the new name currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); EnterNameDialog newNameDialog = new EnterNameDialog(window.getShell(), thingType, originalName); newNameDialog.setShowScope(showScope); newNameDialog.open(); if (newNameDialog.getReturnCode() != Window.OK) { return; // we got cancelled } String newName = newNameDialog.getNewName(); RefactoringScope scope = showScope ? newNameDialog.getSelectedScope() : RefactoringScope.File; // ===================== FIND/SAVE AFFECTED RESOURCES ================= // Find affected resources and save them if they are open in a dirty editor final List<IFile> affectedResources = new ArrayList<IFile>(); affectedResources.add(currentResource); switch (scope) { case File: break; case Project: case Workspace: IContainer container = scope == RefactoringScope.Project ? currentResource.getProject() : currentResource.getWorkspace().getRoot(); JavaScriptResources resources = getJavaScriptResources(container); resources.javascriptFiles.remove(currentResource); resources.htmlFiles.remove(currentResource); affectedResources.addAll(resources.javascriptFiles); affectedResources.addAll(resources.htmlFiles); try { saveOpenResources(window, new HashSet<IFile>(affectedResources)); } catch (InterruptedException e1) { return; // operation was cancelled } break; } // Load all ASTs for (IFile file : affectedResources) { if (file.equals(currentResource)) continue; try { InputStream stream = file.getContents(); try { Reader reader = new InputStreamReader(stream, file.getCharset()); if (isJavaScript(file)) { loader.addSource(new FileSource(file), reader); } else if (isHtml(file)) { List<HtmlJs> frags = Html.extract(reader); for (HtmlJs frag : frags) { if (frag instanceof InlineJs) { InlineJs inl = (InlineJs)frag; loader.addSource(new FileSource(file, inl.getOffset()), inl.getCode()); } } } else { // ?? } } finally { stream.close(); } } catch (CoreException e) { throw new ExecutionException("Could not load file: " + file, e); } catch (IOException e) { throw new ExecutionException("Could not load file: " + file, e); } } // ===================== COMPUTE RENAMING INFO ===================== Renaming renaming = new Renaming(asts); List<ArrayList<AstNode>> questions = renaming.renameNode(targetName); // ===================== ORDERING OF QUESTIONS ===================== // Order questions such that all questions are visited in a forward manner (no jumping back and forth). // Also ensure that the current file is visited first (note: it is always the first entry in affectedResources) final Map<IFile,Integer> file2index = indexMap(affectedResources); final Comparator<ISource> sourceOrd = new Comparator<ISource>() { @Override public int compare(ISource o1, ISource o2) { FileSource fs1 = (FileSource)o1; FileSource fs2 = (FileSource)o2; int deltaIndex = file2index.get(fs1.getFileResource()) - file2index.get(fs2.getFileResource()); if (deltaIndex != 0) return deltaIndex; // if same file, compare by offset in that file return fs1.getOffset() - fs2.getOffset(); } }; final Comparator<AstNode> tokenOrd = new Comparator<AstNode>() { @Override public int compare(AstNode o1, AstNode o2) { int src = sourceOrd.compare(asts.source(o1), asts.source(o2)); if (src != 0) return src; return o1.getAbsolutePosition() - o2.getAbsolutePosition(); } }; // Order questions within each group for (List<AstNode> list : questions) { Collections.sort(list, tokenOrd); } // Order questions by their first token Collections.sort(questions, new Comparator<ArrayList<AstNode>>() { @Override public int compare(ArrayList<AstNode> o1, ArrayList<AstNode> o2) { return tokenOrd.compare(o1.get(0), o2.get(0)); } }); // ===================== ASK EVERY QUESTION ===================== // Prompt user for each group of tokens List<AstNode> autoTokens = new ArrayList<AstNode>(); // automatically selected tokens // Automatically answer the question concerning the selected token // (Handling this here makes it easier to implement the back button in the question loop) for (int i=0; i<questions.size(); i++) { if (questions.get(i).contains(targetName)) { autoTokens.addAll(questions.get(i)); questions.remove(i); break; } } // Ask the questions int questionIndex = 0; List<Integer> yesQuestions = new ArrayList<Integer>(); while (questionIndex < questions.size()) { List<AstNode> names = questions.get(questionIndex); // select the first token in the editor AstNode name = names.get(0); FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); ITextEditor editor; try { // TODO: what if result is not an ITextEditor? editor = (ITextEditor) IDE.openEditor(currentEditor.getEditorSite().getPage(), file); } catch (PartInitException e) { throw new ExecutionException("Could not initialize editor", e); } // reveal token in the editor editor.selectAndReveal(src.getOffset() + NameRef.startPos(name), originalName.length()); // if more than one token is in this group, let the user know somehow String msgSuffix = ""; if (names.size() == 2) { msgSuffix = " (and 1 other)"; } else if (names.size() > 2) { msgSuffix = " (and " + (names.size()-1) + " others)"; } // prompt the user: should this token be renamed? int BACK; // index of the BACK button in the string array below int YES; // index of the YES button in the string array below String[] btns; if (questionIndex > 0) { BACK = 0; YES = 2; btns = new String[] {"< Back", "No", "Yes" }; } else { BACK = 3; YES = 1; btns = new String[] {"No", "Yes" }; } MessageDialog msg = new MessageDialog( window.getShell(), "Rename " + thingType, null, // no title image "Rename this token?" + msgSuffix, MessageDialog.NONE, // no image type btns, YES); int dialogReturnCode = msg.open(); // can be DEFAULT, BACK, YES, or NO // if the dialog was called (e.g. user pressed ESC) then cancel the entire refactoring if (dialogReturnCode == SWT.DEFAULT) return; if (dialogReturnCode == BACK) { // undo last answer if it was yes if (yesQuestions.size() > 0 && yesQuestions.get(yesQuestions.size()-1) == questionIndex-1) { yesQuestions.remove(yesQuestions.size()-1); } questionIndex--; // back to previous question continue; } if (dialogReturnCode == YES) { yesQuestions.add(questionIndex); } questionIndex++; // advance to next question } Set<IFile> modifiedFiles = new HashSet<IFile>(); List<AstNode> tokensToRename = new ArrayList<AstNode>(); tokensToRename.addAll(autoTokens); modifiedFiles.add(currentResource); for (int q : yesQuestions) { tokensToRename.addAll(questions.get(q)); for (AstNode tok : questions.get(q)) { FileSource rsrc = (FileSource)asts.source(tok); modifiedFiles.add(rsrc.getFileResource()); } } // ===================== CLEAN UP UI ===================== // jump back to where the refactoring started // hack: we do this by selecting the original token again // do this before performing the changes, so the offset is still correct currentEditor.getEditorSite().getPage().activate(currentEditor); currentEditor.selectAndReveal(currentSource.getOffset() + NameRef.startPos(targetName), originalName.length()); // ===================== PERFORM CHANGES ===================== // Prepare the change set // In the following be aware of the following differences between TextFileChange and DocumentChange: // TextFileChange: changes are saved automatically, open editors will reload // DocumentChange: changes are not automatically saved, open editors will be marked dirty CompositeChange changeSet = new CompositeChange("Rename " + originalName + " to " + newName); Map<IFile,TextChange> file2changes = new HashMap<IFile,TextChange>(); if (modifiedFiles.size() == 1) { TextChange change = new DocumentChange(changeSet.getName(), doc); change.setEdit(new MultiTextEdit()); file2changes.put(currentResource, change); changeSet.add(change); } Collections.sort(tokensToRename); for (AstNode name : tokensToRename) { FileSource src = (FileSource) asts.source(name); IFile file = src.getFileResource(); TextChange change = file2changes.get(file); if (change == null) { change = new TextFileChange(changeSet.getName(), file); change.setEdit(new MultiTextEdit()); file2changes.put(file, change); changeSet.add(change); } change.addEdit(new ReplaceEdit(src.getOffset() + NameRef.startPos(name), originalName.length(), newName)); } // Execute the change if (newNameDialog.isPreviewSelected()) { RefactoringUtil.previewAndPerform(changeSet, changeSet.getName(), window.getShell(), changeSet.getName()); } else { RefactoringUtil.perform(changeSet, window, modifiedFiles.size() > 1); } }
diff --git a/flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/EventQueueBackingStoreFactory.java b/flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/EventQueueBackingStoreFactory.java index faec50b6..a19bdb45 100644 --- a/flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/EventQueueBackingStoreFactory.java +++ b/flume-ng-channels/flume-file-channel/src/main/java/org/apache/flume/channel/file/EventQueueBackingStoreFactory.java @@ -1,109 +1,109 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.flume.channel.file; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.io.Files; class EventQueueBackingStoreFactory { private static final Logger LOG = LoggerFactory .getLogger(EventQueueBackingStoreFactory.class); private EventQueueBackingStoreFactory() {} static EventQueueBackingStore get(File checkpointFile, int capacity, String name) throws Exception { return get(checkpointFile, capacity, name, true); } static EventQueueBackingStore get(File checkpointFile, int capacity, String name, boolean upgrade) throws Exception { File metaDataFile = Serialization.getMetaDataFile(checkpointFile); RandomAccessFile checkpointFileHandle = null; try { boolean checkpointExists = checkpointFile.exists(); boolean metaDataExists = metaDataFile.exists(); if(metaDataExists) { // if we have a metadata file but no checkpoint file, we have a problem // delete everything in the checkpoint directory and force // a full replay. if(!checkpointExists || checkpointFile.length() == 0) { LOG.warn("MetaData file for checkpoint " + " exists but checkpoint does not. Checkpoint = " + checkpointFile + ", metaDataFile = " + metaDataFile); throw new BadCheckpointException( - "The last checkpoint was not completed correctly. " - + "Please delete all files in the checkpoint directory: " - + checkpointFile.getParentFile()); + "The last checkpoint was not completed correctly, " + + "since Checkpoint file does not exist while metadata " + + "file does."); } } // brand new, use v3 if(!checkpointExists) { if(!checkpointFile.createNewFile()) { throw new IOException("Cannot create " + checkpointFile); } return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } // v3 due to meta file, version will be checked by backing store if(metaDataExists) { return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } checkpointFileHandle = new RandomAccessFile(checkpointFile, "r"); int version = (int)checkpointFileHandle.readLong(); if(Serialization.VERSION_2 == version) { if(upgrade) { return upgrade(checkpointFile, capacity, name); } return new EventQueueBackingStoreFileV2(checkpointFile, capacity, name); } LOG.error("Found version " + Integer.toHexString(version) + " in " + checkpointFile); throw new BadCheckpointException("Checkpoint file exists with " + Serialization.VERSION_3 + " but no metadata file found."); } finally { if(checkpointFileHandle != null) { try { checkpointFileHandle.close(); } catch(IOException e) { LOG.warn("Unable to close " + checkpointFile, e); } } } } private static EventQueueBackingStore upgrade(File checkpointFile, int capacity, String name) throws Exception { LOG.info("Attempting upgrade of " + checkpointFile + " for " + name); EventQueueBackingStoreFileV2 backingStoreV2 = new EventQueueBackingStoreFileV2(checkpointFile, capacity, name); String backupName = checkpointFile.getName() + "-backup-" + System.currentTimeMillis(); Files.copy(checkpointFile, new File(checkpointFile.getParentFile(), backupName)); File metaDataFile = Serialization.getMetaDataFile(checkpointFile); EventQueueBackingStoreFileV3.upgrade(backingStoreV2, checkpointFile, metaDataFile); return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } }
true
true
static EventQueueBackingStore get(File checkpointFile, int capacity, String name, boolean upgrade) throws Exception { File metaDataFile = Serialization.getMetaDataFile(checkpointFile); RandomAccessFile checkpointFileHandle = null; try { boolean checkpointExists = checkpointFile.exists(); boolean metaDataExists = metaDataFile.exists(); if(metaDataExists) { // if we have a metadata file but no checkpoint file, we have a problem // delete everything in the checkpoint directory and force // a full replay. if(!checkpointExists || checkpointFile.length() == 0) { LOG.warn("MetaData file for checkpoint " + " exists but checkpoint does not. Checkpoint = " + checkpointFile + ", metaDataFile = " + metaDataFile); throw new BadCheckpointException( "The last checkpoint was not completed correctly. " + "Please delete all files in the checkpoint directory: " + checkpointFile.getParentFile()); } } // brand new, use v3 if(!checkpointExists) { if(!checkpointFile.createNewFile()) { throw new IOException("Cannot create " + checkpointFile); } return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } // v3 due to meta file, version will be checked by backing store if(metaDataExists) { return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } checkpointFileHandle = new RandomAccessFile(checkpointFile, "r"); int version = (int)checkpointFileHandle.readLong(); if(Serialization.VERSION_2 == version) { if(upgrade) { return upgrade(checkpointFile, capacity, name); } return new EventQueueBackingStoreFileV2(checkpointFile, capacity, name); } LOG.error("Found version " + Integer.toHexString(version) + " in " + checkpointFile); throw new BadCheckpointException("Checkpoint file exists with " + Serialization.VERSION_3 + " but no metadata file found."); } finally { if(checkpointFileHandle != null) { try { checkpointFileHandle.close(); } catch(IOException e) { LOG.warn("Unable to close " + checkpointFile, e); } } } }
static EventQueueBackingStore get(File checkpointFile, int capacity, String name, boolean upgrade) throws Exception { File metaDataFile = Serialization.getMetaDataFile(checkpointFile); RandomAccessFile checkpointFileHandle = null; try { boolean checkpointExists = checkpointFile.exists(); boolean metaDataExists = metaDataFile.exists(); if(metaDataExists) { // if we have a metadata file but no checkpoint file, we have a problem // delete everything in the checkpoint directory and force // a full replay. if(!checkpointExists || checkpointFile.length() == 0) { LOG.warn("MetaData file for checkpoint " + " exists but checkpoint does not. Checkpoint = " + checkpointFile + ", metaDataFile = " + metaDataFile); throw new BadCheckpointException( "The last checkpoint was not completed correctly, " + "since Checkpoint file does not exist while metadata " + "file does."); } } // brand new, use v3 if(!checkpointExists) { if(!checkpointFile.createNewFile()) { throw new IOException("Cannot create " + checkpointFile); } return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } // v3 due to meta file, version will be checked by backing store if(metaDataExists) { return new EventQueueBackingStoreFileV3(checkpointFile, capacity, name); } checkpointFileHandle = new RandomAccessFile(checkpointFile, "r"); int version = (int)checkpointFileHandle.readLong(); if(Serialization.VERSION_2 == version) { if(upgrade) { return upgrade(checkpointFile, capacity, name); } return new EventQueueBackingStoreFileV2(checkpointFile, capacity, name); } LOG.error("Found version " + Integer.toHexString(version) + " in " + checkpointFile); throw new BadCheckpointException("Checkpoint file exists with " + Serialization.VERSION_3 + " but no metadata file found."); } finally { if(checkpointFileHandle != null) { try { checkpointFileHandle.close(); } catch(IOException e) { LOG.warn("Unable to close " + checkpointFile, e); } } } }
diff --git a/server/cpw/mods/fml/server/FMLServerHandler.java b/server/cpw/mods/fml/server/FMLServerHandler.java index 1a1934ad..6fcf004f 100644 --- a/server/cpw/mods/fml/server/FMLServerHandler.java +++ b/server/cpw/mods/fml/server/FMLServerHandler.java @@ -1,178 +1,177 @@ /* * The FML Forge Mod Loader suite. Copyright (C) 2012 cpw * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package cpw.mods.fml.server; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Random; import java.util.logging.Logger; import net.minecraft.server.MinecraftServer; import net.minecraft.src.BaseMod; import net.minecraft.src.BiomeGenBase; import net.minecraft.src.Block; import net.minecraft.src.Entity; import net.minecraft.src.EntityItem; import net.minecraft.src.EntityPlayer; import net.minecraft.src.EntityPlayerMP; import net.minecraft.src.IChunkProvider; import net.minecraft.src.ICommandManager; import net.minecraft.src.IInventory; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.MLProp; import net.minecraft.src.NetworkManager; import net.minecraft.src.Packet1Login; import net.minecraft.src.Packet250CustomPayload; import net.minecraft.src.Packet3Chat; import net.minecraft.src.Profiler; import net.minecraft.src.StringTranslate; import net.minecraft.src.World; import net.minecraft.src.WorldType; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.IFMLSidedHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModContainer; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.ObfuscationReflectionHelper; import cpw.mods.fml.common.ProxyInjector; import cpw.mods.fml.common.Side; import cpw.mods.fml.common.modloader.ModLoaderModContainer; import cpw.mods.fml.common.modloader.ModProperty; import cpw.mods.fml.common.network.EntitySpawnAdjustmentPacket; import cpw.mods.fml.common.network.EntitySpawnPacket; /** * Handles primary communication from hooked code into the system * * The FML entry point is {@link #onPreLoad(MinecraftServer)} called from * {@link MinecraftServer} * * Obfuscated code should focus on this class and other members of the "server" * (or "client") code * * The actual mod loading is handled at arms length by {@link Loader} * * It is expected that a similar class will exist for each target environment: * Bukkit and Client side. * * It should not be directly modified. * * @author cpw * */ public class FMLServerHandler implements IFMLSidedHandler { /** * The singleton */ private static final FMLServerHandler INSTANCE = new FMLServerHandler(); /** * A reference to the server itself */ private MinecraftServer server; private FMLServerHandler() { FMLCommonHandler.instance().beginLoading(this); } /** * Called to start the whole game off from * {@link MinecraftServer#startServer} * * @param minecraftServer */ public void beginServerLoading(MinecraftServer minecraftServer) { server = minecraftServer; ObfuscationReflectionHelper.detectObfuscation(World.class); - FMLCommonHandler.instance().beginLoading(this); Loader.instance().loadMods(); } /** * Called a bit later on during server initialization to finish loading mods */ public void finishServerLoading() { Loader.instance().initializeMods(); } @Override public void haltGame(String message, Throwable exception) { throw new RuntimeException(message, exception); } /** * Get the server instance * * @return */ public MinecraftServer getServer() { return server; } /** * @return the instance */ public static FMLServerHandler instance() { return INSTANCE; } /* (non-Javadoc) * @see cpw.mods.fml.common.IFMLSidedHandler#getAdditionalBrandingInformation() */ @Override public List<String> getAdditionalBrandingInformation() { return null; } /* (non-Javadoc) * @see cpw.mods.fml.common.IFMLSidedHandler#getSide() */ @Override public Side getSide() { return Side.SERVER; } @Override public void showGuiScreen(Object clientGuiElement) { } @Override public Entity spawnEntityIntoClientWorld(Class<? extends Entity> entityClass, EntitySpawnPacket packet) { // NOOP return null; } @Override public void adjustEntityLocationOnClient(EntitySpawnAdjustmentPacket entitySpawnAdjustmentPacket) { // NOOP } }
true
true
public void beginServerLoading(MinecraftServer minecraftServer) { server = minecraftServer; ObfuscationReflectionHelper.detectObfuscation(World.class); FMLCommonHandler.instance().beginLoading(this); Loader.instance().loadMods(); }
public void beginServerLoading(MinecraftServer minecraftServer) { server = minecraftServer; ObfuscationReflectionHelper.detectObfuscation(World.class); Loader.instance().loadMods(); }
diff --git a/agile-apps/agile-app-milestones/src/main/java/org/headsupdev/agile/app/milestones/WorkRemainingTable.java b/agile-apps/agile-app-milestones/src/main/java/org/headsupdev/agile/app/milestones/WorkRemainingTable.java index 15e4441f..1a334bd3 100644 --- a/agile-apps/agile-app-milestones/src/main/java/org/headsupdev/agile/app/milestones/WorkRemainingTable.java +++ b/agile-apps/agile-app-milestones/src/main/java/org/headsupdev/agile/app/milestones/WorkRemainingTable.java @@ -1,146 +1,146 @@ /* * HeadsUp Agile * Copyright 2009-2012 Heads Up Development Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.headsupdev.agile.app.milestones; import org.headsupdev.agile.api.Project; import org.headsupdev.agile.api.User; import org.headsupdev.agile.storage.StoredProject; import org.headsupdev.agile.storage.issues.*; import org.headsupdev.agile.web.components.StripedListView; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.panel.Panel; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * A tabular layout of the duration worked for a milestone * * @author Andrew Williams * @version $Id$ * @since 1.0 */ public class WorkRemainingTable extends Panel { public WorkRemainingTable( String id, final Milestone milestone ) { this( id, milestone.getProject(), milestone.getIssues() ); } public WorkRemainingTable( String id, final MilestoneGroup group ) { this( id, group.getProject(), group.getIssues() ); } protected WorkRemainingTable( String id, final Project project, final Set<Issue> issueSet ) { super( id ); final boolean burndown = Boolean.parseBoolean( project.getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN) ); List<User> users = new LinkedList<User>(); for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && !users.contains( issue.getAssignee() ) ) { users.add( issue.getAssignee() ); } for ( DurationWorked worked : issue.getTimeWorked() ) { if ( worked.getUser() != null && !users.contains( worked.getUser() ) ) { users.add( worked.getUser() ); } } } List<Issue> issues = new LinkedList<Issue>( issueSet ); Collections.sort( issues, new IssueComparator() ); add( new StripedListView<User>( "person", users ) { @Override protected void populateItem( ListItem<User> listItem ) { super.populateItem( listItem ); final User user = listItem.getModelObject(); if ( user.isHiddenInTimeTracking() ) { listItem.setVisible( false ); return; } listItem.add( new Label( "user", user.getFullnameOrUsername() ) ); int estimate = 0; int worked = 0; int remaining = 0; for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && issue.getAssignee().equals( user ) ) { if ( issue.getTimeEstimate() != null && issue.getTimeEstimate().getHours() > 0 ) { double e = issue.getTimeEstimate().getHours(); estimate += e; if ( burndown ) { if (issue.getTimeRequired() != null) { remaining += issue.getTimeRequired().getHours(); } } else { if ( issue.getTimeRequired() != null ) { double r = issue.getTimeRequired().getHours(); double delta = e - r; if ( delta > 0 ) { remaining += delta; } } } } } for ( DurationWorked dur : issue.getTimeWorked() ) { if ( user.equals( dur.getUser() ) && dur.getWorked() != null ) { worked += dur.getWorked().getHours(); } } } - listItem.add( new Label( "estimate", new Duration( estimate ).toString()) ); - listItem.add( new Label( "worked", new Duration( worked ).toString()) ); - listItem.add( new Label( "remaining", new Duration( remaining ).toString()) ); + listItem.add( new Label( "estimate", new Duration( estimate ).toHoursWithFractionString() ) ); + listItem.add( new Label( "worked", new Duration( worked ).toHoursWithFractionString() ) ); + listItem.add( new Label( "remaining", new Duration( remaining ).toHoursWithFractionString() ) ); } } ); } }
true
true
protected WorkRemainingTable( String id, final Project project, final Set<Issue> issueSet ) { super( id ); final boolean burndown = Boolean.parseBoolean( project.getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN) ); List<User> users = new LinkedList<User>(); for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && !users.contains( issue.getAssignee() ) ) { users.add( issue.getAssignee() ); } for ( DurationWorked worked : issue.getTimeWorked() ) { if ( worked.getUser() != null && !users.contains( worked.getUser() ) ) { users.add( worked.getUser() ); } } } List<Issue> issues = new LinkedList<Issue>( issueSet ); Collections.sort( issues, new IssueComparator() ); add( new StripedListView<User>( "person", users ) { @Override protected void populateItem( ListItem<User> listItem ) { super.populateItem( listItem ); final User user = listItem.getModelObject(); if ( user.isHiddenInTimeTracking() ) { listItem.setVisible( false ); return; } listItem.add( new Label( "user", user.getFullnameOrUsername() ) ); int estimate = 0; int worked = 0; int remaining = 0; for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && issue.getAssignee().equals( user ) ) { if ( issue.getTimeEstimate() != null && issue.getTimeEstimate().getHours() > 0 ) { double e = issue.getTimeEstimate().getHours(); estimate += e; if ( burndown ) { if (issue.getTimeRequired() != null) { remaining += issue.getTimeRequired().getHours(); } } else { if ( issue.getTimeRequired() != null ) { double r = issue.getTimeRequired().getHours(); double delta = e - r; if ( delta > 0 ) { remaining += delta; } } } } } for ( DurationWorked dur : issue.getTimeWorked() ) { if ( user.equals( dur.getUser() ) && dur.getWorked() != null ) { worked += dur.getWorked().getHours(); } } } listItem.add( new Label( "estimate", new Duration( estimate ).toString()) ); listItem.add( new Label( "worked", new Duration( worked ).toString()) ); listItem.add( new Label( "remaining", new Duration( remaining ).toString()) ); } } ); }
protected WorkRemainingTable( String id, final Project project, final Set<Issue> issueSet ) { super( id ); final boolean burndown = Boolean.parseBoolean( project.getConfigurationValue( StoredProject.CONFIGURATION_TIMETRACKING_BURNDOWN) ); List<User> users = new LinkedList<User>(); for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && !users.contains( issue.getAssignee() ) ) { users.add( issue.getAssignee() ); } for ( DurationWorked worked : issue.getTimeWorked() ) { if ( worked.getUser() != null && !users.contains( worked.getUser() ) ) { users.add( worked.getUser() ); } } } List<Issue> issues = new LinkedList<Issue>( issueSet ); Collections.sort( issues, new IssueComparator() ); add( new StripedListView<User>( "person", users ) { @Override protected void populateItem( ListItem<User> listItem ) { super.populateItem( listItem ); final User user = listItem.getModelObject(); if ( user.isHiddenInTimeTracking() ) { listItem.setVisible( false ); return; } listItem.add( new Label( "user", user.getFullnameOrUsername() ) ); int estimate = 0; int worked = 0; int remaining = 0; for ( Issue issue : issueSet ) { if ( issue.getAssignee() != null && issue.getAssignee().equals( user ) ) { if ( issue.getTimeEstimate() != null && issue.getTimeEstimate().getHours() > 0 ) { double e = issue.getTimeEstimate().getHours(); estimate += e; if ( burndown ) { if (issue.getTimeRequired() != null) { remaining += issue.getTimeRequired().getHours(); } } else { if ( issue.getTimeRequired() != null ) { double r = issue.getTimeRequired().getHours(); double delta = e - r; if ( delta > 0 ) { remaining += delta; } } } } } for ( DurationWorked dur : issue.getTimeWorked() ) { if ( user.equals( dur.getUser() ) && dur.getWorked() != null ) { worked += dur.getWorked().getHours(); } } } listItem.add( new Label( "estimate", new Duration( estimate ).toHoursWithFractionString() ) ); listItem.add( new Label( "worked", new Duration( worked ).toHoursWithFractionString() ) ); listItem.add( new Label( "remaining", new Duration( remaining ).toHoursWithFractionString() ) ); } } ); }
diff --git a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java b/src/main/java/net/h31ix/anticheat/xray/XRayListener.java index 7cce08f..93580f3 100644 --- a/src/main/java/net/h31ix/anticheat/xray/XRayListener.java +++ b/src/main/java/net/h31ix/anticheat/xray/XRayListener.java @@ -1,64 +1,64 @@ /* * AntiCheat for Bukkit. * Copyright (C) 2012-2013 AntiCheat Team | http://gravitydevelopment.net * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.h31ix.anticheat.xray; import net.h31ix.anticheat.Anticheat; import net.h31ix.anticheat.manage.CheckManager; import net.h31ix.anticheat.manage.CheckType; import net.h31ix.anticheat.util.Configuration; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; public class XRayListener implements Listener { private XRayTracker tracker = Anticheat.getManager().getXRayTracker(); private Configuration config = Anticheat.getManager().getConfiguration(); private CheckManager checkManager = Anticheat.getManager().getCheckManager(); @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (config.logXRay()) { Player p = event.getPlayer(); if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; } String player = p.getName(); if (checkManager.willCheck(p, CheckType.XRAY)) { Material m = event.getBlock().getType(); if (m == Material.DIAMOND_ORE) { tracker.addDiamond(player); } else if (m == Material.IRON_ORE) { tracker.addIron(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else if (m == Material.LAPIS_ORE) { tracker.addLapis(player); - } else if (m == Material.REDSTONE_ORE) { + } else if (m == Material.REDSTONE_ORE || m == Material.GLOWING_REDSTONE_ORE) { tracker.addRedstone(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else { tracker.addBlock(player); } tracker.addTotal(player); } } } }
true
true
public void onBlockBreak(BlockBreakEvent event) { if (config.logXRay()) { Player p = event.getPlayer(); if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; } String player = p.getName(); if (checkManager.willCheck(p, CheckType.XRAY)) { Material m = event.getBlock().getType(); if (m == Material.DIAMOND_ORE) { tracker.addDiamond(player); } else if (m == Material.IRON_ORE) { tracker.addIron(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else if (m == Material.LAPIS_ORE) { tracker.addLapis(player); } else if (m == Material.REDSTONE_ORE) { tracker.addRedstone(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else { tracker.addBlock(player); } tracker.addTotal(player); } } }
public void onBlockBreak(BlockBreakEvent event) { if (config.logXRay()) { Player p = event.getPlayer(); if (p.getGameMode() == GameMode.CREATIVE && !config.trackCreativeXRay()) { return; } String player = p.getName(); if (checkManager.willCheck(p, CheckType.XRAY)) { Material m = event.getBlock().getType(); if (m == Material.DIAMOND_ORE) { tracker.addDiamond(player); } else if (m == Material.IRON_ORE) { tracker.addIron(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else if (m == Material.LAPIS_ORE) { tracker.addLapis(player); } else if (m == Material.REDSTONE_ORE || m == Material.GLOWING_REDSTONE_ORE) { tracker.addRedstone(player); } else if (m == Material.GOLD_ORE) { tracker.addGold(player); } else { tracker.addBlock(player); } tracker.addTotal(player); } } }
diff --git a/LogicMail/src/org/logicprobe/LogicMail/LogicMail.java b/LogicMail/src/org/logicprobe/LogicMail/LogicMail.java index ca6f0db..33e1f60 100644 --- a/LogicMail/src/org/logicprobe/LogicMail/LogicMail.java +++ b/LogicMail/src/org/logicprobe/LogicMail/LogicMail.java @@ -1,184 +1,184 @@ /*- * Copyright (c) 2009, Derek Konigsberg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.logicprobe.LogicMail; import java.util.Calendar; import java.util.Hashtable; import net.rim.blackberry.api.homescreen.HomeScreen; import net.rim.device.api.i18n.Locale; import net.rim.device.api.notification.NotificationsConstants; import net.rim.device.api.notification.NotificationsManager; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.EventLogger; import net.rim.device.api.system.RuntimeStore; import net.rim.device.api.ui.UiApplication; import org.logicprobe.LogicMail.ui.NavigationController; import org.logicprobe.LogicMail.ui.NotificationHandler; import org.logicprobe.LogicMail.conf.AccountConfig; import org.logicprobe.LogicMail.conf.MailSettings; /* * Logging levels: * EventLogger.ALWAYS_LOG = 0 * EventLogger.SEVERE_ERROR = 1 * EventLogger.ERROR = 2 * EventLogger.WARNING = 3 * EventLogger.INFORMATION = 4 * EventLogger.DEBUG_INFO = 5 */ /** * Main class for the application. */ public class LogicMail extends UiApplication { NavigationController navigationController; /** * Instantiates a new instance of the application. * * @param autoStart True if this is the autostart instance, false for normal startup */ public LogicMail(String[] args) { boolean autoStart = false; for(int i=0; i<args.length; i++) { if(args[i].indexOf("autostartup") != -1) { autoStart = true; } } AppInfo.initialize(args); if(autoStart) { doAutoStart(); } else { // Load the configuration MailSettings.getInstance().loadSettings(); // Set the language, if configured String languageCode = MailSettings.getInstance().getGlobalConfig().getLanguageCode(); - if(languageCode != null) { + if(languageCode != null && languageCode.length() > 0) { try { Locale.setDefault(Locale.get(languageCode)); } catch (Exception e) { } } // Log application startup information if(EventLogger.getMinimumLevel() >= EventLogger.INFORMATION) { StringBuffer buf = new StringBuffer(); buf.append("Application startup\r\n"); buf.append("Date: "); buf.append(Calendar.getInstance().getTime().toString()); buf.append("\r\n"); buf.append("Name: "); buf.append(AppInfo.getName()); buf.append("\r\n"); buf.append("Version: "); buf.append(AppInfo.getVersion()); buf.append("\r\n"); buf.append("Platform: "); buf.append(AppInfo.getPlatformVersion()); buf.append("\r\n"); EventLogger.logEvent(AppInfo.GUID, buf.toString().getBytes(), EventLogger.INFORMATION); } // Initialize the notification handler NotificationHandler.getInstance().setEnabled(true); // Initialize the navigation controller navigationController = new NavigationController(this); // Push the mail home screen navigationController.displayMailHome(); } } /** * Run the application. */ public void run() { enterEventDispatcher(); } /** * Method to execute in autostart mode. */ private void doAutoStart() { invokeLater(new Runnable() { public void run() { ApplicationManager myApp = ApplicationManager.getApplicationManager(); boolean keepGoing = true; while (keepGoing) { if (myApp.inStartup()) { try { Thread.sleep(1000); } catch (Exception ex) { } } else { // The BlackBerry has finished its startup process // Configure the rollover icons HomeScreen.updateIcon(AppInfo.getIcon(), 0); HomeScreen.setRolloverIcon(AppInfo.getRolloverIcon(), 0); // Configure a notification source for each account MailSettings mailSettings = MailSettings.getInstance(); mailSettings.loadSettings(); int numAccounts = mailSettings.getNumAccounts(); Hashtable eventSourceMap = new Hashtable(numAccounts); for(int i=0; i<numAccounts; i++) { AccountConfig accountConfig = mailSettings.getAccountConfig(i); LogicMailEventSource eventSource = new LogicMailEventSource(accountConfig.getAcctName(), accountConfig.getUniqueId()); NotificationsManager.registerSource( eventSource.getEventSourceId(), eventSource, NotificationsConstants.CASUAL); eventSourceMap.put(new Long(accountConfig.getUniqueId()), eventSource); } // Save the registered event sources in the runtime store RuntimeStore.getRuntimeStore().put(AppInfo.GUID, eventSourceMap); keepGoing = false; } } //Exit the application. System.exit(0); } }); } }
true
true
public LogicMail(String[] args) { boolean autoStart = false; for(int i=0; i<args.length; i++) { if(args[i].indexOf("autostartup") != -1) { autoStart = true; } } AppInfo.initialize(args); if(autoStart) { doAutoStart(); } else { // Load the configuration MailSettings.getInstance().loadSettings(); // Set the language, if configured String languageCode = MailSettings.getInstance().getGlobalConfig().getLanguageCode(); if(languageCode != null) { try { Locale.setDefault(Locale.get(languageCode)); } catch (Exception e) { } } // Log application startup information if(EventLogger.getMinimumLevel() >= EventLogger.INFORMATION) { StringBuffer buf = new StringBuffer(); buf.append("Application startup\r\n"); buf.append("Date: "); buf.append(Calendar.getInstance().getTime().toString()); buf.append("\r\n"); buf.append("Name: "); buf.append(AppInfo.getName()); buf.append("\r\n"); buf.append("Version: "); buf.append(AppInfo.getVersion()); buf.append("\r\n"); buf.append("Platform: "); buf.append(AppInfo.getPlatformVersion()); buf.append("\r\n"); EventLogger.logEvent(AppInfo.GUID, buf.toString().getBytes(), EventLogger.INFORMATION); } // Initialize the notification handler NotificationHandler.getInstance().setEnabled(true); // Initialize the navigation controller navigationController = new NavigationController(this); // Push the mail home screen navigationController.displayMailHome(); } }
public LogicMail(String[] args) { boolean autoStart = false; for(int i=0; i<args.length; i++) { if(args[i].indexOf("autostartup") != -1) { autoStart = true; } } AppInfo.initialize(args); if(autoStart) { doAutoStart(); } else { // Load the configuration MailSettings.getInstance().loadSettings(); // Set the language, if configured String languageCode = MailSettings.getInstance().getGlobalConfig().getLanguageCode(); if(languageCode != null && languageCode.length() > 0) { try { Locale.setDefault(Locale.get(languageCode)); } catch (Exception e) { } } // Log application startup information if(EventLogger.getMinimumLevel() >= EventLogger.INFORMATION) { StringBuffer buf = new StringBuffer(); buf.append("Application startup\r\n"); buf.append("Date: "); buf.append(Calendar.getInstance().getTime().toString()); buf.append("\r\n"); buf.append("Name: "); buf.append(AppInfo.getName()); buf.append("\r\n"); buf.append("Version: "); buf.append(AppInfo.getVersion()); buf.append("\r\n"); buf.append("Platform: "); buf.append(AppInfo.getPlatformVersion()); buf.append("\r\n"); EventLogger.logEvent(AppInfo.GUID, buf.toString().getBytes(), EventLogger.INFORMATION); } // Initialize the notification handler NotificationHandler.getInstance().setEnabled(true); // Initialize the navigation controller navigationController = new NavigationController(this); // Push the mail home screen navigationController.displayMailHome(); } }
diff --git a/jetty/src/main/java/org/mortbay/jetty/handler/ContextHandler.java b/jetty/src/main/java/org/mortbay/jetty/handler/ContextHandler.java index 8d6468cd1..96b21bf4b 100644 --- a/jetty/src/main/java/org/mortbay/jetty/handler/ContextHandler.java +++ b/jetty/src/main/java/org/mortbay/jetty/handler/ContextHandler.java @@ -1,1251 +1,1254 @@ //======================================================================== //$Id: ContextHandler.java,v 1.16 2005/11/17 11:19:45 gregwilkins Exp $ //Copyright 2004-2005 Mort Bay Consulting Pty. Ltd. //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== package org.mortbay.jetty.handler; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mortbay.io.Buffer; import org.mortbay.jetty.Handler; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.Request; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Dispatcher; import org.mortbay.log.Log; import org.mortbay.log.Logger; import org.mortbay.resource.Resource; import org.mortbay.util.Attributes; import org.mortbay.util.AttributesMap; import org.mortbay.util.LazyList; import org.mortbay.util.Loader; import org.mortbay.util.URIUtil; /* ------------------------------------------------------------ */ /** ContextHandler. * * This handler wraps a call to handle by setting the context and * servlet path, plus setting the context classloader. * * @org.apache.xbean.XBean description="Creates a basic HTTP context" * * @author gregw * */ public class ContextHandler extends WrappedHandler implements Attributes { private static ThreadLocal __context=new ThreadLocal(); /* ------------------------------------------------------------ */ /** Get the current ServletContext implementation. * This call is only valid during a call to doStart and is available to * nested handlers to access the context. * * @return ServletContext implementation */ public static Context getCurrentContext() { Context context = (Context)__context.get(); if (context==null) throw new IllegalStateException("Only valid during call to doStart()"); return context; } private Attributes _attributes; private Attributes _contextAttributes; private ClassLoader _classLoader; private Context _context; private String _contextPath; private HashMap _initParams; private String _displayName; private String _docRoot; private Resource _baseResource; private MimeTypes _mimeTypes; private Map _localeEncodingMap; private String[] _welcomeFiles; private ErrorHandler _errorHandler; private String[] _hosts; private String[] _vhosts; private EventListener[] _eventListeners; Logger logger; private Object _contextListeners; private Object _contextAttributeListeners; private Object _requestListeners; private Object _requestAttributeListeners; /* ------------------------------------------------------------ */ /** * */ public ContextHandler() { super(); _context=new Context(); _attributes=new AttributesMap(); _initParams=new HashMap(); } /* ------------------------------------------------------------ */ public void setServer(Server server) { if (getServer()!=null && getServer()!=server) getServer().getContainer().update(this, _errorHandler, null, "error"); if (server!=null && getServer()!=server) server.getContainer().update(this, null, _errorHandler, "error"); super.setServer(server); if (_errorHandler!=null) _errorHandler.setServer(server); } /* ------------------------------------------------------------ */ /** Set the virtual hosts for the context. * Only requests that have a matching host header or fully qualified * URL will be passed to that context with a virtual host name. * A context with no virtual host names or a null virtual host name is * available to all requests that are not served by a context with a * matching virtual host name. * @param hosts Array of virtual hosts that this context responds to. A * null host name or null/empty array means any hostname is acceptable. * Host names may String representation of IP addresses. */ public void setVirtualHosts(String[] vhosts) { _vhosts=vhosts; } /* ------------------------------------------------------------ */ /** Get the virtual hosts for the context. * Only requests that have a matching host header or fully qualified * URL will be passed to that context with a virtual host name. * A context with no virtual host names or a null virtual host name is * available to all requests that are not served by a context with a * matching virtual host name. * @return Array of virtual hosts that this context responds to. A * null host name or empty array means any hostname is acceptable. * Host names may be String representation of IP addresses. */ public String[] getVirtualHosts() { return _vhosts; } /* ------------------------------------------------------------ */ /** Set the hosts for the context. * Set the real hosts that this context will accept requests for. * If not null or empty, then only requests from server for hosts * in this array are accepted by this context. */ public void setHosts(String[] hosts) { _hosts=hosts; } /* ------------------------------------------------------------ */ /** Get the hosts for the context. */ public String[] getHosts() { return _hosts; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getAttribute(java.lang.String) */ public Object getAttribute(String name) { return _attributes.getAttribute(name); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getAttributeNames() */ public Enumeration getAttributeNames() { return _attributes.getAttributeNames(); } /* ------------------------------------------------------------ */ /** * @return Returns the attributes. */ public Attributes getAttributes() { return _attributes; } /* ------------------------------------------------------------ */ /** * @return Returns the classLoader. */ public ClassLoader getClassLoader() { return _classLoader; } /* ------------------------------------------------------------ */ /** * @return Returns the _contextPath. */ public String getContextPath() { return _contextPath; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getInitParameter(java.lang.String) */ public String getInitParameter(String name) { return (String)_initParams.get(name); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getInitParameterNames() */ public Enumeration getInitParameterNames() { return Collections.enumeration(_initParams.keySet()); } /* ------------------------------------------------------------ */ /** * @return Returns the initParams. */ public HashMap getInitParams() { return _initParams; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServletContextName() */ public String getDisplayName() { return _displayName; } /* ------------------------------------------------------------ */ public EventListener[] getEventListeners() { return _eventListeners; } /* ------------------------------------------------------------ */ public void setEventListeners(EventListener[] eventListeners) { _contextListeners=null; _contextAttributeListeners=null; _requestListeners=null; _requestAttributeListeners=null; _eventListeners=eventListeners; for (int i=0; eventListeners!=null && i<eventListeners.length;i ++) { EventListener listener = _eventListeners[i]; if (listener instanceof ServletContextListener) _contextListeners= LazyList.add(_contextListeners, listener); if (listener instanceof ServletContextAttributeListener) _contextAttributeListeners= LazyList.add(_contextAttributeListeners, listener); if (listener instanceof ServletRequestListener) _requestListeners= LazyList.add(_requestListeners, listener); if (listener instanceof ServletRequestAttributeListener) _requestAttributeListeners= LazyList.add(_requestAttributeListeners, listener); } } /* ------------------------------------------------------------ */ /* * @see org.mortbay.thread.AbstractLifeCycle#doStart() */ protected void doStart() throws Exception { logger=Log.getLogger(getDisplayName()==null?getContextPath():getDisplayName()); ClassLoader old_classloader=null; Thread current_thread=null; Object old_context=null; _contextAttributes=new AttributesMap(); try { // Set the classloader if (_classLoader!=null) { current_thread=Thread.currentThread(); old_classloader=current_thread.getContextClassLoader(); current_thread.setContextClassLoader(_classLoader); } if (_mimeTypes==null) _mimeTypes=new MimeTypes(); old_context=__context.get(); __context.set(_context); if (_errorHandler==null) _errorHandler=new ErrorHandler(); startContext(); } finally { __context.set(old_context); // reset the classloader if (_classLoader!=null) { current_thread.setContextClassLoader(old_classloader); } } } /* ------------------------------------------------------------ */ protected void startContext() throws Exception { super.doStart(); // Context listeners if (_contextListeners != null ) { ServletContextEvent event= new ServletContextEvent(_context); for (int i= 0; i < LazyList.size(_contextListeners); i++) { ((ServletContextListener)LazyList.get(_contextListeners, i)).contextInitialized(event); } } } /* ------------------------------------------------------------ */ /* * @see org.mortbay.thread.AbstractLifeCycle#doStop() */ protected void doStop() throws Exception { ClassLoader old_classloader=null; Thread current_thread=null; Object old_context=__context.get(); __context.set(_context); try { // Set the classloader if (_classLoader!=null) { current_thread=Thread.currentThread(); old_classloader=current_thread.getContextClassLoader(); current_thread.setContextClassLoader(_classLoader); } super.doStop(); // Context listeners if (_contextListeners != null ) { ServletContextEvent event= new ServletContextEvent(_context); for (int i= 0; i < LazyList.size(_contextListeners); i++) { ((ServletContextListener)LazyList.get(_contextListeners, i)).contextDestroyed(event); } } } finally { __context.set(old_context); // reset the classloader if (_classLoader!=null) current_thread.setContextClassLoader(old_classloader); } _contextAttributes.clearAttributes(); _contextAttributes=null; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public boolean handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { boolean handled=false; boolean new_context=false; Request base_request=null; Context old_context=null; String old_context_path=null; String old_servlet_path=null; String old_path_info=null; ClassLoader old_classloader=null; Thread current_thread=null; base_request=(request instanceof Request)?(Request)request:HttpConnection.getCurrentConnection().getRequest(); old_context=base_request.getContext(); // Are we already in this context? if (old_context!=_context) { new_context=true; // Check the vhosts if (_vhosts!=null && _vhosts.length>0) { String vhost=request.getServerName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_vhosts.length;i++) match=_vhosts[i]!=null && _vhosts[i].equalsIgnoreCase(vhost); if (!match) return false; } // Check the real hosts if (_hosts!=null && _hosts.length>0) { String host=request.getLocalName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_hosts.length;i++) match=_hosts[i]!=null && _hosts[i].equalsIgnoreCase(host); if (!match) return false; } // Nope - so check the target. if (dispatch==REQUEST) { if (target.equals(_contextPath)) { target=_contextPath; if (!target.endsWith("/")) { - response.sendRedirect(target+"/"); + if (request.getQueryString()!=null) + response.sendRedirect(target+"/?"+request.getQueryString()); + else + response.sendRedirect(target+"/"); return true; } } else if (target.startsWith(_contextPath) && (_contextPath.length()==1 || target.charAt(_contextPath.length())=='/')) { if (_contextPath.length()>1) target=target.substring(_contextPath.length()); } else { // Not for this context! return false; } } } try { old_context_path=base_request.getContextPath(); old_servlet_path=base_request.getServletPath(); old_path_info=base_request.getPathInfo(); // Update the paths base_request.setContext(_context); if (dispatch!=INCLUDE && target.startsWith("/")) { if (_contextPath.length()==1) base_request.setContextPath(""); else base_request.setContextPath(_contextPath); base_request.setServletPath(null); base_request.setPathInfo(target); } ServletRequestEvent event=null; if (new_context) { // Set the classloader if (_classLoader!=null) { current_thread=Thread.currentThread(); old_classloader=current_thread.getContextClassLoader(); current_thread.setContextClassLoader(_classLoader); } // Handle the REALLY SILLY request events! if (_requestListeners!=null) { event = new ServletRequestEvent(_context,request); for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestInitialized(event); } for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.addEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } // Handle the request try { handled = getHandler().handle(target, request, response, dispatch); } finally { // Handle more REALLY SILLY request events! if (new_context) { for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestDestroyed(event); for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.removeEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } } } finally { if (old_context!=_context) { // reset the classloader if (_classLoader!=null) { current_thread.setContextClassLoader(old_classloader); } // reset the context and servlet path. base_request.setContext(old_context); base_request.setContextPath(old_context_path); base_request.setServletPath(old_servlet_path); base_request.setPathInfo(old_path_info); } } return handled; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { _attributes.removeAttribute(name); } /* ------------------------------------------------------------ */ /* Set a context attribute. * Attributes set via this API cannot be overriden by the ServletContext.setAttribute API. * Their lifecycle spans the stop/start of a context. No attribute listener events are * triggered by this API. * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object) */ public void setAttribute(String name, Object value) { _attributes.setAttribute(name,value); } /* ------------------------------------------------------------ */ /** * @param attributes The attributes to set. */ public void setAttributes(Attributes attributes) { _attributes = attributes; } /* ------------------------------------------------------------ */ public void clearAttributes() { _attributes.clearAttributes(); } /* ------------------------------------------------------------ */ /** * @param classLoader The classLoader to set. */ public void setClassLoader(ClassLoader classLoader) { _classLoader = classLoader; } /* ------------------------------------------------------------ */ /** * @param _contextPath The _contextPath to set. */ public void setContextPath(String contextPath) { if (contextPath!=null && contextPath.length()>1 && contextPath.endsWith("/")) throw new IllegalArgumentException("ends with /"); _contextPath = contextPath; } /* ------------------------------------------------------------ */ /** * @param initParams The initParams to set. */ public void setInitParams(HashMap initParams) { _initParams = initParams; } /* ------------------------------------------------------------ */ /** * @param servletContextName The servletContextName to set. */ public void setDisplayName(String servletContextName) { _displayName = servletContextName; } /* ------------------------------------------------------------ */ /** * @return Returns the resourceBase. */ public Resource getBaseResource() { if (_baseResource==null) return null; return _baseResource; } /* ------------------------------------------------------------ */ /** * @return Returns the base resource as a string. */ public String getResourceBase() { if (_baseResource==null) return null; return _baseResource.toString(); } /* ------------------------------------------------------------ */ /** * @param resourceBase The resourceBase to set. */ public void setBaseResource(Resource base) { _baseResource=base; _docRoot=null; try { File file=_baseResource.getFile(); if (file!=null) { _docRoot=file.getCanonicalPath(); if (_docRoot.endsWith(File.pathSeparator)) _docRoot=_docRoot.substring(0,_docRoot.length()-1); } } catch (Exception e) { Log.warn(e); throw new IllegalArgumentException(base.toString()); } } /* ------------------------------------------------------------ */ /** * @param resourceBase The base resource as a string. */ public void setResourceBase(String resourceBase) { try { setBaseResource(Resource.newResource(resourceBase)); } catch (Exception e) { Log.warn(e); throw new IllegalArgumentException(resourceBase); } } /* ------------------------------------------------------------ */ /** * @return Returns the mimeTypes. */ public MimeTypes getMimeTypes() { return _mimeTypes; } /* ------------------------------------------------------------ */ /** * @param mimeTypes The mimeTypes to set. */ public void setMimeTypes(MimeTypes mimeTypes) { _mimeTypes = mimeTypes; } /* ------------------------------------------------------------ */ /** */ public void setWelcomeFiles(String[] files) { _welcomeFiles=files; } /* ------------------------------------------------------------ */ /** * @return */ public String[] getWelcomeFiles() { return _welcomeFiles; } /* ------------------------------------------------------------ */ /** * @return Returns the errorHandler. */ public ErrorHandler getErrorHandler() { return _errorHandler; } /* ------------------------------------------------------------ */ /** * @param errorHandler The errorHandler to set. */ public void setErrorHandler(ErrorHandler errorHandler) { if (_errorHandler!=null) _errorHandler.setServer(null); if (getServer()!=null) getServer().getContainer().update(this, _errorHandler, errorHandler, "errorHandler"); _errorHandler = errorHandler; if (_errorHandler!=null) _errorHandler.setServer(getServer()); } /* ------------------------------------------------------------ */ public String toString() { return "ContextHandler@"+Integer.toHexString(hashCode())+"{"+getContextPath()+","+getBaseResource()+"}"; } /* ------------------------------------------------------------ */ public synchronized Class loadClass(String className) throws ClassNotFoundException { if (className==null) return null; if (_classLoader==null) return Loader.loadClass(this.getClass(), className); return _classLoader.loadClass(className); } /* ------------------------------------------------------------ */ public void addLocaleEncoding(String locale,String encoding) { if (_localeEncodingMap==null) _localeEncodingMap=new HashMap(); _localeEncodingMap.put(locale, encoding); } /* ------------------------------------------------------------ */ /** * Get the character encoding for a locale. The full locale name is first * looked up in the map of encodings. If no encoding is found, then the * locale language is looked up. * * @param locale a <code>Locale</code> value * @return a <code>String</code> representing the character encoding for * the locale or null if none found. */ public String getLocaleEncoding(Locale locale) { if (_localeEncodingMap==null) return null; String encoding = (String)_localeEncodingMap.get(locale.toString()); if (encoding==null) encoding = (String)_localeEncodingMap.get(locale.getLanguage()); return encoding; } /* ------------------------------------------------------------ */ /* */ public Resource getResource(String path) throws MalformedURLException { if (path==null || !path.startsWith("/")) throw new MalformedURLException(path); if (_baseResource==null) return null; try { path=URIUtil.canonicalPath(path); Resource resource=_baseResource.addPath(path); return resource; } catch(Exception e) { Log.ignore(e); } return null; } /* ------------------------------------------------------------ */ /* */ public Set getResourcePaths(String path) { try { path=URIUtil.canonicalPath(path); Resource resource=getResource(path); if (resource!=null && resource.exists()) { String[] l=resource.list(); if (l!=null) { HashSet set = new HashSet(); for(int i=0;i<l.length;i++) set.add(path+"/"+l[i]); return set; } } } catch(Exception e) { Log.ignore(e); } return Collections.EMPTY_SET; } /* ------------------------------------------------------------ */ /** Context. * @author gregw * */ public class Context implements ServletContext { /* ------------------------------------------------------------ */ private Context() { } /* ------------------------------------------------------------ */ public ContextHandler getContextHandler() { // TODO reduce visibility of this method return ContextHandler.this; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getContext(java.lang.String) */ public ServletContext getContext(String uripath) { // TODO this is a very poor implementation! // TODO move this to Server ContextHandler context=null; Handler[] handlers = getServer().getAllHandlers(); for (int i=0;i<handlers.length;i++) { if (handlers[i]==null || !handlers[i].isStarted() || !(handlers[i] instanceof ContextHandler)) continue; ContextHandler ch = (ContextHandler)handlers[i]; String context_path=ch.getContextPath(); if (uripath.equals(context_path) || (uripath.startsWith(context_path)&&uripath.charAt(context_path.length())=='/')) { if (context==null || context_path.length()>context.getContextPath().length()) context=ch; } } if (context!=null) return context._context; return null; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getMajorVersion() */ public int getMajorVersion() { return 2; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getMimeType(java.lang.String) */ public String getMimeType(String file) { if (_mimeTypes==null) return null; Buffer mime = _mimeTypes.getMimeByExtension(file); if (mime!=null) return mime.toString(); return null; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getMinorVersion() */ public int getMinorVersion() { return 5; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getNamedDispatcher(java.lang.String) */ public RequestDispatcher getNamedDispatcher(String name) { return new Dispatcher(ContextHandler.this, name); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getRealPath(java.lang.String) */ public String getRealPath(String path) { if (_docRoot==null) return null; if (path==null) return null; path=URIUtil.canonicalPath(path); if (!path.startsWith("/")) path="/"+path; if (File.separatorChar!='/') path =path.replace('/', File.separatorChar); return _docRoot+path; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getRequestDispatcher(java.lang.String) */ public RequestDispatcher getRequestDispatcher(String uriInContext) { if (uriInContext == null) return null; if (!uriInContext.startsWith("/")) return null; try { String query=null; int q=0; if ((q=uriInContext.indexOf('?'))>0) { query=uriInContext.substring(q+1); uriInContext=uriInContext.substring(0,q); } if ((q=uriInContext.indexOf(';'))>0) uriInContext=uriInContext.substring(0,q); String pathInContext=URIUtil.canonicalPath(URIUtil.decodePath(uriInContext)); String uri=URIUtil.addPaths(getContextPath(), uriInContext); return new Dispatcher(ContextHandler.this, uri, pathInContext, query); } catch(Exception e) { Log.ignore(e); } return null; } /* ------------------------------------------------------------ */ /* */ public URL getResource(String path) throws MalformedURLException { Resource resource=ContextHandler.this.getResource(path); if (resource!=null && resource.exists()) return resource.getURL(); return null; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getResourceAsStream(java.lang.String) */ public InputStream getResourceAsStream(String path) { try { URL url=getResource(path); if (url==null) return null; return url.openStream(); } catch(Exception e) { Log.ignore(e); return null; } } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getResourcePaths(java.lang.String) */ public Set getResourcePaths(String path) { return ContextHandler.this.getResourcePaths(path); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServerInfo() */ public String getServerInfo() { return "Jetty-6.0"; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServlet(java.lang.String) */ public Servlet getServlet(String name) throws ServletException { return null; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServletNames() */ public Enumeration getServletNames() { return Collections.enumeration(Collections.EMPTY_LIST); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServlets() */ public Enumeration getServlets() { return Collections.enumeration(Collections.EMPTY_LIST); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#log(java.lang.Exception, java.lang.String) */ public void log(Exception exception, String msg) { logger.warn(msg,exception); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#log(java.lang.String) */ public void log(String msg) { logger.info(msg, null, null); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#log(java.lang.String, java.lang.Throwable) */ public void log(String message, Throwable throwable) { logger.warn(message,throwable); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getInitParameter(java.lang.String) */ public String getInitParameter(String name) { return ContextHandler.this.getInitParameter(name); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getInitParameterNames() */ public Enumeration getInitParameterNames() { return ContextHandler.this.getInitParameterNames(); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getAttribute(java.lang.String) */ public synchronized Object getAttribute(String name) { Object o = ContextHandler.this.getAttribute(name); if (o==null) o=_contextAttributes.getAttribute(name); return o; } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getAttributeNames() */ public synchronized Enumeration getAttributeNames() { HashSet set = new HashSet(); Enumeration e = _contextAttributes.getAttributeNames(); while(e.hasMoreElements()) set.add(e.nextElement()); e = ContextHandler.this.getAttributeNames(); while(e.hasMoreElements()) set.add(e.nextElement()); return Collections.enumeration(set); } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#setAttribute(java.lang.String, java.lang.Object) */ public synchronized void setAttribute(String name, Object value) { Object old_value=_contextAttributes==null?null:_contextAttributes.getAttribute(name); if (value==null) _contextAttributes.removeAttribute(name); else _contextAttributes.setAttribute(name,value); if (_contextAttributeListeners!=null) { ServletContextAttributeEvent event = new ServletContextAttributeEvent(_context,name, old_value==null?value:old_value); for(int i=0;i<LazyList.size(_contextAttributeListeners);i++) { ServletContextAttributeListener l = (ServletContextAttributeListener)LazyList.get(_contextAttributeListeners,i); if (old_value==null) l.attributeAdded(event); else if (value==null) l.attributeRemoved(event); else l.attributeReplaced(event); } } } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#removeAttribute(java.lang.String) */ public synchronized void removeAttribute(String name) { Object old_value=_contextAttributes.getAttribute(name); _contextAttributes.removeAttribute(name); if (old_value!=null) { if (_contextAttributeListeners!=null) { ServletContextAttributeEvent event = new ServletContextAttributeEvent(_context,name, old_value); for(int i=0;i<LazyList.size(_contextAttributeListeners);i++) ((ServletContextAttributeListener)LazyList.get(_contextAttributeListeners,i)).attributeRemoved(event); } } } /* ------------------------------------------------------------ */ /* * @see javax.servlet.ServletContext#getServletContextName() */ public String getServletContextName() { String name = ContextHandler.this.getDisplayName(); if (name==null) name=ContextHandler.this.getContextPath(); return name; } /* ------------------------------------------------------------ */ /** * @return Returns the _contextPath. */ public String getContextPath() { return _contextPath; } /* ------------------------------------------------------------ */ public String toString() { return "ServletContext@"+Integer.toHexString(hashCode())+"{"+getContextPath()+","+getBaseResource()+"}"; } } }
true
true
public boolean handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { boolean handled=false; boolean new_context=false; Request base_request=null; Context old_context=null; String old_context_path=null; String old_servlet_path=null; String old_path_info=null; ClassLoader old_classloader=null; Thread current_thread=null; base_request=(request instanceof Request)?(Request)request:HttpConnection.getCurrentConnection().getRequest(); old_context=base_request.getContext(); // Are we already in this context? if (old_context!=_context) { new_context=true; // Check the vhosts if (_vhosts!=null && _vhosts.length>0) { String vhost=request.getServerName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_vhosts.length;i++) match=_vhosts[i]!=null && _vhosts[i].equalsIgnoreCase(vhost); if (!match) return false; } // Check the real hosts if (_hosts!=null && _hosts.length>0) { String host=request.getLocalName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_hosts.length;i++) match=_hosts[i]!=null && _hosts[i].equalsIgnoreCase(host); if (!match) return false; } // Nope - so check the target. if (dispatch==REQUEST) { if (target.equals(_contextPath)) { target=_contextPath; if (!target.endsWith("/")) { response.sendRedirect(target+"/"); return true; } } else if (target.startsWith(_contextPath) && (_contextPath.length()==1 || target.charAt(_contextPath.length())=='/')) { if (_contextPath.length()>1) target=target.substring(_contextPath.length()); } else { // Not for this context! return false; } } } try { old_context_path=base_request.getContextPath(); old_servlet_path=base_request.getServletPath(); old_path_info=base_request.getPathInfo(); // Update the paths base_request.setContext(_context); if (dispatch!=INCLUDE && target.startsWith("/")) { if (_contextPath.length()==1) base_request.setContextPath(""); else base_request.setContextPath(_contextPath); base_request.setServletPath(null); base_request.setPathInfo(target); } ServletRequestEvent event=null; if (new_context) { // Set the classloader if (_classLoader!=null) { current_thread=Thread.currentThread(); old_classloader=current_thread.getContextClassLoader(); current_thread.setContextClassLoader(_classLoader); } // Handle the REALLY SILLY request events! if (_requestListeners!=null) { event = new ServletRequestEvent(_context,request); for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestInitialized(event); } for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.addEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } // Handle the request try { handled = getHandler().handle(target, request, response, dispatch); } finally { // Handle more REALLY SILLY request events! if (new_context) { for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestDestroyed(event); for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.removeEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } } } finally { if (old_context!=_context) { // reset the classloader if (_classLoader!=null) { current_thread.setContextClassLoader(old_classloader); } // reset the context and servlet path. base_request.setContext(old_context); base_request.setContextPath(old_context_path); base_request.setServletPath(old_servlet_path); base_request.setPathInfo(old_path_info); } } return handled; }
public boolean handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { boolean handled=false; boolean new_context=false; Request base_request=null; Context old_context=null; String old_context_path=null; String old_servlet_path=null; String old_path_info=null; ClassLoader old_classloader=null; Thread current_thread=null; base_request=(request instanceof Request)?(Request)request:HttpConnection.getCurrentConnection().getRequest(); old_context=base_request.getContext(); // Are we already in this context? if (old_context!=_context) { new_context=true; // Check the vhosts if (_vhosts!=null && _vhosts.length>0) { String vhost=request.getServerName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_vhosts.length;i++) match=_vhosts[i]!=null && _vhosts[i].equalsIgnoreCase(vhost); if (!match) return false; } // Check the real hosts if (_hosts!=null && _hosts.length>0) { String host=request.getLocalName(); boolean match=false; // TODO consider non-linear lookup for (int i=0;!match && i<_hosts.length;i++) match=_hosts[i]!=null && _hosts[i].equalsIgnoreCase(host); if (!match) return false; } // Nope - so check the target. if (dispatch==REQUEST) { if (target.equals(_contextPath)) { target=_contextPath; if (!target.endsWith("/")) { if (request.getQueryString()!=null) response.sendRedirect(target+"/?"+request.getQueryString()); else response.sendRedirect(target+"/"); return true; } } else if (target.startsWith(_contextPath) && (_contextPath.length()==1 || target.charAt(_contextPath.length())=='/')) { if (_contextPath.length()>1) target=target.substring(_contextPath.length()); } else { // Not for this context! return false; } } } try { old_context_path=base_request.getContextPath(); old_servlet_path=base_request.getServletPath(); old_path_info=base_request.getPathInfo(); // Update the paths base_request.setContext(_context); if (dispatch!=INCLUDE && target.startsWith("/")) { if (_contextPath.length()==1) base_request.setContextPath(""); else base_request.setContextPath(_contextPath); base_request.setServletPath(null); base_request.setPathInfo(target); } ServletRequestEvent event=null; if (new_context) { // Set the classloader if (_classLoader!=null) { current_thread=Thread.currentThread(); old_classloader=current_thread.getContextClassLoader(); current_thread.setContextClassLoader(_classLoader); } // Handle the REALLY SILLY request events! if (_requestListeners!=null) { event = new ServletRequestEvent(_context,request); for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestInitialized(event); } for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.addEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } // Handle the request try { handled = getHandler().handle(target, request, response, dispatch); } finally { // Handle more REALLY SILLY request events! if (new_context) { for(int i=0;i<LazyList.size(_requestListeners);i++) ((ServletRequestListener)LazyList.get(_requestListeners,i)).requestDestroyed(event); for(int i=0;i<LazyList.size(_requestAttributeListeners);i++) base_request.removeEventListener(((ServletRequestListener)LazyList.get(_requestAttributeListeners,i))); } } } finally { if (old_context!=_context) { // reset the classloader if (_classLoader!=null) { current_thread.setContextClassLoader(old_classloader); } // reset the context and servlet path. base_request.setContext(old_context); base_request.setContextPath(old_context_path); base_request.setServletPath(old_servlet_path); base_request.setPathInfo(old_path_info); } } return handled; }
diff --git a/samples/xni/XMLGrammarBuilder.java b/samples/xni/XMLGrammarBuilder.java index d61e31dc8..60ceeefe3 100644 --- a/samples/xni/XMLGrammarBuilder.java +++ b/samples/xni/XMLGrammarBuilder.java @@ -1,325 +1,325 @@ /* * Copyright 1999-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xni; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.parsers.XIncludeAwareParserConfiguration; import org.apache.xerces.parsers.XMLGrammarPreparser; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLGrammarPoolImpl; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xni.parser.XMLParserConfiguration; /** * This sample program illustrates how to use Xerces2's grammar * preparsing and caching functionality. It permits either DTD or * Schema grammars to be parsed, and then allows instance documents to * be validated with them. * <p> Note that, for access to a grammar's contents (via Xerces's * Schema Component model interfaces), slightly different methods need * to be used. Nonetheless, this should go some way to indicating how * grammar preparsing and caching can be coupled in Xerces to achieve * better performance. It's also hoped this sample shows the way * towards combining this functionality in a DOM or SAX context. * * @author Neil Graham, IBM * @version $Id$ */ public class XMLGrammarBuilder { // // Constants // // property IDs: /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: grammar pool. */ public static final String GRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; // feature ids /** Namespaces feature id (http://xml.org/sax/features/namespaces). */ protected static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces"; /** Validation feature id (http://xml.org/sax/features/validation). */ protected static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation"; /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */ protected static final String SCHEMA_VALIDATION_FEATURE_ID = "http://apache.org/xml/features/validation/schema"; /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */ protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations"; // a larg(ish) prime to use for a symbol table to be shared // among // potentially man parsers. Start one as close to 2K (20 // times larger than normal) and see what happens... public static final int BIG_PRIME = 2039; // default settings /** Default Schema full checking support (false). */ protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false; /** Default honour all schema locations (false). */ protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false; // // MAIN // /** Main program entry point. */ public static void main(String argv[]) { // too few parameters if (argv.length < 2) { printUsage(); System.exit(1); } XMLParserConfiguration parserConfiguration = null; String arg = null; int i = 0; arg = argv[i]; if (arg.equals("-p")) { // get parser name i++; String parserName = argv[i]; // create parser try { ClassLoader cl = ObjectFactory.findClassLoader(); parserConfiguration = (XMLParserConfiguration)ObjectFactory.newInstance(parserName, cl, true); } catch (Exception e) { parserConfiguration = null; System.err.println("error: Unable to instantiate parser configuration ("+parserName+")"); } i++; } arg = argv[i]; // process -d Vector externalDTDs = null; if (arg.equals("-d")) { externalDTDs= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { externalDTDs.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (externalDTDs.size() == 0) { printUsage(); System.exit(1); } } // process -f/F and -hs/HS Vector schemas = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; if(i < argv.length) { arg = argv[i]; if (arg.equals("-f")) { schemaFullChecking = true; i++; arg = argv[i]; } else if (arg.equals("-F")) { schemaFullChecking = false; i++; arg = argv[i]; } - else if (arg.equals("-hs")) { + if (arg.equals("-hs")) { honourAllSchemaLocations = true; i++; arg = argv[i]; } else if (arg.equals("-HS")) { honourAllSchemaLocations = false; i++; arg = argv[i]; } if (arg.equals("-a")) { if(externalDTDs != null) { printUsage(); System.exit(1); } // process -a: schema files schemas= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { schemas.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (schemas.size() == 0) { printUsage(); System.exit(1); } } } // process -i: instance files, if any Vector ifiles = null; if (i < argv.length) { if (!arg.equals("-i")) { printUsage(); System.exit(1); } i++; ifiles = new Vector(); while (i < argv.length && !(arg = argv[i]).startsWith("-")) { ifiles.addElement(arg); i++; } // has to be at least one instance file, and there has to be no more // parameters if (ifiles.size() == 0 || i != argv.length) { printUsage(); System.exit(1); } } // now we have all our arguments. We only // need to parse the DTD's/schemas, put them // in a grammar pool, possibly instantiate an // appropriate configuration, and we're on our way. SymbolTable sym = new SymbolTable(BIG_PRIME); XMLGrammarPreparser preparser = new XMLGrammarPreparser(sym); XMLGrammarPoolImpl grammarPool = new XMLGrammarPoolImpl(); boolean isDTD = false; if(externalDTDs != null) { preparser.registerPreparser(XMLGrammarDescription.XML_DTD, null); isDTD = true; } else if(schemas != null) { preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); isDTD = false; } else { System.err.println("No schema or DTD specified!"); System.exit(1); } preparser.setProperty(GRAMMAR_POOL, grammarPool); preparser.setFeature(NAMESPACES_FEATURE_ID, true); preparser.setFeature(VALIDATION_FEATURE_ID, true); // note we can set schema features just in case... preparser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); preparser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); preparser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); // parse the grammar... try { if(isDTD) { for (i = 0; i < externalDTDs.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_DTD, stringToXIS((String)externalDTDs.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } else { // must be schemas! for (i = 0; i < schemas.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, stringToXIS((String)schemas.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Now we have a grammar pool and a SymbolTable; just // build a configuration and we're on our way! if (parserConfiguration == null) { parserConfiguration = new XIncludeAwareParserConfiguration(sym, grammarPool); } else { // set GrammarPool and SymbolTable... parserConfiguration.setProperty(SYMBOL_TABLE, sym); parserConfiguration.setProperty(GRAMMAR_POOL, grammarPool); } // now must reset features, unfortunately: try{ parserConfiguration.setFeature(NAMESPACES_FEATURE_ID, true); parserConfiguration.setFeature(VALIDATION_FEATURE_ID, true); // now we can still do schema features just in case, // so long as it's our configuraiton...... parserConfiguration.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); parserConfiguration.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); parserConfiguration.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // then for each instance file, try to validate it if (ifiles != null) { try { for (i = 0; i < ifiles.size(); i++) { parserConfiguration.parse(stringToXIS((String)ifiles.elementAt(i))); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } // main(String[]) // // Private static methods // /** Prints the usage. */ private static void printUsage() { System.err.println("usage: java xni.XMLGrammarBuilder [-p name] -d uri ... | [-f|-F] [-hs|-HS] -a uri ... [-i uri ...]"); System.err.println(); System.err.println("options:"); System.err.println(" -p name Select parser configuration by name to use for instance validation"); System.err.println(" -d Grammars to preparse are DTD external subsets"); System.err.println(" -f | -F Turn on/off Schema full checking (default "+ (DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off)")); System.err.println(" -hs | -HS Turn on/off honouring of all schema locations (default "+ (DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off)")); System.err.println(" -a uri ... Provide a list of schema documents"); System.err.println(" -i uri ... Provide a list of instance documents to validate"); System.err.println(); System.err.println("NOTE: Both -d and -a cannot be specified!"); } // printUsage() private static XMLInputSource stringToXIS(String uri) { return new XMLInputSource(null, uri, null); } } // class XMLGrammarBuilder
true
true
public static void main(String argv[]) { // too few parameters if (argv.length < 2) { printUsage(); System.exit(1); } XMLParserConfiguration parserConfiguration = null; String arg = null; int i = 0; arg = argv[i]; if (arg.equals("-p")) { // get parser name i++; String parserName = argv[i]; // create parser try { ClassLoader cl = ObjectFactory.findClassLoader(); parserConfiguration = (XMLParserConfiguration)ObjectFactory.newInstance(parserName, cl, true); } catch (Exception e) { parserConfiguration = null; System.err.println("error: Unable to instantiate parser configuration ("+parserName+")"); } i++; } arg = argv[i]; // process -d Vector externalDTDs = null; if (arg.equals("-d")) { externalDTDs= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { externalDTDs.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (externalDTDs.size() == 0) { printUsage(); System.exit(1); } } // process -f/F and -hs/HS Vector schemas = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; if(i < argv.length) { arg = argv[i]; if (arg.equals("-f")) { schemaFullChecking = true; i++; arg = argv[i]; } else if (arg.equals("-F")) { schemaFullChecking = false; i++; arg = argv[i]; } else if (arg.equals("-hs")) { honourAllSchemaLocations = true; i++; arg = argv[i]; } else if (arg.equals("-HS")) { honourAllSchemaLocations = false; i++; arg = argv[i]; } if (arg.equals("-a")) { if(externalDTDs != null) { printUsage(); System.exit(1); } // process -a: schema files schemas= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { schemas.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (schemas.size() == 0) { printUsage(); System.exit(1); } } } // process -i: instance files, if any Vector ifiles = null; if (i < argv.length) { if (!arg.equals("-i")) { printUsage(); System.exit(1); } i++; ifiles = new Vector(); while (i < argv.length && !(arg = argv[i]).startsWith("-")) { ifiles.addElement(arg); i++; } // has to be at least one instance file, and there has to be no more // parameters if (ifiles.size() == 0 || i != argv.length) { printUsage(); System.exit(1); } } // now we have all our arguments. We only // need to parse the DTD's/schemas, put them // in a grammar pool, possibly instantiate an // appropriate configuration, and we're on our way. SymbolTable sym = new SymbolTable(BIG_PRIME); XMLGrammarPreparser preparser = new XMLGrammarPreparser(sym); XMLGrammarPoolImpl grammarPool = new XMLGrammarPoolImpl(); boolean isDTD = false; if(externalDTDs != null) { preparser.registerPreparser(XMLGrammarDescription.XML_DTD, null); isDTD = true; } else if(schemas != null) { preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); isDTD = false; } else { System.err.println("No schema or DTD specified!"); System.exit(1); } preparser.setProperty(GRAMMAR_POOL, grammarPool); preparser.setFeature(NAMESPACES_FEATURE_ID, true); preparser.setFeature(VALIDATION_FEATURE_ID, true); // note we can set schema features just in case... preparser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); preparser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); preparser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); // parse the grammar... try { if(isDTD) { for (i = 0; i < externalDTDs.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_DTD, stringToXIS((String)externalDTDs.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } else { // must be schemas! for (i = 0; i < schemas.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, stringToXIS((String)schemas.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Now we have a grammar pool and a SymbolTable; just // build a configuration and we're on our way! if (parserConfiguration == null) { parserConfiguration = new XIncludeAwareParserConfiguration(sym, grammarPool); } else { // set GrammarPool and SymbolTable... parserConfiguration.setProperty(SYMBOL_TABLE, sym); parserConfiguration.setProperty(GRAMMAR_POOL, grammarPool); } // now must reset features, unfortunately: try{ parserConfiguration.setFeature(NAMESPACES_FEATURE_ID, true); parserConfiguration.setFeature(VALIDATION_FEATURE_ID, true); // now we can still do schema features just in case, // so long as it's our configuraiton...... parserConfiguration.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); parserConfiguration.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); parserConfiguration.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // then for each instance file, try to validate it if (ifiles != null) { try { for (i = 0; i < ifiles.size(); i++) { parserConfiguration.parse(stringToXIS((String)ifiles.elementAt(i))); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } // main(String[])
public static void main(String argv[]) { // too few parameters if (argv.length < 2) { printUsage(); System.exit(1); } XMLParserConfiguration parserConfiguration = null; String arg = null; int i = 0; arg = argv[i]; if (arg.equals("-p")) { // get parser name i++; String parserName = argv[i]; // create parser try { ClassLoader cl = ObjectFactory.findClassLoader(); parserConfiguration = (XMLParserConfiguration)ObjectFactory.newInstance(parserName, cl, true); } catch (Exception e) { parserConfiguration = null; System.err.println("error: Unable to instantiate parser configuration ("+parserName+")"); } i++; } arg = argv[i]; // process -d Vector externalDTDs = null; if (arg.equals("-d")) { externalDTDs= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { externalDTDs.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (externalDTDs.size() == 0) { printUsage(); System.exit(1); } } // process -f/F and -hs/HS Vector schemas = null; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; if(i < argv.length) { arg = argv[i]; if (arg.equals("-f")) { schemaFullChecking = true; i++; arg = argv[i]; } else if (arg.equals("-F")) { schemaFullChecking = false; i++; arg = argv[i]; } if (arg.equals("-hs")) { honourAllSchemaLocations = true; i++; arg = argv[i]; } else if (arg.equals("-HS")) { honourAllSchemaLocations = false; i++; arg = argv[i]; } if (arg.equals("-a")) { if(externalDTDs != null) { printUsage(); System.exit(1); } // process -a: schema files schemas= new Vector(); i++; while (i < argv.length && !(arg = argv[i]).startsWith("-")) { schemas.addElement(arg); i++; } // has to be at least one dTD or schema , and there has to be other parameters if (schemas.size() == 0) { printUsage(); System.exit(1); } } } // process -i: instance files, if any Vector ifiles = null; if (i < argv.length) { if (!arg.equals("-i")) { printUsage(); System.exit(1); } i++; ifiles = new Vector(); while (i < argv.length && !(arg = argv[i]).startsWith("-")) { ifiles.addElement(arg); i++; } // has to be at least one instance file, and there has to be no more // parameters if (ifiles.size() == 0 || i != argv.length) { printUsage(); System.exit(1); } } // now we have all our arguments. We only // need to parse the DTD's/schemas, put them // in a grammar pool, possibly instantiate an // appropriate configuration, and we're on our way. SymbolTable sym = new SymbolTable(BIG_PRIME); XMLGrammarPreparser preparser = new XMLGrammarPreparser(sym); XMLGrammarPoolImpl grammarPool = new XMLGrammarPoolImpl(); boolean isDTD = false; if(externalDTDs != null) { preparser.registerPreparser(XMLGrammarDescription.XML_DTD, null); isDTD = true; } else if(schemas != null) { preparser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null); isDTD = false; } else { System.err.println("No schema or DTD specified!"); System.exit(1); } preparser.setProperty(GRAMMAR_POOL, grammarPool); preparser.setFeature(NAMESPACES_FEATURE_ID, true); preparser.setFeature(VALIDATION_FEATURE_ID, true); // note we can set schema features just in case... preparser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); preparser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); preparser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); // parse the grammar... try { if(isDTD) { for (i = 0; i < externalDTDs.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_DTD, stringToXIS((String)externalDTDs.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } else { // must be schemas! for (i = 0; i < schemas.size(); i++) { Grammar g = preparser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, stringToXIS((String)schemas.elementAt(i))); // we don't really care about g; grammarPool will take care of everything. } } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Now we have a grammar pool and a SymbolTable; just // build a configuration and we're on our way! if (parserConfiguration == null) { parserConfiguration = new XIncludeAwareParserConfiguration(sym, grammarPool); } else { // set GrammarPool and SymbolTable... parserConfiguration.setProperty(SYMBOL_TABLE, sym); parserConfiguration.setProperty(GRAMMAR_POOL, grammarPool); } // now must reset features, unfortunately: try{ parserConfiguration.setFeature(NAMESPACES_FEATURE_ID, true); parserConfiguration.setFeature(VALIDATION_FEATURE_ID, true); // now we can still do schema features just in case, // so long as it's our configuraiton...... parserConfiguration.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true); parserConfiguration.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); parserConfiguration.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // then for each instance file, try to validate it if (ifiles != null) { try { for (i = 0; i < ifiles.size(); i++) { parserConfiguration.parse(stringToXIS((String)ifiles.elementAt(i))); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } // main(String[])
diff --git a/NodeAnimator/src/de/atlassoft/ui/SimulationStatisticDialog.java b/NodeAnimator/src/de/atlassoft/ui/SimulationStatisticDialog.java index a81b523..7905dba 100644 --- a/NodeAnimator/src/de/atlassoft/ui/SimulationStatisticDialog.java +++ b/NodeAnimator/src/de/atlassoft/ui/SimulationStatisticDialog.java @@ -1,547 +1,552 @@ package de.atlassoft.ui; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import de.atlassoft.application.ApplicationService; import de.atlassoft.model.Node; import de.atlassoft.model.ScheduleScheme; import de.atlassoft.model.SimulationStatistic; import de.atlassoft.model.TrainType; import de.atlassoft.util.I18NService; import de.atlassoft.util.I18NSingleton; import de.atlassoft.util.ImageHelper; /** * This class is for the SimulationStatistic Dialog where * you can see the Statistic after a Simulation. * * @author Tobias Ilg */ public class SimulationStatisticDialog { private Shell shell; private ApplicationService applicationService; private SimulationStatistic simulationStatistic; private TabItem statisticsItem; private TabFolder tabFolder; private Composite mainStatisticComposite; /** * Public constructor for the SimulationStatistic Dialog. Creates a new * SimulationStatistic shell and open it. * * @param applicationService * to access application layer */ public SimulationStatisticDialog (ApplicationService applicationService, SimulationStatistic simulationStatistic) { this.applicationService = applicationService; this.simulationStatistic = simulationStatistic; I18NService I18N = I18NSingleton.getInstance(); Display display = Display.getCurrent(); shell = new Shell(display, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); shell.setImage(ImageHelper.getImage("trainIcon")); shell.setText(I18N.getMessage("SimulationStatisticDialog.Title")); shell.setSize(880, 600); shell.setLayout(new GridLayout(1, true)); tabFolder = new TabFolder(shell, SWT.NONE); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tabFolder.setLayout(new RowLayout()); //Statistics item statisticsItem = new TabItem(tabFolder, SWT.NONE); statisticsItem.setText("Statistik"); initUI(); statisticsItem.setControl(mainStatisticComposite); //Heatmap item TabItem heatMapItem = new TabItem(tabFolder, SWT.NONE); heatMapItem.setText("Heatmap"); HeatMapComposite heatMapComposite = new HeatMapComposite(tabFolder, simulationStatistic); heatMapItem.setControl(heatMapComposite.getComposite()); MainWindow.center(shell); shell.layout(); shell.open(); } /** * A method which creates the content, * label, text, buttons and tool tips of * the shell of the SimulationStatistic Dialog. * */ private void initUI() { final I18NService I18N = I18NSingleton.getInstance(); mainStatisticComposite = new Composite (tabFolder, SWT.NULL); mainStatisticComposite.setLayout (new GridLayout(1, true)); double allSec; int min; int sec; //Title of Statistic Label title = new Label(mainStatisticComposite, SWT.NONE); title.setText(I18N.getMessage("SimulationStatisticDialog.Title2") + " '" + applicationService.getModel().getActiveRailwaySys().getID() +"'"); title.setLayoutData(new GridData(SWT.CENTER, SWT.NULL, true, false)); title.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 13, SWT.BOLD))); //Empty Row new Label(mainStatisticComposite, SWT.NONE); //Overall Composite final Composite overallStatisticComposite = new Composite (mainStatisticComposite, SWT.NULL); overallStatisticComposite.setLayout (new GridLayout(2, true)); overallStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Top of the Composite final Composite firstStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); firstStatisticComposite.setLayout (new GridLayout(3, false)); firstStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Total" Label title1 = new Label(firstStatisticComposite, SWT.NULL); title1.setText(I18N.getMessage("SimulationStatisticDialog.littleTitle1")); title1.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); new Label(firstStatisticComposite, SWT.NULL); new Label(firstStatisticComposite, SWT.NULL); // Eleventh row with "NumberOfRides" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfRides") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayRides = new Label(firstStatisticComposite, SWT.NONE); meanDelayRides.setText(String.valueOf(simulationStatistic.getNumberOfRides() + " " + I18N.getMessage("SimulationStatisticDialog.Rides"))); //Twelfth row with "NomberOfNodes" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfNodes") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayNodes = new Label(firstStatisticComposite, SWT.NONE); meanDelayNodes.setText(String.valueOf(simulationStatistic.getInvolvedNodes().size() + " " + I18N.getMessage("SimulationStatisticDialog.Nodes"))); // First row with three labels for "TotalDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.TotalDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label totalDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getTotalDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; totalDelay.setText(min + " min " + sec + " s"); // Second row with three labels for "MeanDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.MeanDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelay.setText(min + " min " + sec + " s"); // Top of the Composite "TrainType" final Composite TrainTypeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); TrainTypeStatisticComposite.setLayout (new GridLayout(1, false)); TrainTypeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "TrainType" Label title2 = new Label(TrainTypeStatisticComposite, SWT.NULL); title2.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayTrainType")); title2.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); //Info of the Composite "TrainType" final Composite secondStatisticComposite = new Composite (TrainTypeStatisticComposite, SWT.NULL); secondStatisticComposite.setLayout (new GridLayout(3, false)); secondStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Third row with three labels for "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle2") + "\t"); new Label(secondStatisticComposite, SWT.NONE).setText("\t\t"); final List<TrainType> trainTypes = simulationStatistic.getInvolvedTrainTypes(); final String[] trainTypeSelection = new String [trainTypes.size()]; int index = 0; for (TrainType type : trainTypes) { trainTypeSelection[index] = type.getName(); index++; } final Combo comboTrainType = new Combo(secondStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboTrainType.setItems(trainTypeSelection); comboTrainType.select(0); // Fourth row with the result of "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE); TrainType selectedTT = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTT = type; } } new Label(secondStatisticComposite, SWT.NONE); final Label meanDelayTrainType = new Label(secondStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedTT); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayTrainType.setText(min + " min " + sec + " s"); //row with Number of TrainRides (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfRidesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTT)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfNodesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTT).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // Listener for the combo TrainType comboTrainType.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; TrainType selectedTrainType = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTrainType = type; } } allSec = simulationStatistic.getMeanDelay(selectedTrainType); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayTrainType.setText(min + " min " + sec); - numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTrainType))); - numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTrainType).size())); + meanDelayTrainType.setText(min + " min " + sec + " s"); + numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTrainType)) + + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); + numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTrainType).size()) + + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); secondStatisticComposite.layout(); } }); // Top of the Composite "Node" final Composite nodeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); nodeStatisticComposite.setLayout (new GridLayout(1, false)); nodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Node" Label title3 = new Label(nodeStatisticComposite, SWT.NULL); title3.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayNode")); title3.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Info of the Composite "Node" final Composite thirdStatisticComposite = new Composite (nodeStatisticComposite, SWT.NULL); thirdStatisticComposite.setLayout (new GridLayout(3, false)); thirdStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Fifth row with "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle3") + "\t"); new Label(thirdStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<Node> nodes = simulationStatistic.getInvolvedNodes(); final String[] nodeSelection = new String [nodes.size()]; index = 0; for (Node node : nodes) { nodeSelection[index] = node.getName(); index++; } final Combo comboNode = new Combo(thirdStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboNode.setItems(nodeSelection); comboNode.select(0); // Sixth row with the result of "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE); Node selectedN = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedN = node; } } new Label(thirdStatisticComposite, SWT.NONE); final Label meanDelayNode = new Label(thirdStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedN); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayNode.setText(min + " min " + sec + " s"); //row with Number of TrainRides (Node) new Label(thirdStatisticComposite, SWT.NONE); new Label(thirdStatisticComposite, SWT.NONE); final Label numberOfRidesN =new Label(thirdStatisticComposite, SWT.NONE); numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedN)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); // Listener for the combo Node comboNode.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; Node selectedNode = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedNode = node; } } allSec = simulationStatistic.getMeanDelay(selectedNode); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayNode.setText(min + " min " + sec); - numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedNode))); + meanDelayNode.setText(min + " min " + sec + " s"); + numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedNode)) + + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); thirdStatisticComposite.layout(); } }); // Top of the Composite final Composite scheduleSchemeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); scheduleSchemeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "ScheduleScheme" Label title4 = new Label(scheduleSchemeStatisticComposite, SWT.NULL); title4.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleScheme")); title4.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fourthStatisticComposite = new Composite (scheduleSchemeStatisticComposite, SWT.NULL); fourthStatisticComposite.setLayout (new GridLayout(3, false)); fourthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Seventh row with "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle4") + "\t"); new Label(fourthStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<ScheduleScheme> scheduleSchemes = simulationStatistic.getInvolvedScheduleSchemes(); final String[] scheduleSchemeSelection = new String [scheduleSchemes.size()]; index = 0; for (ScheduleScheme scheduleScheme : scheduleSchemes) { scheduleSchemeSelection[index] = scheduleScheme.getID(); index++; } final Combo comboScheduleScheme = new Combo(fourthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme.setItems(scheduleSchemeSelection); comboScheduleScheme.select(0); // Eighth row with the result of "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedSS = scheduleScheme; } } new Label(fourthStatisticComposite, SWT.NONE); final Label meanDelayScheduleScheme = new Label(fourthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleScheme.setText(min + " min " + sec + " s"); //row with Number of TrainRides (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfRidesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedSS)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfNodesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedSS).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // toTheEnd(numberOfNodesSS); // Listener for the combo ScheduleScheme comboScheduleScheme.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedScheduleScheme = scheduleScheme; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayScheduleScheme.setText(min + " min " + sec); - numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedScheduleScheme))); - numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedScheduleScheme).size())); + meanDelayScheduleScheme.setText(min + " min " + sec + " s"); + numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedScheduleScheme)) + + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); + numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedScheduleScheme).size()) + + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); fourthStatisticComposite.layout(); } }); //Design final Composite scheduleSchemeAndNodeStatisticComposite = new Composite (mainStatisticComposite, SWT.BORDER); scheduleSchemeAndNodeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeAndNodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); //Title "ScheduleScheme and Node" Label title5 = new Label(scheduleSchemeAndNodeStatisticComposite, SWT.NULL); title5.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleSchemeAndNode")); title5.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fifthStatisticComposite = new Composite (scheduleSchemeAndNodeStatisticComposite, SWT.NULL); fifthStatisticComposite.setLayout (new GridLayout(3, false)); fifthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); // Ninth row with "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle5")); final Combo comboScheduleScheme2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme2.setItems(scheduleSchemeSelection); comboScheduleScheme2.select(0); final Combo comboNode2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } if (selectedScheduleScheme2 != null) { java.util.List<Node> nodes2 = simulationStatistic.getInvolvedNodes(selectedScheduleScheme2); String[] node2Selection = new String [nodes2.size()]; int index2 = 0; for (Node node : nodes2) { node2Selection[index2] = node.getName(); index2++; } comboNode2.setItems(node2Selection); comboNode2.select(0); } // Tenth row with the result of "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedSS2 = scheduleScheme; } } Node selectedN2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedN2 = node; } } + new Label(fifthStatisticComposite, SWT.NONE); final Label meanDelayScheduleSchemeAndNode = new Label(fifthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS2, selectedN2); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); - new Label(fifthStatisticComposite, SWT.NONE).setText("s"); + meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); // Listener for the combo scheduleScheme and Node comboScheduleScheme2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } java.util.List<Node> nodes2 = selectedScheduleScheme2.getStations(); String[] node2Selection = new String [nodes2.size()]; int index = 0; for (Node node : nodes2) { node2Selection[index] = node.getName(); index++; } comboNode2.setItems(node2Selection); comboNode2.select(0); Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); + meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); fifthStatisticComposite.layout(); } }); comboNode2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } }allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; - meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); + meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); fifthStatisticComposite.layout(); } }); new Label(mainStatisticComposite, SWT.NULL); //Information Label infoTitle = new Label(mainStatisticComposite, SWT.NULL); infoTitle.setText(I18N.getMessage("SimulationStatisticDialog.InformationTitle")); infoTitle.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); Label info = new Label(mainStatisticComposite, SWT.NULL); info.setText(I18N.getMessage("SimulationStatisticDialog.Information")); // Thirteenth row with Button "Save as PDF" Button save = new Button(shell, SWT.PUSH); save.setImage(ImageHelper.getImage("pdfIcon")); save.setText(I18N.getMessage("SimulationStatisticDialog.Save")); GridData dataSave = new GridData(GridData.FILL); dataSave.horizontalAlignment = GridData.CENTER; save.setLayoutData(dataSave); // Function of Save-Button save.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { applicationService.showStatisticDoc(simulationStatistic); MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION); messageBox.setText(I18N.getMessage("SimulationStatisticDialog.informationSaved")); messageBox.setMessage(I18N.getMessage("SimulationStatisticDialog.informationStatisticSaved")); shell.setVisible(false); messageBox.open(); shell.close(); } }); } }
false
true
private void initUI() { final I18NService I18N = I18NSingleton.getInstance(); mainStatisticComposite = new Composite (tabFolder, SWT.NULL); mainStatisticComposite.setLayout (new GridLayout(1, true)); double allSec; int min; int sec; //Title of Statistic Label title = new Label(mainStatisticComposite, SWT.NONE); title.setText(I18N.getMessage("SimulationStatisticDialog.Title2") + " '" + applicationService.getModel().getActiveRailwaySys().getID() +"'"); title.setLayoutData(new GridData(SWT.CENTER, SWT.NULL, true, false)); title.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 13, SWT.BOLD))); //Empty Row new Label(mainStatisticComposite, SWT.NONE); //Overall Composite final Composite overallStatisticComposite = new Composite (mainStatisticComposite, SWT.NULL); overallStatisticComposite.setLayout (new GridLayout(2, true)); overallStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Top of the Composite final Composite firstStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); firstStatisticComposite.setLayout (new GridLayout(3, false)); firstStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Total" Label title1 = new Label(firstStatisticComposite, SWT.NULL); title1.setText(I18N.getMessage("SimulationStatisticDialog.littleTitle1")); title1.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); new Label(firstStatisticComposite, SWT.NULL); new Label(firstStatisticComposite, SWT.NULL); // Eleventh row with "NumberOfRides" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfRides") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayRides = new Label(firstStatisticComposite, SWT.NONE); meanDelayRides.setText(String.valueOf(simulationStatistic.getNumberOfRides() + " " + I18N.getMessage("SimulationStatisticDialog.Rides"))); //Twelfth row with "NomberOfNodes" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfNodes") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayNodes = new Label(firstStatisticComposite, SWT.NONE); meanDelayNodes.setText(String.valueOf(simulationStatistic.getInvolvedNodes().size() + " " + I18N.getMessage("SimulationStatisticDialog.Nodes"))); // First row with three labels for "TotalDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.TotalDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label totalDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getTotalDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; totalDelay.setText(min + " min " + sec + " s"); // Second row with three labels for "MeanDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.MeanDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelay.setText(min + " min " + sec + " s"); // Top of the Composite "TrainType" final Composite TrainTypeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); TrainTypeStatisticComposite.setLayout (new GridLayout(1, false)); TrainTypeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "TrainType" Label title2 = new Label(TrainTypeStatisticComposite, SWT.NULL); title2.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayTrainType")); title2.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); //Info of the Composite "TrainType" final Composite secondStatisticComposite = new Composite (TrainTypeStatisticComposite, SWT.NULL); secondStatisticComposite.setLayout (new GridLayout(3, false)); secondStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Third row with three labels for "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle2") + "\t"); new Label(secondStatisticComposite, SWT.NONE).setText("\t\t"); final List<TrainType> trainTypes = simulationStatistic.getInvolvedTrainTypes(); final String[] trainTypeSelection = new String [trainTypes.size()]; int index = 0; for (TrainType type : trainTypes) { trainTypeSelection[index] = type.getName(); index++; } final Combo comboTrainType = new Combo(secondStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboTrainType.setItems(trainTypeSelection); comboTrainType.select(0); // Fourth row with the result of "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE); TrainType selectedTT = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTT = type; } } new Label(secondStatisticComposite, SWT.NONE); final Label meanDelayTrainType = new Label(secondStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedTT); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayTrainType.setText(min + " min " + sec + " s"); //row with Number of TrainRides (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfRidesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTT)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfNodesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTT).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // Listener for the combo TrainType comboTrainType.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; TrainType selectedTrainType = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTrainType = type; } } allSec = simulationStatistic.getMeanDelay(selectedTrainType); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayTrainType.setText(min + " min " + sec); numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTrainType))); numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTrainType).size())); secondStatisticComposite.layout(); } }); // Top of the Composite "Node" final Composite nodeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); nodeStatisticComposite.setLayout (new GridLayout(1, false)); nodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Node" Label title3 = new Label(nodeStatisticComposite, SWT.NULL); title3.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayNode")); title3.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Info of the Composite "Node" final Composite thirdStatisticComposite = new Composite (nodeStatisticComposite, SWT.NULL); thirdStatisticComposite.setLayout (new GridLayout(3, false)); thirdStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Fifth row with "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle3") + "\t"); new Label(thirdStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<Node> nodes = simulationStatistic.getInvolvedNodes(); final String[] nodeSelection = new String [nodes.size()]; index = 0; for (Node node : nodes) { nodeSelection[index] = node.getName(); index++; } final Combo comboNode = new Combo(thirdStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboNode.setItems(nodeSelection); comboNode.select(0); // Sixth row with the result of "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE); Node selectedN = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedN = node; } } new Label(thirdStatisticComposite, SWT.NONE); final Label meanDelayNode = new Label(thirdStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedN); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayNode.setText(min + " min " + sec + " s"); //row with Number of TrainRides (Node) new Label(thirdStatisticComposite, SWT.NONE); new Label(thirdStatisticComposite, SWT.NONE); final Label numberOfRidesN =new Label(thirdStatisticComposite, SWT.NONE); numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedN)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); // Listener for the combo Node comboNode.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; Node selectedNode = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedNode = node; } } allSec = simulationStatistic.getMeanDelay(selectedNode); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayNode.setText(min + " min " + sec); numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedNode))); thirdStatisticComposite.layout(); } }); // Top of the Composite final Composite scheduleSchemeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); scheduleSchemeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "ScheduleScheme" Label title4 = new Label(scheduleSchemeStatisticComposite, SWT.NULL); title4.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleScheme")); title4.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fourthStatisticComposite = new Composite (scheduleSchemeStatisticComposite, SWT.NULL); fourthStatisticComposite.setLayout (new GridLayout(3, false)); fourthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Seventh row with "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle4") + "\t"); new Label(fourthStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<ScheduleScheme> scheduleSchemes = simulationStatistic.getInvolvedScheduleSchemes(); final String[] scheduleSchemeSelection = new String [scheduleSchemes.size()]; index = 0; for (ScheduleScheme scheduleScheme : scheduleSchemes) { scheduleSchemeSelection[index] = scheduleScheme.getID(); index++; } final Combo comboScheduleScheme = new Combo(fourthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme.setItems(scheduleSchemeSelection); comboScheduleScheme.select(0); // Eighth row with the result of "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedSS = scheduleScheme; } } new Label(fourthStatisticComposite, SWT.NONE); final Label meanDelayScheduleScheme = new Label(fourthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleScheme.setText(min + " min " + sec + " s"); //row with Number of TrainRides (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfRidesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedSS)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfNodesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedSS).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // toTheEnd(numberOfNodesSS); // Listener for the combo ScheduleScheme comboScheduleScheme.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedScheduleScheme = scheduleScheme; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleScheme.setText(min + " min " + sec); numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedScheduleScheme))); numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedScheduleScheme).size())); fourthStatisticComposite.layout(); } }); //Design final Composite scheduleSchemeAndNodeStatisticComposite = new Composite (mainStatisticComposite, SWT.BORDER); scheduleSchemeAndNodeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeAndNodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); //Title "ScheduleScheme and Node" Label title5 = new Label(scheduleSchemeAndNodeStatisticComposite, SWT.NULL); title5.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleSchemeAndNode")); title5.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fifthStatisticComposite = new Composite (scheduleSchemeAndNodeStatisticComposite, SWT.NULL); fifthStatisticComposite.setLayout (new GridLayout(3, false)); fifthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); // Ninth row with "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle5")); final Combo comboScheduleScheme2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme2.setItems(scheduleSchemeSelection); comboScheduleScheme2.select(0); final Combo comboNode2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } if (selectedScheduleScheme2 != null) { java.util.List<Node> nodes2 = simulationStatistic.getInvolvedNodes(selectedScheduleScheme2); String[] node2Selection = new String [nodes2.size()]; int index2 = 0; for (Node node : nodes2) { node2Selection[index2] = node.getName(); index2++; } comboNode2.setItems(node2Selection); comboNode2.select(0); } // Tenth row with the result of "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedSS2 = scheduleScheme; } } Node selectedN2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedN2 = node; } } final Label meanDelayScheduleSchemeAndNode = new Label(fifthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS2, selectedN2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); new Label(fifthStatisticComposite, SWT.NONE).setText("s"); // Listener for the combo scheduleScheme and Node comboScheduleScheme2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } java.util.List<Node> nodes2 = selectedScheduleScheme2.getStations(); String[] node2Selection = new String [nodes2.size()]; int index = 0; for (Node node : nodes2) { node2Selection[index] = node.getName(); index++; } comboNode2.setItems(node2Selection); comboNode2.select(0); Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); fifthStatisticComposite.layout(); } }); comboNode2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } }allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec); fifthStatisticComposite.layout(); } }); new Label(mainStatisticComposite, SWT.NULL); //Information Label infoTitle = new Label(mainStatisticComposite, SWT.NULL); infoTitle.setText(I18N.getMessage("SimulationStatisticDialog.InformationTitle")); infoTitle.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); Label info = new Label(mainStatisticComposite, SWT.NULL); info.setText(I18N.getMessage("SimulationStatisticDialog.Information")); // Thirteenth row with Button "Save as PDF" Button save = new Button(shell, SWT.PUSH); save.setImage(ImageHelper.getImage("pdfIcon")); save.setText(I18N.getMessage("SimulationStatisticDialog.Save")); GridData dataSave = new GridData(GridData.FILL); dataSave.horizontalAlignment = GridData.CENTER; save.setLayoutData(dataSave); // Function of Save-Button save.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { applicationService.showStatisticDoc(simulationStatistic); MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION); messageBox.setText(I18N.getMessage("SimulationStatisticDialog.informationSaved")); messageBox.setMessage(I18N.getMessage("SimulationStatisticDialog.informationStatisticSaved")); shell.setVisible(false); messageBox.open(); shell.close(); } }); }
private void initUI() { final I18NService I18N = I18NSingleton.getInstance(); mainStatisticComposite = new Composite (tabFolder, SWT.NULL); mainStatisticComposite.setLayout (new GridLayout(1, true)); double allSec; int min; int sec; //Title of Statistic Label title = new Label(mainStatisticComposite, SWT.NONE); title.setText(I18N.getMessage("SimulationStatisticDialog.Title2") + " '" + applicationService.getModel().getActiveRailwaySys().getID() +"'"); title.setLayoutData(new GridData(SWT.CENTER, SWT.NULL, true, false)); title.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 13, SWT.BOLD))); //Empty Row new Label(mainStatisticComposite, SWT.NONE); //Overall Composite final Composite overallStatisticComposite = new Composite (mainStatisticComposite, SWT.NULL); overallStatisticComposite.setLayout (new GridLayout(2, true)); overallStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Top of the Composite final Composite firstStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); firstStatisticComposite.setLayout (new GridLayout(3, false)); firstStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Total" Label title1 = new Label(firstStatisticComposite, SWT.NULL); title1.setText(I18N.getMessage("SimulationStatisticDialog.littleTitle1")); title1.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); new Label(firstStatisticComposite, SWT.NULL); new Label(firstStatisticComposite, SWT.NULL); // Eleventh row with "NumberOfRides" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfRides") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayRides = new Label(firstStatisticComposite, SWT.NONE); meanDelayRides.setText(String.valueOf(simulationStatistic.getNumberOfRides() + " " + I18N.getMessage("SimulationStatisticDialog.Rides"))); //Twelfth row with "NomberOfNodes" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.NumberOfNodes") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelayNodes = new Label(firstStatisticComposite, SWT.NONE); meanDelayNodes.setText(String.valueOf(simulationStatistic.getInvolvedNodes().size() + " " + I18N.getMessage("SimulationStatisticDialog.Nodes"))); // First row with three labels for "TotalDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.TotalDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label totalDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getTotalDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; totalDelay.setText(min + " min " + sec + " s"); // Second row with three labels for "MeanDelay" new Label(firstStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.MeanDelay") + "\t"); new Label(firstStatisticComposite, SWT.NONE); Label meanDelay = new Label(firstStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelay.setText(min + " min " + sec + " s"); // Top of the Composite "TrainType" final Composite TrainTypeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); TrainTypeStatisticComposite.setLayout (new GridLayout(1, false)); TrainTypeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "TrainType" Label title2 = new Label(TrainTypeStatisticComposite, SWT.NULL); title2.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayTrainType")); title2.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); //Info of the Composite "TrainType" final Composite secondStatisticComposite = new Composite (TrainTypeStatisticComposite, SWT.NULL); secondStatisticComposite.setLayout (new GridLayout(3, false)); secondStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Third row with three labels for "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle2") + "\t"); new Label(secondStatisticComposite, SWT.NONE).setText("\t\t"); final List<TrainType> trainTypes = simulationStatistic.getInvolvedTrainTypes(); final String[] trainTypeSelection = new String [trainTypes.size()]; int index = 0; for (TrainType type : trainTypes) { trainTypeSelection[index] = type.getName(); index++; } final Combo comboTrainType = new Combo(secondStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboTrainType.setItems(trainTypeSelection); comboTrainType.select(0); // Fourth row with the result of "MeanDelay (TrainType)" new Label(secondStatisticComposite, SWT.NONE); TrainType selectedTT = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTT = type; } } new Label(secondStatisticComposite, SWT.NONE); final Label meanDelayTrainType = new Label(secondStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedTT); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayTrainType.setText(min + " min " + sec + " s"); //row with Number of TrainRides (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfRidesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTT)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (TrainType) new Label(secondStatisticComposite, SWT.NONE); new Label(secondStatisticComposite, SWT.NONE); final Label numberOfNodesTT =new Label(secondStatisticComposite, SWT.NONE); numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTT).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // Listener for the combo TrainType comboTrainType.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; TrainType selectedTrainType = null; for (TrainType type : trainTypes) { if (type.getName().equals(comboTrainType.getText())) { selectedTrainType = type; } } allSec = simulationStatistic.getMeanDelay(selectedTrainType); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayTrainType.setText(min + " min " + sec + " s"); numberOfRidesTT.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedTrainType)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); numberOfNodesTT.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedTrainType).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); secondStatisticComposite.layout(); } }); // Top of the Composite "Node" final Composite nodeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); nodeStatisticComposite.setLayout (new GridLayout(1, false)); nodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "Node" Label title3 = new Label(nodeStatisticComposite, SWT.NULL); title3.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayNode")); title3.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Info of the Composite "Node" final Composite thirdStatisticComposite = new Composite (nodeStatisticComposite, SWT.NULL); thirdStatisticComposite.setLayout (new GridLayout(3, false)); thirdStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Fifth row with "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle3") + "\t"); new Label(thirdStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<Node> nodes = simulationStatistic.getInvolvedNodes(); final String[] nodeSelection = new String [nodes.size()]; index = 0; for (Node node : nodes) { nodeSelection[index] = node.getName(); index++; } final Combo comboNode = new Combo(thirdStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboNode.setItems(nodeSelection); comboNode.select(0); // Sixth row with the result of "MeanDelay (Node)" new Label(thirdStatisticComposite, SWT.NONE); Node selectedN = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedN = node; } } new Label(thirdStatisticComposite, SWT.NONE); final Label meanDelayNode = new Label(thirdStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedN); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayNode.setText(min + " min " + sec + " s"); //row with Number of TrainRides (Node) new Label(thirdStatisticComposite, SWT.NONE); new Label(thirdStatisticComposite, SWT.NONE); final Label numberOfRidesN =new Label(thirdStatisticComposite, SWT.NONE); numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedN)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); // Listener for the combo Node comboNode.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; Node selectedNode = null; for (Node node : nodes) { if (node.getName().equals(comboNode.getText())) { selectedNode = node; } } allSec = simulationStatistic.getMeanDelay(selectedNode); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayNode.setText(min + " min " + sec + " s"); numberOfRidesN.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedNode)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); thirdStatisticComposite.layout(); } }); // Top of the Composite final Composite scheduleSchemeStatisticComposite = new Composite (overallStatisticComposite, SWT.BORDER); scheduleSchemeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); //Title "ScheduleScheme" Label title4 = new Label(scheduleSchemeStatisticComposite, SWT.NULL); title4.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleScheme")); title4.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fourthStatisticComposite = new Composite (scheduleSchemeStatisticComposite, SWT.NULL); fourthStatisticComposite.setLayout (new GridLayout(3, false)); fourthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); // Seventh row with "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle4") + "\t"); new Label(fourthStatisticComposite, SWT.NONE).setText("\t\t"); final java.util.List<ScheduleScheme> scheduleSchemes = simulationStatistic.getInvolvedScheduleSchemes(); final String[] scheduleSchemeSelection = new String [scheduleSchemes.size()]; index = 0; for (ScheduleScheme scheduleScheme : scheduleSchemes) { scheduleSchemeSelection[index] = scheduleScheme.getID(); index++; } final Combo comboScheduleScheme = new Combo(fourthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme.setItems(scheduleSchemeSelection); comboScheduleScheme.select(0); // Eighth row with the result of "MeanDelay (ScheduleScheme)" new Label(fourthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedSS = scheduleScheme; } } new Label(fourthStatisticComposite, SWT.NONE); final Label meanDelayScheduleScheme = new Label(fourthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleScheme.setText(min + " min " + sec + " s"); //row with Number of TrainRides (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfRidesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedSS)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); //row with Number of Stations (ScheduleScheme) new Label(fourthStatisticComposite, SWT.NONE); new Label(fourthStatisticComposite, SWT.NONE); final Label numberOfNodesSS =new Label(fourthStatisticComposite, SWT.NONE); numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedSS).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); // toTheEnd(numberOfNodesSS); // Listener for the combo ScheduleScheme comboScheduleScheme.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme.getText())) { selectedScheduleScheme = scheduleScheme; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleScheme.setText(min + " min " + sec + " s"); numberOfRidesSS.setText(String.valueOf(simulationStatistic.getNumberOfRides(selectedScheduleScheme)) + " " + I18N.getMessage("SimulationStatisticDialog.Rides")); numberOfNodesSS.setText(String.valueOf(simulationStatistic.getInvolvedNodes(selectedScheduleScheme).size()) + " " + I18N.getMessage("SimulationStatisticDialog.Nodes")); fourthStatisticComposite.layout(); } }); //Design final Composite scheduleSchemeAndNodeStatisticComposite = new Composite (mainStatisticComposite, SWT.BORDER); scheduleSchemeAndNodeStatisticComposite.setLayout (new GridLayout(1, false)); scheduleSchemeAndNodeStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); //Title "ScheduleScheme and Node" Label title5 = new Label(scheduleSchemeAndNodeStatisticComposite, SWT.NULL); title5.setText(I18N.getMessage("SimulationStatisticDialog.MeanDelayScheduleSchemeAndNode")); title5.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); // Top of the Composite final Composite fifthStatisticComposite = new Composite (scheduleSchemeAndNodeStatisticComposite, SWT.NULL); fifthStatisticComposite.setLayout (new GridLayout(3, false)); fifthStatisticComposite.setLayoutData(new GridData(SWT.FILL, SWT.NULL, true, false)); // Ninth row with "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE).setText(I18N.getMessage("SimulationStatisticDialog.littleTitle5")); final Combo comboScheduleScheme2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); comboScheduleScheme2.setItems(scheduleSchemeSelection); comboScheduleScheme2.select(0); final Combo comboNode2 = new Combo(fifthStatisticComposite, SWT.DROP_DOWN | SWT.READ_ONLY); ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } if (selectedScheduleScheme2 != null) { java.util.List<Node> nodes2 = simulationStatistic.getInvolvedNodes(selectedScheduleScheme2); String[] node2Selection = new String [nodes2.size()]; int index2 = 0; for (Node node : nodes2) { node2Selection[index2] = node.getName(); index2++; } comboNode2.setItems(node2Selection); comboNode2.select(0); } // Tenth row with the result of "MeanDelay (ScheduleScheme, Node)" new Label(fifthStatisticComposite, SWT.NONE); ScheduleScheme selectedSS2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedSS2 = scheduleScheme; } } Node selectedN2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedN2 = node; } } new Label(fifthStatisticComposite, SWT.NONE); final Label meanDelayScheduleSchemeAndNode = new Label(fifthStatisticComposite, SWT.NONE); allSec = simulationStatistic.getMeanDelay(selectedSS2, selectedN2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); // Listener for the combo scheduleScheme and Node comboScheduleScheme2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } java.util.List<Node> nodes2 = selectedScheduleScheme2.getStations(); String[] node2Selection = new String [nodes2.size()]; int index = 0; for (Node node : nodes2) { node2Selection[index] = node.getName(); index++; } comboNode2.setItems(node2Selection); comboNode2.select(0); Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } } allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); fifthStatisticComposite.layout(); } }); comboNode2.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { double allSec; int min; int sec; ScheduleScheme selectedScheduleScheme2 = null; for (ScheduleScheme scheduleScheme : scheduleSchemes) { if (scheduleScheme.getID().equals(comboScheduleScheme2.getText())) { selectedScheduleScheme2 = scheduleScheme; } } Node selectedNode2 = null; for (Node node : nodes) { if (node.getName().equals(comboNode2.getText())) { selectedNode2 = node; } }allSec = simulationStatistic.getMeanDelay(selectedScheduleScheme2, selectedNode2); min = (int) allSec / 60; sec = (int) allSec % 60; meanDelayScheduleSchemeAndNode.setText(min + " min " + sec + " s"); fifthStatisticComposite.layout(); } }); new Label(mainStatisticComposite, SWT.NULL); //Information Label infoTitle = new Label(mainStatisticComposite, SWT.NULL); infoTitle.setText(I18N.getMessage("SimulationStatisticDialog.InformationTitle")); infoTitle.setFont(new Font(Display.getCurrent(), new FontData("Helvetica", 10, SWT.BOLD))); Label info = new Label(mainStatisticComposite, SWT.NULL); info.setText(I18N.getMessage("SimulationStatisticDialog.Information")); // Thirteenth row with Button "Save as PDF" Button save = new Button(shell, SWT.PUSH); save.setImage(ImageHelper.getImage("pdfIcon")); save.setText(I18N.getMessage("SimulationStatisticDialog.Save")); GridData dataSave = new GridData(GridData.FILL); dataSave.horizontalAlignment = GridData.CENTER; save.setLayoutData(dataSave); // Function of Save-Button save.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { applicationService.showStatisticDoc(simulationStatistic); MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION); messageBox.setText(I18N.getMessage("SimulationStatisticDialog.informationSaved")); messageBox.setMessage(I18N.getMessage("SimulationStatisticDialog.informationStatisticSaved")); shell.setVisible(false); messageBox.open(); shell.close(); } }); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/AttachFileAction.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/AttachFileAction.java index 147c596ec..0de678aaa 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/AttachFileAction.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/AttachFileAction.java @@ -1,44 +1,44 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 Mylar committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylar.internal.tasks.ui.actions; import org.eclipse.mylar.internal.tasks.ui.wizards.NewAttachmentWizard; import org.eclipse.mylar.internal.tasks.ui.wizards.NewAttachmentWizardDialog; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.BaseSelectionListenerAction; /** * @author Mik Kersten */ public class AttachFileAction extends BaseSelectionListenerAction { public AttachFileAction() { super("Attach File..."); setId("org.eclipse.mylar.tasks.ui.actions.add.attachment"); } @Override public void run() { Object selection = super.getStructuredSelection().getFirstElement(); if (selection instanceof AbstractRepositoryTask) { AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask)selection; - TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryTask.getUrl()); + TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryTask.getRepositoryKind(), repositoryTask.getRepositoryUrl()); NewAttachmentWizard attachmentWizard = new NewAttachmentWizard(repository, repositoryTask); NewAttachmentWizardDialog dialog = new NewAttachmentWizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), attachmentWizard); attachmentWizard.setDialog(dialog); dialog.create(); dialog.open(); } } }
true
true
public void run() { Object selection = super.getStructuredSelection().getFirstElement(); if (selection instanceof AbstractRepositoryTask) { AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask)selection; TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryTask.getUrl()); NewAttachmentWizard attachmentWizard = new NewAttachmentWizard(repository, repositoryTask); NewAttachmentWizardDialog dialog = new NewAttachmentWizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), attachmentWizard); attachmentWizard.setDialog(dialog); dialog.create(); dialog.open(); } }
public void run() { Object selection = super.getStructuredSelection().getFirstElement(); if (selection instanceof AbstractRepositoryTask) { AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask)selection; TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryTask.getRepositoryKind(), repositoryTask.getRepositoryUrl()); NewAttachmentWizard attachmentWizard = new NewAttachmentWizard(repository, repositoryTask); NewAttachmentWizardDialog dialog = new NewAttachmentWizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), attachmentWizard); attachmentWizard.setDialog(dialog); dialog.create(); dialog.open(); } }
diff --git a/src/edu/wcu/Chargen/ChargenUdpClient.java b/src/edu/wcu/Chargen/ChargenUdpClient.java index 8f3a564..982929a 100644 --- a/src/edu/wcu/Chargen/ChargenUdpClient.java +++ b/src/edu/wcu/Chargen/ChargenUdpClient.java @@ -1,151 +1,151 @@ package edu.wcu.Chargen; import java.io.IOException; import java.io.PrintStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; /** * ChargenUDPClient is a class that extends AbstractChargenClient and provides * a concrete implementation of the printToStream() method using UDP. Data * received from the remote host is printed to the specified PrintStream. * * @author Jeremy Stilwell * @author Alisha Hayman * @version 10/8/13. */ public class ChargenUdpClient extends AbstractChargenClient { /** Time in milliseconds until timeout. */ private static final int TIMEOUT = 5000; /** The port number for the clientSocket. */ private static final int LOCAL_PORT = 12345; /** Client UDP socket. */ private DatagramSocket clientSocket; /** DatagramPacket to hold information to send to server. */ private DatagramPacket packet; /** The buffer array of bytes to send. */ private byte[] buffer; /** * Constructor initializes fields to a given destination host address and * port number. * @param host - The destination host's IP address. * @param port - The destination host's port number. */ public ChargenUdpClient(InetAddress host, int port) { super(host, port); clientSocket = null; packet = null; buffer = new byte[256]; } /** * Initiates communications with the UDP server via PrintStream. * Data received from the remote host is printed to the specified * PrintStream. * @param out - The PrintStream to carry the server's response. * @throws SocketException - when creating a new DatagramSocket. * @throws UnknownHostException - if local host can't be resolved into an * address. */ public void printToStream(PrintStream out) throws SocketTimeoutException, SocketException, UnknownHostException, IOException { //ByteArrayOutputStream baos = new ByteArrayOutputStream(); // call helper method to create the clientSocket clientSocket = makeSocket(LOCAL_PORT); // call helper method to create the packet packet = makePacket(buffer, buffer.length, getHost(), getPort()); // call helper to send and receive data from server (communicate) // received data is stored in buffer communicate(clientSocket, packet, buffer); // print the data from the server using the out PrintStream // TODO: What is this even doing? Is it printing? Where? /*out = new PrintStream(baos); baos.write(buffer); // move above "out = " line?*/ - out.print(new String(packet.getData())); + out.println(new String(packet.getData())); // close the socket and stream out.close(); clientSocket.close(); } /** * Helper method that creates and returns a new DatagramSocket using a given * port number and using the local host address. * @param port - The given destination port number. * @return - A new DatagramSocket to be used to talk to the server. * @throws SocketException - when creating a new DatagramSocket. * @throws UnknownHostException - if local host can't be resolved into an * address. */ private DatagramSocket makeSocket(int port) throws SocketException, UnknownHostException { DatagramSocket newSocket = null; // create new socket newSocket = new DatagramSocket(port, InetAddress.getLocalHost()); return newSocket; } /** * Helper method creates a new DatagramPacket to send between the client * and server during communication. * @param buffer - An array of bytes to hold sent and received data. * @param length - The length of the buffer. * @param host - The IP address of the remote host. * @param port - The remote host's port number. * @return - A new DatagramPacket to use for communication. * @throws UnknownHostException - if invalid information is given to the * packet. */ private DatagramPacket makePacket(byte[] buffer, int length, InetAddress host, int port) throws UnknownHostException { DatagramPacket packet = null; // create new packet packet = new DatagramPacket(buffer, length, host, port); return packet; } /** * Helper method that communicates between client and server. Sends a * DatagramPacket to a server and receives one in response. * @param clientSocket - The socket used for client/server communications. * @param packet - The packet to be exchanged. * @param buffer - The buffer to hold received data. * @throws SocketTimeoutException - when the socket has timed out. * @throws java.net.SocketException - when the receiving socket has * encountered problems. * @throws IOException - if the client and server communicated incorrectly. */ private void communicate(DatagramSocket clientSocket, DatagramPacket packet, byte[] buffer) throws SocketTimeoutException, SocketException, IOException { // send a DatagramPacket to server clientSocket.send(packet); // set timeout time clientSocket.setSoTimeout(TIMEOUT); // receive a DatagramPacket from the server clientSocket.receive(packet); } }
true
true
public void printToStream(PrintStream out) throws SocketTimeoutException, SocketException, UnknownHostException, IOException { //ByteArrayOutputStream baos = new ByteArrayOutputStream(); // call helper method to create the clientSocket clientSocket = makeSocket(LOCAL_PORT); // call helper method to create the packet packet = makePacket(buffer, buffer.length, getHost(), getPort()); // call helper to send and receive data from server (communicate) // received data is stored in buffer communicate(clientSocket, packet, buffer); // print the data from the server using the out PrintStream // TODO: What is this even doing? Is it printing? Where? /*out = new PrintStream(baos); baos.write(buffer); // move above "out = " line?*/ out.print(new String(packet.getData())); // close the socket and stream out.close(); clientSocket.close(); }
public void printToStream(PrintStream out) throws SocketTimeoutException, SocketException, UnknownHostException, IOException { //ByteArrayOutputStream baos = new ByteArrayOutputStream(); // call helper method to create the clientSocket clientSocket = makeSocket(LOCAL_PORT); // call helper method to create the packet packet = makePacket(buffer, buffer.length, getHost(), getPort()); // call helper to send and receive data from server (communicate) // received data is stored in buffer communicate(clientSocket, packet, buffer); // print the data from the server using the out PrintStream // TODO: What is this even doing? Is it printing? Where? /*out = new PrintStream(baos); baos.write(buffer); // move above "out = " line?*/ out.println(new String(packet.getData())); // close the socket and stream out.close(); clientSocket.close(); }
diff --git a/src/main/java/com/gitblit/utils/JGitUtils.java b/src/main/java/com/gitblit/utils/JGitUtils.java index cf6ec26d..3c1173ce 100644 --- a/src/main/java/com/gitblit/utils/JGitUtils.java +++ b/src/main/java/com/gitblit/utils/JGitUtils.java @@ -1,2095 +1,2098 @@ /* * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; import org.apache.commons.io.filefilter.TrueFileFilter; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.TagCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.diff.DiffEntry; import org.eclipse.jgit.diff.DiffEntry.ChangeType; import org.eclipse.jgit.diff.DiffFormatter; import org.eclipse.jgit.diff.RawTextComparator; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.StopWalkException; import org.eclipse.jgit.lib.BlobBasedConfig; import org.eclipse.jgit.lib.CommitBuilder; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.FileMode; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectInserter; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefUpdate; import org.eclipse.jgit.lib.RefUpdate.Result; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryCache.FileKey; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.lib.TreeFormatter; import org.eclipse.jgit.revwalk.RevBlob; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevObject; import org.eclipse.jgit.revwalk.RevSort; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.revwalk.filter.CommitTimeRevFilter; import org.eclipse.jgit.revwalk.filter.RevFilter; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.CredentialsProvider; import org.eclipse.jgit.transport.FetchResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.filter.AndTreeFilter; import org.eclipse.jgit.treewalk.filter.OrTreeFilter; import org.eclipse.jgit.treewalk.filter.PathFilter; import org.eclipse.jgit.treewalk.filter.PathFilterGroup; import org.eclipse.jgit.treewalk.filter.PathSuffixFilter; import org.eclipse.jgit.treewalk.filter.TreeFilter; import org.eclipse.jgit.util.FS; import org.eclipse.jgit.util.io.DisabledOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gitblit.models.GitNote; import com.gitblit.models.PathModel; import com.gitblit.models.PathModel.PathChangeModel; import com.gitblit.models.RefModel; import com.gitblit.models.SubmoduleModel; /** * Collection of static methods for retrieving information from a repository. * * @author James Moger * */ public class JGitUtils { static final Logger LOGGER = LoggerFactory.getLogger(JGitUtils.class); /** * Log an error message and exception. * * @param t * @param repository * if repository is not null it MUST be the {0} parameter in the * pattern. * @param pattern * @param objects */ private static void error(Throwable t, Repository repository, String pattern, Object... objects) { List<Object> parameters = new ArrayList<Object>(); if (objects != null && objects.length > 0) { for (Object o : objects) { parameters.add(o); } } if (repository != null) { parameters.add(0, repository.getDirectory().getAbsolutePath()); } LOGGER.error(MessageFormat.format(pattern, parameters.toArray()), t); } /** * Returns the displayable name of the person in the form "Real Name <email * address>". If the email address is empty, just "Real Name" is returned. * * @param person * @return "Real Name <email address>" or "Real Name" */ public static String getDisplayName(PersonIdent person) { if (StringUtils.isEmpty(person.getEmailAddress())) { return person.getName(); } final StringBuilder r = new StringBuilder(); r.append(person.getName()); r.append(" <"); r.append(person.getEmailAddress()); r.append('>'); return r.toString().trim(); } /** * Encapsulates the result of cloning or pulling from a repository. */ public static class CloneResult { public String name; public FetchResult fetchResult; public boolean createdRepository; } /** * Clone or Fetch a repository. If the local repository does not exist, * clone is called. If the repository does exist, fetch is called. By * default the clone/fetch retrieves the remote heads, tags, and notes. * * @param repositoriesFolder * @param name * @param fromUrl * @return CloneResult * @throws Exception */ public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl) throws Exception { return cloneRepository(repositoriesFolder, name, fromUrl, true, null); } /** * Clone or Fetch a repository. If the local repository does not exist, * clone is called. If the repository does exist, fetch is called. By * default the clone/fetch retrieves the remote heads, tags, and notes. * * @param repositoriesFolder * @param name * @param fromUrl * @param bare * @param credentialsProvider * @return CloneResult * @throws Exception */ public static CloneResult cloneRepository(File repositoriesFolder, String name, String fromUrl, boolean bare, CredentialsProvider credentialsProvider) throws Exception { CloneResult result = new CloneResult(); if (bare) { // bare repository, ensure .git suffix if (!name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) { name += Constants.DOT_GIT_EXT; } } else { // normal repository, strip .git suffix if (name.toLowerCase().endsWith(Constants.DOT_GIT_EXT)) { name = name.substring(0, name.indexOf(Constants.DOT_GIT_EXT)); } } result.name = name; File folder = new File(repositoriesFolder, name); if (folder.exists()) { File gitDir = FileKey.resolve(new File(repositoriesFolder, name), FS.DETECTED); Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).build(); result.fetchResult = fetchRepository(credentialsProvider, repository); repository.close(); } else { CloneCommand clone = new CloneCommand(); clone.setBare(bare); clone.setCloneAllBranches(true); clone.setURI(fromUrl); clone.setDirectory(folder); if (credentialsProvider != null) { clone.setCredentialsProvider(credentialsProvider); } Repository repository = clone.call().getRepository(); // Now we have to fetch because CloneCommand doesn't fetch // refs/notes nor does it allow manual RefSpec. result.createdRepository = true; result.fetchResult = fetchRepository(credentialsProvider, repository); repository.close(); } return result; } /** * Fetch updates from the remote repository. If refSpecs is unspecifed, * remote heads, tags, and notes are retrieved. * * @param credentialsProvider * @param repository * @param refSpecs * @return FetchResult * @throws Exception */ public static FetchResult fetchRepository(CredentialsProvider credentialsProvider, Repository repository, RefSpec... refSpecs) throws Exception { Git git = new Git(repository); FetchCommand fetch = git.fetch(); List<RefSpec> specs = new ArrayList<RefSpec>(); if (refSpecs == null || refSpecs.length == 0) { specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); specs.add(new RefSpec("+refs/tags/*:refs/tags/*")); specs.add(new RefSpec("+refs/notes/*:refs/notes/*")); } else { specs.addAll(Arrays.asList(refSpecs)); } if (credentialsProvider != null) { fetch.setCredentialsProvider(credentialsProvider); } fetch.setRefSpecs(specs); FetchResult fetchRes = fetch.call(); return fetchRes; } /** * Creates a bare repository. * * @param repositoriesFolder * @param name * @return Repository */ public static Repository createRepository(File repositoriesFolder, String name) { return createRepository(repositoriesFolder, name, "FALSE"); } /** * Creates a bare, shared repository. * * @param repositoriesFolder * @param name * @param shared * the setting for the --shared option of "git init". * @return Repository */ public static Repository createRepository(File repositoriesFolder, String name, String shared) { try { Repository repo = null; try { Git git = Git.init().setDirectory(new File(repositoriesFolder, name)).setBare(true).call(); repo = git.getRepository(); } catch (GitAPIException e) { throw new RuntimeException(e); } GitConfigSharedRepository sharedRepository = new GitConfigSharedRepository(shared); if (sharedRepository.isShared()) { StoredConfig config = repo.getConfig(); config.setString("core", null, "sharedRepository", sharedRepository.getValue()); config.setBoolean("receive", null, "denyNonFastforwards", true); config.save(); if (! JnaUtils.isWindows()) { Iterator<File> iter = org.apache.commons.io.FileUtils.iterateFilesAndDirs(repo.getDirectory(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); // Adjust permissions on file/directory while (iter.hasNext()) { adjustSharedPerm(iter.next(), sharedRepository); } } } return repo; } catch (IOException e) { throw new RuntimeException(e); } } private enum GitConfigSharedRepositoryValue { UMASK("0", 0), FALSE("0", 0), OFF("0", 0), NO("0", 0), GROUP("1", 0660), TRUE("1", 0660), ON("1", 0660), YES("1", 0660), ALL("2", 0664), WORLD("2", 0664), EVERYBODY("2", 0664), Oxxx(null, -1); private String configValue; private int permValue; private GitConfigSharedRepositoryValue(String config, int perm) { configValue = config; permValue = perm; }; public String getConfigValue() { return configValue; }; public int getPerm() { return permValue; }; } private static class GitConfigSharedRepository { private int intValue; private GitConfigSharedRepositoryValue enumValue; GitConfigSharedRepository(String s) { if ( s == null || s.trim().isEmpty() ) { enumValue = GitConfigSharedRepositoryValue.GROUP; } else { try { // Try one of the string values enumValue = GitConfigSharedRepositoryValue.valueOf(s.trim().toUpperCase()); } catch (IllegalArgumentException iae) { try { // Try if this is an octal number int i = Integer.parseInt(s, 8); if ( (i & 0600) != 0600 ) { String msg = String.format("Problem with core.sharedRepository filemode value (0%03o).\nThe owner of files must always have read and write permissions.", i); throw new IllegalArgumentException(msg); } intValue = i & 0666; enumValue = GitConfigSharedRepositoryValue.Oxxx; } catch (NumberFormatException nfe) { throw new IllegalArgumentException("Bad configuration value for 'shared': '" + s + "'"); } } } } String getValue() { if ( enumValue == GitConfigSharedRepositoryValue.Oxxx ) { if (intValue == 0) return "0"; return String.format("0%o", intValue); } return enumValue.getConfigValue(); } int getPerm() { if ( enumValue == GitConfigSharedRepositoryValue.Oxxx ) return intValue; return enumValue.getPerm(); } boolean isCustom() { return enumValue == GitConfigSharedRepositoryValue.Oxxx; } boolean isShared() { return (enumValue.getPerm() > 0) || enumValue == GitConfigSharedRepositoryValue.Oxxx; } } /** * Adjust file permissions of a file/directory for shared repositories * * @param path * File that should get its permissions changed. * @param configShared * Configuration string value for the shared mode. * @return Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned. */ public static int adjustSharedPerm(File path, String configShared) { return adjustSharedPerm(path, new GitConfigSharedRepository(configShared)); } /** * Adjust file permissions of a file/directory for shared repositories * * @param path * File that should get its permissions changed. * @param configShared * Configuration setting for the shared mode. * @return Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned. */ public static int adjustSharedPerm(File path, GitConfigSharedRepository configShared) { if (! configShared.isShared()) return 0; if (! path.exists()) return -1; int perm = configShared.getPerm(); JnaUtils.Filestat stat = JnaUtils.getFilestat(path); if (stat == null) return -1; int mode = stat.mode; if (mode < 0) return -1; // Now, here is the kicker: Under Linux, chmod'ing a sgid file whose guid is different from the process' // effective guid will reset the sgid flag of the file. Since there is no way to get the sgid flag back in // that case, we decide to rather not touch is and getting the right permissions will have to be achieved // in a different way, e.g. by using an appropriate umask for the Gitblit process. if (System.getProperty("os.name").toLowerCase().startsWith("linux")) { if ( ((mode & (JnaUtils.S_ISGID | JnaUtils.S_ISUID)) != 0) && stat.gid != JnaUtils.getegid() ) { LOGGER.debug("Not adjusting permissions to prevent clearing suid/sgid bits for '" + path + "'" ); return 0; } } // If the owner has no write access, delete it from group and other, too. if ((mode & JnaUtils.S_IWUSR) == 0) perm &= ~0222; // If the owner has execute access, set it for all blocks that have read access. if ((mode & JnaUtils.S_IXUSR) == JnaUtils.S_IXUSR) perm |= (perm & 0444) >> 2; if (configShared.isCustom()) { // Use the custom value for access permissions. mode = (mode & ~0777) | perm; } else { // Just add necessary bits to existing permissions. mode |= perm; } if (path.isDirectory()) { mode |= (mode & 0444) >> 2; mode |= JnaUtils.S_ISGID; } return JnaUtils.setFilemode(path, mode); } /** * Returns a list of repository names in the specified folder. * * @param repositoriesFolder * @param onlyBare * if true, only bare repositories repositories are listed. If * false all repositories are included. * @param searchSubfolders * recurse into subfolders to find grouped repositories * @param depth * optional recursion depth, -1 = infinite recursion * @param exclusions * list of regex exclusions for matching to folder names * @return list of repository names */ public static List<String> getRepositoryList(File repositoriesFolder, boolean onlyBare, boolean searchSubfolders, int depth, List<String> exclusions) { List<String> list = new ArrayList<String>(); if (repositoriesFolder == null || !repositoriesFolder.exists()) { return list; } List<Pattern> patterns = new ArrayList<Pattern>(); if (!ArrayUtils.isEmpty(exclusions)) { for (String regex : exclusions) { patterns.add(Pattern.compile(regex)); } } list.addAll(getRepositoryList(repositoriesFolder.getAbsolutePath(), repositoriesFolder, onlyBare, searchSubfolders, depth, patterns)); StringUtils.sortRepositorynames(list); list.remove(".git"); // issue-256 return list; } /** * Recursive function to find git repositories. * * @param basePath * basePath is stripped from the repository name as repositories * are relative to this path * @param searchFolder * @param onlyBare * if true only bare repositories will be listed. if false all * repositories are included. * @param searchSubfolders * recurse into subfolders to find grouped repositories * @param depth * recursion depth, -1 = infinite recursion * @param patterns * list of regex patterns for matching to folder names * @return */ private static List<String> getRepositoryList(String basePath, File searchFolder, boolean onlyBare, boolean searchSubfolders, int depth, List<Pattern> patterns) { File baseFile = new File(basePath); List<String> list = new ArrayList<String>(); if (depth == 0) { return list; } int nextDepth = (depth == -1) ? -1 : depth - 1; for (File file : searchFolder.listFiles()) { if (file.isDirectory()) { boolean exclude = false; for (Pattern pattern : patterns) { String path = FileUtils.getRelativePath(baseFile, file).replace('\\', '/'); if (pattern.matcher(path).matches()) { LOGGER.debug(MessageFormat.format("excluding {0} because of rule {1}", path, pattern.pattern())); exclude = true; break; } } if (exclude) { // skip to next file continue; } File gitDir = FileKey.resolve(new File(searchFolder, file.getName()), FS.DETECTED); if (gitDir != null) { if (onlyBare && gitDir.getName().equals(".git")) { continue; } if (gitDir.equals(file) || gitDir.getParentFile().equals(file)) { // determine repository name relative to base path String repository = FileUtils.getRelativePath(baseFile, file); list.add(repository); } else if (searchSubfolders && file.canRead()) { // look for repositories in subfolders list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders, nextDepth, patterns)); } } else if (searchSubfolders && file.canRead()) { // look for repositories in subfolders list.addAll(getRepositoryList(basePath, file, onlyBare, searchSubfolders, nextDepth, patterns)); } } } return list; } /** * Returns the first commit on a branch. If the repository does not exist or * is empty, null is returned. * * @param repository * @param branch * if unspecified, HEAD is assumed. * @return RevCommit */ public static RevCommit getFirstCommit(Repository repository, String branch) { if (!hasCommits(repository)) { return null; } RevCommit commit = null; try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(branch)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(branch); } RevWalk walk = new RevWalk(repository); walk.sort(RevSort.REVERSE); RevCommit head = walk.parseCommit(branchObject); walk.markStart(head); commit = walk.next(); walk.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to determine first commit"); } return commit; } /** * Returns the date of the first commit on a branch. If the repository does * not exist, Date(0) is returned. If the repository does exist bit is * empty, the last modified date of the repository folder is returned. * * @param repository * @param branch * if unspecified, HEAD is assumed. * @return Date of the first commit on a branch */ public static Date getFirstChange(Repository repository, String branch) { RevCommit commit = getFirstCommit(repository, branch); if (commit == null) { if (repository == null || !repository.getDirectory().exists()) { return new Date(0); } // fresh repository return new Date(repository.getDirectory().lastModified()); } return getCommitDate(commit); } /** * Determine if a repository has any commits. This is determined by checking * the for loose and packed objects. * * @param repository * @return true if the repository has commits */ public static boolean hasCommits(Repository repository) { if (repository != null && repository.getDirectory().exists()) { return (new File(repository.getDirectory(), "objects").list().length > 2) || (new File(repository.getDirectory(), "objects/pack").list().length > 0); } return false; } /** * Encapsulates the result of cloning or pulling from a repository. */ public static class LastChange { public Date when; public String who; LastChange() { when = new Date(0); } LastChange(long lastModified) { this.when = new Date(lastModified); } } /** * Returns the date and author of the most recent commit on a branch. If the * repository does not exist Date(0) is returned. If it does exist but is * empty, the last modified date of the repository folder is returned. * * @param repository * @return a LastChange object */ public static LastChange getLastChange(Repository repository) { if (!hasCommits(repository)) { // null repository if (repository == null) { return new LastChange(); } // fresh repository return new LastChange(repository.getDirectory().lastModified()); } List<RefModel> branchModels = getLocalBranches(repository, true, -1); if (branchModels.size() > 0) { // find most recent branch update LastChange lastChange = new LastChange(); for (RefModel branchModel : branchModels) { if (branchModel.getDate().after(lastChange.when)) { lastChange.when = branchModel.getDate(); lastChange.who = branchModel.getAuthorIdent().getName(); } } return lastChange; } // default to the repository folder modification date return new LastChange(repository.getDirectory().lastModified()); } /** * Retrieves a Java Date from a Git commit. * * @param commit * @return date of the commit or Date(0) if the commit is null */ public static Date getCommitDate(RevCommit commit) { if (commit == null) { return new Date(0); } return new Date(commit.getCommitTime() * 1000L); } /** * Retrieves a Java Date from a Git commit. * * @param commit * @return date of the commit or Date(0) if the commit is null */ public static Date getAuthorDate(RevCommit commit) { if (commit == null) { return new Date(0); } return commit.getAuthorIdent().getWhen(); } /** * Returns the specified commit from the repository. If the repository does * not exist or is empty, null is returned. * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @return RevCommit */ public static RevCommit getCommit(Repository repository, String objectId) { if (!hasCommits(repository)) { return null; } RevCommit commit = null; try { // resolve object id ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk walk = new RevWalk(repository); RevCommit rev = walk.parseCommit(branchObject); commit = rev; walk.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get commit {1}", objectId); } return commit; } /** * Retrieves the raw byte content of a file in the specified tree. * * @param repository * @param tree * if null, the RevTree from HEAD is assumed. * @param path * @return content as a byte [] */ public static byte[] getByteContent(Repository repository, RevTree tree, final String path, boolean throwError) { RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); byte[] content = null; try { if (tree == null) { ObjectId object = getDefaultBranch(repository); if (object == null) return null; RevCommit commit = rw.parseCommit(object); tree = commit.getTree(); } tw.reset(tree); while (tw.next()) { if (tw.isSubtree() && !path.equals(tw.getPathString())) { tw.enterSubtree(); continue; } ObjectId entid = tw.getObjectId(0); FileMode entmode = tw.getFileMode(0); if (entmode != FileMode.GITLINK) { RevObject ro = rw.lookupAny(entid, entmode.getObjectType()); rw.parseBody(ro); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectLoader ldr = repository.open(ro.getId(), Constants.OBJ_BLOB); byte[] tmp = new byte[4096]; InputStream in = ldr.openStream(); int n; while ((n = in.read(tmp)) > 0) { os.write(tmp, 0, n); } in.close(); content = os.toByteArray(); } } } catch (Throwable t) { if (throwError) { error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name()); } } finally { rw.dispose(); tw.release(); } return content; } /** * Returns the UTF-8 string content of a file in the specified tree. * * @param repository * @param tree * if null, the RevTree from HEAD is assumed. * @param blobPath * @param charsets optional * @return UTF-8 string content */ public static String getStringContent(Repository repository, RevTree tree, String blobPath, String... charsets) { byte[] content = getByteContent(repository, tree, blobPath, true); if (content == null) { return null; } return StringUtils.decodeString(content, charsets); } /** * Gets the raw byte content of the specified blob object. * * @param repository * @param objectId * @return byte [] blob content */ public static byte[] getByteContent(Repository repository, String objectId) { RevWalk rw = new RevWalk(repository); byte[] content = null; try { RevBlob blob = rw.lookupBlob(ObjectId.fromString(objectId)); rw.parseBody(blob); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectLoader ldr = repository.open(blob.getId(), Constants.OBJ_BLOB); byte[] tmp = new byte[4096]; InputStream in = ldr.openStream(); int n; while ((n = in.read(tmp)) > 0) { os.write(tmp, 0, n); } in.close(); content = os.toByteArray(); } catch (Throwable t) { error(t, repository, "{0} can't find blob {1}", objectId); } finally { rw.dispose(); } return content; } /** * Gets the UTF-8 string content of the blob specified by objectId. * * @param repository * @param objectId * @param charsets optional * @return UTF-8 string content */ public static String getStringContent(Repository repository, String objectId, String... charsets) { byte[] content = getByteContent(repository, objectId); if (content == null) { return null; } return StringUtils.decodeString(content, charsets); } /** * Returns the list of files in the specified folder at the specified * commit. If the repository does not exist or is empty, an empty list is * returned. * * @param repository * @param path * if unspecified, root folder is assumed. * @param commit * if null, HEAD is assumed. * @return list of files in specified path */ public static List<PathModel> getFilesInPath(Repository repository, String path, RevCommit commit) { List<PathModel> list = new ArrayList<PathModel>(); if (!hasCommits(repository)) { return list; } if (commit == null) { commit = getCommit(repository, null); } final TreeWalk tw = new TreeWalk(repository); try { tw.addTree(commit.getTree()); if (!StringUtils.isEmpty(path)) { PathFilter f = PathFilter.create(path); tw.setFilter(f); tw.setRecursive(false); boolean foundFolder = false; while (tw.next()) { if (!foundFolder && tw.isSubtree()) { tw.enterSubtree(); } if (tw.getPathString().equals(path)) { foundFolder = true; continue; } if (foundFolder) { list.add(getPathModel(tw, path, commit)); } } } else { tw.setRecursive(false); while (tw.next()) { list.add(getPathModel(tw, null, commit)); } } } catch (IOException e) { error(e, repository, "{0} failed to get files for commit {1}", commit.getName()); } finally { tw.release(); } Collections.sort(list); return list; } /** * Returns the list of files changed in a specified commit. If the * repository does not exist or is empty, an empty list is returned. * * @param repository * @param commit * if null, HEAD is assumed. * @return list of files changed in a commit */ public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit) { List<PathChangeModel> list = new ArrayList<PathChangeModel>(); if (!hasCommits(repository)) { return list; } RevWalk rw = new RevWalk(repository); try { if (commit == null) { ObjectId object = getDefaultBranch(repository); commit = rw.parseCommit(object); } if (commit.getParentCount() == 0) { TreeWalk tw = new TreeWalk(repository); tw.reset(); tw.setRecursive(true); tw.addTree(commit.getTree()); while (tw.next()) { list.add(new PathChangeModel(tw.getPathString(), tw.getPathString(), 0, tw .getRawMode(0), tw.getObjectId(0).getName(), commit.getId().getName(), ChangeType.ADD)); } tw.release(); } else { RevCommit parent = rw.parseCommit(commit.getParent(0).getId()); DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree()); for (DiffEntry diff : diffs) { String objectId = diff.getNewId().name(); if (diff.getChangeType().equals(ChangeType.DELETE)) { list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff .getNewMode().getBits(), objectId, commit.getId().getName(), diff .getChangeType())); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { list.add(new PathChangeModel(diff.getOldPath(), diff.getNewPath(), 0, diff .getNewMode().getBits(), objectId, commit.getId().getName(), diff .getChangeType())); } else { list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff .getNewMode().getBits(), objectId, commit.getId().getName(), diff .getChangeType())); } } } } catch (Throwable t) { error(t, repository, "{0} failed to determine files in commit!"); } finally { rw.dispose(); } return list; } /** * Returns the list of files changed in a specified commit. If the * repository does not exist or is empty, an empty list is returned. * * @param repository * @param startCommit * earliest commit * @param endCommit * most recent commit. if null, HEAD is assumed. * @return list of files changed in a commit range */ public static List<PathChangeModel> getFilesInRange(Repository repository, RevCommit startCommit, RevCommit endCommit) { List<PathChangeModel> list = new ArrayList<PathChangeModel>(); if (!hasCommits(repository)) { return list; } try { DiffFormatter df = new DiffFormatter(null); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffEntries = df.scan(startCommit.getTree(), endCommit.getTree()); for (DiffEntry diff : diffEntries) { if (diff.getChangeType().equals(ChangeType.DELETE)) { list.add(new PathChangeModel(diff.getOldPath(), diff.getOldPath(), 0, diff .getNewMode().getBits(), diff.getOldId().name(), null, diff .getChangeType())); } else if (diff.getChangeType().equals(ChangeType.RENAME)) { list.add(new PathChangeModel(diff.getOldPath(), diff.getNewPath(), 0, diff .getNewMode().getBits(), diff.getNewId().name(), null, diff .getChangeType())); } else { list.add(new PathChangeModel(diff.getNewPath(), diff.getNewPath(), 0, diff .getNewMode().getBits(), diff.getNewId().name(), null, diff .getChangeType())); } } Collections.sort(list); } catch (Throwable t) { error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit); } return list; } /** * Returns the list of files in the repository on the default branch that * match one of the specified extensions. This is a CASE-SENSITIVE search. * If the repository does not exist or is empty, an empty list is returned. * * @param repository * @param extensions * @return list of files in repository with a matching extension */ public static List<PathModel> getDocuments(Repository repository, List<String> extensions) { return getDocuments(repository, extensions, null); } /** * Returns the list of files in the repository in the specified commit that * match one of the specified extensions. This is a CASE-SENSITIVE search. * If the repository does not exist or is empty, an empty list is returned. * * @param repository * @param extensions * @param objectId * @return list of files in repository with a matching extension */ public static List<PathModel> getDocuments(Repository repository, List<String> extensions, String objectId) { List<PathModel> list = new ArrayList<PathModel>(); if (!hasCommits(repository)) { return list; } RevCommit commit = getCommit(repository, objectId); final TreeWalk tw = new TreeWalk(repository); try { tw.addTree(commit.getTree()); if (extensions != null && extensions.size() > 0) { List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>(); for (String extension : extensions) { if (extension.charAt(0) == '.') { suffixFilters.add(PathSuffixFilter.create("\\" + extension)); } else { // escape the . since this is a regexp filter suffixFilters.add(PathSuffixFilter.create("\\." + extension)); } } TreeFilter filter; if (suffixFilters.size() == 1) { filter = suffixFilters.get(0); } else { filter = OrTreeFilter.create(suffixFilters); } tw.setFilter(filter); tw.setRecursive(true); } while (tw.next()) { list.add(getPathModel(tw, null, commit)); } } catch (IOException e) { error(e, repository, "{0} failed to get documents for commit {1}", commit.getName()); } finally { tw.release(); } Collections.sort(list); return list; } /** * Returns a path model of the current file in the treewalk. * * @param tw * @param basePath * @param commit * @return a path model of the current file in the treewalk */ private static PathModel getPathModel(TreeWalk tw, String basePath, RevCommit commit) { String name; long size = 0; if (StringUtils.isEmpty(basePath)) { name = tw.getPathString(); } else { name = tw.getPathString().substring(basePath.length() + 1); } ObjectId objectId = tw.getObjectId(0); try { if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) { size = tw.getObjectReader().getObjectSize(objectId, Constants.OBJ_BLOB); } } catch (Throwable t) { error(t, null, "failed to retrieve blob size for " + tw.getPathString()); } return new PathModel(name, tw.getPathString(), size, tw.getFileMode(0).getBits(), objectId.getName(), commit.getName()); } /** * Returns a permissions representation of the mode bits. * * @param mode * @return string representation of the mode bits */ public static String getPermissionsFromMode(int mode) { if (FileMode.TREE.equals(mode)) { return "drwxr-xr-x"; } else if (FileMode.REGULAR_FILE.equals(mode)) { return "-rw-r--r--"; } else if (FileMode.EXECUTABLE_FILE.equals(mode)) { return "-rwxr-xr-x"; } else if (FileMode.SYMLINK.equals(mode)) { return "symlink"; } else if (FileMode.GITLINK.equals(mode)) { return "submodule"; } return "missing"; } /** * Returns a list of commits since the minimum date starting from the * specified object id. * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @param minimumDate * @return list of commits */ public static List<RevCommit> getRevLog(Repository repository, String objectId, Date minimumDate) { List<RevCommit> list = new ArrayList<RevCommit>(); if (!hasCommits(repository)) { return list; } try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(branchObject)); rw.setRevFilter(CommitTimeRevFilter.after(minimumDate)); Iterable<RevCommit> revlog = rw; for (RevCommit rev : revlog) { list.add(rev); } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get {1} revlog for minimum date {2}", objectId, minimumDate); } return list; } /** * Returns a list of commits starting from HEAD and working backwards. * * @param repository * @param maxCount * if < 0, all commits for the repository are returned. * @return list of commits */ public static List<RevCommit> getRevLog(Repository repository, int maxCount) { return getRevLog(repository, null, 0, maxCount); } /** * Returns a list of commits starting from the specified objectId using an * offset and maxCount for paging. This is similar to LIMIT n OFFSET p in * SQL. If the repository does not exist or is empty, an empty list is * returned. * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @param offset * @param maxCount * if < 0, all commits are returned. * @return a paged list of commits */ public static List<RevCommit> getRevLog(Repository repository, String objectId, int offset, int maxCount) { return getRevLog(repository, objectId, null, offset, maxCount); } /** * Returns a list of commits for the repository or a path within the * repository. Caller may specify ending revision with objectId. Caller may * specify offset and maxCount to achieve pagination of results. If the * repository does not exist or is empty, an empty list is returned. * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @param path * if unspecified, commits for repository are returned. If * specified, commits for the path are returned. * @param offset * @param maxCount * if < 0, all commits are returned. * @return a paged list of commits */ public static List<RevCommit> getRevLog(Repository repository, String objectId, String path, int offset, int maxCount) { List<RevCommit> list = new ArrayList<RevCommit>(); if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } try { // resolve branch ObjectId startRange = null; ObjectId endRange; if (StringUtils.isEmpty(objectId)) { endRange = getDefaultBranch(repository); } else { if( objectId.contains("..") ) { // range expression String[] parts = objectId.split("\\.\\."); startRange = repository.resolve(parts[0]); endRange = repository.resolve(parts[1]); } else { // objectid endRange= repository.resolve(objectId); } } if (endRange == null) { return list; } RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(endRange)); if (startRange != null) { rw.markUninteresting(rw.parseCommit(startRange)); } if (!StringUtils.isEmpty(path)) { TreeFilter filter = AndTreeFilter.create( PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF); rw.setTreeFilter(filter); } Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path); } return list; } /** * Returns a list of commits for the repository within the range specified * by startRangeId and endRangeId. If the repository does not exist or is * empty, an empty list is returned. * * @param repository * @param startRangeId * the first commit (not included in results) * @param endRangeId * the end commit (included in results) * @return a list of commits */ public static List<RevCommit> getRevLog(Repository repository, String startRangeId, String endRangeId) { List<RevCommit> list = new ArrayList<RevCommit>(); if (!hasCommits(repository)) { return list; } try { ObjectId endRange = repository.resolve(endRangeId); ObjectId startRange = repository.resolve(startRangeId); RevWalk rw = new RevWalk(repository); rw.markStart(rw.parseCommit(endRange)); if (startRange.equals(ObjectId.zeroId())) { // maybe this is a tag or an orphan branch list.add(rw.parseCommit(endRange)); rw.dispose(); return list; } else { rw.markUninteresting(rw.parseCommit(startRange)); } Iterable<RevCommit> revlog = rw; for (RevCommit rev : revlog) { list.add(rev); } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to get revlog for {1}..{2}", startRangeId, endRangeId); } return list; } /** * Search the commit history for a case-insensitive match to the value. * Search results require a specified SearchType of AUTHOR, COMMITTER, or * COMMIT. Results may be paginated using offset and maxCount. If the * repository does not exist or is empty, an empty list is returned. * * @param repository * @param objectId * if unspecified, HEAD is assumed. * @param value * @param type * AUTHOR, COMMITTER, COMMIT * @param offset * @param maxCount * if < 0, all matches are returned * @return matching list of commits */ public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) { - final String lcValue = value.toLowerCase(); List<RevCommit> list = new ArrayList<RevCommit>(); + if (StringUtils.isEmpty(value)) { + return list; + } if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } + final String lcValue = value.toLowerCase(); try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.setRevFilter(new RevFilter() { @Override public RevFilter clone() { // FindBugs complains about this method name. // This is part of JGit design and unrelated to Cloneable. return this; } @Override public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException { boolean include = false; switch (type) { case AUTHOR: include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMITTER: include = (commit.getCommitterIdent().getName().toLowerCase() .indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMIT: include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1; break; } return include; } }); rw.markStart(rw.parseCommit(branchObject)); Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value); } return list; } /** * Returns the default branch to use for a repository. Normally returns * whatever branch HEAD points to, but if HEAD points to nothing it returns * the most recently updated branch. * * @param repository * @return the objectid of a branch * @throws Exception */ public static ObjectId getDefaultBranch(Repository repository) throws Exception { ObjectId object = repository.resolve(Constants.HEAD); if (object == null) { // no HEAD // perhaps non-standard repository, try local branches List<RefModel> branchModels = getLocalBranches(repository, true, -1); if (branchModels.size() > 0) { // use most recently updated branch RefModel branch = null; Date lastDate = new Date(0); for (RefModel branchModel : branchModels) { if (branchModel.getDate().after(lastDate)) { branch = branchModel; lastDate = branch.getDate(); } } object = branch.getReferencedObjectId(); } } return object; } /** * Returns the target of the symbolic HEAD reference for a repository. * Normally returns a branch reference name, but when HEAD is detached, * the commit is matched against the known tags. The most recent matching * tag ref name will be returned if it references the HEAD commit. If * no match is found, the SHA1 is returned. * * @param repository * @return the ref name or the SHA1 for a detached HEAD */ public static String getHEADRef(Repository repository) { String target = null; try { target = repository.getFullBranch(); if (!target.startsWith(Constants.R_HEADS)) { // refers to an actual commit, probably a tag // find latest tag that matches the commit, if any List<RefModel> tagModels = getTags(repository, true, -1); if (tagModels.size() > 0) { RefModel tag = null; Date lastDate = new Date(0); for (RefModel tagModel : tagModels) { if (tagModel.getReferencedObjectId().getName().equals(target) && tagModel.getDate().after(lastDate)) { tag = tagModel; lastDate = tag.getDate(); } } target = tag.getName(); } } } catch (Throwable t) { error(t, repository, "{0} failed to get symbolic HEAD target"); } return target; } /** * Sets the symbolic ref HEAD to the specified target ref. The * HEAD will be detached if the target ref is not a branch. * * @param repository * @param targetRef * @return true if successful */ public static boolean setHEADtoRef(Repository repository, String targetRef) { try { // detach HEAD if target ref is not a branch boolean detach = !targetRef.startsWith(Constants.R_HEADS); RefUpdate.Result result; RefUpdate head = repository.updateRef(Constants.HEAD, detach); if (detach) { // Tag RevCommit commit = getCommit(repository, targetRef); head.setNewObjectId(commit.getId()); result = head.forceUpdate(); } else { result = head.link(targetRef); } switch (result) { case NEW: case FORCED: case NO_CHANGE: case FAST_FORWARD: return true; default: LOGGER.error(MessageFormat.format("{0} HEAD update to {1} returned result {2}", repository.getDirectory().getAbsolutePath(), targetRef, result)); } } catch (Throwable t) { error(t, repository, "{0} failed to set HEAD to {1}", targetRef); } return false; } /** * Sets the local branch ref to point to the specified commit id. * * @param repository * @param branch * @param commitId * @return true if successful */ public static boolean setBranchRef(Repository repository, String branch, String commitId) { String branchName = branch; if (!branchName.startsWith(Constants.R_HEADS)) { branchName = Constants.R_HEADS + branch; } try { RefUpdate refUpdate = repository.updateRef(branchName, false); refUpdate.setNewObjectId(ObjectId.fromString(commitId)); RefUpdate.Result result = refUpdate.forceUpdate(); switch (result) { case NEW: case FORCED: case NO_CHANGE: case FAST_FORWARD: return true; default: LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}", repository.getDirectory().getAbsolutePath(), branchName, commitId, result)); } } catch (Throwable t) { error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId); } return false; } /** * Deletes the specified branch ref. * * @param repository * @param branch * @return true if successful */ public static boolean deleteBranchRef(Repository repository, String branch) { String branchName = branch; if (!branchName.startsWith(Constants.R_HEADS)) { branchName = Constants.R_HEADS + branch; } try { RefUpdate refUpdate = repository.updateRef(branchName, false); refUpdate.setForceUpdate(true); RefUpdate.Result result = refUpdate.delete(); switch (result) { case NEW: case FORCED: case NO_CHANGE: case FAST_FORWARD: return true; default: LOGGER.error(MessageFormat.format("{0} failed to delete to {1} returned result {2}", repository.getDirectory().getAbsolutePath(), branchName, result)); } } catch (Throwable t) { error(t, repository, "{0} failed to delete {1}", branchName); } return false; } /** * Get the full branch and tag ref names for any potential HEAD targets. * * @param repository * @return a list of ref names */ public static List<String> getAvailableHeadTargets(Repository repository) { List<String> targets = new ArrayList<String>(); for (RefModel branchModel : JGitUtils.getLocalBranches(repository, true, -1)) { targets.add(branchModel.getName()); } for (RefModel tagModel : JGitUtils.getTags(repository, true, -1)) { targets.add(tagModel.getName()); } return targets; } /** * Returns all refs grouped by their associated object id. * * @param repository * @return all refs grouped by their referenced object id */ public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository) { return getAllRefs(repository, true); } /** * Returns all refs grouped by their associated object id. * * @param repository * @param includeRemoteRefs * @return all refs grouped by their referenced object id */ public static Map<ObjectId, List<RefModel>> getAllRefs(Repository repository, boolean includeRemoteRefs) { List<RefModel> list = getRefs(repository, org.eclipse.jgit.lib.RefDatabase.ALL, true, -1); Map<ObjectId, List<RefModel>> refs = new HashMap<ObjectId, List<RefModel>>(); for (RefModel ref : list) { if (!includeRemoteRefs && ref.getName().startsWith(Constants.R_REMOTES)) { continue; } ObjectId objectid = ref.getReferencedObjectId(); if (!refs.containsKey(objectid)) { refs.put(objectid, new ArrayList<RefModel>()); } refs.get(objectid).add(ref); } return refs; } /** * Returns the list of tags in the repository. If repository does not exist * or is empty, an empty list is returned. * * @param repository * @param fullName * if true, /refs/tags/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all tags are returned * @return list of tags */ public static List<RefModel> getTags(Repository repository, boolean fullName, int maxCount) { return getRefs(repository, Constants.R_TAGS, fullName, maxCount); } /** * Returns the list of local branches in the repository. If repository does * not exist or is empty, an empty list is returned. * * @param repository * @param fullName * if true, /refs/heads/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all local branches are returned * @return list of local branches */ public static List<RefModel> getLocalBranches(Repository repository, boolean fullName, int maxCount) { return getRefs(repository, Constants.R_HEADS, fullName, maxCount); } /** * Returns the list of remote branches in the repository. If repository does * not exist or is empty, an empty list is returned. * * @param repository * @param fullName * if true, /refs/remotes/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all remote branches are returned * @return list of remote branches */ public static List<RefModel> getRemoteBranches(Repository repository, boolean fullName, int maxCount) { return getRefs(repository, Constants.R_REMOTES, fullName, maxCount); } /** * Returns the list of note branches. If repository does not exist or is * empty, an empty list is returned. * * @param repository * @param fullName * if true, /refs/notes/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all note branches are returned * @return list of note branches */ public static List<RefModel> getNoteBranches(Repository repository, boolean fullName, int maxCount) { return getRefs(repository, Constants.R_NOTES, fullName, maxCount); } /** * Returns the list of refs in the specified base ref. If repository does * not exist or is empty, an empty list is returned. * * @param repository * @param fullName * if true, /refs/yadayadayada is returned. If false, * yadayadayada is returned. * @return list of refs */ public static List<RefModel> getRefs(Repository repository, String baseRef) { return getRefs(repository, baseRef, true, -1); } /** * Returns a list of references in the repository matching "refs". If the * repository is null or empty, an empty list is returned. * * @param repository * @param refs * if unspecified, all refs are returned * @param fullName * if true, /refs/something/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all references are returned * @return list of references */ private static List<RefModel> getRefs(Repository repository, String refs, boolean fullName, int maxCount) { List<RefModel> list = new ArrayList<RefModel>(); if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } try { Map<String, Ref> map = repository.getRefDatabase().getRefs(refs); RevWalk rw = new RevWalk(repository); for (Entry<String, Ref> entry : map.entrySet()) { Ref ref = entry.getValue(); RevObject object = rw.parseAny(ref.getObjectId()); String name = entry.getKey(); if (fullName && !StringUtils.isEmpty(refs)) { name = refs + name; } list.add(new RefModel(name, ref, object)); } rw.dispose(); Collections.sort(list); Collections.reverse(list); if (maxCount > 0 && list.size() > maxCount) { list = new ArrayList<RefModel>(list.subList(0, maxCount)); } } catch (IOException e) { error(e, repository, "{0} failed to retrieve {1}", refs); } return list; } /** * Returns a RefModel for the gh-pages branch in the repository. If the * branch can not be found, null is returned. * * @param repository * @return a refmodel for the gh-pages branch or null */ public static RefModel getPagesBranch(Repository repository) { return getBranch(repository, "gh-pages"); } /** * Returns a RefModel for a specific branch name in the repository. If the * branch can not be found, null is returned. * * @param repository * @return a refmodel for the branch or null */ public static RefModel getBranch(Repository repository, String name) { RefModel branch = null; try { // search for the branch in local heads for (RefModel ref : JGitUtils.getLocalBranches(repository, false, -1)) { if (ref.reference.getName().endsWith(name)) { branch = ref; break; } } // search for the branch in remote heads if (branch == null) { for (RefModel ref : JGitUtils.getRemoteBranches(repository, false, -1)) { if (ref.reference.getName().endsWith(name)) { branch = ref; break; } } } } catch (Throwable t) { LOGGER.error(MessageFormat.format("Failed to find {0} branch!", name), t); } return branch; } /** * Returns the list of submodules for this repository. * * @param repository * @param commit * @return list of submodules */ public static List<SubmoduleModel> getSubmodules(Repository repository, String commitId) { RevCommit commit = getCommit(repository, commitId); return getSubmodules(repository, commit.getTree()); } /** * Returns the list of submodules for this repository. * * @param repository * @param commit * @return list of submodules */ public static List<SubmoduleModel> getSubmodules(Repository repository, RevTree tree) { List<SubmoduleModel> list = new ArrayList<SubmoduleModel>(); byte [] blob = getByteContent(repository, tree, ".gitmodules", false); if (blob == null) { return list; } try { BlobBasedConfig config = new BlobBasedConfig(repository.getConfig(), blob); for (String module : config.getSubsections("submodule")) { String path = config.getString("submodule", module, "path"); String url = config.getString("submodule", module, "url"); list.add(new SubmoduleModel(module, path, url)); } } catch (ConfigInvalidException e) { LOGGER.error("Failed to load .gitmodules file for " + repository.getDirectory(), e); } return list; } /** * Returns the submodule definition for the specified path at the specified * commit. If no module is defined for the path, null is returned. * * @param repository * @param commit * @param path * @return a submodule definition or null if there is no submodule */ public static SubmoduleModel getSubmoduleModel(Repository repository, String commitId, String path) { for (SubmoduleModel model : getSubmodules(repository, commitId)) { if (model.path.equals(path)) { return model; } } return null; } public static String getSubmoduleCommitId(Repository repository, String path, RevCommit commit) { String commitId = null; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path))); try { tw.reset(commit.getTree()); while (tw.next()) { if (tw.isSubtree() && !path.equals(tw.getPathString())) { tw.enterSubtree(); continue; } if (FileMode.GITLINK == tw.getFileMode(0)) { commitId = tw.getObjectId(0).getName(); break; } } } catch (Throwable t) { error(t, repository, "{0} can't find {1} in commit {2}", path, commit.name()); } finally { rw.dispose(); tw.release(); } return commitId; } /** * Returns the list of notes entered about the commit from the refs/notes * namespace. If the repository does not exist or is empty, an empty list is * returned. * * @param repository * @param commit * @return list of notes */ public static List<GitNote> getNotesOnCommit(Repository repository, RevCommit commit) { List<GitNote> list = new ArrayList<GitNote>(); if (!hasCommits(repository)) { return list; } List<RefModel> noteBranches = getNoteBranches(repository, true, -1); for (RefModel notesRef : noteBranches) { RevTree notesTree = JGitUtils.getCommit(repository, notesRef.getName()).getTree(); // flat notes list String notePath = commit.getName(); String text = getStringContent(repository, notesTree, notePath); if (!StringUtils.isEmpty(text)) { List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1); RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history .size() - 1)); GitNote gitNote = new GitNote(noteRef, text); list.add(gitNote); continue; } // folder structure StringBuilder sb = new StringBuilder(commit.getName()); sb.insert(2, '/'); notePath = sb.toString(); text = getStringContent(repository, notesTree, notePath); if (!StringUtils.isEmpty(text)) { List<RevCommit> history = getRevLog(repository, notesRef.getName(), notePath, 0, -1); RefModel noteRef = new RefModel(notesRef.displayName, null, history.get(history .size() - 1)); GitNote gitNote = new GitNote(noteRef, text); list.add(gitNote); } } return list; } /** * this method creates an incremental revision number as a tag according to * the amount of already existing tags, which start with a defined prefix. * * @param repository * @param objectId * @param tagger * @param prefix * @param intPattern * @param message * @return true if operation was successful, otherwise false */ public static boolean createIncrementalRevisionTag(Repository repository, String objectId, PersonIdent tagger, String prefix, String intPattern, String message) { boolean result = false; Iterator<Entry<String, Ref>> iterator = repository.getTags().entrySet().iterator(); long lastRev = 0; while (iterator.hasNext()) { Entry<String, Ref> entry = iterator.next(); if (entry.getKey().startsWith(prefix)) { try { long val = Long.parseLong(entry.getKey().substring(prefix.length())); if (val > lastRev) { lastRev = val; } } catch (Exception e) { // this tag is NOT an incremental revision tag } } } DecimalFormat df = new DecimalFormat(intPattern); result = createTag(repository, objectId, tagger, prefix + df.format((lastRev + 1)), message); return result; } /** * creates a tag in a repository * * @param repository * @param objectId, the ref the tag points towards * @param tagger, the person tagging the object * @param tag, the string label * @param message, the string message * @return boolean, true if operation was successful, otherwise false */ public static boolean createTag(Repository repository, String objectId, PersonIdent tagger, String tag, String message) { try { Git gitClient = Git.open(repository.getDirectory()); TagCommand tagCommand = gitClient.tag(); tagCommand.setTagger(tagger); tagCommand.setMessage(message); if (objectId != null) { RevObject revObj = getCommit(repository, objectId); tagCommand.setObjectId(revObj); } tagCommand.setName(tag); Ref call = tagCommand.call(); return call != null ? true : false; } catch (Exception e) { error(e, repository, "Failed to create tag {1} in repository {0}", objectId, tag); } return false; } /** * Create an orphaned branch in a repository. * * @param repository * @param branchName * @param author * if unspecified, Gitblit will be the author of this new branch * @return true if successful */ public static boolean createOrphanBranch(Repository repository, String branchName, PersonIdent author) { boolean success = false; String message = "Created branch " + branchName; if (author == null) { author = new PersonIdent("Gitblit", "gitblit@localhost"); } try { ObjectInserter odi = repository.newObjectInserter(); try { // Create a blob object to insert into a tree ObjectId blobId = odi.insert(Constants.OBJ_BLOB, message.getBytes(Constants.CHARACTER_ENCODING)); // Create a tree object to reference from a commit TreeFormatter tree = new TreeFormatter(); tree.append(".branch", FileMode.REGULAR_FILE, blobId); ObjectId treeId = odi.insert(tree); // Create a commit object CommitBuilder commit = new CommitBuilder(); commit.setAuthor(author); commit.setCommitter(author); commit.setEncoding(Constants.CHARACTER_ENCODING); commit.setMessage(message); commit.setTreeId(treeId); // Insert the commit into the repository ObjectId commitId = odi.insert(commit); odi.flush(); RevWalk revWalk = new RevWalk(repository); try { RevCommit revCommit = revWalk.parseCommit(commitId); if (!branchName.startsWith("refs/")) { branchName = "refs/heads/" + branchName; } RefUpdate ru = repository.updateRef(branchName); ru.setNewObjectId(commitId); ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false); Result rc = ru.forceUpdate(); switch (rc) { case NEW: case FORCED: case FAST_FORWARD: success = true; break; default: success = false; } } finally { revWalk.release(); } } finally { odi.release(); } } catch (Throwable t) { error(t, repository, "Failed to create orphan branch {1} in repository {0}", branchName); } return success; } /** * Reads the sparkleshare id, if present, from the repository. * * @param repository * @return an id or null */ public static String getSparkleshareId(Repository repository) { byte[] content = getByteContent(repository, null, ".sparkleshare", false); if (content == null) { return null; } return StringUtils.decodeString(content); } }
false
true
public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) { final String lcValue = value.toLowerCase(); List<RevCommit> list = new ArrayList<RevCommit>(); if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.setRevFilter(new RevFilter() { @Override public RevFilter clone() { // FindBugs complains about this method name. // This is part of JGit design and unrelated to Cloneable. return this; } @Override public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException { boolean include = false; switch (type) { case AUTHOR: include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMITTER: include = (commit.getCommitterIdent().getName().toLowerCase() .indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMIT: include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1; break; } return include; } }); rw.markStart(rw.parseCommit(branchObject)); Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value); } return list; }
public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value, final com.gitblit.Constants.SearchType type, int offset, int maxCount) { List<RevCommit> list = new ArrayList<RevCommit>(); if (StringUtils.isEmpty(value)) { return list; } if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } final String lcValue = value.toLowerCase(); try { // resolve branch ObjectId branchObject; if (StringUtils.isEmpty(objectId)) { branchObject = getDefaultBranch(repository); } else { branchObject = repository.resolve(objectId); } RevWalk rw = new RevWalk(repository); rw.setRevFilter(new RevFilter() { @Override public RevFilter clone() { // FindBugs complains about this method name. // This is part of JGit design and unrelated to Cloneable. return this; } @Override public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException, MissingObjectException, IncorrectObjectTypeException, IOException { boolean include = false; switch (type) { case AUTHOR: include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1) || (commit.getAuthorIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMITTER: include = (commit.getCommitterIdent().getName().toLowerCase() .indexOf(lcValue) > -1) || (commit.getCommitterIdent().getEmailAddress().toLowerCase() .indexOf(lcValue) > -1); break; case COMMIT: include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1; break; } return include; } }); rw.markStart(rw.parseCommit(branchObject)); Iterable<RevCommit> revlog = rw; if (offset > 0) { int count = 0; for (RevCommit rev : revlog) { count++; if (count > offset) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } } else { for (RevCommit rev : revlog) { list.add(rev); if (maxCount > 0 && list.size() == maxCount) { break; } } } rw.dispose(); } catch (Throwable t) { error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value); } return list; }
diff --git a/src/net/invisioncraft/plugins/salesmania/commands/salesmania/LocaleCommand.java b/src/net/invisioncraft/plugins/salesmania/commands/salesmania/LocaleCommand.java index 30a9daa..f5c68e3 100644 --- a/src/net/invisioncraft/plugins/salesmania/commands/salesmania/LocaleCommand.java +++ b/src/net/invisioncraft/plugins/salesmania/commands/salesmania/LocaleCommand.java @@ -1,72 +1,86 @@ package net.invisioncraft.plugins.salesmania.commands.salesmania; import net.invisioncraft.plugins.salesmania.CommandHandler; import net.invisioncraft.plugins.salesmania.Salesmania; import net.invisioncraft.plugins.salesmania.configuration.Locale; import net.invisioncraft.plugins.salesmania.configuration.LocaleSettings; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; /** * Owner: Byte 2 O Software LLC * Date: 5/23/12 * Time: 8:01 PM */ /* Copyright 2012 Byte 2 O Software LLC This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class LocaleCommand extends CommandHandler { LocaleSettings localeSettings; enum LocaleCommands { LIST, SET } public LocaleCommand(Salesmania plugin) { super(plugin); localeSettings = plugin.getSettings().getLocaleSettings(); } @Override public boolean execute(CommandSender sender, Command command, String label, String[] args) { - LocaleCommands localeCommand = LocaleCommands.valueOf(args[1].toUpperCase()); Locale locale = plugin.getLocaleHandler().getLocale(sender); + LocaleCommands localeCommand; + // Syntax + try { + localeCommand = LocaleCommands.valueOf(args[1].toUpperCase()); + } catch (IllegalArgumentException ex) { + sender.sendMessage(locale.getMessageList("Syntax.Salesmania.salesmania").toArray(new String[0])); + return false; + } switch(localeCommand) { case LIST: String localeList = ""; for (String localeName : localeSettings.getLocales()) { - localeList.concat(locale + " "); + localeList = localeList.concat(localeName + " "); } sender.sendMessage(String.format( - locale.getMessage("Locale.list"), + locale.getMessage("Locale.available"), localeList)); + break; case SET: + if(args.length < 3) { + sender.sendMessage(locale.getMessageList("Syntax.Salesmania.salesmania").toArray(new String[0])); + return false; + } if(plugin.getLocaleHandler().setLocale(sender, args[2])) { locale = plugin.getLocaleHandler().getLocale(sender); sender.sendMessage(String.format( locale.getMessage("Locale.changed"), locale.getName())); } else { sender.sendMessage(String.format( locale.getMessage("Locale.notFound"), args[2])); } + break; default: return false; } + return true; } }
false
true
public boolean execute(CommandSender sender, Command command, String label, String[] args) { LocaleCommands localeCommand = LocaleCommands.valueOf(args[1].toUpperCase()); Locale locale = plugin.getLocaleHandler().getLocale(sender); switch(localeCommand) { case LIST: String localeList = ""; for (String localeName : localeSettings.getLocales()) { localeList.concat(locale + " "); } sender.sendMessage(String.format( locale.getMessage("Locale.list"), localeList)); case SET: if(plugin.getLocaleHandler().setLocale(sender, args[2])) { locale = plugin.getLocaleHandler().getLocale(sender); sender.sendMessage(String.format( locale.getMessage("Locale.changed"), locale.getName())); } else { sender.sendMessage(String.format( locale.getMessage("Locale.notFound"), args[2])); } default: return false; } }
public boolean execute(CommandSender sender, Command command, String label, String[] args) { Locale locale = plugin.getLocaleHandler().getLocale(sender); LocaleCommands localeCommand; // Syntax try { localeCommand = LocaleCommands.valueOf(args[1].toUpperCase()); } catch (IllegalArgumentException ex) { sender.sendMessage(locale.getMessageList("Syntax.Salesmania.salesmania").toArray(new String[0])); return false; } switch(localeCommand) { case LIST: String localeList = ""; for (String localeName : localeSettings.getLocales()) { localeList = localeList.concat(localeName + " "); } sender.sendMessage(String.format( locale.getMessage("Locale.available"), localeList)); break; case SET: if(args.length < 3) { sender.sendMessage(locale.getMessageList("Syntax.Salesmania.salesmania").toArray(new String[0])); return false; } if(plugin.getLocaleHandler().setLocale(sender, args[2])) { locale = plugin.getLocaleHandler().getLocale(sender); sender.sendMessage(String.format( locale.getMessage("Locale.changed"), locale.getName())); } else { sender.sendMessage(String.format( locale.getMessage("Locale.notFound"), args[2])); } break; default: return false; } return true; }
diff --git a/To_DoList/src/csci422/CandN/to_dolist/ListViewsFactory.java b/To_DoList/src/csci422/CandN/to_dolist/ListViewsFactory.java index 7c83220..a21f0bd 100644 --- a/To_DoList/src/csci422/CandN/to_dolist/ListViewsFactory.java +++ b/To_DoList/src/csci422/CandN/to_dolist/ListViewsFactory.java @@ -1,101 +1,101 @@ /* *Chris Card *Nathan harvey *10/26/12 *This class manages content displayed on the widget */ package csci422.CandN.to_dolist; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.RemoteViews; import android.widget.RemoteViewsService.RemoteViewsFactory; public class ListViewsFactory implements RemoteViewsFactory { private Context ctxt = null; private ToDoHelper helper = null; private Cursor tasks = null; public ListViewsFactory(Context ctxt, Intent intent) { this.ctxt = ctxt; } public int getCount() { return tasks.getCount(); } public long getItemId(int position) { tasks.moveToPosition(position); return tasks.getInt(0); } public RemoteViews getLoadingView() { // TODO Auto-generated method stub return null; } @TargetApi(11) public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.widget_row); tasks.moveToPosition(position); row.setTextViewText(android.R.id.text1, tasks.getString(1)); - if(tasks.getInt(2) < 95) + if(tasks.getInt(2) >= 95) { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_on_background); } else { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_off_background); } Intent i = new Intent(); Bundle extras = new Bundle(); extras.putString(DetailForm.DETAIL_EXTRA, String.valueOf(tasks.getInt(0))); i.putExtras(extras); row.setOnClickFillInIntent(android.R.id.text1, i); return row; } public int getViewTypeCount() { return 1; } public boolean hasStableIds() { return true; } public void onCreate() { helper = new ToDoHelper(ctxt); tasks = helper.getReadableDatabase().rawQuery("SELECT _ID, title, state FROM todos", null); } public void onDataSetChanged() { // TODO Auto-generated method stub } public void onDestroy() { tasks.close(); helper.close(); } }
true
true
public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.widget_row); tasks.moveToPosition(position); row.setTextViewText(android.R.id.text1, tasks.getString(1)); if(tasks.getInt(2) < 95) { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_on_background); } else { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_off_background); } Intent i = new Intent(); Bundle extras = new Bundle(); extras.putString(DetailForm.DETAIL_EXTRA, String.valueOf(tasks.getInt(0))); i.putExtras(extras); row.setOnClickFillInIntent(android.R.id.text1, i); return row; }
public RemoteViews getViewAt(int position) { RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.widget_row); tasks.moveToPosition(position); row.setTextViewText(android.R.id.text1, tasks.getString(1)); if(tasks.getInt(2) >= 95) { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_on_background); } else { row.setImageViewResource(R.id.checkImage, R.drawable.checkbox_off_background); } Intent i = new Intent(); Bundle extras = new Bundle(); extras.putString(DetailForm.DETAIL_EXTRA, String.valueOf(tasks.getInt(0))); i.putExtras(extras); row.setOnClickFillInIntent(android.R.id.text1, i); return row; }
diff --git a/test-src/com/redhat/ceylon/ceylondoc/test/CeylonDocToolTest.java b/test-src/com/redhat/ceylon/ceylondoc/test/CeylonDocToolTest.java index 4f25e7613..60ed7c38b 100644 --- a/test-src/com/redhat/ceylon/ceylondoc/test/CeylonDocToolTest.java +++ b/test-src/com/redhat/ceylon/ceylondoc/test/CeylonDocToolTest.java @@ -1,295 +1,295 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.ceylondoc.test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.Assert; import org.junit.Test; import com.redhat.ceylon.ceylondoc.CeylonDocTool; import com.redhat.ceylon.ceylondoc.Util; import com.redhat.ceylon.compiler.java.tools.CeyloncTool; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.sun.source.util.JavacTask; public class CeylonDocToolTest { private CeylonDocTool tool(String pathname, String testName, String moduleName, String... repositories) throws IOException { CeylonDocTool tool = new CeylonDocTool(Arrays.asList(new File(pathname)), Arrays.asList(repositories), Arrays.asList(moduleName), true/* throw on error */); File dir = new File(System.getProperty("java.io.tmpdir"), "CeylonDocToolTest/" + testName); if (dir.exists()) { Util.delete(dir); } tool.setOutputRepository(dir.getAbsolutePath()); return tool; } protected void assertFileExists(File destDir, String path) { File file = new File(destDir, path); Assert.assertTrue(file + " doesn't exist", file.exists()); Assert.assertTrue(file + " exists but is not a file", file.isFile()); } protected void assertFileNotExists(File destDir, String path) { File file = new File(destDir, path); Assert.assertFalse(file + " does exist", file.exists()); } protected void assertDirectoryExists(File destDir, String path) { File file = new File(destDir, path); Assert.assertTrue(file + " doesn't exist", file.exists()); Assert.assertTrue(file + " exist but isn't a directory", file.isDirectory()); } static interface GrepAsserter { void makeAssertions(Matcher matcher); } static GrepAsserter AT_LEAST_ONE_MATCH = new GrepAsserter() { @Override public void makeAssertions(Matcher matcher) { Assert.assertTrue("Zero matches for " + matcher.pattern().pattern(), matcher.find()); } }; static GrepAsserter NO_MATCHES = new GrepAsserter() { @Override public void makeAssertions(Matcher matcher) { boolean found = matcher.find(); if (found) { Assert.fail("Unexpected match for " + matcher.pattern().pattern() + ": " + matcher.group(0)); } } }; protected void assertMatchInFile(File destDir, String path, Pattern pattern, GrepAsserter asserter) throws IOException { assertFileExists(destDir, path); Charset charset = Charset.forName("UTF-8"); File file = new File(destDir, path); FileInputStream stream = new FileInputStream(file); try { FileChannel channel = stream.getChannel(); try { MappedByteBuffer map = channel.map(MapMode.READ_ONLY, 0, channel.size()); CharBuffer chars = charset.decode(map); Matcher matcher = pattern.matcher(chars); asserter.makeAssertions(matcher); } finally { channel.close(); } } finally { stream.close(); } } protected void assertMatchInFile(File destDir, String path, Pattern pattern) throws IOException { assertMatchInFile(destDir, path, pattern, AT_LEAST_ONE_MATCH); } protected void assertNoMatchInFile(File destDir, String path, Pattern pattern) throws IOException { assertMatchInFile(destDir, path, pattern, NO_MATCHES); } @Test public void moduleA() throws IOException { String pathname = "test-src/com/redhat/ceylon/ceylondoc/test/modules/single"; String testName = "moduleA"; CeylonDocTool tool = tool(pathname, testName, "a"); tool.setShowPrivate(false); tool.setOmitSource(false); tool.makeDoc(); Module module = new Module(); module.setName(Arrays.asList("a")); module.setVersion("3.1.4"); File destDir = getOutputDir(tool, module); assertDirectoryExists(destDir, ".resources"); assertFileExists(destDir, ".resources/index.js"); assertFileExists(destDir, ".resources/icons.png"); assertFileExists(destDir, "index.html"); assertFileExists(destDir, "search.html"); assertFileExists(destDir, "interface_Types.html"); assertFileNotExists(destDir, "class_PrivateClass.html"); assertFileExists(destDir, "class_SharedClass.html"); assertFileExists(destDir, "class_CaseSensitive.html"); assertFileNotExists(destDir, "class_caseSensitive.html"); assertFileExists(destDir, "object_caseSensitive.html"); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> module")); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> package")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedAttribute'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateAttribute'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedGetter'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateGetter'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedMethod'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateMethod'.*?>")); assertMatchInFile(destDir, "index.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "interface_Types.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<div class='throws'>Throws:")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("OverflowException<p>if the number is too large to be represented as an integer</p>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubException.html'>StubException</a><p><code>when</code> with <strong>WIKI</strong> syntax</p>")); assertFileExists(destDir, "interface_StubClass.StubInnerInterface.html"); assertFileExists(destDir, "class_StubClass.StubInnerClass.html"); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Interfaces")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Classes")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubClass.StubInnerClass.html'>StubInnerClass</a>")); assertMatchInFile(destDir, "interface_StubClass.StubInnerInterface.html", - Pattern.compile("Enclosing class: <a href='class_StubClass.html'>StubClass</a>")); + Pattern.compile("Enclosing class: <i class='icon-class'></i><a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", - Pattern.compile("Enclosing class: <a href='class_StubClass.html'>StubClass</a>")); + Pattern.compile("Enclosing class: <i class='icon-class'></i><a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", Pattern.compile("Satisfied Interfaces: <a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertIcons(destDir); } private void assertIcons(File destDir) throws IOException { assertMatchInFile(destDir, "interface_StubInterface.html", Pattern.compile("Interface <i class='icon-interface'></i><code>StubInterface</code>")); assertMatchInFile(destDir, "interface_StubInterface.html", Pattern.compile("id='defaultMethod'><td><code><i class='icon-shared-member'></i>")); assertMatchInFile(destDir, "interface_StubInterface.html", Pattern.compile("id='formalMethod'><td><code><i class='icon-shared-member'><i class='icon-decoration-formal'></i></i>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<i class='icon-interface'></i><a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<i class='icon-class'></i><a href='class_StubClass.StubInnerClass.html'>StubInnerClass</a>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<i class='icon-class'></i>StubClass()")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("id='formalMethod'><td><code><i class='icon-shared-member'><i class='icon-decoration-impl'></i></i>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("id='defaultMethod'><td><code><i class='icon-shared-member'><i class='icon-decoration-over'></i></i>")); } private File getOutputDir(CeylonDocTool tool, Module module) { String outputRepo = tool.getOutputRepository(); return new File(com.redhat.ceylon.compiler.java.util.Util.getModulePath(new File(outputRepo), module), "module-doc"); } @Test public void moduleAWithPrivate() throws IOException { String pathname = "test-src/com/redhat/ceylon/ceylondoc/test/modules/single"; String testName = "moduleAWithPrivate"; CeylonDocTool tool = tool(pathname, testName, "a"); tool.setShowPrivate(true); tool.setOmitSource(false); tool.makeDoc(); Module module = new Module(); module.setName(Arrays.asList("a")); module.setVersion("3.1.4"); File destDir = getOutputDir(tool, module); assertDirectoryExists(destDir, ".resources"); assertFileExists(destDir, ".resources/index.js"); assertFileExists(destDir, "index.html"); assertFileExists(destDir, "search.html"); assertFileExists(destDir, "interface_Types.html"); assertFileExists(destDir, "class_PrivateClass.html"); assertFileExists(destDir, "class_SharedClass.html"); assertFileExists(destDir, "class_CaseSensitive.html"); assertFileNotExists(destDir, "class_caseSensitive.html"); assertFileExists(destDir, "object_caseSensitive.html"); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> module")); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> package")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedAttribute'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateAttribute'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedGetter'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateGetter'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedMethod'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateMethod'.*?>")); } @Test public void dependentOnBinaryModule() throws IOException { String pathname = "test-src/com/redhat/ceylon/ceylondoc/test/modules/dependency"; String testName = "dependentOnBinaryModule"; // compile the b module compile(pathname+"/b", "b"); CeylonDocTool tool = tool(pathname+"/c", testName, "c", "build/ceylon-cars"); tool.makeDoc(); } private void compile(String pathname, String moduleName) throws IOException { CeyloncTool compiler = new CeyloncTool(); List<String> options = Arrays.asList("-src", pathname, "-out", "build/ceylon-cars"); JavacTask task = compiler.getTask(null, null, null, options, Arrays.asList(moduleName), null); Boolean ret = task.call(); Assert.assertEquals("Compilation failed", Boolean.TRUE, ret); } }
false
true
public void moduleA() throws IOException { String pathname = "test-src/com/redhat/ceylon/ceylondoc/test/modules/single"; String testName = "moduleA"; CeylonDocTool tool = tool(pathname, testName, "a"); tool.setShowPrivate(false); tool.setOmitSource(false); tool.makeDoc(); Module module = new Module(); module.setName(Arrays.asList("a")); module.setVersion("3.1.4"); File destDir = getOutputDir(tool, module); assertDirectoryExists(destDir, ".resources"); assertFileExists(destDir, ".resources/index.js"); assertFileExists(destDir, ".resources/icons.png"); assertFileExists(destDir, "index.html"); assertFileExists(destDir, "search.html"); assertFileExists(destDir, "interface_Types.html"); assertFileNotExists(destDir, "class_PrivateClass.html"); assertFileExists(destDir, "class_SharedClass.html"); assertFileExists(destDir, "class_CaseSensitive.html"); assertFileNotExists(destDir, "class_caseSensitive.html"); assertFileExists(destDir, "object_caseSensitive.html"); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> module")); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> package")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedAttribute'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateAttribute'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedGetter'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateGetter'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedMethod'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateMethod'.*?>")); assertMatchInFile(destDir, "index.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "interface_Types.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<div class='throws'>Throws:")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("OverflowException<p>if the number is too large to be represented as an integer</p>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubException.html'>StubException</a><p><code>when</code> with <strong>WIKI</strong> syntax</p>")); assertFileExists(destDir, "interface_StubClass.StubInnerInterface.html"); assertFileExists(destDir, "class_StubClass.StubInnerClass.html"); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Interfaces")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Classes")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubClass.StubInnerClass.html'>StubInnerClass</a>")); assertMatchInFile(destDir, "interface_StubClass.StubInnerInterface.html", Pattern.compile("Enclosing class: <a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", Pattern.compile("Enclosing class: <a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", Pattern.compile("Satisfied Interfaces: <a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertIcons(destDir); }
public void moduleA() throws IOException { String pathname = "test-src/com/redhat/ceylon/ceylondoc/test/modules/single"; String testName = "moduleA"; CeylonDocTool tool = tool(pathname, testName, "a"); tool.setShowPrivate(false); tool.setOmitSource(false); tool.makeDoc(); Module module = new Module(); module.setName(Arrays.asList("a")); module.setVersion("3.1.4"); File destDir = getOutputDir(tool, module); assertDirectoryExists(destDir, ".resources"); assertFileExists(destDir, ".resources/index.js"); assertFileExists(destDir, ".resources/icons.png"); assertFileExists(destDir, "index.html"); assertFileExists(destDir, "search.html"); assertFileExists(destDir, "interface_Types.html"); assertFileNotExists(destDir, "class_PrivateClass.html"); assertFileExists(destDir, "class_SharedClass.html"); assertFileExists(destDir, "class_CaseSensitive.html"); assertFileNotExists(destDir, "class_caseSensitive.html"); assertFileExists(destDir, "object_caseSensitive.html"); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> module")); assertMatchInFile(destDir, "index.html", Pattern.compile("This is a <strong>test</strong> package")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedAttribute'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateAttribute'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedGetter'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateGetter'.*?>")); assertMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='sharedMethod'.*?>")); assertNoMatchInFile(destDir, "class_SharedClass.html", Pattern.compile("<.*? id='privateMethod'.*?>")); assertMatchInFile(destDir, "index.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "interface_Types.html", Pattern.compile("<div class='by'>By: Tom Bentley</div>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<div class='throws'>Throws:")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("OverflowException<p>if the number is too large to be represented as an integer</p>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubException.html'>StubException</a><p><code>when</code> with <strong>WIKI</strong> syntax</p>")); assertFileExists(destDir, "interface_StubClass.StubInnerInterface.html"); assertFileExists(destDir, "class_StubClass.StubInnerClass.html"); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Interfaces")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("Nested Classes")); assertMatchInFile(destDir, "class_StubClass.html", Pattern.compile("<a href='class_StubClass.StubInnerClass.html'>StubInnerClass</a>")); assertMatchInFile(destDir, "interface_StubClass.StubInnerInterface.html", Pattern.compile("Enclosing class: <i class='icon-class'></i><a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", Pattern.compile("Enclosing class: <i class='icon-class'></i><a href='class_StubClass.html'>StubClass</a>")); assertMatchInFile(destDir, "class_StubClass.StubInnerClass.html", Pattern.compile("Satisfied Interfaces: <a href='interface_StubClass.StubInnerInterface.html'>StubInnerInterface</a>")); assertIcons(destDir); }
diff --git a/biz.aQute.repository/src/aQute/bnd/deployer/repository/CachingUriResourceHandle.java b/biz.aQute.repository/src/aQute/bnd/deployer/repository/CachingUriResourceHandle.java index aaa63ca0c..a2f82254a 100644 --- a/biz.aQute.repository/src/aQute/bnd/deployer/repository/CachingUriResourceHandle.java +++ b/biz.aQute.repository/src/aQute/bnd/deployer/repository/CachingUriResourceHandle.java @@ -1,350 +1,350 @@ package aQute.bnd.deployer.repository; import java.io.*; import java.net.*; import java.security.*; import aQute.bnd.deployer.http.*; import aQute.bnd.service.*; import aQute.bnd.service.url.*; import aQute.lib.hex.*; import aQute.lib.io.*; import aQute.service.reporter.*; /** * <p> * This resource handler downloads remote resources on demand, and caches them * as local files. Resources that are already local (i.e. <code>file:...</code> * URLs) are returned directly. * </p> * <p> * Two alternative caching modes are available. When the mode is * {@link CachingMode#PreferCache}, the cached file will always be returned if * it exists; therefore to refresh from the remote resource it will be necessary * to delete the cache. When the mode is {@link CachingMode#PreferRemote}, the * first call to {@link #request()} will always attempt to download the remote * resource, and only uses the pre-downloaded cache if the remote could not be * downloaded (e.g. because the network is offline). * </p> * * @author njbartlett */ public class CachingUriResourceHandle implements ResourceHandle { private static final String SHA_256 = "SHA-256"; @Deprecated public static enum CachingMode { /** * Always use the cached file, if it exists. */ @Deprecated PreferCache, /** * Download the remote resource if possible, falling back to the cached * file if remote fails. Subsequently the cached resource will be used. */ @Deprecated PreferRemote; } static final String FILE_SCHEME = "file"; static final String FILE_PREFIX = FILE_SCHEME + ":"; static final String HTTP_SCHEME = "http"; static final String HTTP_PREFIX = HTTP_SCHEME + ":"; static final String UTF_8 = "UTF-8"; final File cacheDir; final URLConnector connector; // The resolved, absolute URL of the resource final URL url; final String sha; // The local file, if the resource IS a file, otherwise null. final File localFile; // The cached file copy of the resource, if it is remote and has been // downloaded. final File cachedFile; final File shaFile; final CachingMode mode; Reporter reporter; @Deprecated public CachingUriResourceHandle(URI uri, File cacheDir, CachingMode mode) throws IOException { this(uri, cacheDir, new DefaultURLConnector(), mode); } @Deprecated public CachingUriResourceHandle(URI uri, File cacheDir, URLConnector connector, CachingMode mode) throws IOException { this(uri, cacheDir, connector, mode, null); } public CachingUriResourceHandle(URI uri, final File cacheDir, URLConnector connector, String sha) throws IOException { this(uri, cacheDir, connector, CachingMode.PreferRemote, sha); } @Deprecated public CachingUriResourceHandle(URI uri, final File cacheDir, URLConnector connector, CachingMode mode, String sha) throws IOException { this.cacheDir = cacheDir; this.connector = connector; this.mode = mode; this.sha = sha; if (!uri.isAbsolute()) throw new IllegalArgumentException("Relative URIs are not permitted."); if (FILE_SCHEME.equals(uri.getScheme())) { this.localFile = new File(uri.getPath()); this.url = uri.toURL(); this.cachedFile = null; this.shaFile = null; } else { this.url = uri.toURL(); this.localFile = null; this.cachedFile = mapRemoteURL(url); this.shaFile = mapSHAFile(cachedFile); } } public void setReporter(Reporter reporter) { this.reporter = reporter; } static File resolveFile(String baseFileName, String fileName) { File resolved; File baseFile = new File(baseFileName); if (baseFile.isDirectory()) resolved = new File(baseFile, fileName); else if (baseFile.isFile()) resolved = new File(baseFile.getParentFile(), fileName); else throw new IllegalArgumentException("Cannot resolve relative to non-existant base file path: " + baseFileName); return resolved; } private File mapRemoteURL(URL url) throws UnsupportedEncodingException, IOException { String localDirName; String localFileName; String fullUrl = url.toExternalForm(); int lastSlashIndex = fullUrl.lastIndexOf('/'); File localDir; if (lastSlashIndex > -1) { localDirName = URLEncoder.encode(fullUrl.substring(0, lastSlashIndex), UTF_8); localDir = new File(cacheDir, localDirName); if (localDir.exists() && !localDir.isDirectory()) { localDir = cacheDir; localFileName = URLEncoder.encode(fullUrl, UTF_8); } else { localFileName = URLEncoder.encode(fullUrl.substring(lastSlashIndex + 1), UTF_8); } } else { localDir = cacheDir; localFileName = URLEncoder.encode(fullUrl, UTF_8); } if (!localDir.exists() && !localDir.mkdirs()) { throw new IOException("Could not create directory " + localDir); } return new File(localDir, localFileName); } private static File mapSHAFile(File cachedFile) { return new File(cachedFile.getAbsolutePath() + ".sha"); } public String getName() { return url.toString(); } public Location getLocation() { Location result; if (localFile != null) result = Location.local; else if (cachedFile.exists()) result = Location.remote_cached; else result = Location.remote; return result; } public File request() throws IOException { if (localFile != null) return localFile; if (cachedFile == null) throw new IllegalStateException("Invalid URLResourceHandle: both local file and cache file location are uninitialised."); // Check whether the cached copy exist and has the right SHA. boolean cacheExists = cachedFile.isFile(); boolean cacheValidated; if (cacheExists) { if (sha == null) cacheValidated = false; else { String cachedSHA = getCachedSHA(); cacheValidated = sha.equalsIgnoreCase(cachedSHA); } } else { cacheValidated = false; } if (cacheValidated) return cachedFile; try { InputStream data = connector.connect(url); // Save the data to the cache ensureCacheDirExists(); String serverSHA = copyWithSHA(data, new FileOutputStream(cachedFile)); // Check the SHA of the received data if (sha != null && !sha.equalsIgnoreCase(serverSHA)) { shaFile.delete(); cachedFile.delete(); throw new IOException(String.format("Invalid SHA on remote resource", url)); } saveSHAFile(serverSHA); return cachedFile; } catch (IOException e) { if (sha == null) { // Remote access failed, use the cache if it exists AND if the original SHA was not known. if (cacheExists) { if (reporter != null) - reporter.warning("Download of remote resource %s failed, using local cache %s. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); + reporter.warning("Using local cache; downloading %s failed (%s).", url, e); return cachedFile; } else { if (reporter != null) - reporter.error("Download of remote resource %s failed and cache file %s not available. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); - throw new IOException(String.format("Download of remote resource %s failed and cache file %s not available, see log for details.", url, cachedFile)); + reporter.error("Downloading %s failed (%s) and cache file %s is not available. Trace: %s", url, e, cachedFile, collectStackTrace(e)); + throw new IOException(String.format("Downloading %s failed and cache file %s is not available, see log for details.", url, cachedFile)); } } else { // Can only get here if the cache was missing or didn't match the SHA, and remote access failed. if (reporter != null) - reporter.error("Download of remote resource %s failed and cache file %s unavailable/invalid. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); - throw new IOException(String.format("Download of remote resource %s failed and cache file %s unavailable/invalid, see log for details.", url, cachedFile)); + reporter.error("Downloading %s failed (%s) and cache file %s is not available or doesn't match the expected checksum. Trace: %s", url, e, cachedFile, collectStackTrace(e)); + throw new IOException(String.format("Downloading %s failed and cache file %s is not available or doesn't match the expected checksum, see log for details.", url, cachedFile)); } } } private String copyWithSHA(InputStream input, FileOutputStream output) throws IOException { MessageDigest digest; try { digest = MessageDigest.getInstance(SHA_256); DigestOutputStream digestOutput = new DigestOutputStream(output, digest); IO.copy(input, digestOutput); return Hex.toHexString(digest.digest()); } catch (NoSuchAlgorithmException e) { // Can't happen... hopefully... throw new IOException(e.getMessage()); } finally { IO.close(input); IO.close(output); } } private void ensureCacheDirExists() throws IOException { if (cacheDir.isDirectory()) return; if (cacheDir.exists()) { String message = String.format("Cannot create cache directory in path %s: the path exists but is not a directory", cacheDir.getCanonicalPath()); if (reporter != null) reporter.error(message); throw new IOException(message); } if (!cacheDir.mkdirs()) { String message = String.format("Failed to create cache directory in path %s", cacheDir.getCanonicalPath()); if (reporter != null) reporter.error(message); throw new IOException(message); } } private static String collectStackTrace(Throwable t) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); PrintStream pps = new PrintStream(buffer, false, "UTF-8"); t.printStackTrace(pps); return buffer.toString("UTF-8"); } catch (UnsupportedEncodingException e) { return null; } } String getCachedSHA() throws IOException { String content = readSHAFile(); if (content == null) { content = calculateSHA(cachedFile); saveSHAFile(content); } return content; } static String calculateSHA(File file) throws IOException { MessageDigest digest; byte[] buf = new byte[1024]; InputStream stream = null; try { digest = MessageDigest.getInstance(SHA_256); stream = new FileInputStream(file); while (true) { int bytesRead = stream.read(buf, 0, 1024); if (bytesRead < 0) break; digest.update(buf, 0, bytesRead); } } catch (NoSuchAlgorithmException e) { // Can't happen... hopefully... throw new IOException(e.getMessage()); } finally { if (stream != null) stream.close(); } return Hex.toHexString(digest.digest()); } String readSHAFile() throws IOException { String result; if (shaFile != null && shaFile.isFile()) result = IO.collect(shaFile); else result = null; return result; } void saveSHAFile(String contents) { try { IO.copy(IO.stream(contents), shaFile); } catch (IOException e) { shaFile.delete(); // Errors saving the SHA should not interfere with the download if (reporter != null) reporter.error("Failed to save SHA file %s (%s)", shaFile, e.getMessage()); } } }
false
true
public File request() throws IOException { if (localFile != null) return localFile; if (cachedFile == null) throw new IllegalStateException("Invalid URLResourceHandle: both local file and cache file location are uninitialised."); // Check whether the cached copy exist and has the right SHA. boolean cacheExists = cachedFile.isFile(); boolean cacheValidated; if (cacheExists) { if (sha == null) cacheValidated = false; else { String cachedSHA = getCachedSHA(); cacheValidated = sha.equalsIgnoreCase(cachedSHA); } } else { cacheValidated = false; } if (cacheValidated) return cachedFile; try { InputStream data = connector.connect(url); // Save the data to the cache ensureCacheDirExists(); String serverSHA = copyWithSHA(data, new FileOutputStream(cachedFile)); // Check the SHA of the received data if (sha != null && !sha.equalsIgnoreCase(serverSHA)) { shaFile.delete(); cachedFile.delete(); throw new IOException(String.format("Invalid SHA on remote resource", url)); } saveSHAFile(serverSHA); return cachedFile; } catch (IOException e) { if (sha == null) { // Remote access failed, use the cache if it exists AND if the original SHA was not known. if (cacheExists) { if (reporter != null) reporter.warning("Download of remote resource %s failed, using local cache %s. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); return cachedFile; } else { if (reporter != null) reporter.error("Download of remote resource %s failed and cache file %s not available. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); throw new IOException(String.format("Download of remote resource %s failed and cache file %s not available, see log for details.", url, cachedFile)); } } else { // Can only get here if the cache was missing or didn't match the SHA, and remote access failed. if (reporter != null) reporter.error("Download of remote resource %s failed and cache file %s unavailable/invalid. Original exception: %s. Trace: %s", url, cachedFile, e, collectStackTrace(e)); throw new IOException(String.format("Download of remote resource %s failed and cache file %s unavailable/invalid, see log for details.", url, cachedFile)); } } }
public File request() throws IOException { if (localFile != null) return localFile; if (cachedFile == null) throw new IllegalStateException("Invalid URLResourceHandle: both local file and cache file location are uninitialised."); // Check whether the cached copy exist and has the right SHA. boolean cacheExists = cachedFile.isFile(); boolean cacheValidated; if (cacheExists) { if (sha == null) cacheValidated = false; else { String cachedSHA = getCachedSHA(); cacheValidated = sha.equalsIgnoreCase(cachedSHA); } } else { cacheValidated = false; } if (cacheValidated) return cachedFile; try { InputStream data = connector.connect(url); // Save the data to the cache ensureCacheDirExists(); String serverSHA = copyWithSHA(data, new FileOutputStream(cachedFile)); // Check the SHA of the received data if (sha != null && !sha.equalsIgnoreCase(serverSHA)) { shaFile.delete(); cachedFile.delete(); throw new IOException(String.format("Invalid SHA on remote resource", url)); } saveSHAFile(serverSHA); return cachedFile; } catch (IOException e) { if (sha == null) { // Remote access failed, use the cache if it exists AND if the original SHA was not known. if (cacheExists) { if (reporter != null) reporter.warning("Using local cache; downloading %s failed (%s).", url, e); return cachedFile; } else { if (reporter != null) reporter.error("Downloading %s failed (%s) and cache file %s is not available. Trace: %s", url, e, cachedFile, collectStackTrace(e)); throw new IOException(String.format("Downloading %s failed and cache file %s is not available, see log for details.", url, cachedFile)); } } else { // Can only get here if the cache was missing or didn't match the SHA, and remote access failed. if (reporter != null) reporter.error("Downloading %s failed (%s) and cache file %s is not available or doesn't match the expected checksum. Trace: %s", url, e, cachedFile, collectStackTrace(e)); throw new IOException(String.format("Downloading %s failed and cache file %s is not available or doesn't match the expected checksum, see log for details.", url, cachedFile)); } } }
diff --git a/src/cc/hughes/droidchatty/PostFormatter.java b/src/cc/hughes/droidchatty/PostFormatter.java index 65df2b7..57f5b65 100644 --- a/src/cc/hughes/droidchatty/PostFormatter.java +++ b/src/cc/hughes/droidchatty/PostFormatter.java @@ -1,46 +1,46 @@ package cc.hughes.droidchatty; import android.text.Html; import android.text.Spanned; public class PostFormatter { public static Spanned formatContent(Post post, boolean multiLine) { return formatContent(post.getUserName(), post.getContent(), multiLine); } public static Spanned formatContent(Thread thread, boolean multiLine) { return formatContent(thread.getUserName(), thread.getContent(), multiLine); } public static Spanned formatContent(String userName, String content, boolean multiLine) { // special case fix for shacknews links if (userName.equalsIgnoreCase("shacknews")) content = content.replaceAll("&lt;(/?)a(.*?)&gt;", "<$1a$2>"); // convert shack's css into real font colors since Html.fromHtml doesn't supporty css of any kind content = content.replaceAll("<span class=\"jt_red\">(.*?)</span>", "<font color=\"#ff0000\">$1</font>"); content = content.replaceAll("<span class=\"jt_green\">(.*?)</span>", "<font color=\"#8dc63f\">$1</font>"); content = content.replaceAll("<span class=\"jt_pink\">(.*?)</span>", "<font color=\"#f49ac1\">$1</font>"); content = content.replaceAll("<span class=\"jt_olive\">(.*?)</span>", "<font color=\"#808000\">$1</font>"); content = content.replaceAll("<span class=\"jt_fuchsia\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_yellow\">(.*?)</span>", "<font color=\"#ffde00\">$1</font>"); content = content.replaceAll("<span class=\"jt_blue\">(.*?)</span>", "<font color=\"#44aedf\">$1</font>"); content = content.replaceAll("<span class=\"jt_lime\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_orange\">(.*?)</span>", "<font color=\"#f7941c\">$1</font>"); content = content.replaceAll("<span class=\"jt_bold\">(.*?)</span>", "<b>$1</b>"); content = content.replaceAll("<span class=\"jt_italic\">(.*?)</span>", "<i>$1</i>"); content = content.replaceAll("<span class=\"jt_underline\">(.*?)</span>", "<u>$1</u>"); - content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>1</del>"); + content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>$1</del>"); // if this is for a preview, change newlines into spaces if (!multiLine) content = content.replaceAll("<br />", " "); return Html.fromHtml(content); } }
true
true
public static Spanned formatContent(String userName, String content, boolean multiLine) { // special case fix for shacknews links if (userName.equalsIgnoreCase("shacknews")) content = content.replaceAll("&lt;(/?)a(.*?)&gt;", "<$1a$2>"); // convert shack's css into real font colors since Html.fromHtml doesn't supporty css of any kind content = content.replaceAll("<span class=\"jt_red\">(.*?)</span>", "<font color=\"#ff0000\">$1</font>"); content = content.replaceAll("<span class=\"jt_green\">(.*?)</span>", "<font color=\"#8dc63f\">$1</font>"); content = content.replaceAll("<span class=\"jt_pink\">(.*?)</span>", "<font color=\"#f49ac1\">$1</font>"); content = content.replaceAll("<span class=\"jt_olive\">(.*?)</span>", "<font color=\"#808000\">$1</font>"); content = content.replaceAll("<span class=\"jt_fuchsia\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_yellow\">(.*?)</span>", "<font color=\"#ffde00\">$1</font>"); content = content.replaceAll("<span class=\"jt_blue\">(.*?)</span>", "<font color=\"#44aedf\">$1</font>"); content = content.replaceAll("<span class=\"jt_lime\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_orange\">(.*?)</span>", "<font color=\"#f7941c\">$1</font>"); content = content.replaceAll("<span class=\"jt_bold\">(.*?)</span>", "<b>$1</b>"); content = content.replaceAll("<span class=\"jt_italic\">(.*?)</span>", "<i>$1</i>"); content = content.replaceAll("<span class=\"jt_underline\">(.*?)</span>", "<u>$1</u>"); content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>1</del>"); // if this is for a preview, change newlines into spaces if (!multiLine) content = content.replaceAll("<br />", " "); return Html.fromHtml(content); }
public static Spanned formatContent(String userName, String content, boolean multiLine) { // special case fix for shacknews links if (userName.equalsIgnoreCase("shacknews")) content = content.replaceAll("&lt;(/?)a(.*?)&gt;", "<$1a$2>"); // convert shack's css into real font colors since Html.fromHtml doesn't supporty css of any kind content = content.replaceAll("<span class=\"jt_red\">(.*?)</span>", "<font color=\"#ff0000\">$1</font>"); content = content.replaceAll("<span class=\"jt_green\">(.*?)</span>", "<font color=\"#8dc63f\">$1</font>"); content = content.replaceAll("<span class=\"jt_pink\">(.*?)</span>", "<font color=\"#f49ac1\">$1</font>"); content = content.replaceAll("<span class=\"jt_olive\">(.*?)</span>", "<font color=\"#808000\">$1</font>"); content = content.replaceAll("<span class=\"jt_fuchsia\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_yellow\">(.*?)</span>", "<font color=\"#ffde00\">$1</font>"); content = content.replaceAll("<span class=\"jt_blue\">(.*?)</span>", "<font color=\"#44aedf\">$1</font>"); content = content.replaceAll("<span class=\"jt_lime\">(.*?)</span>", "<font color=\"#c0ffc0\">$1</font>"); content = content.replaceAll("<span class=\"jt_orange\">(.*?)</span>", "<font color=\"#f7941c\">$1</font>"); content = content.replaceAll("<span class=\"jt_bold\">(.*?)</span>", "<b>$1</b>"); content = content.replaceAll("<span class=\"jt_italic\">(.*?)</span>", "<i>$1</i>"); content = content.replaceAll("<span class=\"jt_underline\">(.*?)</span>", "<u>$1</u>"); content = content.replaceAll("<span class=\"jt_strike\">(.*?)</span>", "<del>$1</del>"); // if this is for a preview, change newlines into spaces if (!multiLine) content = content.replaceAll("<br />", " "); return Html.fromHtml(content); }
diff --git a/core/src/com/google/zxing/qrcode/QRCodeReader.java b/core/src/com/google/zxing/qrcode/QRCodeReader.java index 33c50b8a..2a12c6dd 100644 --- a/core/src/com/google/zxing/qrcode/QRCodeReader.java +++ b/core/src/com/google/zxing/qrcode/QRCodeReader.java @@ -1,165 +1,166 @@ /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.ChecksumException; import com.google.zxing.DecodeHintType; import com.google.zxing.FormatException; import com.google.zxing.NotFoundException; import com.google.zxing.Reader; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.ResultPoint; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.DecoderResult; import com.google.zxing.common.DetectorResult; import com.google.zxing.qrcode.decoder.Decoder; import com.google.zxing.qrcode.detector.Detector; import java.util.Hashtable; /** * This implementation can detect and decode QR Codes in an image. * * @author Sean Owen */ public class QRCodeReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private final Decoder decoder = new Decoder(); protected Decoder getDecoder() { return decoder; } /** * Locates and decodes a QR code in an image. * * @return a String representing the content encoded by the QR code * @throws NotFoundException if a QR code cannot be found * @throws FormatException if a QR code cannot be decoded * @throws ChecksumException if error correction fails */ public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } public Result decode(BinaryBitmap image, Hashtable hints) throws NotFoundException, ChecksumException, FormatException { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.getBlackMatrix()); decoderResult = decoder.decode(bits, hints); points = NO_POINTS; } else { DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(hints); decoderResult = decoder.decode(detectorResult.getBits(), hints); points = detectorResult.getPoints(); } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE); if (decoderResult.getByteSegments() != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, decoderResult.getByteSegments()); } if (decoderResult.getECLevel() != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, decoderResult.getECLevel().toString()); } return result; } public void reset() { // do nothing } /** * This method detects a barcode in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a barcode, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ public static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int height = image.getHeight(); int width = image.getWidth(); int minDimension = Math.min(height, width); // And then keep tracking across the top-left black module to determine module size //int moduleEnd = borderWidth; int[] leftTopBlack = image.getTopLeftOnBit(); if (leftTopBlack == null) { throw NotFoundException.getNotFoundInstance(); } int x = leftTopBlack[0]; int y = leftTopBlack[1]; while (x < minDimension && y < minDimension && image.get(x, y)) { x++; y++; } if (x == minDimension || y == minDimension) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = x - leftTopBlack[0]; if (moduleSize == 0) { throw NotFoundException.getNotFoundInstance(); } // And now find where the rightmost black module on the first row ends int rowEndOfSymbol = width - 1; while (rowEndOfSymbol > x && !image.get(rowEndOfSymbol, y)) { rowEndOfSymbol--; } if (rowEndOfSymbol <= x) { throw NotFoundException.getNotFoundInstance(); } rowEndOfSymbol++; // Make sure width of barcode is a multiple of module size if ((rowEndOfSymbol - x) % moduleSize != 0) { throw NotFoundException.getNotFoundInstance(); } int dimension = 1 + ((rowEndOfSymbol - x) / moduleSize); // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a - // little off, this will help recover. - x -= moduleSize >> 1; - y -= moduleSize >> 1; + // little off, this will help recover. Need to back up at least 1. + int backOffAmount = moduleSize == 1 ? 1 : moduleSize >> 1; + x -= backOffAmount; + y -= backOffAmount; if ((x + (dimension - 1) * moduleSize) >= width || (y + (dimension - 1) * moduleSize) >= height) { throw NotFoundException.getNotFoundInstance(); } // Now just read off the bits BitMatrix bits = new BitMatrix(dimension); for (int i = 0; i < dimension; i++) { int iOffset = y + i * moduleSize; for (int j = 0; j < dimension; j++) { if (image.get(x + j * moduleSize, iOffset)) { bits.set(j, i); } } } return bits; } }
true
true
public static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int height = image.getHeight(); int width = image.getWidth(); int minDimension = Math.min(height, width); // And then keep tracking across the top-left black module to determine module size //int moduleEnd = borderWidth; int[] leftTopBlack = image.getTopLeftOnBit(); if (leftTopBlack == null) { throw NotFoundException.getNotFoundInstance(); } int x = leftTopBlack[0]; int y = leftTopBlack[1]; while (x < minDimension && y < minDimension && image.get(x, y)) { x++; y++; } if (x == minDimension || y == minDimension) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = x - leftTopBlack[0]; if (moduleSize == 0) { throw NotFoundException.getNotFoundInstance(); } // And now find where the rightmost black module on the first row ends int rowEndOfSymbol = width - 1; while (rowEndOfSymbol > x && !image.get(rowEndOfSymbol, y)) { rowEndOfSymbol--; } if (rowEndOfSymbol <= x) { throw NotFoundException.getNotFoundInstance(); } rowEndOfSymbol++; // Make sure width of barcode is a multiple of module size if ((rowEndOfSymbol - x) % moduleSize != 0) { throw NotFoundException.getNotFoundInstance(); } int dimension = 1 + ((rowEndOfSymbol - x) / moduleSize); // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. x -= moduleSize >> 1; y -= moduleSize >> 1; if ((x + (dimension - 1) * moduleSize) >= width || (y + (dimension - 1) * moduleSize) >= height) { throw NotFoundException.getNotFoundInstance(); } // Now just read off the bits BitMatrix bits = new BitMatrix(dimension); for (int i = 0; i < dimension; i++) { int iOffset = y + i * moduleSize; for (int j = 0; j < dimension; j++) { if (image.get(x + j * moduleSize, iOffset)) { bits.set(j, i); } } } return bits; }
public static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException { int height = image.getHeight(); int width = image.getWidth(); int minDimension = Math.min(height, width); // And then keep tracking across the top-left black module to determine module size //int moduleEnd = borderWidth; int[] leftTopBlack = image.getTopLeftOnBit(); if (leftTopBlack == null) { throw NotFoundException.getNotFoundInstance(); } int x = leftTopBlack[0]; int y = leftTopBlack[1]; while (x < minDimension && y < minDimension && image.get(x, y)) { x++; y++; } if (x == minDimension || y == minDimension) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = x - leftTopBlack[0]; if (moduleSize == 0) { throw NotFoundException.getNotFoundInstance(); } // And now find where the rightmost black module on the first row ends int rowEndOfSymbol = width - 1; while (rowEndOfSymbol > x && !image.get(rowEndOfSymbol, y)) { rowEndOfSymbol--; } if (rowEndOfSymbol <= x) { throw NotFoundException.getNotFoundInstance(); } rowEndOfSymbol++; // Make sure width of barcode is a multiple of module size if ((rowEndOfSymbol - x) % moduleSize != 0) { throw NotFoundException.getNotFoundInstance(); } int dimension = 1 + ((rowEndOfSymbol - x) / moduleSize); // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. Need to back up at least 1. int backOffAmount = moduleSize == 1 ? 1 : moduleSize >> 1; x -= backOffAmount; y -= backOffAmount; if ((x + (dimension - 1) * moduleSize) >= width || (y + (dimension - 1) * moduleSize) >= height) { throw NotFoundException.getNotFoundInstance(); } // Now just read off the bits BitMatrix bits = new BitMatrix(dimension); for (int i = 0; i < dimension; i++) { int iOffset = y + i * moduleSize; for (int j = 0; j < dimension; j++) { if (image.get(x + j * moduleSize, iOffset)) { bits.set(j, i); } } } return bits; }
diff --git a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/configuration/VariationIterator.java b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/configuration/VariationIterator.java index d3e741a..c481b98 100644 --- a/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/configuration/VariationIterator.java +++ b/simbeeotic-core/src/main/java/harvard/robobees/simbeeotic/configuration/VariationIterator.java @@ -1,292 +1,292 @@ package harvard.robobees.simbeeotic.configuration; import harvard.robobees.simbeeotic.configuration.scenario.Scenario; import harvard.robobees.simbeeotic.configuration.scenario.Variable; import harvard.robobees.simbeeotic.configuration.scenario.Variables; import harvard.robobees.simbeeotic.configuration.variable.AbstractLoopingVariable; import harvard.robobees.simbeeotic.configuration.variable.LoopingVariableFactory; import harvard.robobees.simbeeotic.configuration.variable.RandomVariable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; /** * @author bkate */ public class VariationIterator implements Iterator<Variation>, Iterable<Variation> { // the number of repetitions that this controller should perform private int numRepetitions = 1; // looping controls private int curRepetition = 0; // the list of variable maps (one per execution) private List<Variation> variableMaps = new ArrayList<Variation>(); private Iterator<Variation> backingIter; public VariationIterator(Scenario rawScenario) { List<AbstractLoopingVariable> variables = null; LoopingVariableFactory varFact = new LoopingVariableFactory(); AbstractLoopingVariable masterSeed = varFact.newMasterSeedVariable(rawScenario.getMasterSeed()); Variables loopingVars = rawScenario.getLooping().getVariables(); if (loopingVars != null) { variables = new ArrayList<AbstractLoopingVariable>(); for (Variable varDef : loopingVars.getVariable()) { variables.add(varFact.newVariable(varDef)); } } else { variables = new ArrayList<AbstractLoopingVariable>(); } // start parsing the looping variables List<AbstractLoopingVariable> ordered = new ArrayList<AbstractLoopingVariable>(); List<AbstractLoopingVariable> deps = new ArrayList<AbstractLoopingVariable>(); Set<String> names = new HashSet<String>(); // bin the variables into those with and without dependencies for (AbstractLoopingVariable var : variables) { if (names.contains(var.getName())) { throw new InvalidScenarioException("Two looping variables have the same name: " + var.getName() + "."); } if (var.getDependencies().isEmpty()) { ordered.add(var); } else { deps.add(var); } names.add(var.getName()); } // create an ordered list of variables - in order of execution that can ensure dependency resolution. // this algorithm goes through each variable that has a dependency and tries to insert it into the BACK // of the ordered list of variables. if the enabling variables are present, it is inserted, otherwise // it is skipped until the next iteration. if no variables are inserted on an iteration but the list of // variables is not exhausted, then the variables remaining cannot be inserted because of a missing dependency // or a cyclical relationship. as long as the variables are inserted into the back of the list, and the // variables are executed in list order, all dependencies will be resolved properly. while(deps.size() > 0) { List<AbstractLoopingVariable> inserted = new ArrayList<AbstractLoopingVariable>(); for (AbstractLoopingVariable var : deps) { // determine if the variable can be inserted into the tree yet (if all its parents are present) boolean canInsert = true; // look if each dependency can be satisfied for (String dependency : var.getDependencies()) { boolean found = false; for (AbstractLoopingVariable enabler : ordered) { if (enabler.getName().equals(dependency)) { found = true; break; } } // did not find a required dependency in the ordered list if (!found) { canInsert = false; break; } } // all dependencies satisfied, insert it into the ordered list and add it to the list of inserted vars if (canInsert) { ordered.add(var); inserted.add(var); } } if (inserted.size() > 0) { // something was inserted on this iteration, remove it from consideration next time for (AbstractLoopingVariable var : inserted) { deps.remove(var); } } else { // nothing was inserted from the list, so dependencies are unresolvable throw new InvalidScenarioException("Cannot resolve variable dependency. Either a dependency does " + "not exist, or there is a cycle in the variable dependency graph."); } } // outer loop is for the master seeds for (String currMasterSeed : masterSeed.getValues()) { - long seed = Long.valueOf(currMasterSeed); + long seed = (long)Math.floor(Double.valueOf(currMasterSeed)); Random rand = new Random(seed); List<Variation> finishedMaps = new LinkedList<Variation>(); // set the seeds for all externally seeded random variables by // drawing from a master stream derived from the current master seed. for (AbstractLoopingVariable var : variables) { if (var instanceof RandomVariable) { RandomVariable rVar = (RandomVariable)var; if (rVar.isExternallySeeded()) { rVar.setSeed("" + rand.nextLong()); } } } // parametrically combine the variables to define a list of variable maps for (AbstractLoopingVariable var : ordered) { // special case of the first variable if (finishedMaps.isEmpty()) { // Make a map for each value of this variable List<String> values = var.getValues(); for(String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(); nextVariableMap.put(var.getName(), value); finishedMaps.add(new VariationImpl(seed, nextVariableMap)); } continue; } List<Variation> newMaps = new ArrayList<Variation>(); // go through each existing map and add the value from this variable to it for (Variation existing : finishedMaps) { Set<String> varDeps = var.getDependencies(); // set the values of the dependencies of this variable from the values in the current existing map for(String depName : varDeps) { var.setDependencyValue(depName, existing.getVariables().get(depName)); } // Get the values of this variable and make a variation of the existing map for each one List<String> values = var.getValues(); if (values.size() == 1) { // special case to avoid copying the map existing.getVariables().put(var.getName(), values.get(0)); newMaps.add(existing); } else { // make a copy of the existing map for each value for (String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(existing.getVariables()); nextVariableMap.put(var.getName(), value); newMaps.add(new VariationImpl(seed, nextVariableMap)); } } } finishedMaps = newMaps; } // no variable maps defined, make an empty for the default context if (finishedMaps.isEmpty()) { finishedMaps.add(new VariationImpl(seed, new HashMap<String, String>())); } variableMaps.addAll(finishedMaps); } backingIter = variableMaps.iterator(); } public int size() { return variableMaps.size() * numRepetitions; } /** {@inheritDoc} */ public synchronized boolean hasNext() { return (backingIter.hasNext() || (curRepetition < numRepetitions )); } /** {@inheritDoc} */ public Variation next() { if (!backingIter.hasNext() && hasNext()) { backingIter = variableMaps.iterator(); // reset position } Variation ret = backingIter.next(); if (!backingIter.hasNext()) { this.curRepetition++; } return ret; } /** {@inheritDoc} */ public void remove() { throw new UnsupportedOperationException("Can not remove scenario variations from the Iterator"); } /** * This class is also iterable so it can easily be used from enhanced for loops */ public Iterator<Variation> iterator() { return this; } private static final class VariationImpl implements Variation { private long seed; private Map<String, String> variables; private VariationImpl(long seed, Map<String, String> variables) { this.seed = seed; this.variables = variables; } public long getSeed() { return seed; } public Map<String, String> getVariables() { return variables; } } }
true
true
public VariationIterator(Scenario rawScenario) { List<AbstractLoopingVariable> variables = null; LoopingVariableFactory varFact = new LoopingVariableFactory(); AbstractLoopingVariable masterSeed = varFact.newMasterSeedVariable(rawScenario.getMasterSeed()); Variables loopingVars = rawScenario.getLooping().getVariables(); if (loopingVars != null) { variables = new ArrayList<AbstractLoopingVariable>(); for (Variable varDef : loopingVars.getVariable()) { variables.add(varFact.newVariable(varDef)); } } else { variables = new ArrayList<AbstractLoopingVariable>(); } // start parsing the looping variables List<AbstractLoopingVariable> ordered = new ArrayList<AbstractLoopingVariable>(); List<AbstractLoopingVariable> deps = new ArrayList<AbstractLoopingVariable>(); Set<String> names = new HashSet<String>(); // bin the variables into those with and without dependencies for (AbstractLoopingVariable var : variables) { if (names.contains(var.getName())) { throw new InvalidScenarioException("Two looping variables have the same name: " + var.getName() + "."); } if (var.getDependencies().isEmpty()) { ordered.add(var); } else { deps.add(var); } names.add(var.getName()); } // create an ordered list of variables - in order of execution that can ensure dependency resolution. // this algorithm goes through each variable that has a dependency and tries to insert it into the BACK // of the ordered list of variables. if the enabling variables are present, it is inserted, otherwise // it is skipped until the next iteration. if no variables are inserted on an iteration but the list of // variables is not exhausted, then the variables remaining cannot be inserted because of a missing dependency // or a cyclical relationship. as long as the variables are inserted into the back of the list, and the // variables are executed in list order, all dependencies will be resolved properly. while(deps.size() > 0) { List<AbstractLoopingVariable> inserted = new ArrayList<AbstractLoopingVariable>(); for (AbstractLoopingVariable var : deps) { // determine if the variable can be inserted into the tree yet (if all its parents are present) boolean canInsert = true; // look if each dependency can be satisfied for (String dependency : var.getDependencies()) { boolean found = false; for (AbstractLoopingVariable enabler : ordered) { if (enabler.getName().equals(dependency)) { found = true; break; } } // did not find a required dependency in the ordered list if (!found) { canInsert = false; break; } } // all dependencies satisfied, insert it into the ordered list and add it to the list of inserted vars if (canInsert) { ordered.add(var); inserted.add(var); } } if (inserted.size() > 0) { // something was inserted on this iteration, remove it from consideration next time for (AbstractLoopingVariable var : inserted) { deps.remove(var); } } else { // nothing was inserted from the list, so dependencies are unresolvable throw new InvalidScenarioException("Cannot resolve variable dependency. Either a dependency does " + "not exist, or there is a cycle in the variable dependency graph."); } } // outer loop is for the master seeds for (String currMasterSeed : masterSeed.getValues()) { long seed = Long.valueOf(currMasterSeed); Random rand = new Random(seed); List<Variation> finishedMaps = new LinkedList<Variation>(); // set the seeds for all externally seeded random variables by // drawing from a master stream derived from the current master seed. for (AbstractLoopingVariable var : variables) { if (var instanceof RandomVariable) { RandomVariable rVar = (RandomVariable)var; if (rVar.isExternallySeeded()) { rVar.setSeed("" + rand.nextLong()); } } } // parametrically combine the variables to define a list of variable maps for (AbstractLoopingVariable var : ordered) { // special case of the first variable if (finishedMaps.isEmpty()) { // Make a map for each value of this variable List<String> values = var.getValues(); for(String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(); nextVariableMap.put(var.getName(), value); finishedMaps.add(new VariationImpl(seed, nextVariableMap)); } continue; } List<Variation> newMaps = new ArrayList<Variation>(); // go through each existing map and add the value from this variable to it for (Variation existing : finishedMaps) { Set<String> varDeps = var.getDependencies(); // set the values of the dependencies of this variable from the values in the current existing map for(String depName : varDeps) { var.setDependencyValue(depName, existing.getVariables().get(depName)); } // Get the values of this variable and make a variation of the existing map for each one List<String> values = var.getValues(); if (values.size() == 1) { // special case to avoid copying the map existing.getVariables().put(var.getName(), values.get(0)); newMaps.add(existing); } else { // make a copy of the existing map for each value for (String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(existing.getVariables()); nextVariableMap.put(var.getName(), value); newMaps.add(new VariationImpl(seed, nextVariableMap)); } } } finishedMaps = newMaps; } // no variable maps defined, make an empty for the default context if (finishedMaps.isEmpty()) { finishedMaps.add(new VariationImpl(seed, new HashMap<String, String>())); } variableMaps.addAll(finishedMaps); } backingIter = variableMaps.iterator(); }
public VariationIterator(Scenario rawScenario) { List<AbstractLoopingVariable> variables = null; LoopingVariableFactory varFact = new LoopingVariableFactory(); AbstractLoopingVariable masterSeed = varFact.newMasterSeedVariable(rawScenario.getMasterSeed()); Variables loopingVars = rawScenario.getLooping().getVariables(); if (loopingVars != null) { variables = new ArrayList<AbstractLoopingVariable>(); for (Variable varDef : loopingVars.getVariable()) { variables.add(varFact.newVariable(varDef)); } } else { variables = new ArrayList<AbstractLoopingVariable>(); } // start parsing the looping variables List<AbstractLoopingVariable> ordered = new ArrayList<AbstractLoopingVariable>(); List<AbstractLoopingVariable> deps = new ArrayList<AbstractLoopingVariable>(); Set<String> names = new HashSet<String>(); // bin the variables into those with and without dependencies for (AbstractLoopingVariable var : variables) { if (names.contains(var.getName())) { throw new InvalidScenarioException("Two looping variables have the same name: " + var.getName() + "."); } if (var.getDependencies().isEmpty()) { ordered.add(var); } else { deps.add(var); } names.add(var.getName()); } // create an ordered list of variables - in order of execution that can ensure dependency resolution. // this algorithm goes through each variable that has a dependency and tries to insert it into the BACK // of the ordered list of variables. if the enabling variables are present, it is inserted, otherwise // it is skipped until the next iteration. if no variables are inserted on an iteration but the list of // variables is not exhausted, then the variables remaining cannot be inserted because of a missing dependency // or a cyclical relationship. as long as the variables are inserted into the back of the list, and the // variables are executed in list order, all dependencies will be resolved properly. while(deps.size() > 0) { List<AbstractLoopingVariable> inserted = new ArrayList<AbstractLoopingVariable>(); for (AbstractLoopingVariable var : deps) { // determine if the variable can be inserted into the tree yet (if all its parents are present) boolean canInsert = true; // look if each dependency can be satisfied for (String dependency : var.getDependencies()) { boolean found = false; for (AbstractLoopingVariable enabler : ordered) { if (enabler.getName().equals(dependency)) { found = true; break; } } // did not find a required dependency in the ordered list if (!found) { canInsert = false; break; } } // all dependencies satisfied, insert it into the ordered list and add it to the list of inserted vars if (canInsert) { ordered.add(var); inserted.add(var); } } if (inserted.size() > 0) { // something was inserted on this iteration, remove it from consideration next time for (AbstractLoopingVariable var : inserted) { deps.remove(var); } } else { // nothing was inserted from the list, so dependencies are unresolvable throw new InvalidScenarioException("Cannot resolve variable dependency. Either a dependency does " + "not exist, or there is a cycle in the variable dependency graph."); } } // outer loop is for the master seeds for (String currMasterSeed : masterSeed.getValues()) { long seed = (long)Math.floor(Double.valueOf(currMasterSeed)); Random rand = new Random(seed); List<Variation> finishedMaps = new LinkedList<Variation>(); // set the seeds for all externally seeded random variables by // drawing from a master stream derived from the current master seed. for (AbstractLoopingVariable var : variables) { if (var instanceof RandomVariable) { RandomVariable rVar = (RandomVariable)var; if (rVar.isExternallySeeded()) { rVar.setSeed("" + rand.nextLong()); } } } // parametrically combine the variables to define a list of variable maps for (AbstractLoopingVariable var : ordered) { // special case of the first variable if (finishedMaps.isEmpty()) { // Make a map for each value of this variable List<String> values = var.getValues(); for(String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(); nextVariableMap.put(var.getName(), value); finishedMaps.add(new VariationImpl(seed, nextVariableMap)); } continue; } List<Variation> newMaps = new ArrayList<Variation>(); // go through each existing map and add the value from this variable to it for (Variation existing : finishedMaps) { Set<String> varDeps = var.getDependencies(); // set the values of the dependencies of this variable from the values in the current existing map for(String depName : varDeps) { var.setDependencyValue(depName, existing.getVariables().get(depName)); } // Get the values of this variable and make a variation of the existing map for each one List<String> values = var.getValues(); if (values.size() == 1) { // special case to avoid copying the map existing.getVariables().put(var.getName(), values.get(0)); newMaps.add(existing); } else { // make a copy of the existing map for each value for (String value : values) { Map<String, String> nextVariableMap = new HashMap<String, String>(existing.getVariables()); nextVariableMap.put(var.getName(), value); newMaps.add(new VariationImpl(seed, nextVariableMap)); } } } finishedMaps = newMaps; } // no variable maps defined, make an empty for the default context if (finishedMaps.isEmpty()) { finishedMaps.add(new VariationImpl(seed, new HashMap<String, String>())); } variableMaps.addAll(finishedMaps); } backingIter = variableMaps.iterator(); }
diff --git a/src/mkpc/fligthcontrol/MKCameraControlWindow.java b/src/mkpc/fligthcontrol/MKCameraControlWindow.java index 8368cc7..37f86c2 100644 --- a/src/mkpc/fligthcontrol/MKCameraControlWindow.java +++ b/src/mkpc/fligthcontrol/MKCameraControlWindow.java @@ -1,182 +1,183 @@ package mkpc.fligthcontrol; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import mkpc.log.LogSystem; import mkpc.webcam.WebcamView; import org.jdesktop.application.Application; /*** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class MKCameraControlWindow extends javax.swing.JFrame { /** * */ private static final long serialVersionUID = 1L; private JButton btn_makePhoto; private JLabel lbl_webcamBackground; private JSlider nickCameraSlider; private JSlider rollCameraSlider; /** * Auto-generated main method to display this JFrame */ public MKCameraControlWindow() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addKeyEventDispatcher(new MKKeyDispatcher()); { btn_makePhoto = new JButton(); getContentPane().add(btn_makePhoto); btn_makePhoto.setBounds(35, 30, 128, 28); btn_makePhoto.setName("btn_makePhoto"); btn_makePhoto.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_makePhotoActionPerformed(evt); } }); } { rollCameraSlider = new JSlider(); getContentPane().add(rollCameraSlider); rollCameraSlider.setBounds(35, 309, 320, 16); + rollCameraSlider.setName("rollCameraSlider"); rollCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { rollCameraSliderStateChanged(evt); } }); } { nickCameraSlider = new JSlider(); getContentPane().add(nickCameraSlider); nickCameraSlider.setBounds(12, 63, 11, 240); nickCameraSlider.setName("nickCameraSlider"); nickCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { nickCameraSliderStateChanged(evt); } }); } { lbl_webcamBackground = new JLabel(); getContentPane().add(lbl_webcamBackground); lbl_webcamBackground.setBounds(35, 63, 320, 240); lbl_webcamBackground.setName("lbl_webcamBackground"); lbl_webcamBackground.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { WebcamView webcamView = new WebcamView("vfw://0"); getContentPane().add(webcamView); webcamView.setBounds(35, 63, 320, 240); } pack(); this.setSize(442, 370); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } private void btn_makePhotoActionPerformed(ActionEvent evt) { LogSystem.CLog("btn_makePhoto.actionPerformed, event="+evt); } private void nickCameraSliderStateChanged(ChangeEvent evt) { LogSystem.CLog("nickCameraSlider.stateChanged, event="+evt); } private void rollCameraSliderStateChanged(ChangeEvent evt) { LogSystem.CLog("rollCameraSlider.stateChanged, event="+evt); } private class MKKeyDispatcher implements KeyEventDispatcher { @Override public boolean dispatchKeyEvent(KeyEvent e) { if(isActive() == true) { if (e.getID() == KeyEvent.KEY_PRESSED) { System.out.println("Keynumber: "+e.getKeyCode()); switch (e.getKeyCode()) { case 10: //Enter LogSystem.CLog("FOTO geschossen"); break; case 37: //arrow left rollCameraSlider.setValue(rollCameraSlider.getValue()-1); break; case 38: //arrow up nickCameraSlider.setValue(nickCameraSlider.getValue()+1); break; case 39: //arrow right rollCameraSlider.setValue(rollCameraSlider.getValue()+1); break; case 40: //arrow down nickCameraSlider.setValue(nickCameraSlider.getValue()-1); break; default: break; } } else if (e.getID() == KeyEvent.KEY_RELEASED) { System.out.println("2test2"); } else if (e.getID() == KeyEvent.KEY_TYPED) { System.out.println("3test3"); } } return false; } } }
true
true
private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addKeyEventDispatcher(new MKKeyDispatcher()); { btn_makePhoto = new JButton(); getContentPane().add(btn_makePhoto); btn_makePhoto.setBounds(35, 30, 128, 28); btn_makePhoto.setName("btn_makePhoto"); btn_makePhoto.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_makePhotoActionPerformed(evt); } }); } { rollCameraSlider = new JSlider(); getContentPane().add(rollCameraSlider); rollCameraSlider.setBounds(35, 309, 320, 16); rollCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { rollCameraSliderStateChanged(evt); } }); } { nickCameraSlider = new JSlider(); getContentPane().add(nickCameraSlider); nickCameraSlider.setBounds(12, 63, 11, 240); nickCameraSlider.setName("nickCameraSlider"); nickCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { nickCameraSliderStateChanged(evt); } }); } { lbl_webcamBackground = new JLabel(); getContentPane().add(lbl_webcamBackground); lbl_webcamBackground.setBounds(35, 63, 320, 240); lbl_webcamBackground.setName("lbl_webcamBackground"); lbl_webcamBackground.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { WebcamView webcamView = new WebcamView("vfw://0"); getContentPane().add(webcamView); webcamView.setBounds(35, 63, 320, 240); } pack(); this.setSize(442, 370); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } }
private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); manager.addKeyEventDispatcher(new MKKeyDispatcher()); { btn_makePhoto = new JButton(); getContentPane().add(btn_makePhoto); btn_makePhoto.setBounds(35, 30, 128, 28); btn_makePhoto.setName("btn_makePhoto"); btn_makePhoto.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btn_makePhotoActionPerformed(evt); } }); } { rollCameraSlider = new JSlider(); getContentPane().add(rollCameraSlider); rollCameraSlider.setBounds(35, 309, 320, 16); rollCameraSlider.setName("rollCameraSlider"); rollCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { rollCameraSliderStateChanged(evt); } }); } { nickCameraSlider = new JSlider(); getContentPane().add(nickCameraSlider); nickCameraSlider.setBounds(12, 63, 11, 240); nickCameraSlider.setName("nickCameraSlider"); nickCameraSlider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { nickCameraSliderStateChanged(evt); } }); } { lbl_webcamBackground = new JLabel(); getContentPane().add(lbl_webcamBackground); lbl_webcamBackground.setBounds(35, 63, 320, 240); lbl_webcamBackground.setName("lbl_webcamBackground"); lbl_webcamBackground.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { WebcamView webcamView = new WebcamView("vfw://0"); getContentPane().add(webcamView); webcamView.setBounds(35, 63, 320, 240); } pack(); this.setSize(442, 370); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } }
diff --git a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java index e266876e3..c59cca072 100755 --- a/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java +++ b/activemq-core/src/main/java/org/apache/activemq/store/jdbc/adapter/BlobJDBCAdapter.java @@ -1,138 +1,139 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.store.jdbc.adapter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.jms.JMSException; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.MessageId; import org.apache.activemq.store.jdbc.TransactionContext; import org.apache.activemq.util.ByteArrayOutputStream; /** * This JDBCAdapter inserts and extracts BLOB data using the getBlob()/setBlob() * operations. This is a little more involved since to insert a blob you have * to: * * 1: insert empty blob. 2: select the blob 3: finally update the blob with data * value. * * The databases/JDBC drivers that use this adapter are: * <ul> * <li></li> * </ul> * * @org.apache.xbean.XBean element="blobJDBCAdapter" * * */ public class BlobJDBCAdapter extends DefaultJDBCAdapter { @Override public void doAddMessage(TransactionContext c, long sequence, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration, byte priority) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { // Add the Blob record. s = c.getConnection().prepareStatement(statements.getAddMessageStatement()); s.setLong(1, sequence); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); s.setLong(6, priority); + s.setString(7, " "); if (s.executeUpdate() != 1) { throw new IOException("Failed to add broker message: " + messageID + " in container."); } s.close(); // Select the blob record so that we can update it. s = c.getConnection().prepareStatement(statements.getFindMessageByIdStatement()); s.setLong(1, sequence); rs = s.executeQuery(); if (!rs.next()) { throw new IOException("Failed select blob for message: " + messageID + " in container."); } // Update the blob Blob blob = rs.getBlob(1); OutputStream stream = blob.setBinaryStream(data.length); stream.write(data); stream.close(); s.close(); // Update the row with the updated blob s = c.getConnection().prepareStatement(statements.getUpdateMessageStatement()); s.setBlob(1, blob); s.setLong(2, sequence); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } } @Override public byte[] doGetMessage(TransactionContext c, MessageId id) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { s = c.getConnection().prepareStatement(statements.getFindMessageStatement()); s.setString(1, id.getProducerId().toString()); s.setLong(2, id.getProducerSequenceId()); rs = s.executeQuery(); if (!rs.next()) { return null; } Blob blob = rs.getBlob(1); InputStream is = blob.getBinaryStream(); ByteArrayOutputStream os = new ByteArrayOutputStream((int)blob.length()); int ch; while ((ch = is.read()) >= 0) { os.write(ch); } is.close(); os.close(); return os.toByteArray(); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } } }
true
true
public void doAddMessage(TransactionContext c, long sequence, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration, byte priority) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { // Add the Blob record. s = c.getConnection().prepareStatement(statements.getAddMessageStatement()); s.setLong(1, sequence); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); s.setLong(6, priority); if (s.executeUpdate() != 1) { throw new IOException("Failed to add broker message: " + messageID + " in container."); } s.close(); // Select the blob record so that we can update it. s = c.getConnection().prepareStatement(statements.getFindMessageByIdStatement()); s.setLong(1, sequence); rs = s.executeQuery(); if (!rs.next()) { throw new IOException("Failed select blob for message: " + messageID + " in container."); } // Update the blob Blob blob = rs.getBlob(1); OutputStream stream = blob.setBinaryStream(data.length); stream.write(data); stream.close(); s.close(); // Update the row with the updated blob s = c.getConnection().prepareStatement(statements.getUpdateMessageStatement()); s.setBlob(1, blob); s.setLong(2, sequence); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } }
public void doAddMessage(TransactionContext c, long sequence, MessageId messageID, ActiveMQDestination destination, byte[] data, long expiration, byte priority) throws SQLException, IOException { PreparedStatement s = null; ResultSet rs = null; cleanupExclusiveLock.readLock().lock(); try { // Add the Blob record. s = c.getConnection().prepareStatement(statements.getAddMessageStatement()); s.setLong(1, sequence); s.setString(2, messageID.getProducerId().toString()); s.setLong(3, messageID.getProducerSequenceId()); s.setString(4, destination.getQualifiedName()); s.setLong(5, expiration); s.setLong(6, priority); s.setString(7, " "); if (s.executeUpdate() != 1) { throw new IOException("Failed to add broker message: " + messageID + " in container."); } s.close(); // Select the blob record so that we can update it. s = c.getConnection().prepareStatement(statements.getFindMessageByIdStatement()); s.setLong(1, sequence); rs = s.executeQuery(); if (!rs.next()) { throw new IOException("Failed select blob for message: " + messageID + " in container."); } // Update the blob Blob blob = rs.getBlob(1); OutputStream stream = blob.setBinaryStream(data.length); stream.write(data); stream.close(); s.close(); // Update the row with the updated blob s = c.getConnection().prepareStatement(statements.getUpdateMessageStatement()); s.setBlob(1, blob); s.setLong(2, sequence); } finally { cleanupExclusiveLock.readLock().unlock(); close(rs); close(s); } }
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java index 24bf9833d..7ca9a210e 100644 --- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java +++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/HelloWorldFileAction.java @@ -1,142 +1,144 @@ package org.jboss.tools.esb.ui.bot.tests.examples; import org.jboss.tools.ui.bot.ext.SWTEclipseExt; import org.jboss.tools.ui.bot.ext.SWTOpenExt; import org.jboss.tools.ui.bot.ext.SWTTestExt; import org.jboss.tools.ui.bot.ext.Timing; import org.jboss.tools.ui.bot.ext.config.Annotations.Require; import org.jboss.tools.ui.bot.ext.config.Annotations.Server; import org.jboss.tools.ui.bot.ext.config.Annotations.ServerState; import org.jboss.tools.ui.bot.ext.config.Annotations.ServerType; import org.jboss.tools.ui.bot.ext.gen.ActionItem; import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.ESBESBFile; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotView; import org.eclipse.swtbot.swt.finder.SWTBot; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableItem; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem; import org.jboss.tools.ui.bot.ext.gen.ActionItem.NewObject.GeneralFolder; @Require(server=@Server(type=ServerType.SOA,state=ServerState.Running)) public class HelloWorldFileAction extends ESBExampleTest { public static String inputDir = "inputDir"; public static String outputDir = "outputDir"; public static String errorDir = "errorDir"; public static String projectName = "helloworld_file_action"; public static String clientProjectName = "helloworld_file_action_client"; public static String baseDir = null; @Override public String getExampleName() { return "JBoss ESB HelloWorld File Action Example - ESB"; } @Override public String[] getProjectNames() { return new String[] {"helloworld_file_action","helloworld_file_action_client"}; } @Override protected void executeExample() { /* Create the data directories needed by the quickstart */ bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(inputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(outputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(errorDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); /* We need to get the project base dir for the directory definitions in jboss-esb.xml */ SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select(); bot.menu("File").menu("Properties").click(); if (System.getProperty("file.separator").equals("/")) { baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); } else { /* Needed to avoid a syntax error with Windows \ dir path characters */ //baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator"); + baseDir = bot.textWithLabel("Location:").getText(); + System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ; baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz"); } // if (System.getProperty("file.separator").equals("/")) { // baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); // } // else { // baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator"); // } bot.button("OK").click(); theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml"); SWTBot theEditor = editor.bot(); theEditor.tree(0).expandNode("jboss-esb.xml", true); SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml"); SWTBotTreeItem providers = jbossesbxml.getNode("Providers"); SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1"); SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel"); SWTBotTreeItem filter = helloFileChannel.getNode("Filter"); filter.select(); theEditor.text("@INPUTDIR@").setText(baseDir + inputDir); theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir); theEditor.text("@ERRORDIR@").setText(baseDir + errorDir); editor.save(); bot.sleep(Timing.time30S()); //bot.sleep(30000l); /* Deploy the quickstart */ super.executeExample(); /* Now, edit the client code */ theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select(); theClientProject.expand(); //bot.sleep(30000l); editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); theEditor = editor.bot(); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); theEditor.styledText().insertText(10, 0, "//"); theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n"); theEditor.styledText().insertText(12, 0, "//"); theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n"); theEditor.styledText().insertText(14, 0, "//"); theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n"); theEditor.styledText().insertText(16, 0, "//"); theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); theEditor.styledText().insertText(23, 0, "//"); theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); //bot.sleep(30000l); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); editor.save(); //bot.sleep(30000l); String text = executeClientGetServerOutput(getExampleClientProjectName(),"src", "org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]")); assertNotNull("Calling JMS Send message failed, nothing appened to server log",text); assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World")); SWTTestExt.servers.removeAllProjectsFromServer(); } }
true
true
protected void executeExample() { /* Create the data directories needed by the quickstart */ bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(inputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(outputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(errorDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); /* We need to get the project base dir for the directory definitions in jboss-esb.xml */ SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select(); bot.menu("File").menu("Properties").click(); if (System.getProperty("file.separator").equals("/")) { baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); } else { /* Needed to avoid a syntax error with Windows \ dir path characters */ //baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator"); baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz"); } // if (System.getProperty("file.separator").equals("/")) { // baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); // } // else { // baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator"); // } bot.button("OK").click(); theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml"); SWTBot theEditor = editor.bot(); theEditor.tree(0).expandNode("jboss-esb.xml", true); SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml"); SWTBotTreeItem providers = jbossesbxml.getNode("Providers"); SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1"); SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel"); SWTBotTreeItem filter = helloFileChannel.getNode("Filter"); filter.select(); theEditor.text("@INPUTDIR@").setText(baseDir + inputDir); theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir); theEditor.text("@ERRORDIR@").setText(baseDir + errorDir); editor.save(); bot.sleep(Timing.time30S()); //bot.sleep(30000l); /* Deploy the quickstart */ super.executeExample(); /* Now, edit the client code */ theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select(); theClientProject.expand(); //bot.sleep(30000l); editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); theEditor = editor.bot(); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); theEditor.styledText().insertText(10, 0, "//"); theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n"); theEditor.styledText().insertText(12, 0, "//"); theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n"); theEditor.styledText().insertText(14, 0, "//"); theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n"); theEditor.styledText().insertText(16, 0, "//"); theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); theEditor.styledText().insertText(23, 0, "//"); theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); //bot.sleep(30000l); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); editor.save(); //bot.sleep(30000l); String text = executeClientGetServerOutput(getExampleClientProjectName(),"src", "org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]")); assertNotNull("Calling JMS Send message failed, nothing appened to server log",text); assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World")); SWTTestExt.servers.removeAllProjectsFromServer(); }
protected void executeExample() { /* Create the data directories needed by the quickstart */ bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(inputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(outputDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); bot.menu("File").menu("New").menu("Folder").click(); bot.tree(0).getTreeItem(projectName).select(); bot.text(1).setText(errorDir); bot.button("&Finish").click(); bot.sleep(Timing.time3S()); /* We need to get the project base dir for the directory definitions in jboss-esb.xml */ SWTBotView theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theProject = bot.tree(0).getTreeItem(projectName).select(); bot.menu("File").menu("Properties").click(); if (System.getProperty("file.separator").equals("/")) { baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); } else { /* Needed to avoid a syntax error with Windows \ dir path characters */ //baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), System.getProperty("file.separator") + System.getProperty("file.separator")) + System.getProperty("file.separator"); baseDir = bot.textWithLabel("Location:").getText(); System.out.println("DEBUG baseDir = " + bot.textWithLabel("Location:").getText()) ; baseDir = bot.textWithLabel("Location:").getText().replaceAll(System.getProperty("file.separator"), "zzz"); } // if (System.getProperty("file.separator").equals("/")) { // baseDir = bot.textWithLabel("Location:").getText() + System.getProperty("file.separator"); // } // else { // baseDir = bot.textWithLabel("Location:").getText().replaceAll("\\", "\\\\") + System.getProperty("file.separator"); // } bot.button("OK").click(); theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotEditor editor = projectExplorer.openFile(projectName, "esbcontent","META-INF","jboss-esb.xml"); SWTBot theEditor = editor.bot(); theEditor.tree(0).expandNode("jboss-esb.xml", true); SWTBotTreeItem jbossesbxml = theEditor.tree(0).getTreeItem("jboss-esb.xml"); SWTBotTreeItem providers = jbossesbxml.getNode("Providers"); SWTBotTreeItem FSProvider1 = providers.getNode("FSprovider1"); SWTBotTreeItem helloFileChannel = FSProvider1.getNode("helloFileChannel"); SWTBotTreeItem filter = helloFileChannel.getNode("Filter"); filter.select(); theEditor.text("@INPUTDIR@").setText(baseDir + inputDir); theEditor.text("@OUTPUTDIR@").setText(baseDir + outputDir); theEditor.text("@ERRORDIR@").setText(baseDir + errorDir); editor.save(); bot.sleep(Timing.time30S()); //bot.sleep(30000l); /* Deploy the quickstart */ super.executeExample(); /* Now, edit the client code */ theSWTBotView = open.viewOpen(ActionItem.View.GeneralNavigator.LABEL); SWTBotTreeItem theClientProject = bot.tree(0).getTreeItem(clientProjectName).select(); theClientProject.expand(); //bot.sleep(30000l); editor = projectExplorer.openFile(clientProjectName, "src","org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); theEditor = editor.bot(); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); theEditor.styledText().insertText(10, 0, "//"); theEditor.styledText().insertText(11, 0, "\t\tString inputDirectory = \"" + baseDir + "\" + System.getProperty(\"file.separator\") + \"inputDir\";\n"); theEditor.styledText().insertText(12, 0, "//"); theEditor.styledText().insertText(13, 0, "\t\tString fileName = \"MyInput.dat" + "\";\n"); theEditor.styledText().insertText(14, 0, "//"); theEditor.styledText().insertText(15, 0, "\t\tString fileContents = \"Hello World In A File\";\n"); theEditor.styledText().insertText(16, 0, "//"); theEditor.styledText().insertText(17, 0, "\t\tFile x = new File(inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); theEditor.styledText().insertText(23, 0, "//"); theEditor.styledText().insertText(24, 0, "\t\tSystem.out.println(\"Error while writing the file: \" + inputDirectory + System.getProperty(\"file.separator\") + fileName);\n"); //bot.sleep(30000l); //System.out.println ("DEBUG " + theEditor.styledText().getText() ); editor.save(); //bot.sleep(30000l); String text = executeClientGetServerOutput(getExampleClientProjectName(),"src", "org.jboss.soa.esb.samples.quickstart.helloworldfileaction.test", "CreateTestFile.java"); assertFalse ("Test fails due to ESB deployment error: NNNN", text.contains("ERROR [org.apache.juddi.v3.client.transport.wrapper.RequestHandler]")); assertNotNull("Calling JMS Send message failed, nothing appened to server log",text); assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Body: Hello World")); SWTTestExt.servers.removeAllProjectsFromServer(); }
diff --git a/devel/web/web-application/src/main/java/net/contextfw/web/application/internal/component/ScriptElementBuilder.java b/devel/web/web-application/src/main/java/net/contextfw/web/application/internal/component/ScriptElementBuilder.java index 2664936..3390644 100644 --- a/devel/web/web-application/src/main/java/net/contextfw/web/application/internal/component/ScriptElementBuilder.java +++ b/devel/web/web-application/src/main/java/net/contextfw/web/application/internal/component/ScriptElementBuilder.java @@ -1,31 +1,31 @@ package net.contextfw.web.application.internal.component; import net.contextfw.web.application.WebApplicationException; import net.contextfw.web.application.component.DOMBuilder; import net.contextfw.web.application.component.Script; import com.google.gson.Gson; class ScriptElementBuilder extends NamedBuilder { private final ComponentBuilder componentBuilder; private final Gson gson; protected ScriptElementBuilder(ComponentBuilder componentBuilder, Gson gson, PropertyAccess<Object> propertyAccess, String name, String accessName) { super(propertyAccess, name, accessName); this.componentBuilder = componentBuilder; this.gson = gson; } @Override void buildNamedValue(DOMBuilder b, String name, Object value) { if (value != null) { if (value instanceof Script) { ((Script) value).build(b.descend(name), gson, componentBuilder); } else { - throw new WebApplicationException("Instance of '"+value.getClass().getName()+"' is not a sub class of Script"); + throw new WebApplicationException("Instance of '"+value.getClass().getName()+"' is not a subclass of Script"); } } } }
true
true
void buildNamedValue(DOMBuilder b, String name, Object value) { if (value != null) { if (value instanceof Script) { ((Script) value).build(b.descend(name), gson, componentBuilder); } else { throw new WebApplicationException("Instance of '"+value.getClass().getName()+"' is not a sub class of Script"); } } }
void buildNamedValue(DOMBuilder b, String name, Object value) { if (value != null) { if (value instanceof Script) { ((Script) value).build(b.descend(name), gson, componentBuilder); } else { throw new WebApplicationException("Instance of '"+value.getClass().getName()+"' is not a subclass of Script"); } } }
diff --git a/src/haven/HavenApplet.java b/src/haven/HavenApplet.java index 1afac24..ed8e6eb 100644 --- a/src/haven/HavenApplet.java +++ b/src/haven/HavenApplet.java @@ -1,118 +1,118 @@ package haven; import java.applet.*; import java.net.URL; import java.awt.*; import java.awt.event.*; public class HavenApplet extends Applet { ThreadGroup p; HavenPanel h; boolean running = false; private class ErrorPanel extends Canvas implements haven.error.ErrorStatus { String status = ""; boolean ar = false; public ErrorPanel() { setBackground(Color.BLACK); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if(ar && !running) { HavenApplet.this.remove(ErrorPanel.this); startgame(); } } }); } public void goterror(Throwable t) { stopgame(); setSize(HavenApplet.this.getSize()); HavenApplet.this.add(this); repaint(); } public void connecting() { status = "Connecting to error report server..."; repaint(); } public void sending() { status = "Sending error report..."; repaint(); } public void done() { status = "Done"; ar = true; repaint(); } public void senderror(Exception e) { status = "Could not send error report"; ar = true; repaint(); } public void paint(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); FontMetrics m = g.getFontMetrics(); int y = 0; g.drawString("An error has occurred.", 0, y + m.getAscent()); y += m.getHeight(); g.drawString(status, 0, y + m.getAscent()); y += m.getHeight(); if(ar) { g.drawString("Click to restart the game", 0, y + m.getAscent()); y += m.getHeight(); } } } public void destroy() { p.interrupt(); } public void startgame() { if(running) return; h = new HavenPanel(800, 600); add(h); h.init(); p = new haven.error.ErrorHandler(new ErrorPanel()); Thread main = new Thread(p, new Runnable() { public void run() { Bootstrap b = new Bootstrap(h.ui, false); b.setaddr(getCodeBase().getHost()); try { - Resource.baseurl = new URL("http", getCodeBase().getHost(), 80, "/res"); + Resource.baseurl = new URL("http", getCodeBase().getHost(), 80, "/res/"); } catch(java.net.MalformedURLException e) { throw(new RuntimeException(e)); } b.start(); Thread main = new Thread(Utils.tg(), h, "Haven applet main thread"); main.start(); } }); main.start(); running = true; } public void stopgame() { if(!running) return; p.interrupt(); remove(h); p = null; h = null; running = false; } public void init() { resize(800, 600); startgame(); } }
true
true
public void startgame() { if(running) return; h = new HavenPanel(800, 600); add(h); h.init(); p = new haven.error.ErrorHandler(new ErrorPanel()); Thread main = new Thread(p, new Runnable() { public void run() { Bootstrap b = new Bootstrap(h.ui, false); b.setaddr(getCodeBase().getHost()); try { Resource.baseurl = new URL("http", getCodeBase().getHost(), 80, "/res"); } catch(java.net.MalformedURLException e) { throw(new RuntimeException(e)); } b.start(); Thread main = new Thread(Utils.tg(), h, "Haven applet main thread"); main.start(); } }); main.start(); running = true; }
public void startgame() { if(running) return; h = new HavenPanel(800, 600); add(h); h.init(); p = new haven.error.ErrorHandler(new ErrorPanel()); Thread main = new Thread(p, new Runnable() { public void run() { Bootstrap b = new Bootstrap(h.ui, false); b.setaddr(getCodeBase().getHost()); try { Resource.baseurl = new URL("http", getCodeBase().getHost(), 80, "/res/"); } catch(java.net.MalformedURLException e) { throw(new RuntimeException(e)); } b.start(); Thread main = new Thread(Utils.tg(), h, "Haven applet main thread"); main.start(); } }); main.start(); running = true; }
diff --git a/core/src/test/java/org/apache/mahout/df/split/OptIgSplitTest.java b/core/src/test/java/org/apache/mahout/df/split/OptIgSplitTest.java index 95eb33fd9..3d83259f6 100644 --- a/core/src/test/java/org/apache/mahout/df/split/OptIgSplitTest.java +++ b/core/src/test/java/org/apache/mahout/df/split/OptIgSplitTest.java @@ -1,61 +1,61 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.df.split; import java.util.Random; import org.apache.mahout.common.RandomUtils; import org.apache.mahout.df.data.Data; import org.apache.mahout.df.data.Utils; import junit.framework.TestCase; public class OptIgSplitTest extends TestCase { protected static final int nbAttributes = 20; protected static final int numInstances = 100; @Override protected void setUp() throws Exception { super.setUp(); RandomUtils.useTestSeed(); } public void testComputeSplit() throws Exception { int n = 100; IgSplit ref = new DefaultIgSplit(); IgSplit opt = new OptIgSplit(); Random rng = RandomUtils.getRandom(); Data data = Utils.randomData(rng, nbAttributes, numInstances); for (int nloop = 0; nloop < n; nloop++) { int attr = rng.nextInt(data.getDataset().nbAttributes()); // System.out.println("IsNumerical: " + data.dataset.isNumerical(attr)); Split expected = ref.computeSplit(data, attr); Split actual = opt.computeSplit(data, attr); - assertEquals(expected.ig, actual.ig); + assertEquals(expected.ig, actual.ig, 0.0000001); assertEquals(expected.split, actual.split); } } }
true
true
public void testComputeSplit() throws Exception { int n = 100; IgSplit ref = new DefaultIgSplit(); IgSplit opt = new OptIgSplit(); Random rng = RandomUtils.getRandom(); Data data = Utils.randomData(rng, nbAttributes, numInstances); for (int nloop = 0; nloop < n; nloop++) { int attr = rng.nextInt(data.getDataset().nbAttributes()); // System.out.println("IsNumerical: " + data.dataset.isNumerical(attr)); Split expected = ref.computeSplit(data, attr); Split actual = opt.computeSplit(data, attr); assertEquals(expected.ig, actual.ig); assertEquals(expected.split, actual.split); } }
public void testComputeSplit() throws Exception { int n = 100; IgSplit ref = new DefaultIgSplit(); IgSplit opt = new OptIgSplit(); Random rng = RandomUtils.getRandom(); Data data = Utils.randomData(rng, nbAttributes, numInstances); for (int nloop = 0; nloop < n; nloop++) { int attr = rng.nextInt(data.getDataset().nbAttributes()); // System.out.println("IsNumerical: " + data.dataset.isNumerical(attr)); Split expected = ref.computeSplit(data, attr); Split actual = opt.computeSplit(data, attr); assertEquals(expected.ig, actual.ig, 0.0000001); assertEquals(expected.split, actual.split); } }
diff --git a/src/main/java/de/cismet/extensions/timeasy/TimEasyPureNewFeature.java b/src/main/java/de/cismet/extensions/timeasy/TimEasyPureNewFeature.java index 862445f..ce8938d 100644 --- a/src/main/java/de/cismet/extensions/timeasy/TimEasyPureNewFeature.java +++ b/src/main/java/de/cismet/extensions/timeasy/TimEasyPureNewFeature.java @@ -1,195 +1,195 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.extensions.timeasy; import Sirius.navigator.connection.SessionManager; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.Node; import Sirius.server.newuser.permission.Permission; import Sirius.server.newuser.permission.PermissionHolder; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import edu.umd.cs.piccolo.event.PInputEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.geom.Point2D; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import de.cismet.cismap.commons.WorldToScreenTransform; import de.cismet.cismap.commons.features.InputEventAwareFeature; import de.cismet.cismap.commons.features.PureNewFeature; import de.cismet.cismap.commons.features.XStyledFeature; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.gui.piccolo.PFeature; import de.cismet.cismap.commons.tools.PFeatureTools; import de.cismet.tools.gui.StaticSwingTools; /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ public class TimEasyPureNewFeature extends PureNewFeature implements InputEventAwareFeature { //~ Instance fields -------------------------------------------------------- private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass()); private String classId = java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("classID"); private String domainserver = java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("domainserver"); private int parentNodeId = new Integer(java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("parentNodeId")).intValue(); //~ Constructors ----------------------------------------------------------- /** * Creates a new TimEasyPureNewFeature object. * * @param g DOCUMENT ME! */ public TimEasyPureNewFeature(final Geometry g) { super(g); } /** * Creates a new TimEasyPureNewFeature object. * * @param point DOCUMENT ME! * @param wtst DOCUMENT ME! */ public TimEasyPureNewFeature(final Point2D point, final WorldToScreenTransform wtst) { super(point, wtst); } /** * Creates a new TimEasyPureNewFeature object. * * @param canvasPoints DOCUMENT ME! * @param wtst DOCUMENT ME! */ public TimEasyPureNewFeature(final Point2D[] canvasPoints, final WorldToScreenTransform wtst) { super(canvasPoints, wtst); } /** * Creates a new TimEasyPureNewFeature object. * * @param coordArr DOCUMENT ME! * @param wtst DOCUMENT ME! */ public TimEasyPureNewFeature(final Coordinate[] coordArr, final WorldToScreenTransform wtst) { super(coordArr, wtst); } //~ Methods ---------------------------------------------------------------- @Override public boolean noFurtherEventProcessing(final PInputEvent event) { return true; } @Override public void mouseWheelRotated(final PInputEvent event) { } @Override public void mouseReleased(final PInputEvent event) { } @Override public void mousePressed(final PInputEvent event) { } @Override public void mouseMoved(final PInputEvent event) { } @Override public void mouseExited(final PInputEvent event) { } @Override public void mouseEntered(final PInputEvent event) { } @Override public void mouseDragged(final PInputEvent event) { } @Override public void mouseClicked(final PInputEvent event) { try { event.setHandled(noFurtherEventProcessing(event)); final MetaClass metaClass = SessionManager.getProxy().getMetaClass(classId + "@" + domainserver); final String userkey = SessionManager.getSession().getUser().getUserGroup().getKey().toString(); final Permission permission = PermissionHolder.WRITEPERMISSION; final boolean writePermission = metaClass.getPermissions().hasPermission(userkey, permission); // Node parentNode=SessionManager.getProxy().getNode(parentNodeId,domainserver); final boolean timLiegPermission = metaClass.getPermissions() - .hasWritePermission(SessionManager.getSession().getUser().getUserGroup()); + .hasWritePermission(SessionManager.getSession().getUser()); final Object o = PFeatureTools.getFirstValidObjectUnderPointer(event, new Class[] { PFeature.class }); if (event.getComponent() instanceof MappingComponent) { final MappingComponent mc = (MappingComponent)event.getComponent(); if (event.getModifiers() == InputEvent.BUTTON3_MASK) { // &&writePermission) { if (log.isDebugEnabled()) { log.debug("right mouseclick"); } if ((o instanceof PFeature) && (((PFeature)o).getFeature() instanceof XStyledFeature)) { final XStyledFeature xf = (XStyledFeature)((PFeature)o).getFeature(); if (log.isDebugEnabled()) { log.debug("valid object under pointer"); } final JPopupMenu popup = new JPopupMenu("Test"); final JMenuItem m = new JMenuItem("TIM Merker anlegen"); m.setIcon(xf.getIconImage()); m.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (log.isDebugEnabled()) { log.debug("TIM Action performed"); } log.info("permission an TimLieg:" + timLiegPermission); if (true || timLiegPermission) { final TimEasyDialog ted = new TimEasyDialog( StaticSwingTools.getParentFrame(mc), true, TimEasyPureNewFeature.this, mc); ted.pack(); ted.setLocationRelativeTo(mc); ted.setVisible(true); } else { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(mc), java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("keine_rechte_am_parentnode"), "TimEasy Fehler", JOptionPane.ERROR_MESSAGE); } } }); popup.add(m); popup.show(mc, (int)event.getCanvasPosition().getX(), (int)event.getCanvasPosition().getY()); } } } } catch (Throwable t) { log.error("Fehler beim Aufruf des TIM Easy Dialog.", t); } } }
true
true
public void mouseClicked(final PInputEvent event) { try { event.setHandled(noFurtherEventProcessing(event)); final MetaClass metaClass = SessionManager.getProxy().getMetaClass(classId + "@" + domainserver); final String userkey = SessionManager.getSession().getUser().getUserGroup().getKey().toString(); final Permission permission = PermissionHolder.WRITEPERMISSION; final boolean writePermission = metaClass.getPermissions().hasPermission(userkey, permission); // Node parentNode=SessionManager.getProxy().getNode(parentNodeId,domainserver); final boolean timLiegPermission = metaClass.getPermissions() .hasWritePermission(SessionManager.getSession().getUser().getUserGroup()); final Object o = PFeatureTools.getFirstValidObjectUnderPointer(event, new Class[] { PFeature.class }); if (event.getComponent() instanceof MappingComponent) { final MappingComponent mc = (MappingComponent)event.getComponent(); if (event.getModifiers() == InputEvent.BUTTON3_MASK) { // &&writePermission) { if (log.isDebugEnabled()) { log.debug("right mouseclick"); } if ((o instanceof PFeature) && (((PFeature)o).getFeature() instanceof XStyledFeature)) { final XStyledFeature xf = (XStyledFeature)((PFeature)o).getFeature(); if (log.isDebugEnabled()) { log.debug("valid object under pointer"); } final JPopupMenu popup = new JPopupMenu("Test"); final JMenuItem m = new JMenuItem("TIM Merker anlegen"); m.setIcon(xf.getIconImage()); m.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (log.isDebugEnabled()) { log.debug("TIM Action performed"); } log.info("permission an TimLieg:" + timLiegPermission); if (true || timLiegPermission) { final TimEasyDialog ted = new TimEasyDialog( StaticSwingTools.getParentFrame(mc), true, TimEasyPureNewFeature.this, mc); ted.pack(); ted.setLocationRelativeTo(mc); ted.setVisible(true); } else { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(mc), java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("keine_rechte_am_parentnode"), "TimEasy Fehler", JOptionPane.ERROR_MESSAGE); } } }); popup.add(m); popup.show(mc, (int)event.getCanvasPosition().getX(), (int)event.getCanvasPosition().getY()); } } } } catch (Throwable t) { log.error("Fehler beim Aufruf des TIM Easy Dialog.", t); } } }
public void mouseClicked(final PInputEvent event) { try { event.setHandled(noFurtherEventProcessing(event)); final MetaClass metaClass = SessionManager.getProxy().getMetaClass(classId + "@" + domainserver); final String userkey = SessionManager.getSession().getUser().getUserGroup().getKey().toString(); final Permission permission = PermissionHolder.WRITEPERMISSION; final boolean writePermission = metaClass.getPermissions().hasPermission(userkey, permission); // Node parentNode=SessionManager.getProxy().getNode(parentNodeId,domainserver); final boolean timLiegPermission = metaClass.getPermissions() .hasWritePermission(SessionManager.getSession().getUser()); final Object o = PFeatureTools.getFirstValidObjectUnderPointer(event, new Class[] { PFeature.class }); if (event.getComponent() instanceof MappingComponent) { final MappingComponent mc = (MappingComponent)event.getComponent(); if (event.getModifiers() == InputEvent.BUTTON3_MASK) { // &&writePermission) { if (log.isDebugEnabled()) { log.debug("right mouseclick"); } if ((o instanceof PFeature) && (((PFeature)o).getFeature() instanceof XStyledFeature)) { final XStyledFeature xf = (XStyledFeature)((PFeature)o).getFeature(); if (log.isDebugEnabled()) { log.debug("valid object under pointer"); } final JPopupMenu popup = new JPopupMenu("Test"); final JMenuItem m = new JMenuItem("TIM Merker anlegen"); m.setIcon(xf.getIconImage()); m.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (log.isDebugEnabled()) { log.debug("TIM Action performed"); } log.info("permission an TimLieg:" + timLiegPermission); if (true || timLiegPermission) { final TimEasyDialog ted = new TimEasyDialog( StaticSwingTools.getParentFrame(mc), true, TimEasyPureNewFeature.this, mc); ted.pack(); ted.setLocationRelativeTo(mc); ted.setVisible(true); } else { JOptionPane.showMessageDialog( StaticSwingTools.getParentFrame(mc), java.util.ResourceBundle.getBundle("de/cismet/extensions/timeasy/Bundle") .getString("keine_rechte_am_parentnode"), "TimEasy Fehler", JOptionPane.ERROR_MESSAGE); } } }); popup.add(m); popup.show(mc, (int)event.getCanvasPosition().getX(), (int)event.getCanvasPosition().getY()); } } } } catch (Throwable t) { log.error("Fehler beim Aufruf des TIM Easy Dialog.", t); } } }
diff --git a/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeper.java b/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeper.java index dff77f9..4f3a226 100644 --- a/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeper.java +++ b/trunk/src/edu/umich/lsa/cscs/gridsweeper/GridSweeper.java @@ -1,784 +1,784 @@ package edu.umich.lsa.cscs.gridsweeper; import org.ggf.drmaa.*; import java.io.*; import java.text.DateFormat; import java.util.*; import static edu.umich.lsa.cscs.gridsweeper.StringUtils.*; import static edu.umich.lsa.cscs.gridsweeper.DateUtils.*; import static edu.umich.lsa.cscs.gridsweeper.DLogger.*; /** * The GridSweeper command-line tool for job submission. Takes a .gsexp * XML experiment file and/or a bunch of command line options and submits * the resulting experiment to the grid via DRMAA. * Warning: begun on a houseboat in Paris. May still contain strange French bugs. * * @author Ed Baskerville * */ public class GridSweeper { enum RunType { RUN, DRY, NORUN } class CaseRun { ExperimentCase expCase; String caseId; int runNum; int rngSeed; JobInfo jobInfo = null; RunResults runResults = null; public CaseRun(ExperimentCase expCase, String caseId, int runNum, int rngSeed) { this.expCase = expCase; this.caseId = caseId; this.runNum = runNum; this.rngSeed = rngSeed; } public String getRunString() { String runStr; if(caseId.equals("")) runStr = "run " + runNum; else runStr = caseId + ", run " + runNum; return runStr; } } static String className; static { className = GridSweeper.class.toString(); } String root; String pid; Experiment experiment; RunType runType = RunType.RUN; List<ExperimentCase> cases = null; boolean useFileTransfer = false; Calendar cal; String dateStr; String timeStr; String expDir; String email; String fileTransferSubpath; Session drmaaSession; StringMap caseIdToJobIdMap; Map<String, CaseRun> jobIdToRunMap; PrintStream msgOut; public GridSweeper() throws GridSweeperException { root = System.getenv("GRIDSWEEPER_ROOT"); if(root == null) throw new GridSweeperException("GRIDSWEEPER_ROOT environment variable not set."); pid = getPid(); cal = Calendar.getInstance(); msgOut = System.err; } private String getPid() throws GridSweeperException { String pid; try { String getPidPath = appendPathComponent(root, "bin/gsgetpid"); Process pidProc = Runtime.getRuntime().exec(getPidPath); BufferedReader getPidReader = new BufferedReader(new InputStreamReader(pidProc.getInputStream())); pid = getPidReader.readLine(); } catch(Exception e) { throw new GridSweeperException("Could not get pid."); } if(pid == null) { throw new GridSweeperException("Could not get pid."); } return pid; } /** * Generates experiment cases and sets up in preparation for grid submission. * Experiment results are collated in a master experiment directory, * specified in the user settings, in a subdirectory tagged with the experiment name * and date/time ({@code <name>/YYYY-MM-DD/hh-mm-ss}). If a shared filesystem is not * available, files are first staged to the experiment results directory on the * file transfer system. * Finally, a DRMAA session is established, and each case is submitted. * @throws GridSweeperException */ public void submitExperiment() throws GridSweeperException { if(runType == RunType.NORUN) return; email = experiment.getSettings().getSetting("EmailAddress"); if(email == null) { msgOut.println("Warning: no email address provided; " + " using local user account."); email = System.getProperty("user.name"); } String expName = experiment.getName(); if(runType == RunType.DRY) { msgOut.println("Performing dry run for experiment \"" + expName + "\"..."); } else { msgOut.println("Running experiment \"" + experiment.getName() + "\"..."); } Settings settings = experiment.getSettings(); // Assemble cases cases = experiment.generateCases(); // Set up main experiment directory setUpExperimentDirectory(settings); // Set up directory & input files on file transfer system if asked for if(runType == RunType.RUN && settings.getBooleanProperty("UseFileTransfer", false)) { setUpFileTransfer(settings); } // Create experiment XML in output directory String xmlPath = appendPathComponent(expDir, "experiment.gsexp"); try { experiment.writeToFile(xmlPath, true); } catch(Exception e) { throw new GridSweeperException("Could not write experiment XML to" + xmlPath, e); } // Enumerate and submit cases submitCases(); // Finally, switch(runType) { case DRY: msgOut.println("Dry run complete."); break; case RUN: msgOut.println("Experiment submitted."); break; } } private void setUpExperimentDirectory(Settings settings) throws GridSweeperException { try { String expsDir = expandTildeInPath(settings.getProperty("ResultsDirectory", "~/Results")); // First set up big directory for the whole experiment // Located in <resultsDir>/<experimentName>/<experimentDate>/<experimentTime> String expName = experiment.getName(); if(expName == null) { throw new GridSweeperException("Experiment name must be specified."); } dateStr = getDateString(cal); timeStr = getTimeString(cal); String expSubDir = String.format("%s%s%s%s%s", expName, getFileSeparator(), dateStr, getFileSeparator(), timeStr); expDir = appendPathComponent(expsDir, expSubDir); finer("Experiment subdirectory: " + expDir); File expDirFile = new File(expDir); expDirFile.mkdirs(); msgOut.println("Created experiment directory \"" + expDir + "\"."); } catch(Exception e) { throw new GridSweeperException("Could not create experiment directory " + expDir, e); } } private void setUpFileTransfer(Settings settings) throws GridSweeperException { FileTransferSystem fts = null; try { msgOut.println("Setting up file transfer system..."); String className = settings.getProperty("FileTransferSystemClassName", "edu.umich.lsa.cscs.gridsweeper.FTPFileTransferSystem"); fts = FileTransferSystemFactory.getFactory().getFileTransferSystem(className, settings); fts.connect(); boolean alreadyExists; do { fileTransferSubpath = UUID.randomUUID().toString(); alreadyExists = fts.fileExists(fileTransferSubpath); } while(alreadyExists); msgOut.println("Done setting up file transfer."); // If file transfer is on, make the directory // and upload input files StringMap inputFiles = experiment.getInputFiles(); if(inputFiles.size() > 0) { msgOut.println("Uploading input files..."); String inputDir = appendPathComponent(fileTransferSubpath, "input"); fts.makeDirectory(inputDir); for(String localPath : inputFiles.keySet()) { String remotePath = appendPathComponent(inputDir, inputFiles.get(localPath)); msgOut.println("Uploading file \"" + localPath + "\" to \"" + remotePath + "\""); fts.uploadFile(localPath, remotePath); } msgOut.println("Done uploading input files."); } fts.disconnect(); } catch(Exception e) { throw new GridSweeperException("Could not set up file trasfer system", e); } } public void submitCases() throws GridSweeperException { if(runType == RunType.NORUN) return; try { // Establish DRMAA session, unless this is a dry run if(runType == RunType.RUN) { msgOut.println("Establishing grid session"); drmaaSession = SessionFactory.getFactory().getSession(); drmaaSession.init(null); } // Set up and run each case caseIdToJobIdMap = new StringMap(); jobIdToRunMap = new HashMap<String, CaseRun>(); if(cases.size() > 1) msgOut.println("Submitting cases:"); for(ExperimentCase expCase : cases) { runCase(expCase); } if(cases.size() > 1) msgOut.println("All cases submitted."); } catch(Exception e) { throw new GridSweeperException("Could not run experiment", e); } } /** * Submits a single experiment case. This means running one job for each * run of the case (one for each random seed). * @param expCase The experiment case to run. * @throws FileNotFoundException If the case directory cannot be found/created. * @throws DrmaaException If a DRMAA error occurs (in {@link #runCaseRun}). * @throws IOException If the case XML cannot be written out (in {@link #runCaseRun}). */ public void runCase(ExperimentCase expCase) throws FileNotFoundException, DrmaaException, IOException { String caseSubDir = experiment.getDirectoryNameForCase(expCase); String caseDir = appendPathComponent(expDir, caseSubDir); finer("Case subdirectory: " + caseDir); File caseDirFile = new File(caseDir); caseDirFile.mkdirs(); String caseName; if(caseSubDir.equals("")) { caseName = experiment.getName() + " (" + dateStr + ", " + timeStr + ")"; } else { caseName = experiment.getName() + " - " + caseSubDir + " (" + dateStr + ", " + timeStr + ")"; } // Write XML String xmlPath = appendPathComponent(caseDir, "case.gscase"); ExperimentCaseXMLWriter xmlWriter = new ExperimentCaseXMLWriter( xmlPath, expCase, caseName); xmlWriter.writeXML(); if(!caseSubDir.equals("")) { msgOut.println(caseSubDir); } // Run each individual run on the grid List<Integer> rngSeeds = expCase.getRngSeeds(); for(int i = 0; i < rngSeeds.size(); i++) { CaseRun run = new CaseRun(expCase, caseSubDir, i, rngSeeds.get(i)); runCaseRun(run); } } /** * Submits a single run of an experiment case. * @param expCase The case to run. * @param caseDir The full path to where files are stored for this case. * @param caseSubDir The case directory relative to the experiment results directory. * @param i The run number for this run. * @param rngSeed The random seed for this run. * @throws DrmaaException If a DRMAA error occurs during job submission. * @throws IOException If the case XML cannot be written out. */ public void runCaseRun(CaseRun run) throws DrmaaException, IOException { ExperimentCase expCase = run.expCase; String caseId = run.caseId; int runNum = run.runNum; int rngSeed = run.rngSeed; String caseDir; if(caseId.equals("")) caseDir = expDir; else caseDir = appendPathComponent(expDir, caseId); Settings settings = experiment.getSettings(); String caseRunName; if(caseId.equals("")) { caseRunName = experiment.getName() + " - run " + runNum + " (" + dateStr + ", " + timeStr + ")"; } else { caseRunName = experiment.getName() + " - " + caseId + " - run " + runNum + " (" + dateStr + ", " + timeStr + ")"; } if(runType == RunType.RUN) { // Write setup file String stdinPath = appendPathComponent(caseDir, ".gsweep_in." + runNum); RunSetup setup = new RunSetup(settings, experiment.getInputFiles(), caseId, expCase.getParameterMap(), experiment.getNumRuns(), runNum, rngSeed, experiment.getOutputFiles()); ObjectOutputStream stdinStream = new ObjectOutputStream(new FileOutputStream(stdinPath)); stdinStream.writeObject(setup); stdinStream.close(); // Generate job template JobTemplate jt = drmaaSession.createJobTemplate(); jt.setJobName(caseRunName); jt.setRemoteCommand(appendPathComponent(root, "bin/gsrunner")); if(!useFileTransfer) jt.setWorkingDirectory(caseDir); jt.setInputPath(":" + stdinPath); jt.setOutputPath(":" + appendPathComponent(caseDir, ".gsweep_out." + runNum)); jt.setErrorPath(":" + appendPathComponent(caseDir, ".gsweep_err." + runNum)); jt.setBlockEmail(true); try { jt.setTransferFiles(new FileTransferMode(true, true, true)); } catch(DrmaaException e) { // If setTransferFiles isn't supported, we'll hope that the system defaults to // transfering them. This works for SGE. } Properties environment = new Properties(); environment.setProperty("GRIDSWEEPER_ROOT", root); String classpath = System.getenv("CLASSPATH"); if(classpath != null) environment.setProperty("CLASSPATH", classpath); jt.setJobEnvironment(environment); String jobId = drmaaSession.runJob(jt); caseIdToJobIdMap.put(caseId + "." + runNum, jobId); jobIdToRunMap.put(jobId, run); fine("run in runmap: " + jobIdToRunMap.get(jobId)); drmaaSession.deleteJobTemplate(jt); msgOut.println(" Submitted run " + runNum + " (DRMAA job ID " + jobId + ")"); } else { msgOut.println(" Not submitting run " + runNum + " (dry run)"); } fine("run: " + run); } public void daemonize() throws GridSweeperException { if(runType != RunType.RUN) return; try { // Open PrintStream to status.log in experiment directory String logPath = appendPathComponent(expDir, "status.log"); PrintStream logOut = new PrintStream(new FileOutputStream(logPath)); msgOut.println("Detaching from console " + "(monitoring process id: " + pid + ")..."); msgOut.println("Status output will be written to:"); msgOut.println(" " + logPath); msgOut.println("and an email will be sent to " + email + " upon experiment completion."); msgOut.println("You may now close this console or log out" + " without disturbing the experiment."); msgOut = logOut; System.out.close(); System.err.close(); msgOut.println("Job monitoring process ID: " + pid); } catch(Exception e) { throw new GridSweeperException("An error occurred trying to " + "detach from the console."); } } /** * Cleans up: for now, just closes the DRMAA session. * @throws GridSweeperException If the DRMAA {@code exit()} call fails. */ public void finish() throws GridSweeperException { if(runType == RunType.NORUN) return; if(runType == RunType.RUN) { msgOut.println("Waiting for jobs to complete..."); StringList drmaaErrorList = new StringList(); StringList gsErrorList = new StringList(); StringList execErrorList = new StringList(); int runCount = jobIdToRunMap.size(); for(int i = 0; i < runCount; i++) { JobInfo info; try { info = drmaaSession.wait( Session.JOB_IDS_SESSION_ANY, Session.TIMEOUT_WAIT_FOREVER); } catch(DrmaaException e) { throw new GridSweeperException("Waiting for job completion failed.", e); } String jobId = info.getJobId(); fine("got wait for job ID " + jobId); fine("jobIdToRunMap: " + jobIdToRunMap.toString()); CaseRun run = jobIdToRunMap.get(jobId); fine("run: " + run); run.jobInfo = info; String caseId = run.caseId; int runNum = run.runNum; String runStr = run.getRunString(); msgOut.println("Completed run " + runStr + " (DRMAA job ID " + jobId + ")"); // Check for DRMAA errors if(info.hasCoreDump() || info.hasSignaled() || info.wasAborted() || info.getExitStatus() != 0) { drmaaErrorList.add(jobId); msgOut.println(" (Warning: DRMAA reports that the run did not " + "complete normally.)"); } // Load RunResults from disk else try { String caseDir = appendPathComponent(expDir, caseId); String stdoutPath = appendPathComponent(caseDir, ".gsweep_out." + runNum); fine("Loading RunResults from " + stdoutPath); FileInputStream fileStream = new FileInputStream(stdoutPath); ObjectInputStream objStream = new ObjectInputStream(fileStream); RunResults runResults = (RunResults)objStream.readObject(); run.runResults = runResults; if(runResults == null || runResults.getException() != null) { gsErrorList.add(jobId); msgOut.println(" (Warning: a GridSweeper exception occurred" + " while performing this run.)"); } else if(runResults.getStatus() != 0) { execErrorList.add(jobId); msgOut.println(" (Warning: this run exited with an" + "error code.)"); } } catch(Exception e) { msgOut.print(" (Warning: an exception occurred loading the" + " run results for this run: "); e.printStackTrace(msgOut); msgOut.println(" .)"); gsErrorList.add(jobId); } msgOut.format("%d of %d complete (%.1f%%).\n", i + 1, runCount, (double)(i + 1)/runCount * 100); } msgOut.println("All jobs completed."); sendEmail(drmaaErrorList, gsErrorList, execErrorList); try { // Finish it up drmaaSession.exit(); } catch(DrmaaException e) { throw new GridSweeperException("Received exception ending DRMAA session", e); } } else { sendEmail(null, null, null); } } private void sendEmail(StringList drmaaErrorList, StringList gsErrorList, StringList execErrorList) throws GridSweeperException { String expName = experiment.getName(); String subject = expName + " complete"; // Construct and write out message String messagePath = appendPathComponent(expDir, ".gsweep_email"); StringBuffer message = new StringBuffer(); if(runType == RunType.RUN) message.append("GridSweeper experiment run complete.\n\n"); else message.append("GridSweeper experiment dry run complete.\n\n"); message.append(" Experiment name: " + expName + "\n"); message.append(" Results directory: " + expDir + "\n"); message.append(" Submitted at: "); DateFormat format = DateFormat.getDateTimeInstance(); message.append(format.format(new Date(cal.getTimeInMillis()))); message.append("\n"); message.append(" Elapsed time: "); long elapsedMilli = (new Date()).getTime() - cal.getTimeInMillis(); elapsedMilli /= 1000; long seconds = elapsedMilli % 60; elapsedMilli /= 60; long minutes = elapsedMilli % 60; elapsedMilli /= 60; long hours = elapsedMilli; message.append("" + hours + "h" + minutes + "m" + seconds + "s"); message.append("\n\n"); if(runType == RunType.RUN) { // Print error messages, if present int errorCount = drmaaErrorList.size() + gsErrorList.size() + execErrorList.size(); if(errorCount == 0) { message.append("No errors occurred.\n"); } else { int runCount = jobIdToRunMap.size(); - message.append(String.format("%d of %d runs had errors (%.1f%%).\n", + message.append(String.format("%d of %d runs had errors (%.1f%%)...\n\n", errorCount, runCount, (double)errorCount/runCount * 100)); // Start with DRMAA-detected errors for(String jobId : drmaaErrorList) { CaseRun run = jobIdToRunMap.get(jobId); JobInfo info = run.jobInfo; String runStr = run.getRunString(); message.append("DRMAA returned an error for " + runStr + ":\n"); if(info.hasCoreDump()) { message.append(" A core dump occurred.\n"); } if(info.hasSignaled()) { message.append(" The job ended with signal " + info.getTerminatingSignal() + ".\n"); } if(info.wasAborted()) { message.append(" The job was aborted.\n"); } if(info.hasExited() && info.getExitStatus() != 0) { message.append(" The job exited with status " + info.getExitStatus() + ".\n"); } message.append("\n"); } // And then GridSweeper errors... for(String jobId : gsErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("An internal error occurred in GridSweeper for " + runStr + ": \n"); if(results == null) { message.append(" The run results object could not be loaded.\n"); } else { Exception exception = results.getException(); if(exception != null) { message.append(" A Java exception occurred:\n "); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); String stackStr = sw.getBuffer().toString(); message.append(stackStr); } else { message.append(" An unknown error occurred.\n"); } } message.append("\n"); } // And finally nonzero status from the executable itself... for(String jobId : execErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("The " + runStr + " exited with status " + results.getStatus() + ".\n\n"); } } } try { FileWriter fw = new FileWriter(messagePath); fw.write(message.toString()); fw.close(); } catch(IOException e) { throw new GridSweeperException("Could not write email file."); } String command = appendPathComponent(root, "bin/gsmail"); String[] commandAndArgs = {command, subject, email, messagePath}; try { Runtime.getRuntime().exec(commandAndArgs); } catch (IOException e) { throw new GridSweeperException("Could not send email.", e); } msgOut.println("Sent notification email to " + email + "."); } public void setRunType(RunType runType) { this.runType = runType; } public void setExperiment(Experiment experiment) { this.experiment = experiment; } }
true
true
private void sendEmail(StringList drmaaErrorList, StringList gsErrorList, StringList execErrorList) throws GridSweeperException { String expName = experiment.getName(); String subject = expName + " complete"; // Construct and write out message String messagePath = appendPathComponent(expDir, ".gsweep_email"); StringBuffer message = new StringBuffer(); if(runType == RunType.RUN) message.append("GridSweeper experiment run complete.\n\n"); else message.append("GridSweeper experiment dry run complete.\n\n"); message.append(" Experiment name: " + expName + "\n"); message.append(" Results directory: " + expDir + "\n"); message.append(" Submitted at: "); DateFormat format = DateFormat.getDateTimeInstance(); message.append(format.format(new Date(cal.getTimeInMillis()))); message.append("\n"); message.append(" Elapsed time: "); long elapsedMilli = (new Date()).getTime() - cal.getTimeInMillis(); elapsedMilli /= 1000; long seconds = elapsedMilli % 60; elapsedMilli /= 60; long minutes = elapsedMilli % 60; elapsedMilli /= 60; long hours = elapsedMilli; message.append("" + hours + "h" + minutes + "m" + seconds + "s"); message.append("\n\n"); if(runType == RunType.RUN) { // Print error messages, if present int errorCount = drmaaErrorList.size() + gsErrorList.size() + execErrorList.size(); if(errorCount == 0) { message.append("No errors occurred.\n"); } else { int runCount = jobIdToRunMap.size(); message.append(String.format("%d of %d runs had errors (%.1f%%).\n", errorCount, runCount, (double)errorCount/runCount * 100)); // Start with DRMAA-detected errors for(String jobId : drmaaErrorList) { CaseRun run = jobIdToRunMap.get(jobId); JobInfo info = run.jobInfo; String runStr = run.getRunString(); message.append("DRMAA returned an error for " + runStr + ":\n"); if(info.hasCoreDump()) { message.append(" A core dump occurred.\n"); } if(info.hasSignaled()) { message.append(" The job ended with signal " + info.getTerminatingSignal() + ".\n"); } if(info.wasAborted()) { message.append(" The job was aborted.\n"); } if(info.hasExited() && info.getExitStatus() != 0) { message.append(" The job exited with status " + info.getExitStatus() + ".\n"); } message.append("\n"); } // And then GridSweeper errors... for(String jobId : gsErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("An internal error occurred in GridSweeper for " + runStr + ": \n"); if(results == null) { message.append(" The run results object could not be loaded.\n"); } else { Exception exception = results.getException(); if(exception != null) { message.append(" A Java exception occurred:\n "); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); String stackStr = sw.getBuffer().toString(); message.append(stackStr); } else { message.append(" An unknown error occurred.\n"); } } message.append("\n"); } // And finally nonzero status from the executable itself... for(String jobId : execErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("The " + runStr + " exited with status " + results.getStatus() + ".\n\n"); } } } try { FileWriter fw = new FileWriter(messagePath); fw.write(message.toString()); fw.close(); } catch(IOException e) { throw new GridSweeperException("Could not write email file."); } String command = appendPathComponent(root, "bin/gsmail"); String[] commandAndArgs = {command, subject, email, messagePath}; try { Runtime.getRuntime().exec(commandAndArgs); } catch (IOException e) { throw new GridSweeperException("Could not send email.", e); } msgOut.println("Sent notification email to " + email + "."); }
private void sendEmail(StringList drmaaErrorList, StringList gsErrorList, StringList execErrorList) throws GridSweeperException { String expName = experiment.getName(); String subject = expName + " complete"; // Construct and write out message String messagePath = appendPathComponent(expDir, ".gsweep_email"); StringBuffer message = new StringBuffer(); if(runType == RunType.RUN) message.append("GridSweeper experiment run complete.\n\n"); else message.append("GridSweeper experiment dry run complete.\n\n"); message.append(" Experiment name: " + expName + "\n"); message.append(" Results directory: " + expDir + "\n"); message.append(" Submitted at: "); DateFormat format = DateFormat.getDateTimeInstance(); message.append(format.format(new Date(cal.getTimeInMillis()))); message.append("\n"); message.append(" Elapsed time: "); long elapsedMilli = (new Date()).getTime() - cal.getTimeInMillis(); elapsedMilli /= 1000; long seconds = elapsedMilli % 60; elapsedMilli /= 60; long minutes = elapsedMilli % 60; elapsedMilli /= 60; long hours = elapsedMilli; message.append("" + hours + "h" + minutes + "m" + seconds + "s"); message.append("\n\n"); if(runType == RunType.RUN) { // Print error messages, if present int errorCount = drmaaErrorList.size() + gsErrorList.size() + execErrorList.size(); if(errorCount == 0) { message.append("No errors occurred.\n"); } else { int runCount = jobIdToRunMap.size(); message.append(String.format("%d of %d runs had errors (%.1f%%)...\n\n", errorCount, runCount, (double)errorCount/runCount * 100)); // Start with DRMAA-detected errors for(String jobId : drmaaErrorList) { CaseRun run = jobIdToRunMap.get(jobId); JobInfo info = run.jobInfo; String runStr = run.getRunString(); message.append("DRMAA returned an error for " + runStr + ":\n"); if(info.hasCoreDump()) { message.append(" A core dump occurred.\n"); } if(info.hasSignaled()) { message.append(" The job ended with signal " + info.getTerminatingSignal() + ".\n"); } if(info.wasAborted()) { message.append(" The job was aborted.\n"); } if(info.hasExited() && info.getExitStatus() != 0) { message.append(" The job exited with status " + info.getExitStatus() + ".\n"); } message.append("\n"); } // And then GridSweeper errors... for(String jobId : gsErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("An internal error occurred in GridSweeper for " + runStr + ": \n"); if(results == null) { message.append(" The run results object could not be loaded.\n"); } else { Exception exception = results.getException(); if(exception != null) { message.append(" A Java exception occurred:\n "); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exception.printStackTrace(pw); String stackStr = sw.getBuffer().toString(); message.append(stackStr); } else { message.append(" An unknown error occurred.\n"); } } message.append("\n"); } // And finally nonzero status from the executable itself... for(String jobId : execErrorList) { CaseRun run = jobIdToRunMap.get(jobId); RunResults results = run.runResults; String runStr = run.getRunString(); message.append("The " + runStr + " exited with status " + results.getStatus() + ".\n\n"); } } } try { FileWriter fw = new FileWriter(messagePath); fw.write(message.toString()); fw.close(); } catch(IOException e) { throw new GridSweeperException("Could not write email file."); } String command = appendPathComponent(root, "bin/gsmail"); String[] commandAndArgs = {command, subject, email, messagePath}; try { Runtime.getRuntime().exec(commandAndArgs); } catch (IOException e) { throw new GridSweeperException("Could not send email.", e); } msgOut.println("Sent notification email to " + email + "."); }
diff --git a/src/Game.java b/src/Game.java index db44a0f..824e453 100644 --- a/src/Game.java +++ b/src/Game.java @@ -1,70 +1,70 @@ /** * Created with IntelliJ IDEA. * User: Notandi * Date: 12.11.2012 * Time: 17:02 */ import java.util.Scanner; public class Game { public User player1; public User player2; public Board board; public boolean turn; public Game() { setPlayers(); board = new Board(); loop(); } public void setPlayers() { Scanner in = new Scanner(System.in); System.out.println("Enter name of player 1:"); String name; name = in.nextLine(); player1 = new User(name, 'X'); System.out.println("Enter name of player 2:"); name = in.nextLine(); player2 = new User(name, 'O'); //in.close(); } public void loop() { boolean isPlayer1 = true; User user; Scanner in = new Scanner(System.in); - while (board.checkWinner() == 'X') { + while (board.checkWinner() == 'x') { user = (isPlayer1) ? player1 : player2; int cell; do { System.out.println(board); System.out.println(user.getName() + " - pick a cell 1-9:"); cell = in.nextInt(); } while (!board.updateBoard(user.getSign(), cell-1)); isPlayer1 = !isPlayer1; } in.close(); } public static void main(String[] args) { Game g = new Game(); } }
true
true
public void loop() { boolean isPlayer1 = true; User user; Scanner in = new Scanner(System.in); while (board.checkWinner() == 'X') { user = (isPlayer1) ? player1 : player2; int cell; do { System.out.println(board); System.out.println(user.getName() + " - pick a cell 1-9:"); cell = in.nextInt(); } while (!board.updateBoard(user.getSign(), cell-1)); isPlayer1 = !isPlayer1; } in.close(); }
public void loop() { boolean isPlayer1 = true; User user; Scanner in = new Scanner(System.in); while (board.checkWinner() == 'x') { user = (isPlayer1) ? player1 : player2; int cell; do { System.out.println(board); System.out.println(user.getName() + " - pick a cell 1-9:"); cell = in.nextInt(); } while (!board.updateBoard(user.getSign(), cell-1)); isPlayer1 = !isPlayer1; } in.close(); }
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index 45ecfd2e7..95f89c0cc 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -1,2378 +1,2378 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import static com.android.inputmethod.latin.Constants.ImeOption.FORCE_ASCII; import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE; import static com.android.inputmethod.latin.Constants.ImeOption.NO_MICROPHONE_COMPAT; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Rect; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; import android.net.ConnectivityManager; import android.os.Debug; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.CorrectionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodSubtype; import com.android.inputmethod.accessibility.AccessibilityUtils; import com.android.inputmethod.accessibility.AccessibleKeyboardViewProxy; import com.android.inputmethod.compat.CompatUtils; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; import com.android.inputmethod.compat.InputMethodServiceCompatUtils; import com.android.inputmethod.compat.SuggestionSpanUtils; import com.android.inputmethod.keyboard.KeyDetector; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.KeyboardView; import com.android.inputmethod.keyboard.MainKeyboardView; import com.android.inputmethod.latin.LocaleUtils.RunInLocale; import com.android.inputmethod.latin.Utils.Stats; import com.android.inputmethod.latin.define.ProductionFlag; import com.android.inputmethod.latin.suggestions.SuggestionStripView; import com.android.inputmethod.research.ResearchLogger; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Locale; /** * Input method implementation for Qwerty'ish keyboard. */ public class LatinIME extends InputMethodService implements KeyboardActionListener, SuggestionStripView.Listener, TargetApplicationGetter.OnTargetApplicationKnownListener, Suggest.SuggestInitializationListener { private static final String TAG = LatinIME.class.getSimpleName(); private static final boolean TRACE = false; private static boolean DEBUG; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; private static final int PENDING_IMS_CALLBACK_DURATION = 800; /** * The name of the scheme used by the Package Manager to warn of a new package installation, * replacement or removal. */ private static final String SCHEME_PACKAGE = "package"; private static final int SPACE_STATE_NONE = 0; // Double space: the state where the user pressed space twice quickly, which LatinIME // resolved as period-space. Undoing this converts the period to a space. private static final int SPACE_STATE_DOUBLE = 1; // Swap punctuation: the state where a weak space and a punctuation from the suggestion strip // have just been swapped. Undoing this swaps them back; the space is still considered weak. private static final int SPACE_STATE_SWAP_PUNCTUATION = 2; // Weak space: a space that should be swapped only by suggestion strip punctuation. Weak // spaces happen when the user presses space, accepting the current suggestion (whether // it's an auto-correction or not). private static final int SPACE_STATE_WEAK = 3; // Phantom space: a not-yet-inserted space that should get inserted on the next input, // character provided it's not a separator. If it's a separator, the phantom space is dropped. // Phantom spaces happen when a user chooses a word from the suggestion strip. private static final int SPACE_STATE_PHANTOM = 4; // Current space state of the input method. This can be any of the above constants. private int mSpaceState; private SettingsValues mCurrentSettings; private View mExtractArea; private View mKeyPreviewBackingView; private View mSuggestionsContainer; private SuggestionStripView mSuggestionStripView; /* package for tests */ Suggest mSuggest; private CompletionInfo[] mApplicationSpecifiedCompletions; private ApplicationInfo mTargetApplicationInfo; private InputMethodManagerCompatWrapper mImm; private Resources mResources; private SharedPreferences mPrefs; /* package for tests */ final KeyboardSwitcher mKeyboardSwitcher; private final SubtypeSwitcher mSubtypeSwitcher; private boolean mShouldSwitchToLastSubtype = true; private boolean mIsMainDictionaryAvailable; private UserBinaryDictionary mUserDictionary; private UserHistoryDictionary mUserHistoryDictionary; private boolean mIsUserDictionaryAvailable; private LastComposedWord mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; private final WordComposer mWordComposer = new WordComposer(); private RichInputConnection mConnection = new RichInputConnection(this); // Keep track of the last selection range to decide if we need to show word alternatives private static final int NOT_A_CURSOR_POSITION = -1; private int mLastSelectionStart = NOT_A_CURSOR_POSITION; private int mLastSelectionEnd = NOT_A_CURSOR_POSITION; // Whether we are expecting an onUpdateSelection event to fire. If it does when we don't // "expect" it, it means the user actually moved the cursor. private boolean mExpectingUpdateSelection; private int mDeleteCount; private long mLastKeyTime; private AudioAndHapticFeedbackManager mFeedbackManager; // Member variables for remembering the current device orientation. private int mDisplayOrientation; // Object for reacting to adding/removing a dictionary pack. private BroadcastReceiver mDictionaryPackInstallReceiver = new DictionaryPackInstallBroadcastReceiver(this); // Keeps track of most recently inserted text (multi-character key) for reverting private CharSequence mEnteredText; private boolean mIsAutoCorrectionIndicatorOn; private AlertDialog mOptionsDialog; private final boolean mIsHardwareAcceleratedDrawingEnabled; public final UIHandler mHandler = new UIHandler(this); public static class UIHandler extends StaticInnerHandlerWrapper<LatinIME> { private static final int MSG_UPDATE_SHIFT_STATE = 0; private static final int MSG_PENDING_IMS_CALLBACK = 1; private static final int MSG_UPDATE_SUGGESTION_STRIP = 2; private static final int MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 3; private static final int ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT = 1; private int mDelayUpdateSuggestions; private int mDelayUpdateShiftState; private long mDoubleSpacesTurnIntoPeriodTimeout; private long mDoubleSpaceTimerStart; public UIHandler(final LatinIME outerInstance) { super(outerInstance); } public void onCreate() { final Resources res = getOuterInstance().getResources(); mDelayUpdateSuggestions = res.getInteger(R.integer.config_delay_update_suggestions); mDelayUpdateShiftState = res.getInteger(R.integer.config_delay_update_shift_state); mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger( R.integer.config_double_spaces_turn_into_period_timeout); } @Override public void handleMessage(final Message msg) { final LatinIME latinIme = getOuterInstance(); final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; switch (msg.what) { case MSG_UPDATE_SUGGESTION_STRIP: latinIme.updateSuggestionStrip(); break; case MSG_UPDATE_SHIFT_STATE: switcher.updateShiftState(); break; case MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: latinIme.showGesturePreviewAndSuggestionStrip((SuggestedWords)msg.obj, msg.arg1 == ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT); break; } } public void postUpdateSuggestionStrip() { sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTION_STRIP), mDelayUpdateSuggestions); } public void cancelUpdateSuggestionStrip() { removeMessages(MSG_UPDATE_SUGGESTION_STRIP); } public boolean hasPendingUpdateSuggestions() { return hasMessages(MSG_UPDATE_SUGGESTION_STRIP); } public void postUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState); } public void cancelUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); } public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText) { removeMessages(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP); final int arg1 = dismissGestureFloatingPreviewText ? ARG1_DISMISS_GESTURE_FLOATING_PREVIEW_TEXT : 0; obtainMessage(MSG_SHOW_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, arg1, 0, suggestedWords) .sendToTarget(); } public void startDoubleSpacesTimer() { mDoubleSpaceTimerStart = SystemClock.uptimeMillis(); } public void cancelDoubleSpacesTimer() { mDoubleSpaceTimerStart = 0; } public boolean isAcceptingDoubleSpaces() { return SystemClock.uptimeMillis() - mDoubleSpaceTimerStart < mDoubleSpacesTurnIntoPeriodTimeout; } // Working variables for the following methods. private boolean mIsOrientationChanging; private boolean mPendingSuccessiveImsCallback; private boolean mHasPendingStartInput; private boolean mHasPendingFinishInputView; private boolean mHasPendingFinishInput; private EditorInfo mAppliedEditorInfo; public void startOrientationChanging() { removeMessages(MSG_PENDING_IMS_CALLBACK); resetPendingImsCallback(); mIsOrientationChanging = true; final LatinIME latinIme = getOuterInstance(); if (latinIme.isInputViewShown()) { latinIme.mKeyboardSwitcher.saveKeyboardState(); } } private void resetPendingImsCallback() { mHasPendingFinishInputView = false; mHasPendingFinishInput = false; mHasPendingStartInput = false; } private void executePendingImsCallback(final LatinIME latinIme, final EditorInfo editorInfo, boolean restarting) { if (mHasPendingFinishInputView) latinIme.onFinishInputViewInternal(mHasPendingFinishInput); if (mHasPendingFinishInput) latinIme.onFinishInputInternal(); if (mHasPendingStartInput) latinIme.onStartInputInternal(editorInfo, restarting); resetPendingImsCallback(); } public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the second onStartInput after orientation changed. mHasPendingStartInput = true; } else { if (mIsOrientationChanging && restarting) { // This is the first onStartInput after orientation changed. mIsOrientationChanging = false; mPendingSuccessiveImsCallback = true; } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputInternal(editorInfo, restarting); } } public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK) && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { // Typically this is the second onStartInputView after orientation changed. resetPendingImsCallback(); } else { if (mPendingSuccessiveImsCallback) { // This is the first onStartInputView after orientation changed. mPendingSuccessiveImsCallback = false; resetPendingImsCallback(); sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), PENDING_IMS_CALLBACK_DURATION); } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputViewInternal(editorInfo, restarting); mAppliedEditorInfo = editorInfo; } } public void onFinishInputView(final boolean finishingInput) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInputView after orientation changed. mHasPendingFinishInputView = true; } else { final LatinIME latinIme = getOuterInstance(); latinIme.onFinishInputViewInternal(finishingInput); mAppliedEditorInfo = null; } } public void onFinishInput() { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInput after orientation changed. mHasPendingFinishInput = true; } else { final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, null, false); latinIme.onFinishInputInternal(); } } } public LatinIME() { super(); mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mIsHardwareAcceleratedDrawingEnabled = InputMethodServiceCompatUtils.enableHardwareAcceleration(this); Log.i(TAG, "Hardware accelerated drawing: " + mIsHardwareAcceleratedDrawingEnabled); } @Override public void onCreate() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs = prefs; LatinImeLogger.init(this, prefs); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.getInstance().init(this, prefs); } InputMethodManagerCompatWrapper.init(this); SubtypeSwitcher.init(this); KeyboardSwitcher.init(this, prefs); AccessibilityUtils.init(this); super.onCreate(); mImm = InputMethodManagerCompatWrapper.getInstance(); mHandler.onCreate(); DEBUG = LatinImeLogger.sDBG; final Resources res = getResources(); mResources = res; loadSettings(); ImfUtils.setAdditionalInputMethodSubtypes(this, mCurrentSettings.getAdditionalSubtypes()); initSuggest(); mDisplayOrientation = res.getConfiguration().orientation; // Register to receive ringer mode change and network state change. // Also receive installation and removal of a dictionary pack. final IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); registerReceiver(mReceiver, filter); final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); packageFilter.addDataScheme(SCHEME_PACKAGE); registerReceiver(mDictionaryPackInstallReceiver, packageFilter); final IntentFilter newDictFilter = new IntentFilter(); newDictFilter.addAction( DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION); registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); } // Has to be package-visible for unit tests /* package for test */ void loadSettings() { // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() // is not guaranteed. It may even be called at the same time on a different thread. if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); final InputAttributes inputAttributes = new InputAttributes(getCurrentInputEditorInfo(), isFullscreenMode()); final RunInLocale<SettingsValues> job = new RunInLocale<SettingsValues>() { @Override protected SettingsValues job(Resources res) { return new SettingsValues(mPrefs, inputAttributes, LatinIME.this); } }; mCurrentSettings = job.runInLocale(mResources, mSubtypeSwitcher.getCurrentSubtypeLocale()); mFeedbackManager = new AudioAndHapticFeedbackManager(this, mCurrentSettings); resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); } // Note that this method is called from a non-UI thread. @Override public void onUpdateMainDictionaryAvailability(final boolean isMainDictionaryAvailable) { mIsMainDictionaryAvailable = isMainDictionaryAvailable; final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.setMainDictionaryAvailability(isMainDictionaryAvailable); } } private void initSuggest() { final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); final String localeStr = subtypeLocale.toString(); final ContactsBinaryDictionary oldContactsDictionary; if (mSuggest != null) { oldContactsDictionary = mSuggest.getContactsDictionary(); mSuggest.close(); } else { oldContactsDictionary = null; } mSuggest = new Suggest(this /* Context */, subtypeLocale, this /* SuggestInitializationListener */); if (mCurrentSettings.mCorrectionEnabled) { mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); } mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.getInstance().initSuggest(mSuggest); } mUserDictionary = new UserBinaryDictionary(this, localeStr); mIsUserDictionaryAvailable = mUserDictionary.isEnabled(); mSuggest.setUserDictionary(mUserDictionary); resetContactsDictionary(oldContactsDictionary); // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() // is not guaranteed. It may even be called at the same time on a different thread. if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); mUserHistoryDictionary = UserHistoryDictionary.getInstance(this, localeStr, mPrefs); mSuggest.setUserHistoryDictionary(mUserHistoryDictionary); } /** * Resets the contacts dictionary in mSuggest according to the user settings. * * This method takes an optional contacts dictionary to use when the locale hasn't changed * since the contacts dictionary can be opened or closed as necessary depending on the settings. * * @param oldContactsDictionary an optional dictionary to use, or null */ private void resetContactsDictionary(final ContactsBinaryDictionary oldContactsDictionary) { final boolean shouldSetDictionary = (null != mSuggest && mCurrentSettings.mUseContactsDict); final ContactsBinaryDictionary dictionaryToUse; if (!shouldSetDictionary) { // Make sure the dictionary is closed. If it is already closed, this is a no-op, // so it's safe to call it anyways. if (null != oldContactsDictionary) oldContactsDictionary.close(); dictionaryToUse = null; } else { final Locale locale = mSubtypeSwitcher.getCurrentSubtypeLocale(); if (null != oldContactsDictionary) { if (!oldContactsDictionary.mLocale.equals(locale)) { // If the locale has changed then recreate the contacts dictionary. This // allows locale dependent rules for handling bigram name predictions. oldContactsDictionary.close(); dictionaryToUse = new ContactsBinaryDictionary(this, locale); } else { // Make sure the old contacts dictionary is opened. If it is already open, // this is a no-op, so it's safe to call it anyways. oldContactsDictionary.reopen(this); dictionaryToUse = oldContactsDictionary; } } else { dictionaryToUse = new ContactsBinaryDictionary(this, locale); } } if (null != mSuggest) { mSuggest.setContactsDictionary(dictionaryToUse); } } /* package private */ void resetSuggestMainDict() { final Locale subtypeLocale = mSubtypeSwitcher.getCurrentSubtypeLocale(); mSuggest.resetMainDict(this, subtypeLocale, this /* SuggestInitializationListener */); mIsMainDictionaryAvailable = DictionaryFactory.isDictionaryAvailable(this, subtypeLocale); } @Override public void onDestroy() { if (mSuggest != null) { mSuggest.close(); mSuggest = null; } unregisterReceiver(mReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); } @Override public void onConfigurationChanged(final Configuration conf) { // System locale has been changed. Needs to reload keyboard. if (mSubtypeSwitcher.onConfigurationChanged(conf, this)) { loadKeyboard(); } // If orientation changed while predicting, commit the change if (mDisplayOrientation != conf.orientation) { mDisplayOrientation = conf.orientation; mHandler.startOrientationChanging(); mConnection.beginBatchEdit(); commitTyped(LastComposedWord.NOT_A_SEPARATOR); mConnection.finishComposingText(); mConnection.endBatchEdit(); if (isShowingOptionDialog()) { mOptionsDialog.dismiss(); } } super.onConfigurationChanged(conf); } @Override public View onCreateInputView() { return mKeyboardSwitcher.onCreateInputView(mIsHardwareAcceleratedDrawingEnabled); } @Override public void setInputView(final View view) { super.setInputView(view); mExtractArea = getWindow().getWindow().getDecorView() .findViewById(android.R.id.extractArea); mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing); mSuggestionsContainer = view.findViewById(R.id.suggestions_container); mSuggestionStripView = (SuggestionStripView)view.findViewById(R.id.suggestion_strip_view); if (mSuggestionStripView != null) mSuggestionStripView.setListener(this, view); if (LatinImeLogger.sVISUALDEBUG) { mKeyPreviewBackingView.setBackgroundColor(0x10FF0000); } } @Override public void setCandidatesView(final View view) { // To ensure that CandidatesView will never be set. return; } @Override public void onStartInput(final EditorInfo editorInfo, final boolean restarting) { mHandler.onStartInput(editorInfo, restarting); } @Override public void onStartInputView(final EditorInfo editorInfo, final boolean restarting) { mHandler.onStartInputView(editorInfo, restarting); } @Override public void onFinishInputView(final boolean finishingInput) { mHandler.onFinishInputView(finishingInput); } @Override public void onFinishInput() { mHandler.onFinishInput(); } @Override public void onCurrentInputMethodSubtypeChanged(final InputMethodSubtype subtype) { // Note that the calling sequence of onCreate() and onCurrentInputMethodSubtypeChanged() // is not guaranteed. It may even be called at the same time on a different thread. mSubtypeSwitcher.updateSubtype(subtype); loadKeyboard(); } private void onStartInputInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInput(editorInfo, restarting); } @SuppressWarnings("deprecation") private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); if (LatinImeLogger.sDBG) { throw new NullPointerException("Null EditorInfo in onStartInputView()"); } return; } if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions)); Log.d(TAG, "All caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) + ", sentence caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) + ", word caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); } if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs); } if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); } if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); } mTargetApplicationInfo = TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName); if (null == mTargetApplicationInfo) { new TargetApplicationGetter(this /* context */, this /* listener */) .execute(editorInfo.packageName); } LatinImeLogger.onStartInputView(editorInfo); // In landscape mode, this method gets called without the input view being created. if (mainKeyboardView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart || mLastSelectionEnd != editorInfo.initialSelEnd; final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; if (isDifferentTextField) { final boolean currentSubtypeEnabled = mSubtypeSwitcher .updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled(); if (!currentSubtypeEnabled) { // Current subtype is disabled. Needs to update subtype and keyboard. final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype( this, mSubtypeSwitcher.getNoLanguageSubtype()); mSubtypeSwitcher.updateSubtype(newSubtype); loadKeyboard(); } } // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); mApplicationSpecifiedCompletions = null; if (isDifferentTextField || selectionChanged) { // If the selection changed, we reset the input state. Essentially, we come here with // restarting == true when the app called setText() or similar. We should reset the // state if the app set the text to something else, but keep it if it set a suggestion // or something. mEnteredText = null; resetComposingState(true /* alsoResetLastComposedWord */); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; if (mSuggestionStripView != null) { // This will set the punctuation suggestions if next word suggestion is off; // otherwise it will clear the suggestion strip. setPunctuationSuggestions(); } } - mConnection.resetCachesUponCursorMove(mLastSelectionStart); + mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart); if (isDifferentTextField) { mainKeyboardView.closing(); loadSettings(); if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) { mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); } switcher.loadKeyboard(editorInfo, mCurrentSettings); } setSuggestionStripShownInternal( isSuggestionsStripVisible(), /* needsInputViewShown */ false); mLastSelectionStart = editorInfo.initialSelStart; mLastSelectionEnd = editorInfo.initialSelEnd; // If we come here something in the text state is very likely to have changed. // We should update the shift state regardless of whether we are restarting or not, because // this is not perceived as a layout change that may be disruptive like we may have with // switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the // field gets emptied and we need to re-evaluate the shift state, but not the whole layout // which would be disruptive. // Space state must be updated before calling updateShiftState mKeyboardSwitcher.updateShiftState(); mHandler.cancelUpdateSuggestionStrip(); mHandler.cancelDoubleSpacesTimer(); mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable); mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn, mCurrentSettings.mKeyPreviewPopupDismissDelay); mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled); mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled, mCurrentSettings.mGestureFloatingPreviewTextEnabled); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } // Callback for the TargetApplicationGetter @Override public void onTargetApplicationKnown(final ApplicationInfo info) { mTargetApplicationInfo = info; } @Override public void onWindowHidden() { if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onWindowHidden(mLastSelectionStart, mLastSelectionEnd, getCurrentInputConnection()); } super.onWindowHidden(); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } } private void onFinishInputInternal() { super.onFinishInput(); LatinImeLogger.commit(); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.getInstance().latinIME_onFinishInputInternal(); } final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } } private void onFinishInputViewInternal(final boolean finishingInput) { super.onFinishInputView(finishingInput); mKeyboardSwitcher.onFinishInputView(); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.cancelAllMessages(); } // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestionStrip(); } @Override public void onUpdateSelection(final int oldSelStart, final int oldSelEnd, final int newSelStart, final int newSelEnd, final int composingSpanStart, final int composingSpanEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart, composingSpanEnd); if (DEBUG) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", lss=" + mLastSelectionStart + ", lse=" + mLastSelectionEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + composingSpanStart + ", ce=" + composingSpanEnd); } if (ProductionFlag.IS_EXPERIMENTAL) { final boolean expectingUpdateSelectionFromLogger = ResearchLogger.getAndClearLatinIMEExpectingUpdateSelection(); ResearchLogger.latinIME_onUpdateSelection(mLastSelectionStart, mLastSelectionEnd, oldSelStart, oldSelEnd, newSelStart, newSelEnd, composingSpanStart, composingSpanEnd, mExpectingUpdateSelection, expectingUpdateSelectionFromLogger, mConnection); if (expectingUpdateSelectionFromLogger) { // TODO: Investigate. Quitting now sounds wrong - we won't do the resetting work return; } } // TODO: refactor the following code to be less contrived. // "newSelStart != composingSpanEnd" || "newSelEnd != composingSpanEnd" means // that the cursor is not at the end of the composing span, or there is a selection. // "mLastSelectionStart != newSelStart" means that the cursor is not in the same place // as last time we were called (if there is a selection, it means the start hasn't // changed, so it's the end that did). final boolean selectionChanged = (newSelStart != composingSpanEnd || newSelEnd != composingSpanEnd) && mLastSelectionStart != newSelStart; // if composingSpanStart and composingSpanEnd are -1, it means there is no composing // span in the view - we can use that to narrow down whether the cursor was moved // by us or not. If we are composing a word but there is no composing span, then // we know for sure the cursor moved while we were composing and we should reset // the state. final boolean noComposingSpan = composingSpanStart == -1 && composingSpanEnd == -1; if (!mExpectingUpdateSelection && !mConnection.isBelatedExpectedUpdate(oldSelStart, newSelStart)) { // TAKE CARE: there is a race condition when we enter this test even when the user // did not explicitly move the cursor. This happens when typing fast, where two keys // turn this flag on in succession and both onUpdateSelection() calls arrive after // the second one - the first call successfully avoids this test, but the second one // enters. For the moment we rely on noComposingSpan to further reduce the impact. // TODO: the following is probably better done in resetEntireInputState(). // it should only happen when the cursor moved, and the very purpose of the // test below is to narrow down whether this happened or not. Likewise with // the call to updateShiftState. // We set this to NONE because after a cursor move, we don't want the space // state-related special processing to kick in. mSpaceState = SPACE_STATE_NONE; if ((!mWordComposer.isComposingWord()) || selectionChanged || noComposingSpan) { resetEntireInputState(newSelStart); } mKeyboardSwitcher.updateShiftState(); } mExpectingUpdateSelection = false; // TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not // here. It would probably be too expensive to call directly here but we may want to post a // message to delay it. The point would be to unify behavior between backspace to the // end of a word and manually put the pointer at the end of the word. // Make a note of the cursor position mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; } /** * This is called when the user has clicked on the extracted text view, * when running in fullscreen mode. The default implementation hides * the suggestions view when this happens, but only if the extracted text * editor has a vertical scroll bar because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return; super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the suggestions view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedCursorMovement(final int dx, final int dy) { if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) return; super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { LatinImeLogger.commit(); mKeyboardSwitcher.onHideWindow(); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } super.hideWindow(); } @Override public void onDisplayCompletions(final CompletionInfo[] applicationSpecifiedCompletions) { if (DEBUG) { Log.i(TAG, "Received completions:"); if (applicationSpecifiedCompletions != null) { for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); } } } if (!mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return; mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; if (applicationSpecifiedCompletions == null) { clearSuggestionStrip(); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onDisplayCompletions(null); } return; } final ArrayList<SuggestedWords.SuggestedWordInfo> applicationSuggestedWords = SuggestedWords.getFromApplicationSpecifiedCompletions( applicationSpecifiedCompletions); final SuggestedWords suggestedWords = new SuggestedWords( applicationSuggestedWords, false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, false /* isPunctuationSuggestions */, false /* isObsoleteSuggestions */, false /* isPrediction */); // When in fullscreen mode, show completions generated by the application final boolean isAutoCorrection = false; setSuggestionStrip(suggestedWords, isAutoCorrection); setAutoCorrectionIndicator(isAutoCorrection); // TODO: is this the right thing to do? What should we auto-correct to in // this case? This says to keep whatever the user typed. mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); setSuggestionStripShown(true); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onDisplayCompletions(applicationSpecifiedCompletions); } } private void setSuggestionStripShownInternal(final boolean shown, final boolean needsInputViewShown) { // TODO: Modify this if we support suggestions with hard keyboard if (onEvaluateInputViewShown() && mSuggestionsContainer != null) { final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); final boolean inputViewShown = (mainKeyboardView != null) ? mainKeyboardView.isShown() : false; final boolean shouldShowSuggestions = shown && (needsInputViewShown ? inputViewShown : true); if (isFullscreenMode()) { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.GONE); } else { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE); } } } private void setSuggestionStripShown(final boolean shown) { setSuggestionStripShownInternal(shown, /* needsInputViewShown */true); } private int getAdjustedBackingViewHeight() { final int currentHeight = mKeyPreviewBackingView.getHeight(); if (currentHeight > 0) { return currentHeight; } final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView == null) { return 0; } final int keyboardHeight = mainKeyboardView.getHeight(); final int suggestionsHeight = mSuggestionsContainer.getHeight(); final int displayHeight = mResources.getDisplayMetrics().heightPixels; final Rect rect = new Rect(); mKeyPreviewBackingView.getWindowVisibleDisplayFrame(rect); final int notificationBarHeight = rect.top; final int remainingHeight = displayHeight - notificationBarHeight - suggestionsHeight - keyboardHeight; final LayoutParams params = mKeyPreviewBackingView.getLayoutParams(); params.height = mSuggestionStripView.setMoreSuggestionsHeight(remainingHeight); mKeyPreviewBackingView.setLayoutParams(params); return params.height; } @Override public void onComputeInsets(final InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView == null || mSuggestionsContainer == null) { return; } final int adjustedBackingHeight = getAdjustedBackingViewHeight(); final boolean backingGone = (mKeyPreviewBackingView.getVisibility() == View.GONE); final int backingHeight = backingGone ? 0 : adjustedBackingHeight; // In fullscreen mode, the height of the extract area managed by InputMethodService should // be considered. // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0 : mSuggestionsContainer.getHeight(); final int extraHeight = extractHeight + backingHeight + suggestionsHeight; int touchY = extraHeight; // Need to set touchable region only if input view is being shown if (mainKeyboardView.isShown()) { if (mSuggestionsContainer.getVisibility() == View.VISIBLE) { touchY -= suggestionsHeight; } final int touchWidth = mainKeyboardView.getWidth(); final int touchHeight = mainKeyboardView.getHeight() + extraHeight // Extend touchable region below the keyboard. + EXTENDED_TOUCHABLE_REGION_HEIGHT; outInsets.touchableInsets = InputMethodService.Insets.TOUCHABLE_INSETS_REGION; outInsets.touchableRegion.set(0, touchY, touchWidth, touchHeight); } outInsets.contentTopInsets = touchY; outInsets.visibleTopInsets = touchY; } @Override public boolean onEvaluateFullscreenMode() { // Reread resource value here, because this method is called by framework anytime as needed. final boolean isFullscreenModeAllowed = mCurrentSettings.isFullscreenModeAllowed(getResources()); return super.onEvaluateFullscreenMode() && isFullscreenModeAllowed; } @Override public void updateFullscreenMode() { super.updateFullscreenMode(); if (mKeyPreviewBackingView == null) return; // In fullscreen mode, no need to have extra space to show the key preview. // If not, we should have extra space above the keyboard to show the key preview. mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); } // This will reset the whole input state to the starting state. It will clear // the composing word, reset the last composed word, tell the inputconnection about it. private void resetEntireInputState(final int newCursorPosition) { resetComposingState(true /* alsoResetLastComposedWord */); if (mCurrentSettings.mBigramPredictionEnabled) { clearSuggestionStrip(); } else { setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false); } mConnection.resetCachesUponCursorMove(newCursorPosition); } private void resetComposingState(final boolean alsoResetLastComposedWord) { mWordComposer.reset(); if (alsoResetLastComposedWord) mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; } private void commitTyped(final String separatorString) { if (!mWordComposer.isComposingWord()) return; final CharSequence typedWord = mWordComposer.getTypedWord(); if (typedWord.length() > 0) { mConnection.commitText(typedWord, 1); final CharSequence prevWord = addToUserHistoryDictionary(typedWord); mLastComposedWord = mWordComposer.commitWord( LastComposedWord.COMMIT_TYPE_USER_TYPED_WORD, typedWord.toString(), separatorString, prevWord); } } // Called from the KeyboardSwitcher which needs to know auto caps state to display // the right layout. public int getCurrentAutoCapsState() { if (!mCurrentSettings.mAutoCap) return Constants.TextUtils.CAP_MODE_OFF; final EditorInfo ei = getCurrentInputEditorInfo(); if (ei == null) return Constants.TextUtils.CAP_MODE_OFF; final int inputType = ei.inputType; // Warning: this depends on mSpaceState, which may not be the most current value. If // mSpaceState gets updated later, whoever called this may need to be told about it. return mConnection.getCursorCapsMode(inputType, mSubtypeSwitcher.getCurrentSubtypeLocale(), SPACE_STATE_PHANTOM == mSpaceState); } // Factor in auto-caps and manual caps and compute the current caps mode. private int getActualCapsMode() { final int manual = mKeyboardSwitcher.getManualCapsMode(); if (manual != WordComposer.CAPS_MODE_OFF) return manual; final int auto = getCurrentAutoCapsState(); if (0 != (auto & TextUtils.CAP_MODE_CHARACTERS)) { return WordComposer.CAPS_MODE_AUTO_SHIFT_LOCKED; } if (0 != auto) return WordComposer.CAPS_MODE_AUTO_SHIFTED; return WordComposer.CAPS_MODE_OFF; } private void swapSwapperAndSpace() { CharSequence lastTwo = mConnection.getTextBeforeCursor(2, 0); // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == Keyboard.CODE_SPACE) { mConnection.deleteSurroundingText(2, 0); mConnection.commitText(lastTwo.charAt(1) + " ", 1); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_swapSwapperAndSpace(); } mKeyboardSwitcher.updateShiftState(); } } private boolean maybeDoubleSpace() { if (!mCurrentSettings.mCorrectionEnabled) return false; if (!mHandler.isAcceptingDoubleSpaces()) return false; final CharSequence lastThree = mConnection.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && canBeFollowedByPeriod(lastThree.charAt(0)) && lastThree.charAt(1) == Keyboard.CODE_SPACE && lastThree.charAt(2) == Keyboard.CODE_SPACE) { mHandler.cancelDoubleSpacesTimer(); mConnection.deleteSurroundingText(2, 0); mConnection.commitText(". ", 1); mKeyboardSwitcher.updateShiftState(); return true; } return false; } private static boolean canBeFollowedByPeriod(final int codePoint) { // TODO: Check again whether there really ain't a better way to check this. // TODO: This should probably be language-dependant... return Character.isLetterOrDigit(codePoint) || codePoint == Keyboard.CODE_SINGLE_QUOTE || codePoint == Keyboard.CODE_DOUBLE_QUOTE || codePoint == Keyboard.CODE_CLOSING_PARENTHESIS || codePoint == Keyboard.CODE_CLOSING_SQUARE_BRACKET || codePoint == Keyboard.CODE_CLOSING_CURLY_BRACKET || codePoint == Keyboard.CODE_CLOSING_ANGLE_BRACKET; } // Callback for the {@link SuggestionStripView}, to call when the "add to dictionary" hint is // pressed. @Override public boolean addWordToUserDictionary(final String word) { mUserDictionary.addWordToUserDictionary(word, 128); return true; } private static boolean isAlphabet(final int code) { return Character.isLetter(code); } private void onSettingsKeyPressed() { if (isShowingOptionDialog()) return; showSubtypeSelectorAndSettings(); } // Virtual codes representing custom requests. These are used in onCustomRequest() below. public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1; @Override public boolean onCustomRequest(final int requestCode) { if (isShowingOptionDialog()) return false; switch (requestCode) { case CODE_SHOW_INPUT_METHOD_PICKER: if (ImfUtils.hasMultipleEnabledIMEsOrSubtypes( this, true /* include aux subtypes */)) { mImm.showInputMethodPicker(); return true; } return false; } return false; } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } private static int getActionId(final Keyboard keyboard) { return keyboard != null ? keyboard.mId.imeActionId() : EditorInfo.IME_ACTION_NONE; } private void performEditorAction(final int actionId) { mConnection.performEditorAction(actionId); } private void handleLanguageSwitchKey() { final boolean includesOtherImes = mCurrentSettings.mIncludesOtherImesInLanguageSwitchList; final IBinder token = getWindow().getWindow().getAttributes().token; if (mShouldSwitchToLastSubtype) { final InputMethodSubtype lastSubtype = mImm.getLastInputMethodSubtype(); final boolean lastSubtypeBelongsToThisIme = ImfUtils.checkIfSubtypeBelongsToThisImeAndEnabled(this, lastSubtype); if ((includesOtherImes || lastSubtypeBelongsToThisIme) && mImm.switchToLastInputMethod(token)) { mShouldSwitchToLastSubtype = false; } else { mImm.switchToNextInputMethod(token, !includesOtherImes); mShouldSwitchToLastSubtype = true; } } else { mImm.switchToNextInputMethod(token, !includesOtherImes); } } private void sendDownUpKeyEventForBackwardCompatibility(final int code) { final long eventTime = SystemClock.uptimeMillis(); mConnection.sendKeyEvent(new KeyEvent(eventTime, eventTime, KeyEvent.ACTION_DOWN, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); mConnection.sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, KeyEvent.ACTION_UP, code, 0, 0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE)); } private void sendKeyCodePoint(final int code) { // TODO: Remove this special handling of digit letters. // For backward compatibility. See {@link InputMethodService#sendKeyChar(char)}. if (code >= '0' && code <= '9') { sendDownUpKeyEventForBackwardCompatibility(code - '0' + KeyEvent.KEYCODE_0); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_sendKeyCodePoint(code); } return; } // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because // we want to be able to compile against the Ice Cream Sandwich SDK. if (Keyboard.CODE_ENTER == code && mTargetApplicationInfo != null && mTargetApplicationInfo.targetSdkVersion < 16) { // Backward compatibility mode. Before Jelly bean, the keyboard would simulate // a hardware keyboard event on pressing enter or delete. This is bad for many // reasons (there are race conditions with commits) but some applications are // relying on this behavior so we continue to support it for older apps. sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_ENTER); } else { final String text = new String(new int[] { code }, 0, 1); mConnection.commitText(text, text.length()); } } // Implementation of {@link KeyboardActionListener}. @Override public void onCodeInput(final int primaryCode, final int x, final int y) { final long when = SystemClock.uptimeMillis(); if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; mConnection.beginBatchEdit(); final KeyboardSwitcher switcher = mKeyboardSwitcher; // The space state depends only on the last character pressed and its own previous // state. Here, we revert the space state to neutral if the key is actually modifying // the input contents (any non-shift key), which is what we should do for // all inputs that do not result in a special state. Each character handling is then // free to override the state as they see fit. final int spaceState = mSpaceState; if (!mWordComposer.isComposingWord()) mIsAutoCorrectionIndicatorOn = false; // TODO: Consolidate the double space timer, mLastKeyTime, and the space state. if (primaryCode != Keyboard.CODE_SPACE) { mHandler.cancelDoubleSpacesTimer(); } boolean didAutoCorrect = false; switch (primaryCode) { case Keyboard.CODE_DELETE: mSpaceState = SPACE_STATE_NONE; handleBackspace(spaceState); mDeleteCount++; mExpectingUpdateSelection = true; mShouldSwitchToLastSubtype = true; LatinImeLogger.logOnDelete(x, y); break; case Keyboard.CODE_SHIFT: case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: // Shift and symbol key is handled in onPressKey() and onReleaseKey(). break; case Keyboard.CODE_SETTINGS: onSettingsKeyPressed(); break; case Keyboard.CODE_SHORTCUT: mSubtypeSwitcher.switchToShortcutIME(this); break; case Keyboard.CODE_ACTION_ENTER: performEditorAction(getActionId(switcher.getKeyboard())); break; case Keyboard.CODE_ACTION_NEXT: performEditorAction(EditorInfo.IME_ACTION_NEXT); break; case Keyboard.CODE_ACTION_PREVIOUS: performEditorAction(EditorInfo.IME_ACTION_PREVIOUS); break; case Keyboard.CODE_LANGUAGE_SWITCH: handleLanguageSwitchKey(); break; case Keyboard.CODE_RESEARCH: if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.getInstance().onResearchKeySelected(this); } break; default: mSpaceState = SPACE_STATE_NONE; if (mCurrentSettings.isWordSeparator(primaryCode)) { didAutoCorrect = handleSeparator(primaryCode, x, y, spaceState); } else { if (SPACE_STATE_PHANTOM == spaceState) { if (ProductionFlag.IS_INTERNAL) { if (mWordComposer.isComposingWord() && mWordComposer.isBatchMode()) { Stats.onAutoCorrection( "", mWordComposer.getTypedWord(), " ", mWordComposer); } } commitTyped(LastComposedWord.NOT_A_SEPARATOR); } final int keyX, keyY; final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); if (keyboard != null && keyboard.hasProximityCharsCorrection(primaryCode)) { keyX = x; keyY = y; } else { keyX = Constants.NOT_A_COORDINATE; keyY = Constants.NOT_A_COORDINATE; } handleCharacter(primaryCode, keyX, keyY, spaceState); } mExpectingUpdateSelection = true; mShouldSwitchToLastSubtype = true; break; } switcher.onCodeInput(primaryCode); // Reset after any single keystroke, except shift and symbol-shift if (!didAutoCorrect && primaryCode != Keyboard.CODE_SHIFT && primaryCode != Keyboard.CODE_SWITCH_ALPHA_SYMBOL) mLastComposedWord.deactivate(); if (Keyboard.CODE_DELETE != primaryCode) { mEnteredText = null; } mConnection.endBatchEdit(); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onCodeInput(primaryCode, x, y); } } // Called from PointerTracker through the KeyboardActionListener interface @Override public void onTextInput(final CharSequence rawText) { mConnection.beginBatchEdit(); if (mWordComposer.isComposingWord()) { commitCurrentAutoCorrection(rawText.toString()); } else { resetComposingState(true /* alsoResetLastComposedWord */); } mHandler.postUpdateSuggestionStrip(); final CharSequence text = specificTldProcessingOnTextInput(rawText); if (SPACE_STATE_PHANTOM == mSpaceState) { sendKeyCodePoint(Keyboard.CODE_SPACE); } mConnection.commitText(text, 1); mConnection.endBatchEdit(); // Space state must be updated before calling updateShiftState mSpaceState = SPACE_STATE_NONE; mKeyboardSwitcher.updateShiftState(); mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT); mEnteredText = text; } @Override public void onStartBatchInput() { mConnection.beginBatchEdit(); if (mWordComposer.isComposingWord()) { if (ProductionFlag.IS_INTERNAL) { if (mWordComposer.isBatchMode()) { Stats.onAutoCorrection("", mWordComposer.getTypedWord(), " ", mWordComposer); } } if (mWordComposer.size() <= 1) { // We auto-correct the previous (typed, not gestured) string iff it's one character // long. The reason for this is, even in the middle of gesture typing, you'll still // tap one-letter words and you want them auto-corrected (typically, "i" in English // should become "I"). However for any longer word, we assume that the reason for // tapping probably is that the word you intend to type is not in the dictionary, // so we do not attempt to correct, on the assumption that if that was a dictionary // word, the user would probably have gestured instead. commitCurrentAutoCorrection(LastComposedWord.NOT_A_SEPARATOR); } else { commitTyped(LastComposedWord.NOT_A_SEPARATOR); } mExpectingUpdateSelection = true; // The following is necessary for the case where the user typed something but didn't // manual pick it and didn't input any separator. mSpaceState = SPACE_STATE_PHANTOM; } mConnection.endBatchEdit(); mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode()); } private static final class BatchInputUpdater implements Handler.Callback { private final Handler mHandler; private LatinIME mLatinIme; private BatchInputUpdater() { final HandlerThread handlerThread = new HandlerThread( BatchInputUpdater.class.getSimpleName()); handlerThread.start(); mHandler = new Handler(handlerThread.getLooper(), this); } // Initialization-on-demand holder private static final class OnDemandInitializationHolder { public static final BatchInputUpdater sInstance = new BatchInputUpdater(); } public static BatchInputUpdater getInstance() { return OnDemandInitializationHolder.sInstance; } private static final int MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP = 1; @Override public boolean handleMessage(final Message msg) { switch (msg.what) { case MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP: final SuggestedWords suggestedWords = getSuggestedWordsGesture( (InputPointers)msg.obj, mLatinIme); showGesturePreviewAndSuggestionStrip( suggestedWords, false /* dismissGestureFloatingPreviewText */, mLatinIme); break; } return true; } public void updateGesturePreviewAndSuggestionStrip(final InputPointers batchPointers, final LatinIME latinIme) { mLatinIme = latinIme; if (mHandler.hasMessages(MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP)) { return; } mHandler.obtainMessage( MSG_UPDATE_GESTURE_PREVIEW_AND_SUGGESTION_STRIP, batchPointers) .sendToTarget(); } public void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText, final LatinIME latinIme) { latinIme.mHandler.showGesturePreviewAndSuggestionStrip( suggestedWords, dismissGestureFloatingPreviewText); } // {@link LatinIME#getSuggestedWords(int)} method calls with same session id have to // be synchronized. public synchronized SuggestedWords getSuggestedWordsGesture( final InputPointers batchPointers, final LatinIME latinIme) { latinIme.mWordComposer.setBatchInputPointers(batchPointers); return latinIme.getSuggestedWords(Suggest.SESSION_GESTURE); } } private void showGesturePreviewAndSuggestionStrip(final SuggestedWords suggestedWords, final boolean dismissGestureFloatingPreviewText) { final String batchInputText = (suggestedWords.size() > 0) ? suggestedWords.getWord(0) : null; final KeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); mainKeyboardView.showGestureFloatingPreviewText(batchInputText); showSuggestionStrip(suggestedWords, null); if (dismissGestureFloatingPreviewText) { mainKeyboardView.dismissGestureFloatingPreviewText(); } } @Override public void onUpdateBatchInput(final InputPointers batchPointers) { BatchInputUpdater.getInstance().updateGesturePreviewAndSuggestionStrip(batchPointers, this); } @Override public void onEndBatchInput(final InputPointers batchPointers) { final BatchInputUpdater batchInputUpdater = BatchInputUpdater.getInstance(); final SuggestedWords suggestedWords = batchInputUpdater.getSuggestedWordsGesture( batchPointers, this); batchInputUpdater.showGesturePreviewAndSuggestionStrip( suggestedWords, true /* dismissGestureFloatingPreviewText */, this); final String batchInputText = (suggestedWords.size() > 0) ? suggestedWords.getWord(0) : null; if (TextUtils.isEmpty(batchInputText)) { return; } mWordComposer.setBatchInputWord(batchInputText); mConnection.beginBatchEdit(); if (SPACE_STATE_PHANTOM == mSpaceState) { sendKeyCodePoint(Keyboard.CODE_SPACE); } mConnection.setComposingText(batchInputText, 1); mExpectingUpdateSelection = true; mConnection.endBatchEdit(); // Space state must be updated before calling updateShiftState mSpaceState = SPACE_STATE_PHANTOM; mKeyboardSwitcher.updateShiftState(); } private CharSequence specificTldProcessingOnTextInput(final CharSequence text) { if (text.length() <= 1 || text.charAt(0) != Keyboard.CODE_PERIOD || !Character.isLetter(text.charAt(1))) { // Not a tld: do nothing. return text; } // We have a TLD (or something that looks like this): make sure we don't add // a space even if currently in phantom mode. mSpaceState = SPACE_STATE_NONE; final CharSequence lastOne = mConnection.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_PERIOD) { return text.subSequence(1, text.length()); } else { return text; } } // Called from PointerTracker through the KeyboardActionListener interface @Override public void onCancelInput() { // User released a finger outside any key mKeyboardSwitcher.onCancelInput(); } private void handleBackspace(final int spaceState) { // In many cases, we may have to put the keyboard in auto-shift state again. However // we want to wait a few milliseconds before doing it to avoid the keyboard flashing // during key repeat. mHandler.postUpdateShiftState(); if (mWordComposer.isComposingWord()) { final int length = mWordComposer.size(); if (length > 0) { // Immediately after a batch input. if (SPACE_STATE_PHANTOM == spaceState) { mWordComposer.reset(); } else { mWordComposer.deleteLast(); } mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); mHandler.postUpdateSuggestionStrip(); } else { mConnection.deleteSurroundingText(1, 0); } } else { if (mLastComposedWord.canRevertCommit()) { if (ProductionFlag.IS_INTERNAL) { Stats.onAutoCorrectionCancellation(); } revertCommit(); return; } if (mEnteredText != null && mConnection.sameAsTextBeforeCursor(mEnteredText)) { // Cancel multi-character input: remove the text we just entered. // This is triggered on backspace after a key that inputs multiple characters, // like the smiley key or the .com key. final int length = mEnteredText.length(); mConnection.deleteSurroundingText(length, 0); mEnteredText = null; // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. // In addition we know that spaceState is false, and that we should not be // reverting any autocorrect at this point. So we can safely return. return; } if (SPACE_STATE_DOUBLE == spaceState) { mHandler.cancelDoubleSpacesTimer(); if (mConnection.revertDoubleSpace()) { // No need to reset mSpaceState, it has already be done (that's why we // receive it as a parameter) return; } } else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) { if (mConnection.revertSwapPunctuation()) { // Likewise return; } } // No cancelling of commit/double space/swap: we have a regular backspace. // We should backspace one char and restart suggestion if at the end of a word. if (mLastSelectionStart != mLastSelectionEnd) { // If there is a selection, remove it. final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart; mConnection.setSelection(mLastSelectionEnd, mLastSelectionEnd); mConnection.deleteSurroundingText(lengthToDelete, 0); } else { // There is no selection, just delete one character. if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) { // This should never happen. Log.e(TAG, "Backspace when we don't know the selection position"); } // 16 is android.os.Build.VERSION_CODES.JELLY_BEAN but we can't write it because // we want to be able to compile against the Ice Cream Sandwich SDK. if (mTargetApplicationInfo != null && mTargetApplicationInfo.targetSdkVersion < 16) { // Backward compatibility mode. Before Jelly bean, the keyboard would simulate // a hardware keyboard event on pressing enter or delete. This is bad for many // reasons (there are race conditions with commits) but some applications are // relying on this behavior so we continue to support it for older apps. sendDownUpKeyEventForBackwardCompatibility(KeyEvent.KEYCODE_DEL); } else { mConnection.deleteSurroundingText(1, 0); } if (mDeleteCount > DELETE_ACCELERATE_AT) { mConnection.deleteSurroundingText(1, 0); } } if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { restartSuggestionsOnWordBeforeCursorIfAtEndOfWord(); } } } private boolean maybeStripSpace(final int code, final int spaceState, final boolean isFromSuggestionStrip) { if (Keyboard.CODE_ENTER == code && SPACE_STATE_SWAP_PUNCTUATION == spaceState) { mConnection.removeTrailingSpace(); return false; } else if ((SPACE_STATE_WEAK == spaceState || SPACE_STATE_SWAP_PUNCTUATION == spaceState) && isFromSuggestionStrip) { if (mCurrentSettings.isWeakSpaceSwapper(code)) { return true; } else { if (mCurrentSettings.isWeakSpaceStripper(code)) { mConnection.removeTrailingSpace(); } return false; } } else { return false; } } private void handleCharacter(final int primaryCode, final int x, final int y, final int spaceState) { boolean isComposingWord = mWordComposer.isComposingWord(); if (SPACE_STATE_PHANTOM == spaceState && !mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) { if (isComposingWord) { // Sanity check throw new RuntimeException("Should not be composing here"); } sendKeyCodePoint(Keyboard.CODE_SPACE); } // NOTE: isCursorTouchingWord() is a blocking IPC call, so it often takes several // dozen milliseconds. Avoid calling it as much as possible, since we are on the UI // thread here. if (!isComposingWord && (isAlphabet(primaryCode) || mCurrentSettings.isSymbolExcludedFromWordSeparators(primaryCode)) && mCurrentSettings.isSuggestionsRequested(mDisplayOrientation) && !mConnection.isCursorTouchingWord(mCurrentSettings)) { // Reset entirely the composing state anyway, then start composing a new word unless // the character is a single quote. The idea here is, single quote is not a // separator and it should be treated as a normal character, except in the first // position where it should not start composing a word. isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != primaryCode); // Here we don't need to reset the last composed word. It will be reset // when we commit this one, if we ever do; if on the other hand we backspace // it entirely and resume suggestions on the previous word, we'd like to still // have touch coordinates for it. resetComposingState(false /* alsoResetLastComposedWord */); } if (isComposingWord) { final int keyX, keyY; if (KeyboardActionListener.Adapter.isInvalidCoordinate(x) || KeyboardActionListener.Adapter.isInvalidCoordinate(y)) { keyX = x; keyY = y; } else { final KeyDetector keyDetector = mKeyboardSwitcher.getMainKeyboardView().getKeyDetector(); keyX = keyDetector.getTouchX(x); keyY = keyDetector.getTouchY(y); } mWordComposer.add(primaryCode, keyX, keyY); // If it's the first letter, make note of auto-caps state if (mWordComposer.size() == 1) { mWordComposer.setCapitalizedModeAtStartComposingTime(getActualCapsMode()); } mConnection.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); } else { final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x); sendKeyCodePoint(primaryCode); if (swapWeakSpace) { swapSwapperAndSpace(); mSpaceState = SPACE_STATE_WEAK; } // In case the "add to dictionary" hint was still displayed. if (null != mSuggestionStripView) mSuggestionStripView.dismissAddToDictionaryHint(); } mHandler.postUpdateSuggestionStrip(); if (ProductionFlag.IS_INTERNAL) { Utils.Stats.onNonSeparator((char)primaryCode, x, y); } } // Returns true if we did an autocorrection, false otherwise. private boolean handleSeparator(final int primaryCode, final int x, final int y, final int spaceState) { boolean didAutoCorrect = false; // Handle separator if (mWordComposer.isComposingWord()) { if (mCurrentSettings.mCorrectionEnabled) { // TODO: maybe cache Strings in an <String> sparse array or something commitCurrentAutoCorrection(new String(new int[]{primaryCode}, 0, 1)); didAutoCorrect = true; } else { commitTyped(new String(new int[]{primaryCode}, 0, 1)); } } final boolean swapWeakSpace = maybeStripSpace(primaryCode, spaceState, Constants.SUGGESTION_STRIP_COORDINATE == x); if (SPACE_STATE_PHANTOM == spaceState && mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) { sendKeyCodePoint(Keyboard.CODE_SPACE); } sendKeyCodePoint(primaryCode); if (Keyboard.CODE_SPACE == primaryCode) { if (mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { if (maybeDoubleSpace()) { mSpaceState = SPACE_STATE_DOUBLE; } else if (!isShowingPunctuationList()) { mSpaceState = SPACE_STATE_WEAK; } } mHandler.startDoubleSpacesTimer(); if (!mConnection.isCursorTouchingWord(mCurrentSettings)) { mHandler.postUpdateSuggestionStrip(); } } else { if (swapWeakSpace) { swapSwapperAndSpace(); mSpaceState = SPACE_STATE_SWAP_PUNCTUATION; } else if (SPACE_STATE_PHANTOM == spaceState && !mCurrentSettings.isWeakSpaceStripper(primaryCode) && !mCurrentSettings.isPhantomSpacePromotingSymbol(primaryCode)) { // If we are in phantom space state, and the user presses a separator, we want to // stay in phantom space state so that the next keypress has a chance to add the // space. For example, if I type "Good dat", pick "day" from the suggestion strip // then insert a comma and go on to typing the next word, I want the space to be // inserted automatically before the next word, the same way it is when I don't // input the comma. // The case is a little different if the separator is a space stripper. Such a // separator does not normally need a space on the right (that's the difference // between swappers and strippers), so we should not stay in phantom space state if // the separator is a stripper. Hence the additional test above. mSpaceState = SPACE_STATE_PHANTOM; } // Set punctuation right away. onUpdateSelection will fire but tests whether it is // already displayed or not, so it's okay. setPunctuationSuggestions(); } if (ProductionFlag.IS_INTERNAL) { Utils.Stats.onSeparator((char)primaryCode, x, y); } mKeyboardSwitcher.updateShiftState(); return didAutoCorrect; } private CharSequence getTextWithUnderline(final CharSequence text) { return mIsAutoCorrectionIndicatorOn ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text) : text; } private void handleClose() { commitTyped(LastComposedWord.NOT_A_SEPARATOR); requestHideSelf(0); final MainKeyboardView mainKeyboardView = mKeyboardSwitcher.getMainKeyboardView(); if (mainKeyboardView != null) { mainKeyboardView.closing(); } } // TODO: make this private // Outside LatinIME, only used by the test suite. /* package for tests */ boolean isShowingPunctuationList() { if (mSuggestionStripView == null) return false; return mCurrentSettings.mSuggestPuncList == mSuggestionStripView.getSuggestions(); } private boolean isSuggestionsStripVisible() { if (mSuggestionStripView == null) return false; if (mSuggestionStripView.isShowingAddToDictionaryHint()) return true; if (!mCurrentSettings.isSuggestionStripVisibleInOrientation(mDisplayOrientation)) return false; if (mCurrentSettings.isApplicationSpecifiedCompletionsOn()) return true; return mCurrentSettings.isSuggestionsRequested(mDisplayOrientation); } private void clearSuggestionStrip() { setSuggestionStrip(SuggestedWords.EMPTY, false); setAutoCorrectionIndicator(false); } private void setSuggestionStrip(final SuggestedWords words, final boolean isAutoCorrection) { if (mSuggestionStripView != null) { mSuggestionStripView.setSuggestions(words); mKeyboardSwitcher.onAutoCorrectionStateChanged(isAutoCorrection); } } private void setAutoCorrectionIndicator(final boolean newAutoCorrectionIndicator) { // Put a blue underline to a word in TextView which will be auto-corrected. if (mIsAutoCorrectionIndicatorOn != newAutoCorrectionIndicator && mWordComposer.isComposingWord()) { mIsAutoCorrectionIndicatorOn = newAutoCorrectionIndicator; final CharSequence textWithUnderline = getTextWithUnderline(mWordComposer.getTypedWord()); mConnection.setComposingText(textWithUnderline, 1); } } private void updateSuggestionStrip() { mHandler.cancelUpdateSuggestionStrip(); // Check if we have a suggestion engine attached. if (mSuggest == null || !mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)) { if (mWordComposer.isComposingWord()) { Log.w(TAG, "Called updateSuggestionsOrPredictions but suggestions were not " + "requested!"); mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); } return; } if (!mWordComposer.isComposingWord() && !mCurrentSettings.mBigramPredictionEnabled) { setPunctuationSuggestions(); return; } final SuggestedWords suggestedWords = getSuggestedWords(Suggest.SESSION_TYPING); final String typedWord = mWordComposer.getTypedWord(); showSuggestionStrip(suggestedWords, typedWord); } private SuggestedWords getSuggestedWords(final int sessionId) { final String typedWord = mWordComposer.getTypedWord(); // Get the word on which we should search the bigrams. If we are composing a word, it's // whatever is *before* the half-committed word in the buffer, hence 2; if we aren't, we // should just skip whitespace if any, so 1. // TODO: this is slow (2-way IPC) - we should probably cache this instead. final CharSequence prevWord = mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, mWordComposer.isComposingWord() ? 2 : 1); final SuggestedWords suggestedWords = mSuggest.getSuggestedWords(mWordComposer, prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(), mCurrentSettings.mCorrectionEnabled, sessionId); return maybeRetrieveOlderSuggestions(typedWord, suggestedWords); } private SuggestedWords maybeRetrieveOlderSuggestions(final CharSequence typedWord, final SuggestedWords suggestedWords) { // TODO: consolidate this into getSuggestedWords // We update the suggestion strip only when we have some suggestions to show, i.e. when // the suggestion count is > 1; else, we leave the old suggestions, with the typed word // replaced with the new one. However, when the word is a dictionary word, or when the // length of the typed word is 1 or 0 (after a deletion typically), we do want to remove the // old suggestions. Also, if we are showing the "add to dictionary" hint, we need to // revert to suggestions - although it is unclear how we can come here if it's displayed. if (suggestedWords.size() > 1 || typedWord.length() <= 1 || !suggestedWords.mTypedWordValid || mSuggestionStripView.isShowingAddToDictionaryHint()) { return suggestedWords; } else { SuggestedWords previousSuggestions = mSuggestionStripView.getSuggestions(); if (previousSuggestions == mCurrentSettings.mSuggestPuncList) { previousSuggestions = SuggestedWords.EMPTY; } final ArrayList<SuggestedWords.SuggestedWordInfo> typedWordAndPreviousSuggestions = SuggestedWords.getTypedWordAndPreviousSuggestions( typedWord, previousSuggestions); return new SuggestedWords(typedWordAndPreviousSuggestions, false /* typedWordValid */, false /* hasAutoCorrectionCandidate */, false /* isPunctuationSuggestions */, true /* isObsoleteSuggestions */, false /* isPrediction */); } } private void showSuggestionStrip(final SuggestedWords suggestedWords, final CharSequence typedWord) { if (null == suggestedWords || suggestedWords.size() <= 0) { clearSuggestionStrip(); return; } final CharSequence autoCorrection; if (suggestedWords.size() > 0) { if (suggestedWords.mWillAutoCorrect) { autoCorrection = suggestedWords.getWord(1); } else { autoCorrection = typedWord; } } else { autoCorrection = null; } mWordComposer.setAutoCorrection(autoCorrection); final boolean isAutoCorrection = suggestedWords.willAutoCorrect(); setSuggestionStrip(suggestedWords, isAutoCorrection); setAutoCorrectionIndicator(isAutoCorrection); setSuggestionStripShown(isSuggestionsStripVisible()); } private void commitCurrentAutoCorrection(final String separatorString) { // Complete any pending suggestions query first if (mHandler.hasPendingUpdateSuggestions()) { updateSuggestionStrip(); } final CharSequence typedAutoCorrection = mWordComposer.getAutoCorrectionOrNull(); final String typedWord = mWordComposer.getTypedWord(); final CharSequence autoCorrection = (typedAutoCorrection != null) ? typedAutoCorrection : typedWord; if (autoCorrection != null) { if (TextUtils.isEmpty(typedWord)) { throw new RuntimeException("We have an auto-correction but the typed word " + "is empty? Impossible! I must commit suicide."); } if (ProductionFlag.IS_INTERNAL) { Stats.onAutoCorrection( typedWord, autoCorrection.toString(), separatorString, mWordComposer); } mExpectingUpdateSelection = true; commitChosenWord(autoCorrection, LastComposedWord.COMMIT_TYPE_DECIDED_WORD, separatorString); if (!typedWord.equals(autoCorrection)) { // This will make the correction flash for a short while as a visual clue // to the user that auto-correction happened. It has no other effect; in particular // note that this won't affect the text inside the text field AT ALL: it only makes // the segment of text starting at the supplied index and running for the length // of the auto-correction flash. At this moment, the "typedWord" argument is // ignored by TextView. mConnection.commitCorrection( new CorrectionInfo(mLastSelectionEnd - typedWord.length(), typedWord, autoCorrection)); } } } // Called from {@link SuggestionStripView} through the {@link SuggestionStripView#Listener} // interface @Override public void pickSuggestionManually(final int index, final CharSequence suggestion) { final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions(); // If this is a punctuation picked from the suggestion strip, pass it to onCodeInput if (suggestion.length() == 1 && isShowingPunctuationList()) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion("", suggestion.toString(), index, suggestedWords); // Rely on onCodeInput to do the complicated swapping/stripping logic consistently. final int primaryCode = suggestion.charAt(0); onCodeInput(primaryCode, Constants.SUGGESTION_STRIP_COORDINATE, Constants.SUGGESTION_STRIP_COORDINATE); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_punctuationSuggestion(index, suggestion); } return; } mConnection.beginBatchEdit(); if (SPACE_STATE_PHANTOM == mSpaceState && suggestion.length() > 0 // In the batch input mode, a manually picked suggested word should just replace // the current batch input text and there is no need for a phantom space. && !mWordComposer.isBatchMode()) { int firstChar = Character.codePointAt(suggestion, 0); if ((!mCurrentSettings.isWeakSpaceStripper(firstChar)) && (!mCurrentSettings.isWeakSpaceSwapper(firstChar))) { sendKeyCodePoint(Keyboard.CODE_SPACE); } } if (mCurrentSettings.isApplicationSpecifiedCompletionsOn() && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { if (mSuggestionStripView != null) { mSuggestionStripView.clear(); } mKeyboardSwitcher.updateShiftState(); resetComposingState(true /* alsoResetLastComposedWord */); final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; mConnection.commitCompletion(completionInfo); mConnection.endBatchEdit(); return; } // We need to log before we commit, because the word composer will store away the user // typed word. final String replacedWord = mWordComposer.getTypedWord().toString(); LatinImeLogger.logOnManualSuggestion(replacedWord, suggestion.toString(), index, suggestedWords); mExpectingUpdateSelection = true; commitChosenWord(suggestion, LastComposedWord.COMMIT_TYPE_MANUAL_PICK, LastComposedWord.NOT_A_SEPARATOR); if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_pickSuggestionManually(replacedWord, index, suggestion); } mConnection.endBatchEdit(); // Don't allow cancellation of manual pick mLastComposedWord.deactivate(); // Space state must be updated before calling updateShiftState mSpaceState = SPACE_STATE_PHANTOM; mKeyboardSwitcher.updateShiftState(); // We should show the "Touch again to save" hint if the user pressed the first entry // AND it's in none of our current dictionaries (main, user or otherwise). // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If the suggestion is not in the dictionary, the hint should be shown. && !AutoCorrection.isValidWord(mSuggest.getUnigramDictionaries(), suggestion, true); if (ProductionFlag.IS_INTERNAL) { Stats.onSeparator((char)Keyboard.CODE_SPACE, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); } if (showingAddToDictionaryHint && mIsUserDictionaryAvailable) { mSuggestionStripView.showAddToDictionaryHint( suggestion, mCurrentSettings.mHintToSaveText); } else { // If we're not showing the "Touch again to save", then update the suggestion strip. mHandler.postUpdateSuggestionStrip(); } } /** * Commits the chosen word to the text field and saves it for later retrieval. */ private void commitChosenWord(final CharSequence chosenWord, final int commitType, final String separatorString) { final SuggestedWords suggestedWords = mSuggestionStripView.getSuggestions(); mConnection.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan( this, chosenWord, suggestedWords, mIsMainDictionaryAvailable), 1); // Add the word to the user history dictionary final CharSequence prevWord = addToUserHistoryDictionary(chosenWord); // TODO: figure out here if this is an auto-correct or if the best word is actually // what user typed. Note: currently this is done much later in // LastComposedWord#didCommitTypedWord by string equality of the remembered // strings. mLastComposedWord = mWordComposer.commitWord(commitType, chosenWord.toString(), separatorString, prevWord); } private void setPunctuationSuggestions() { if (mCurrentSettings.mBigramPredictionEnabled) { clearSuggestionStrip(); } else { setSuggestionStrip(mCurrentSettings.mSuggestPuncList, false); } setAutoCorrectionIndicator(false); setSuggestionStripShown(isSuggestionsStripVisible()); } private CharSequence addToUserHistoryDictionary(final CharSequence suggestion) { if (TextUtils.isEmpty(suggestion)) return null; if (mSuggest == null) return null; // If correction is not enabled, we don't add words to the user history dictionary. // That's to avoid unintended additions in some sensitive fields, or fields that // expect to receive non-words. if (!mCurrentSettings.mCorrectionEnabled) return null; final UserHistoryDictionary userHistoryDictionary = mUserHistoryDictionary; if (userHistoryDictionary != null) { final CharSequence prevWord = mConnection.getNthPreviousWord(mCurrentSettings.mWordSeparators, 2); final String secondWord; if (mWordComposer.wasAutoCapitalized() && !mWordComposer.isMostlyCaps()) { secondWord = suggestion.toString().toLowerCase( mSubtypeSwitcher.getCurrentSubtypeLocale()); } else { secondWord = suggestion.toString(); } // We demote unrecognized words (frequency < 0, below) by specifying them as "invalid". // We don't add words with 0-frequency (assuming they would be profanity etc.). final int maxFreq = AutoCorrection.getMaxFrequency( mSuggest.getUnigramDictionaries(), suggestion); if (maxFreq == 0) return null; userHistoryDictionary.addToUserHistory(null == prevWord ? null : prevWord.toString(), secondWord, maxFreq > 0); return prevWord; } return null; } /** * Check if the cursor is actually at the end of a word. If so, restart suggestions on this * word, else do nothing. */ private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() { final CharSequence word = mConnection.getWordBeforeCursorIfAtEndOfWord(mCurrentSettings); if (null != word) { restartSuggestionsOnWordBeforeCursor(word); } } private void restartSuggestionsOnWordBeforeCursor(final CharSequence word) { mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard()); final int length = word.length(); mConnection.deleteSurroundingText(length, 0); mConnection.setComposingText(word, 1); mHandler.postUpdateSuggestionStrip(); } private void revertCommit() { final CharSequence previousWord = mLastComposedWord.mPrevWord; final String originallyTypedWord = mLastComposedWord.mTypedWord; final CharSequence committedWord = mLastComposedWord.mCommittedWord; final int cancelLength = committedWord.length(); final int separatorLength = LastComposedWord.getSeparatorLength( mLastComposedWord.mSeparatorString); // TODO: should we check our saved separator against the actual contents of the text view? final int deleteLength = cancelLength + separatorLength; if (DEBUG) { if (mWordComposer.isComposingWord()) { throw new RuntimeException("revertCommit, but we are composing a word"); } final String wordBeforeCursor = mConnection.getTextBeforeCursor(deleteLength, 0) .subSequence(0, cancelLength).toString(); if (!TextUtils.equals(committedWord, wordBeforeCursor)) { throw new RuntimeException("revertCommit check failed: we thought we were " + "reverting \"" + committedWord + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); } } mConnection.deleteSurroundingText(deleteLength, 0); if (!TextUtils.isEmpty(previousWord) && !TextUtils.isEmpty(committedWord)) { mUserHistoryDictionary.cancelAddingUserHistory( previousWord.toString(), committedWord.toString()); } mConnection.commitText(originallyTypedWord + mLastComposedWord.mSeparatorString, 1); if (ProductionFlag.IS_INTERNAL) { Stats.onSeparator(mLastComposedWord.mSeparatorString, Constants.NOT_A_COORDINATE, Constants.NOT_A_COORDINATE); } if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_revertCommit(originallyTypedWord); } // Don't restart suggestion yet. We'll restart if the user deletes the // separator. mLastComposedWord = LastComposedWord.NOT_A_COMPOSED_WORD; // We have a separator between the word and the cursor: we should show predictions. mHandler.postUpdateSuggestionStrip(); } // Used by the RingCharBuffer public boolean isWordSeparator(final int code) { return mCurrentSettings.isWordSeparator(code); } // TODO: Make this private // Outside LatinIME, only used by the {@link InputTestsBase} test suite. /* package for test */ void loadKeyboard() { // When the device locale is changed in SetupWizard etc., this method may get called via // onConfigurationChanged before SoftInputWindow is shown. initSuggest(); loadSettings(); if (mKeyboardSwitcher.getMainKeyboardView() != null) { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mCurrentSettings); } // Since we just changed languages, we should re-evaluate suggestions with whatever word // we are currently composing. If we are not composing anything, we may want to display // predictions or punctuation signs (which is done by the updateSuggestionStrip anyway). mHandler.postUpdateSuggestionStrip(); } // TODO: Remove this method from {@link LatinIME} and move {@link FeedbackManager} to // {@link KeyboardSwitcher}. Called from KeyboardSwitcher public void hapticAndAudioFeedback(final int primaryCode) { mFeedbackManager.hapticAndAudioFeedback( primaryCode, mKeyboardSwitcher.getMainKeyboardView()); } // Callback called by PointerTracker through the KeyboardActionListener. This is called when a // key is depressed; release matching call is onReleaseKey below. @Override public void onPressKey(final int primaryCode) { mKeyboardSwitcher.onPressKey(primaryCode); } // Callback by PointerTracker through the KeyboardActionListener. This is called when a key // is released; press matching call is onPressKey above. @Override public void onReleaseKey(final int primaryCode, final boolean withSliding) { mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding); // If accessibility is on, ensure the user receives keyboard state updates. if (AccessibilityUtils.getInstance().isTouchExplorationEnabled()) { switch (primaryCode) { case Keyboard.CODE_SHIFT: AccessibleKeyboardViewProxy.getInstance().notifyShiftState(); break; case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: AccessibleKeyboardViewProxy.getInstance().notifySymbolsState(); break; } } if (Keyboard.CODE_DELETE == primaryCode) { // This is a stopgap solution to avoid leaving a high surrogate alone in a text view. // In the future, we need to deprecate deteleSurroundingText() and have a surrogate // pair-friendly way of deleting characters in InputConnection. final CharSequence lastChar = mConnection.getTextBeforeCursor(1, 0); if (!TextUtils.isEmpty(lastChar) && Character.isHighSurrogate(lastChar.charAt(0))) { mConnection.deleteSurroundingText(1, 0); } } } // receive ringer mode change and network state change. private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { final String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { mSubtypeSwitcher.onNetworkStateChanged(intent); } else if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { mFeedbackManager.onRingerModeChanged(); } } }; private void launchSettings() { handleClose(); launchSubActivity(SettingsActivity.class); } // Called from debug code only public void launchDebugSettings() { handleClose(); launchSubActivity(DebugSettingsActivity.class); } public void launchKeyboardedDialogActivity(final Class<? extends Activity> activityClass) { // Put the text in the attached EditText into a safe, saved state before switching to a // new activity that will also use the soft keyboard. commitTyped(LastComposedWord.NOT_A_SEPARATOR); launchSubActivity(activityClass); } private void launchSubActivity(final Class<? extends Activity> activityClass) { Intent intent = new Intent(); intent.setClass(LatinIME.this, activityClass); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { // TODO: Should use new string "Select active input modes". getString(R.string.language_selection_title), getString(R.string.english_ime_settings), }; final Context context = this; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: Intent intent = CompatUtils.getInputLanguageSelectionIntent( ImfUtils.getInputMethodIdOfThisIme(context), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(items, listener) .setTitle(title); showOptionDialog(builder.create()); } public void showOptionDialog(final AlertDialog dialog) { final IBinder windowToken = mKeyboardSwitcher.getMainKeyboardView().getWindowToken(); if (windowToken == null) { return; } dialog.setCancelable(true); dialog.setCanceledOnTouchOutside(true); final Window window = dialog.getWindow(); final WindowManager.LayoutParams lp = window.getAttributes(); lp.token = windowToken; lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog = dialog; dialog.show(); } public void debugDumpStateAndCrashWithException(final String context) { final StringBuilder s = new StringBuilder(); s.append("Target application : ").append(mTargetApplicationInfo.name) .append("\nPackage : ").append(mTargetApplicationInfo.packageName) .append("\nTarget app sdk version : ") .append(mTargetApplicationInfo.targetSdkVersion) .append("\nAttributes : ").append(mCurrentSettings.getInputAttributesDebugString()) .append("\nContext : ").append(context); throw new RuntimeException(s.toString()); } @Override protected void dump(final FileDescriptor fd, final PrintWriter fout, final String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; p.println(" Keyboard mode = " + keyboardMode); p.println(" mIsSuggestionsSuggestionsRequested = " + mCurrentSettings.isSuggestionsRequested(mDisplayOrientation)); p.println(" mCorrectionEnabled=" + mCurrentSettings.mCorrectionEnabled); p.println(" isComposingWord=" + mWordComposer.isComposingWord()); p.println(" mSoundOn=" + mCurrentSettings.mSoundOn); p.println(" mVibrateOn=" + mCurrentSettings.mVibrateOn); p.println(" mKeyPreviewPopupOn=" + mCurrentSettings.mKeyPreviewPopupOn); p.println(" inputAttributes=" + mCurrentSettings.getInputAttributesDebugString()); } }
true
true
private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); if (LatinImeLogger.sDBG) { throw new NullPointerException("Null EditorInfo in onStartInputView()"); } return; } if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions)); Log.d(TAG, "All caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) + ", sentence caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) + ", word caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); } if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs); } if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); } if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); } mTargetApplicationInfo = TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName); if (null == mTargetApplicationInfo) { new TargetApplicationGetter(this /* context */, this /* listener */) .execute(editorInfo.packageName); } LatinImeLogger.onStartInputView(editorInfo); // In landscape mode, this method gets called without the input view being created. if (mainKeyboardView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart || mLastSelectionEnd != editorInfo.initialSelEnd; final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; if (isDifferentTextField) { final boolean currentSubtypeEnabled = mSubtypeSwitcher .updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled(); if (!currentSubtypeEnabled) { // Current subtype is disabled. Needs to update subtype and keyboard. final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype( this, mSubtypeSwitcher.getNoLanguageSubtype()); mSubtypeSwitcher.updateSubtype(newSubtype); loadKeyboard(); } } // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); mApplicationSpecifiedCompletions = null; if (isDifferentTextField || selectionChanged) { // If the selection changed, we reset the input state. Essentially, we come here with // restarting == true when the app called setText() or similar. We should reset the // state if the app set the text to something else, but keep it if it set a suggestion // or something. mEnteredText = null; resetComposingState(true /* alsoResetLastComposedWord */); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; if (mSuggestionStripView != null) { // This will set the punctuation suggestions if next word suggestion is off; // otherwise it will clear the suggestion strip. setPunctuationSuggestions(); } } mConnection.resetCachesUponCursorMove(mLastSelectionStart); if (isDifferentTextField) { mainKeyboardView.closing(); loadSettings(); if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) { mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); } switcher.loadKeyboard(editorInfo, mCurrentSettings); } setSuggestionStripShownInternal( isSuggestionsStripVisible(), /* needsInputViewShown */ false); mLastSelectionStart = editorInfo.initialSelStart; mLastSelectionEnd = editorInfo.initialSelEnd; // If we come here something in the text state is very likely to have changed. // We should update the shift state regardless of whether we are restarting or not, because // this is not perceived as a layout change that may be disruptive like we may have with // switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the // field gets emptied and we need to re-evaluate the shift state, but not the whole layout // which would be disruptive. // Space state must be updated before calling updateShiftState mKeyboardSwitcher.updateShiftState(); mHandler.cancelUpdateSuggestionStrip(); mHandler.cancelDoubleSpacesTimer(); mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable); mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn, mCurrentSettings.mKeyPreviewPopupDismissDelay); mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled); mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled, mCurrentSettings.mGestureFloatingPreviewTextEnabled); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); }
private void onStartInputViewInternal(final EditorInfo editorInfo, final boolean restarting) { super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; final MainKeyboardView mainKeyboardView = switcher.getMainKeyboardView(); if (editorInfo == null) { Log.e(TAG, "Null EditorInfo in onStartInputView()"); if (LatinImeLogger.sDBG) { throw new NullPointerException("Null EditorInfo in onStartInputView()"); } return; } if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions)); Log.d(TAG, "All caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) + ", sentence caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) + ", word caps = " + ((editorInfo.inputType & InputType.TYPE_TEXT_FLAG_CAP_WORDS) != 0)); } if (ProductionFlag.IS_EXPERIMENTAL) { ResearchLogger.latinIME_onStartInputViewInternal(editorInfo, mPrefs); } if (InputAttributes.inPrivateImeOptions(null, NO_MICROPHONE_COMPAT, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use " + getPackageName() + "." + NO_MICROPHONE + " instead"); } if (InputAttributes.inPrivateImeOptions(getPackageName(), FORCE_ASCII, editorInfo)) { Log.w(TAG, "Deprecated private IME option specified: " + editorInfo.privateImeOptions); Log.w(TAG, "Use EditorInfo.IME_FLAG_FORCE_ASCII flag instead"); } mTargetApplicationInfo = TargetApplicationGetter.getCachedApplicationInfo(editorInfo.packageName); if (null == mTargetApplicationInfo) { new TargetApplicationGetter(this /* context */, this /* listener */) .execute(editorInfo.packageName); } LatinImeLogger.onStartInputView(editorInfo); // In landscape mode, this method gets called without the input view being created. if (mainKeyboardView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(mainKeyboardView, editorInfo, restarting); } final boolean selectionChanged = mLastSelectionStart != editorInfo.initialSelStart || mLastSelectionEnd != editorInfo.initialSelEnd; final boolean inputTypeChanged = !mCurrentSettings.isSameInputType(editorInfo); final boolean isDifferentTextField = !restarting || inputTypeChanged; if (isDifferentTextField) { final boolean currentSubtypeEnabled = mSubtypeSwitcher .updateParametersOnStartInputViewAndReturnIfCurrentSubtypeEnabled(); if (!currentSubtypeEnabled) { // Current subtype is disabled. Needs to update subtype and keyboard. final InputMethodSubtype newSubtype = ImfUtils.getCurrentInputMethodSubtype( this, mSubtypeSwitcher.getNoLanguageSubtype()); mSubtypeSwitcher.updateSubtype(newSubtype); loadKeyboard(); } } // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); mApplicationSpecifiedCompletions = null; if (isDifferentTextField || selectionChanged) { // If the selection changed, we reset the input state. Essentially, we come here with // restarting == true when the app called setText() or similar. We should reset the // state if the app set the text to something else, but keep it if it set a suggestion // or something. mEnteredText = null; resetComposingState(true /* alsoResetLastComposedWord */); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; if (mSuggestionStripView != null) { // This will set the punctuation suggestions if next word suggestion is off; // otherwise it will clear the suggestion strip. setPunctuationSuggestions(); } } mConnection.resetCachesUponCursorMove(editorInfo.initialSelStart); if (isDifferentTextField) { mainKeyboardView.closing(); loadSettings(); if (mSuggest != null && mCurrentSettings.mCorrectionEnabled) { mSuggest.setAutoCorrectionThreshold(mCurrentSettings.mAutoCorrectionThreshold); } switcher.loadKeyboard(editorInfo, mCurrentSettings); } setSuggestionStripShownInternal( isSuggestionsStripVisible(), /* needsInputViewShown */ false); mLastSelectionStart = editorInfo.initialSelStart; mLastSelectionEnd = editorInfo.initialSelEnd; // If we come here something in the text state is very likely to have changed. // We should update the shift state regardless of whether we are restarting or not, because // this is not perceived as a layout change that may be disruptive like we may have with // switcher.loadKeyboard; in apps like Talk, we come here when the text is sent and the // field gets emptied and we need to re-evaluate the shift state, but not the whole layout // which would be disruptive. // Space state must be updated before calling updateShiftState mKeyboardSwitcher.updateShiftState(); mHandler.cancelUpdateSuggestionStrip(); mHandler.cancelDoubleSpacesTimer(); mainKeyboardView.setMainDictionaryAvailability(mIsMainDictionaryAvailable); mainKeyboardView.setKeyPreviewPopupEnabled(mCurrentSettings.mKeyPreviewPopupOn, mCurrentSettings.mKeyPreviewPopupDismissDelay); mainKeyboardView.setGestureHandlingEnabledByUser(mCurrentSettings.mGestureInputEnabled); mainKeyboardView.setGesturePreviewMode(mCurrentSettings.mGesturePreviewTrailEnabled, mCurrentSettings.mGestureFloatingPreviewTextEnabled); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); }
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/TeamsServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/TeamsServlet.java index d9eb084..c29c88c 100644 --- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/TeamsServlet.java +++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/TeamsServlet.java @@ -1,38 +1,37 @@ package org.cvut.wa2.projectcontrol; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; public class TeamsServlet extends HttpServlet{ private static final long serialVersionUID = -2505608701798341438L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); UserService service = UserServiceFactory.getUserService(); User user = service.getCurrentUser(); if(user!= null){ DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); } else{ resp.sendRedirect("/projectcontrol"); } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); UserService service = UserServiceFactory.getUserService(); User user = service.getCurrentUser(); if(user!= null){ DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); } else{ resp.sendRedirect("/projectcontrol"); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserService service = UserServiceFactory.getUserService(); User user = service.getCurrentUser(); if(user!= null){ DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); } else{ resp.sendRedirect("/projectcontrol"); } }
diff --git a/ext/complex-types/src/main/java/org/modelinglab/ocl/ext/complextypes/evaluator/date/DateDayOfWeekEvaluator.java b/ext/complex-types/src/main/java/org/modelinglab/ocl/ext/complextypes/evaluator/date/DateDayOfWeekEvaluator.java index 12ee42f..3d6f500 100644 --- a/ext/complex-types/src/main/java/org/modelinglab/ocl/ext/complextypes/evaluator/date/DateDayOfWeekEvaluator.java +++ b/ext/complex-types/src/main/java/org/modelinglab/ocl/ext/complextypes/evaluator/date/DateDayOfWeekEvaluator.java @@ -1,29 +1,29 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.modelinglab.ocl.ext.complextypes.evaluator.date; import org.modelinglab.ocl.core.ast.Operation; import org.modelinglab.ocl.core.values.EnumValue; import org.modelinglab.ocl.core.values.OclValue; import org.modelinglab.ocl.ext.complextypes.classes.AGDate.AGDateObject; import org.modelinglab.ocl.ext.complextypes.classes.AGDayOfWeek; import org.modelinglab.ocl.ext.complextypes.operations.date.DateDayOfWeek; /** * */ public class DateDayOfWeekEvaluator extends AbstractDateEvaluator { @Override public OclValue<?> visitDate(AGDateObject val, SwitchArgument arg) { - return new EnumValue(AGDayOfWeek.getInstance().getLiteral(val.getJodaDateTime().getDayOfWeek())); + return new EnumValue(AGDayOfWeek.getInstance().getLiteral(val.getJodaDateTime().getDayOfWeek() - 1)); } @Override public Operation getEvaluableOperation() { return DateDayOfWeek.getInstance(); } }
true
true
public OclValue<?> visitDate(AGDateObject val, SwitchArgument arg) { return new EnumValue(AGDayOfWeek.getInstance().getLiteral(val.getJodaDateTime().getDayOfWeek())); }
public OclValue<?> visitDate(AGDateObject val, SwitchArgument arg) { return new EnumValue(AGDayOfWeek.getInstance().getLiteral(val.getJodaDateTime().getDayOfWeek() - 1)); }
diff --git a/src/main/java/org/andrill/conop/pp/Placements.java b/src/main/java/org/andrill/conop/pp/Placements.java index 8c8747d..ec704c1 100644 --- a/src/main/java/org/andrill/conop/pp/Placements.java +++ b/src/main/java/org/andrill/conop/pp/Placements.java @@ -1,120 +1,127 @@ package org.andrill.conop.pp; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import org.andrill.conop.pp.SummarySpreadsheet.Summary; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; /** * Generates a placements summary sheet with event placements and interpolated * ages. * * @author Josh Reed ([email protected]) */ public class Placements implements Summary { protected int after(final List<Map<String, String>> events, final int position) { for (int i = position + 1; i < events.size(); i++) { if (events.get(i).containsKey("agemin")) { return i; } } return -1; } protected int before(final List<Map<String, String>> events, final int position) { for (int i = position - 1; i >= 0; i--) { if (events.get(i).containsKey("agemin")) { return i; } } return -1; } @Override public void generate(final Workbook workbook, final RunInfo run) { - Sheet sheet = workbook.createSheet(); + Sheet sheet = workbook.createSheet(run.getName()); // sort our sections List<Map<String, String>> sections = run.getSections(); Collections.sort(sections, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o1.get("id")).compareTo(new Integer(o2.get("id"))); } }); // sort our events List<Map<String, String>> events = run.getEvents(); Collections.sort(events, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o2.get("solution")).compareTo(new Integer(o1.get("solution"))); } }); // create our header style CellStyle style = sheet.getWorkbook().createCellStyle(); Font font = sheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); style.setBorderBottom(CellStyle.BORDER_THIN); // write out our header row Row header = sheet.createRow(0); header.createCell(0).setCellValue("Event"); header.createCell(1).setCellValue("Type"); header.createCell(2).setCellValue("Rank"); header.createCell(3).setCellValue("Min Age"); header.createCell(4).setCellValue("Max Age"); for (int i = 0; i < sections.size(); i++) { - header.createCell(i + 5).setCellValue(sections.get(i).get("name")); + header.createCell(2 * i + 5).setCellValue(sections.get(i).get("name") + " (O)"); + header.createCell(2 * i + 6).setCellValue(sections.get(i).get("name") + " (P)"); } for (Cell cell : header) { cell.setCellStyle(style); } for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); Row row = sheet.createRow(i + 1); row.createCell(0).setCellValue(event.get("name")); row.createCell(1).setCellValue(event.get("typename")); row.createCell(2).setCellValue(Integer.parseInt(event.get("solution"))); if (event.containsKey("agemin")) { row.createCell(3).setCellValue(Double.parseDouble(event.get("agemin"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemin"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemin"))); if (after == -1) { after = events.size(); } - row.createCell(3).setCellValue(a1 + ((a2 - a1) / (after - before))); + row.createCell(3).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } if (event.containsKey("agemax")) { row.createCell(4).setCellValue(Double.parseDouble(event.get("agemax"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemax"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemax"))); if (after == -1) { after = events.size(); } - row.createCell(4).setCellValue(a1 + ((a2 - a1) / (after - before))); + row.createCell(4).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } - for (int j = 1; j <= sections.size(); j++) { - row.createCell(j + 4).setCellValue(Double.parseDouble(event.get("placed." + j))); + for (int j = 0; j < sections.size(); j++) { + for (Map<String, String> o : run.getObservations()) { + if (event.get("id").equals(o.get("event.id")) && event.get("type").equals(o.get("event.type")) + && o.get("section.id").equals("" + (j + 1))) { + row.createCell(2 * j + 5).setCellValue(Double.parseDouble(o.get("level"))); + } + } + row.createCell(2 * j + 6).setCellValue(Double.parseDouble(event.get("placed." + (j + 1)))); } } } }
false
true
public void generate(final Workbook workbook, final RunInfo run) { Sheet sheet = workbook.createSheet(); // sort our sections List<Map<String, String>> sections = run.getSections(); Collections.sort(sections, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o1.get("id")).compareTo(new Integer(o2.get("id"))); } }); // sort our events List<Map<String, String>> events = run.getEvents(); Collections.sort(events, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o2.get("solution")).compareTo(new Integer(o1.get("solution"))); } }); // create our header style CellStyle style = sheet.getWorkbook().createCellStyle(); Font font = sheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); style.setBorderBottom(CellStyle.BORDER_THIN); // write out our header row Row header = sheet.createRow(0); header.createCell(0).setCellValue("Event"); header.createCell(1).setCellValue("Type"); header.createCell(2).setCellValue("Rank"); header.createCell(3).setCellValue("Min Age"); header.createCell(4).setCellValue("Max Age"); for (int i = 0; i < sections.size(); i++) { header.createCell(i + 5).setCellValue(sections.get(i).get("name")); } for (Cell cell : header) { cell.setCellStyle(style); } for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); Row row = sheet.createRow(i + 1); row.createCell(0).setCellValue(event.get("name")); row.createCell(1).setCellValue(event.get("typename")); row.createCell(2).setCellValue(Integer.parseInt(event.get("solution"))); if (event.containsKey("agemin")) { row.createCell(3).setCellValue(Double.parseDouble(event.get("agemin"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemin"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemin"))); if (after == -1) { after = events.size(); } row.createCell(3).setCellValue(a1 + ((a2 - a1) / (after - before))); } if (event.containsKey("agemax")) { row.createCell(4).setCellValue(Double.parseDouble(event.get("agemax"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemax"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemax"))); if (after == -1) { after = events.size(); } row.createCell(4).setCellValue(a1 + ((a2 - a1) / (after - before))); } for (int j = 1; j <= sections.size(); j++) { row.createCell(j + 4).setCellValue(Double.parseDouble(event.get("placed." + j))); } } }
public void generate(final Workbook workbook, final RunInfo run) { Sheet sheet = workbook.createSheet(run.getName()); // sort our sections List<Map<String, String>> sections = run.getSections(); Collections.sort(sections, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o1.get("id")).compareTo(new Integer(o2.get("id"))); } }); // sort our events List<Map<String, String>> events = run.getEvents(); Collections.sort(events, new Comparator<Map<String, String>>() { @Override public int compare(final Map<String, String> o1, final Map<String, String> o2) { return new Integer(o2.get("solution")).compareTo(new Integer(o1.get("solution"))); } }); // create our header style CellStyle style = sheet.getWorkbook().createCellStyle(); Font font = sheet.getWorkbook().createFont(); font.setBoldweight(Font.BOLDWEIGHT_BOLD); style.setFont(font); style.setBorderBottom(CellStyle.BORDER_THIN); // write out our header row Row header = sheet.createRow(0); header.createCell(0).setCellValue("Event"); header.createCell(1).setCellValue("Type"); header.createCell(2).setCellValue("Rank"); header.createCell(3).setCellValue("Min Age"); header.createCell(4).setCellValue("Max Age"); for (int i = 0; i < sections.size(); i++) { header.createCell(2 * i + 5).setCellValue(sections.get(i).get("name") + " (O)"); header.createCell(2 * i + 6).setCellValue(sections.get(i).get("name") + " (P)"); } for (Cell cell : header) { cell.setCellStyle(style); } for (int i = 0; i < events.size(); i++) { Map<String, String> event = events.get(i); Row row = sheet.createRow(i + 1); row.createCell(0).setCellValue(event.get("name")); row.createCell(1).setCellValue(event.get("typename")); row.createCell(2).setCellValue(Integer.parseInt(event.get("solution"))); if (event.containsKey("agemin")) { row.createCell(3).setCellValue(Double.parseDouble(event.get("agemin"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemin"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemin"))); if (after == -1) { after = events.size(); } row.createCell(3).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } if (event.containsKey("agemax")) { row.createCell(4).setCellValue(Double.parseDouble(event.get("agemax"))); } else { int before = before(events, i); int after = after(events, i); double a1 = (before == -1 ? 0.0 : Double.parseDouble(events.get(before).get("agemax"))); double a2 = (after == -1 ? a1 : Double.parseDouble(events.get(after).get("agemax"))); if (after == -1) { after = events.size(); } row.createCell(4).setCellValue(a1 + ((a2 - a1) / (after - before)) * (i - before)); } for (int j = 0; j < sections.size(); j++) { for (Map<String, String> o : run.getObservations()) { if (event.get("id").equals(o.get("event.id")) && event.get("type").equals(o.get("event.type")) && o.get("section.id").equals("" + (j + 1))) { row.createCell(2 * j + 5).setCellValue(Double.parseDouble(o.get("level"))); } } row.createCell(2 * j + 6).setCellValue(Double.parseDouble(event.get("placed." + (j + 1)))); } } }