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/scstool/src/scstool/proc/CapacityService.java b/scstool/src/scstool/proc/CapacityService.java index 086d274..5779e80 100644 --- a/scstool/src/scstool/proc/CapacityService.java +++ b/scstool/src/scstool/proc/CapacityService.java @@ -1,244 +1,244 @@ /** * */ package scstool.proc; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import scstool.obj.BillOfMaterial; import scstool.obj.Material; import scstool.obj.WaitingList; import scstool.obj.WorkPlan; import scstool.obj.Workplace; import scstool.utils.Repository; /** * Kapazitätenplanung * * @author reinhold * */ public class CapacityService { final static Double FIRST_SHIFT_SALARY = 0.45; final static Double SECOND_SHIFT_SALARY = 0.55; final static Double THIRD_SHIFT_SALARY = 0.7; final static Double OVERTIME_SALARY = 0.9; final static Integer FIRST_SHIFT = 2400; final static Integer FIRST_SHIFT_OVERTIME = 3600; final static Integer SECOND_SHIFT = 4800; final static Integer SECOND_SHIFT_OVERTIME = 6000; final static Integer THIRD_SHIFT = 7200; private static final Double RISIKO = risk(); /** * @return */ private static double risk() { return new Double( 1 + (Repository.getInstance().getRiskPercente() / 100)); } /** * Kalkuliert die benötigte Kapazität für einen Arbeitsplatz ohne die * Materialien in der Warteschlange. * * @param workplace * der Arbeitsplatz * @param productionProgram * das Produktionsprogramm als Integer Array(Index 0 die ID,Index * 1 die Anzahl) * @return die benötigte Kapazität in Minuten mit Rüstzeit */ public static Integer calculateWorkplaceCapacity(Workplace workplace, List<Integer[]> productionProgram) { List<Material> done = new ArrayList<>(); Integer result = 0; // suche in dem Produktionsprogramm // prodMat ist ein Integer[] auf Index 0 ist die Material ID und auf // Index 1 die produzierende Anzahl for (Integer[] prodMat : productionProgram) { // suche in den Arbeitsplänen für einen Arbeitsplatz for (WorkPlan plan : workplace.getWorkplan()) { // suche in den Stücklisteneinträgen in den Arbeitsplänen for (BillOfMaterial bom : plan.getBillOfMaterial()) { // nach dem zu fertigenden Material Material component = bom.getComponent(); // wenn das fertigende Material in der Liste enthalten ist // wurde es schon hinzugefügt if (!done.contains(component)) { // wenn das Material im Produktionsprogramm gleich sind if (prodMat[0] == component.getId()) { // addiere die produzierende Zeit result += (plan.getProductionTime() * prodMat[1]); // addiere die Rüstzeit result += plan.getSetupTime(); done.add(component); } } } } } return result; } /** * Rechnet die noch einzurechnende Kapazität für einen Arbeitsplatz. * * @param workplace * @return */ public static Integer calculateWaitingListCapacity(Workplace workplace) { Integer result = 0; Repository repo = Repository.getInstance(); for (WaitingList wl : repo.getInWork()) { result += wl.getTimeneed(); } return result; } public LinkedHashMap<Workplace, Integer[]> capaciting() { DatabaseContentHandler dbch = DatabaseContentHandler.get(); List<Integer[]> productionProgram = Repository.getInstance() .getProductionProgram(); LinkedHashMap<Workplace, Integer[]> result = new LinkedHashMap<>(); for (Workplace workplace : dbch.getAllWorkplaces()) { Integer capacity = calculateWorkplaceCapacity(workplace, productionProgram); capacity += calculateWaitingListCapacity(workplace); Integer[] resultList = calculateShift(workplace, capacity); result.put(workplace, resultList); } return result; } /** * Berechnet die Schicht und die Überstunden pro Tag.<br/> * Dabei ist auf dem Index 0 die Schicht <br/> * und auf dem Index 1 die Überstunden. * * @param workplace * der Arbeitsplatz * @param capacity * die Kapazität * @return zwei Integer Werte auf dem Index 0 die Schicht auf dem Index 1 * die Überstunden pro Tag */ public static Integer[] calculateShift(Workplace workplace, Integer capacity) { Double costsSecondShift = Double.MAX_VALUE; Double costsThirdShift = Double.MAX_VALUE; Double costsFirstShift = Double.MAX_VALUE; if (capacity < FIRST_SHIFT_OVERTIME) { costsFirstShift = getCosts(workplace, capacity, FIRST_SHIFT, FIRST_SHIFT_SALARY); } if (capacity < SECOND_SHIFT_OVERTIME) { costsSecondShift = getCosts(workplace, capacity, SECOND_SHIFT, SECOND_SHIFT_SALARY); } if (capacity < THIRD_SHIFT) { costsThirdShift = getCosts(workplace, capacity, THIRD_SHIFT, THIRD_SHIFT_SALARY); } return chooseShift(capacity, costsFirstShift, costsSecondShift, costsThirdShift); } /** * Berechnet die Kosten einer Schicht auf einer<br/> * bestimmten Maschine mit der angegebenen Kapazität * * @param workplace * der Arbeitsplatz für die Maschinenkosten * @param capacity * die Kapazität * @param shift * die Minuten einer Schicht * @return die Kosten */ private static Double getCosts(Workplace workplace, Integer capacity, final Integer shift, Double salary) { Double costsShift; // Lohnkosten für eine Schicht double salaryForShift = salary * shift; // Variable Maschinenkosten double varCostforShift = (workplace.getVarMachineCosts() - workplace .getFixMachineCosts()) * capacity; // Fixe Maschinenkosten double fixCostforShift = workplace.getFixMachineCosts() * shift; costsShift = salaryForShift + varCostforShift + fixCostforShift; // Überstundenbezahlung if (capacity > shift) { costsShift += OVERTIME_SALARY * (capacity - shift); } return costsShift; } /** * Algorithmus zum Auswählen der Schicht. * * @param capacity * die Kapazität * @param costsFirstShift * Kosten der ersten Schicht * @param costsSecondShift * Kosten der zweiten Schicht * @param costsThirdShift * Kosten der dritten Schicht * @return zwei Integer Werte auf dem Index 0 die Schicht auf dem Index 1 * die Überstunden pro Tag */ private static Integer[] chooseShift(Integer capacity, Double costsFirstShift, Double costsSecondShift, Double costsThirdShift) { Integer[] result = new Integer[3]; if (costsFirstShift < costsSecondShift && costsFirstShift < costsThirdShift) { result[0] = 1; if (capacity > FIRST_SHIFT) { result[1] = (int) (((capacity - FIRST_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsSecondShift < costsThirdShift && costsSecondShift < costsFirstShift) { - result[1] = 2; + result[0] = 2; if (capacity > SECOND_SHIFT) { result[1] = (int) (((capacity - SECOND_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsThirdShift < costsFirstShift && costsThirdShift < costsSecondShift) { - result[1] = 3; + result[0] = 3; if (capacity > THIRD_SHIFT) { result[1] = (int) (((capacity - THIRD_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } result[2] = capacity; return result; } }
false
true
private static Integer[] chooseShift(Integer capacity, Double costsFirstShift, Double costsSecondShift, Double costsThirdShift) { Integer[] result = new Integer[3]; if (costsFirstShift < costsSecondShift && costsFirstShift < costsThirdShift) { result[0] = 1; if (capacity > FIRST_SHIFT) { result[1] = (int) (((capacity - FIRST_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsSecondShift < costsThirdShift && costsSecondShift < costsFirstShift) { result[1] = 2; if (capacity > SECOND_SHIFT) { result[1] = (int) (((capacity - SECOND_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsThirdShift < costsFirstShift && costsThirdShift < costsSecondShift) { result[1] = 3; if (capacity > THIRD_SHIFT) { result[1] = (int) (((capacity - THIRD_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } result[2] = capacity; return result; }
private static Integer[] chooseShift(Integer capacity, Double costsFirstShift, Double costsSecondShift, Double costsThirdShift) { Integer[] result = new Integer[3]; if (costsFirstShift < costsSecondShift && costsFirstShift < costsThirdShift) { result[0] = 1; if (capacity > FIRST_SHIFT) { result[1] = (int) (((capacity - FIRST_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsSecondShift < costsThirdShift && costsSecondShift < costsFirstShift) { result[0] = 2; if (capacity > SECOND_SHIFT) { result[1] = (int) (((capacity - SECOND_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } if (costsThirdShift < costsFirstShift && costsThirdShift < costsSecondShift) { result[0] = 3; if (capacity > THIRD_SHIFT) { result[1] = (int) (((capacity - THIRD_SHIFT) / 5) * RISIKO); } else { result[1] = 0; } } result[2] = capacity; return result; }
diff --git a/cli/src/main/java/com/gooddata/processor/GdcDI.java b/cli/src/main/java/com/gooddata/processor/GdcDI.java index 9193c1b5..8e15976b 100644 --- a/cli/src/main/java/com/gooddata/processor/GdcDI.java +++ b/cli/src/main/java/com/gooddata/processor/GdcDI.java @@ -1,1493 +1,1494 @@ /* * Copyright (c) 2009, GoodData Corporation. All rights reserved. * * Redistribution and use 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 the GoodData Corporation 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 HOLDER 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.gooddata.processor; import java.io.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.ListResourceBundle; import java.util.Properties; import com.gooddata.connector.*; import com.gooddata.connector.FacebookConnector; import com.gooddata.integration.model.Column; import com.gooddata.integration.model.SLI; import com.gooddata.integration.rest.GdcRESTApiWrapper; import com.gooddata.integration.rest.MetadataObject; import com.gooddata.modeling.model.SourceSchema; import com.gooddata.util.DatabaseToCsv; import com.gooddata.util.StringUtil; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.auth.AuthScheme; import org.apache.commons.httpclient.auth.CredentialsNotAvailableException; import org.apache.commons.httpclient.auth.CredentialsProvider; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.gooddata.exception.GdcException; import com.gooddata.exception.GdcRestApiException; import com.gooddata.exception.HttpMethodException; import com.gooddata.exception.InternalErrorException; import com.gooddata.exception.InvalidArgumentException; import com.gooddata.exception.InvalidCommandException; import com.gooddata.exception.InvalidParameterException; import com.gooddata.exception.ModelException; import com.gooddata.exception.ProcessingException; import com.gooddata.exception.SfdcException; import com.gooddata.integration.rest.configuration.NamePasswordConfiguration; import com.gooddata.naming.N; import com.gooddata.processor.parser.DIScriptParser; import com.gooddata.processor.parser.ParseException; import com.gooddata.util.FileUtil; import javax.print.attribute.URISyntax; /** * The GoodData Data Integration CLI processor. * * @author jiri.zaloudek * @author Zdenek Svoboda <zd@gooddata.org> * @version 1.0 */ public class GdcDI implements Executor { private static Logger l = Logger.getLogger(GdcDI.class); //Options data public static String[] CLI_PARAM_HELP = {"help","H"}; public static String[] CLI_PARAM_USERNAME = {"username","u"}; public static String[] CLI_PARAM_PASSWORD = {"password","p"}; public static String[] CLI_PARAM_HOST = {"host","h"}; public static String[] CLI_PARAM_FTP_HOST = {"ftphost","f"}; public static String[] CLI_PARAM_PROJECT = {"project","i"}; public static String[] CLI_PARAM_PROTO = {"proto","t"}; public static String[] CLI_PARAM_INSECURE = {"insecure","s"}; public static String[] CLI_PARAM_EXECUTE = {"execute","e"}; public static String[] CLI_PARAM_VERSION = {"version","V"}; public static String[] CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY = {"default-date-fk","D"}; public static String CLI_PARAM_SCRIPT = "script"; private static String DEFAULT_PROPERTIES = "gdi.properties"; // Command line options private static Options ops = new Options(); public static Option[] Options = { new Option(CLI_PARAM_HELP[1], CLI_PARAM_HELP[0], false, "Print command reference"), new Option(CLI_PARAM_USERNAME[1], CLI_PARAM_USERNAME[0], true, "GoodData username"), new Option(CLI_PARAM_PASSWORD[1], CLI_PARAM_PASSWORD[0], true, "GoodData password"), new Option(CLI_PARAM_HOST[1], CLI_PARAM_HOST[0], true, "GoodData host"), new Option(CLI_PARAM_FTP_HOST[1], CLI_PARAM_FTP_HOST[0], true, "GoodData data stage host"), new Option(CLI_PARAM_PROJECT[1], CLI_PARAM_PROJECT[0], true, "GoodData project identifier (a string like nszfbgkr75otujmc4smtl6rf5pnmz9yl)"), new Option(CLI_PARAM_PROTO[1], CLI_PARAM_PROTO[0], true, "HTTP or HTTPS (deprecated)"), new Option(CLI_PARAM_INSECURE[1], CLI_PARAM_INSECURE[0], false, "Disable encryption"), new Option(CLI_PARAM_VERSION[1], CLI_PARAM_VERSION[0], false, "Prints the tool version."), new Option(CLI_PARAM_EXECUTE[1], CLI_PARAM_EXECUTE[0], true, "Commands and params to execute before the commands in provided files"), new Option(CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY[1], CLI_PARAM_DEFAULT_DATE_FOREIGN_KEY[0], true, "Foreign key to represent an 'unknown' date") }; private CliParams cliParams = null; private Connector[] connectors = null; private ProcessingContext context = new ProcessingContext(); private boolean finishedSucessfuly = false; private static long LOCK_EXPIRATION_TIME = 1000 * 3600; // 1 hour private final static String BUILD_NUMBER = ""; private GdcDI(CommandLine ln, Properties defaults) { try { cliParams = parse(ln, defaults); cliParams.setHttpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); cliParams.setFtpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_FTP_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); connectors = instantiateConnectors(); String execute = cliParams.get(CLI_PARAM_EXECUTE[0]); String scripts = cliParams.get(CLI_PARAM_SCRIPT); if(execute!= null && scripts != null && execute.length()>0 && scripts.length()>0) { throw new InvalidArgumentException("You can't execute a script and use the -e command line parameter at the same time."); } if(execute!= null && execute.length() > 0) { l.debug("Executing arg="+execute); execute(execute); } if(scripts!= null && scripts.length() > 0) { String[] sas = scripts.split(","); for(String script : sas) { l.debug("Executing file="+script); execute(new File(script)); } } if(cliParams.containsKey(CLI_PARAM_HELP[0])) l.info(commandsHelp()); finishedSucessfuly = true; } catch (InvalidArgumentException e) { l.error("Invalid or missing argument: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gooddata-cli [<options> ...] -H|--help|<script>|-e <command>", ops); finishedSucessfuly = false; } catch (InvalidCommandException e) { l.error("Invalid command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InvalidParameterException e) { l.error("Invalid command parameter: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (SfdcException e) { l.error("Error communicating with SalesForce: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ProcessingException e) { l.error("Error processing command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ModelException e) { l.error("Model issue: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (IOException e) { l.error("Encountered an IO problem. Please check that all files that you use in your command line arguments and commands exist." + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InternalErrorException e) { Throwable c = e.getCause(); if( c != null && c instanceof SQLException) { l.error("Error extracting data. Can't process the incoming data. Please check the CSV file " + "separator and consistency (same number of columns in each row). Also, please make sure " + "that the number of columns in your XML config file matches the number of rows in your " + "data source. Make sure that your file is readable by other users (particularly the mysql user). " + "More info: ", c); } else { l.error("Internal error: " + e.getMessage()); l.debug(e); c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } } finishedSucessfuly = false; } catch (HttpMethodException e) { l.debug("Error executing GoodData REST API: " + e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } String msg = e.getMessage(); String requestId = e.getRequestId(); if (requestId != null) { msg += "\n\n" + "If you believe this is not your fault, good people from support\n" + "portal (http://support.gooddata.com) may help you.\n\n" + "Show them this error ID: " + requestId; } l.error(msg); finishedSucessfuly = false; } catch (GdcRestApiException e) { l.error("REST API invocation error: " + e.getMessage()); l.debug(e, e); Throwable c = e.getCause(); while(c!=null) { if(c instanceof HttpMethodException) { HttpMethodException ex = (HttpMethodException)c; String msg = ex.getMessage(); if(msg != null && msg.length()>0 && msg.indexOf("/ldm/manage")>0) { l.error("Error creating/updating logical data model (executing MAQL DDL)."); if(msg.indexOf(".date")>0) { l.error("Bad time dimension schemaReference."); } else { l.error("You are either trying to create a data object that already exists " + "(executing the same MAQL multiple times) or providing a wrong reference " + "or schemaReference in your XML configuration."); } } } l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (GdcException e) { l.error("Unrecognized error: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } finally { - context.getRestApi(cliParams).logout(); + if(cliParams != null) + context.getRestApi(cliParams).logout(); } } /** * Parse and validate the cli arguments * @param ln parsed command line * @return parsed cli parameters wrapped in the CliParams * @throws InvalidArgumentException in case of nonexistent or incorrect cli args */ protected CliParams parse(CommandLine ln, Properties defaults) throws InvalidArgumentException { l.debug("Parsing cli "+ln); CliParams cp = new CliParams(); for( Option o : Options) { String name = o.getLongOpt(); if (ln.hasOption(name)) { cp.put(name,ln.getOptionValue(name)); } else if (defaults.getProperty(name) != null) { cp.put(name, defaults.getProperty(name)); } } if(cp.containsKey(CLI_PARAM_VERSION[0])) { l.info("GoodData CL version 1.2.45" + ((BUILD_NUMBER.length()>0) ? ", build "+BUILD_NUMBER : ".")); System.exit(0); } // use default host if there is no host in the CLI params if(!cp.containsKey(CLI_PARAM_HOST[0])) { cp.put(CLI_PARAM_HOST[0], Defaults.DEFAULT_HOST); } l.debug("Using host "+cp.get(CLI_PARAM_HOST[0])); // create default FTP host if there is no host in the CLI params if(!cp.containsKey(CLI_PARAM_FTP_HOST[0])) { String[] hcs = cp.get(CLI_PARAM_HOST[0]).split("\\."); if(hcs != null && hcs.length > 0) { String ftpHost = ""; for(int i=0; i<hcs.length; i++) { if(i>0) ftpHost += "." + hcs[i]; else ftpHost = hcs[i] + N.FTP_SRV_SUFFIX; } cp.put(CLI_PARAM_FTP_HOST[0],ftpHost); } else { throw new InvalidArgumentException("Invalid format of the GoodData REST API host: " + cp.get(CLI_PARAM_HOST[0])); } } l.debug("Using FTP host "+cp.get(CLI_PARAM_FTP_HOST[0])); // Default to secure protocol if there is no host in the CLI params // Assume insecure protocol if user specifies "HTTPS", for backwards compatibility if(cp.containsKey(CLI_PARAM_PROTO[0])) { String proto = ln.getOptionValue(CLI_PARAM_PROTO[0]).toLowerCase(); if(!"http".equalsIgnoreCase(proto) && !"https".equalsIgnoreCase(proto)) { throw new InvalidArgumentException("Invalid '"+CLI_PARAM_PROTO[0]+"' parameter. Use HTTP or HTTPS."); } if ("http".equalsIgnoreCase(proto)) { cp.put(CLI_PARAM_INSECURE[0], "true"); } } if(cp.containsKey(CLI_PARAM_INSECURE[0])) cp.put(CLI_PARAM_INSECURE[0], "true"); l.debug("Using " + (cp.containsKey(CLI_PARAM_INSECURE[0]) ? "in" : "") + "secure protocols"); if (ln.getArgs().length == 0 && !ln.hasOption(CLI_PARAM_EXECUTE[0]) && !ln.hasOption(CLI_PARAM_HELP[0])) { throw new InvalidArgumentException("No command has been given, quitting."); } String scripts = ""; for (final String arg : ln.getArgs()) { if(scripts.length()>0) scripts += ","+arg; else scripts += arg; } cp.put(CLI_PARAM_SCRIPT, scripts); return cp; } /** * Executes the commands in String * @param commandsStr commands string */ public void execute(final String commandsStr) { List<Command> cmds = new ArrayList<Command>(); cmds.addAll(parseCmd(commandsStr)); for(Command command : cmds) { boolean processed = false; for(int i=0; i<connectors.length && !processed; i++) { processed = connectors[i].processCommand(command, cliParams, context); } if(!processed) this.processCommand(command, cliParams, context); } } /** * Executes the commands in file * @param scriptFile file with commands * @throws IOException in case of an IO issue */ public void execute(final File scriptFile) throws IOException { List<Command> cmds = new ArrayList<Command>(); cmds.addAll(parseCmd(FileUtil.readStringFromFile(scriptFile.getAbsolutePath()))); for(Command command : cmds) { boolean processed = false; for(int i=0; i<connectors.length && !processed; i++) { processed = connectors[i].processCommand(command, cliParams, context); } if(!processed) processed = this.processCommand(command, cliParams, context); if(!processed) throw new InvalidCommandException("Unknown command '"+command.getCommand()+"'"); } } /** * Returns the help for commands * @return help text */ public static String commandsHelp() { try { final InputStream is = CliParams.class.getResourceAsStream("/com/gooddata/processor/COMMANDS.txt"); if (is == null) throw new IOException(); return FileUtil.readStringFromStream(is); } catch (IOException e) { l.error("Could not read com/gooddata/processor/COMMANDS.txt"); } return ""; } private static boolean checkJavaVersion() { String version = System.getProperty("java.version"); if(version.startsWith("1.8") || version.startsWith("1.7") || version.startsWith("1.6") || version.startsWith("1.5")) return true; l.error("You're running Java "+version+". Please use Java 1.5 or higher for running this tool. " + "Please refer to http://java.sun.com/javase/downloads/index.jsp for a more recent Java version."); throw new InternalErrorException("You're running Java "+version+". Please use use Java 1.5 or higher for running this tool. " + "Please refer to http://java.sun.com/javase/downloads/index.jsp for a more recent Java version."); } /** * The main CLI processor * @param args command line argument */ public static void main(String[] args) { checkJavaVersion(); String logConfig = System.getProperty("log4j.configuration"); if(logConfig != null && logConfig.length()>0) { File lc = new File(logConfig); if(lc.exists()) { PropertyConfigurator.configure(logConfig); Properties defaults = loadDefaults(); for(Option o : Options) ops.addOption(o); try { CommandLineParser parser = new GnuParser(); CommandLine cmdline = parser.parse(ops, args); GdcDI gdi = new GdcDI(cmdline, defaults); if (!gdi.finishedSucessfuly) { System.exit(1); } } catch (org.apache.commons.cli.ParseException e) { l.error("Error parsing command line parameters: ",e); l.debug("Error parsing command line parameters",e); } } else { l.error("Can't find the logging config. Please configure the logging via the log4j.configuration."); } } else { l.error("Can't find the logging config. Please configure the logging via the log4j.configuration."); } } private void setupHttpProxies() { //CredentialsProvider proxyCredentials = new BasicCredentialsProvider (); } /** * Parses the commands * @param cmd commands string * @return array of commands * @throws InvalidCommandException in case there is an invalid command */ protected static List<Command> parseCmd(String cmd) throws InvalidCommandException { l.debug("Parsing comands: "+cmd); try { if(cmd != null && cmd.length()>0) { Reader r = new StringReader(cmd); DIScriptParser parser = new DIScriptParser(r); List<Command> commands = parser.parse(); l.debug("Running "+commands.size()+" commands."); for(Command c : commands) { l.debug("Command="+c.getCommand()+" params="+c.getParameters()); } return commands; } } catch(ParseException e) { throw new InvalidCommandException("Can't parse command '" + cmd + "'"); } throw new InvalidCommandException("Can't parse command (empty command)."); } /** * {@inheritDoc} */ public boolean processCommand(Command c, CliParams cli, ProcessingContext ctx) throws ProcessingException { l.debug("Processing command "+c.getCommand()); try { // take project id from command line, may be override in the script if (cliParams.get(CLI_PARAM_PROJECT[0]) != null) { ctx.setProjectId(cliParams.get(CLI_PARAM_PROJECT[0])); } if(c.match("CreateProject")) { createProject(c, cli, ctx); } else if(c.match("DropProject") || c.match("DeleteProject")) { dropProject(c, cli, ctx); } else if(c.match("OpenProject")) { ctx.setProjectId(c.getParamMandatory("id")); c.paramsProcessed(); l.debug("Opened project id="+ctx.getProjectId()); l.info("Opened project id="+ctx.getProjectId()); } else if(c.match("StoreProject") || c.match("RememberProject")) { storeProject(c, cli, ctx); } else if(c.match("ExecuteDml")) { executeDML(c, cli, ctx); } else if(c.match("RetrieveProject") || c.match("UseProject")) { retrieveProject(c, cli, ctx); } else if(c.match("ExportProject")) { exportProject(c, cli, ctx); } else if(c.match("ImportProject")) { importProject(c, cli, ctx); } else if(c.match( "Lock")) { lock(c, cli, ctx); } else if(c.match("GetReports")) { getReports(c, cli, ctx); } else if(c.match("CreateUser")) { createUser(c, cli, ctx); } else if(c.match("AddUsersToProject")) { addUsersToProject(c, cli, ctx); } else if(c.match("DisableUsersInProject")) { disableUsersInProject(c, cli, ctx); } else if(c.match("GetProjectUsers")) { getProjectUsers(c, cli, ctx); } else if(c.match("InviteUser")) { inviteUser(c, cli, ctx); } else if(c.match("ExecuteReports")) { executeReports(c, cli, ctx); } else if(c.match("StoreMetadataObject")) { storeMdObject(c, cli, ctx); } else if(c.match("DropMetadataObject")) { dropMdObject(c, cli, ctx); } else if(c.match("RetrieveMetadataObject")) { getMdObject(c, cli, ctx); } else if(c.match("ExportMetadataObjects")) { exportMDObject(c, cli, ctx); } else if(c.match("ImportMetadataObjects")) { importMDObject(c, cli, ctx); } else if(c.match("ExportJdbcToCsv")) { exportJdbcToCsv(c, cli, ctx); } else if(c.match("MigrateDatasets")) { migrateDatasets(c, cli, ctx); } else if(c.match("GenerateManifests")) { generateManifests(c, cli, ctx); } else { l.debug("No match command "+c.getCommand()); return false; } } catch (IOException e) { l.debug("Processing command "+c.getCommand()+" failed",e); throw new ProcessingException(e); } catch (InterruptedException e) { l.debug("Processing command "+c.getCommand()+" failed",e); throw new ProcessingException(e); } l.debug("Command processing "+c.getCommand()+" finished."); return true; } /** * Executes MAQL DML * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void executeDML(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.debug("Executing MAQL DML."); String pid = ctx.getProjectIdMandatory(); final String cmd = c.getParamMandatory("maql"); c.paramsProcessed(); String taskUri = ctx.getRestApi(p).executeDML(pid, cmd); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking MAQL DML execution status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("MAQL DML execution status = "+status); Thread.sleep(500); } l.info("MAQL DML execution finished with status "+status); if("ERROR".equalsIgnoreCase(status)) { l.error("Error executing the MAQL DML. Check debug log for more details."); throw new GdcRestApiException("Error executing the MAQL DML. Check debug log for more details."); } } else { l.error("MAQL DML execution hasn't returned any task URI."); throw new InternalErrorException("MAQL DML execution hasn't returned any task URI."); } l.debug("Finished MAQL DML execution."); l.info("MAQL DML command '"+cmd+"' successfully executed."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void exportProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Exporting project."); String pid = ctx.getProjectIdMandatory(); final String eu = c.getParamMandatory("exportUsers"); final boolean exportUsers = (eu != null && "true".equalsIgnoreCase(eu)); final String ed = c.getParamMandatory("exportData"); final boolean exportData = (ed != null && "true".equalsIgnoreCase(ed)); final String fileName = c.getParamMandatory("tokenFile"); String au = c.getParam("authorizedUsers"); c.paramsProcessed(); String[] authorizedUsers = null; if(au != null && au.length() > 0) { authorizedUsers = au.split(","); } GdcRESTApiWrapper.ProjectExportResult r = ctx.getRestApi(p).exportProject(pid, exportUsers, exportData, authorizedUsers); String taskUri = r.getTaskUri(); String token = r.getExportToken(); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking project export status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Project export status = "+status); Thread.sleep(500); } l.info("Project export finished with status "+status); if("OK".equalsIgnoreCase(status) || "WARNING".equalsIgnoreCase(status)) { FileUtil.writeStringToFile(token, fileName); } else { l.error("Error exporting project. Check debug log for more details."); throw new GdcRestApiException("Error exporting project. Check debug log for more details."); } } else { l.error("Project export hasn't returned any task URI."); throw new InternalErrorException("Project export hasn't returned any task URI."); } l.debug("Finished project export."); l.info("Project "+pid+" successfully exported. Import token is "+token); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Imports project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void importProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Importing project."); String pid = ctx.getProjectIdMandatory(); final String tokenFile = c.getParamMandatory("tokenFile"); c.paramsProcessed(); String token = FileUtil.readStringFromFile(tokenFile).trim(); String taskUri = ctx.getRestApi(p).importProject(pid, token); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking project import status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Project import status = "+status); Thread.sleep(500); } l.info("Project import finished with status "+status); if("ERROR".equalsIgnoreCase(status)) { l.error("Error importing project. Check debug log for more details."); throw new GdcRestApiException("Error importing project. Check debug log for more details."); } } else { l.error("Project import hasn't returned any task URI."); throw new InternalErrorException("Project import hasn't returned any task URI."); } l.debug("Finished project import."); l.info("Project "+pid+" successfully imported."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports MD objects * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void exportMDObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Exporting metadata objects."); String token; String pid = ctx.getProjectIdMandatory(); final String fileName = c.getParamMandatory("tokenFile"); final String idscs = c.getParamMandatory("objectIDs"); c.paramsProcessed(); if(idscs != null && idscs.length() >0) { String[] idss = idscs.split(","); List<Integer> ids = new ArrayList<Integer>(); for(String id : idss) { try { ids.add(Integer.parseInt(id)); } catch (NumberFormatException e) { l.debug("Invalid metadata object ID "+id,e); l.error("Invalid metadata object ID "+id); throw new InvalidParameterException("Invalid metadata object ID "+id,e); } } GdcRESTApiWrapper.ProjectExportResult r = ctx.getRestApi(p).exportMD(pid,ids); String taskUri = r.getTaskUri(); token = r.getExportToken(); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking MD export status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getTaskManStatus(taskUri); l.debug("MD export status = "+status); Thread.sleep(500); } l.info("MD export finished with status "+status); if("OK".equalsIgnoreCase(status) || "WARNING".equalsIgnoreCase(status)) { FileUtil.writeStringToFile(token, fileName); } else { l.error("Error exporting metadata. Check debug log for more details."); throw new GdcRestApiException("Error exporting metadata. Check debug log for more details."); } } else { l.error("MD export hasn't returned any task URI."); throw new InternalErrorException("MD export hasn't returned any task URI."); } } else { l.debug("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); l.error("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); throw new InvalidParameterException("The objectIDs parameter must contain a comma separated list of metadata object IDs!"); } l.debug("Finished MD export."); l.info("Project "+pid+" metadata successfully exported. Import token is "+token); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Imports MD objects * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void importMDObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { l.info("Importing metadata objects."); String pid = ctx.getProjectIdMandatory(); final String tokenFile = c.getParamMandatory("tokenFile"); String token = FileUtil.readStringFromFile(tokenFile).trim(); /* Currently not supported final String ov = c.getParam("overwrite"); final boolean overwrite = (ov != null && "true".equalsIgnoreCase(ov)); */ final String ul = c.getParam("updateLDM"); final boolean updateLDM = (ul != null && "true".equalsIgnoreCase(ul)); final boolean overwrite = true; c.paramsProcessed(); String taskUri = ctx.getRestApi(p).importMD(pid, token, overwrite, updateLDM); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking MD import status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getTaskManStatus(taskUri); l.debug("MD import status = "+status); Thread.sleep(500); } l.info("MD import finished with status "+status); if("ERROR".equalsIgnoreCase(status)) { l.error("Error importing MD. Check debug log for more details."); throw new GdcRestApiException("Error importing MD. Check debug log for more details."); } } else { l.error("MD import hasn't returned any task URI."); throw new InternalErrorException("MD import hasn't returned any task URI."); } l.debug("Finished metadata import."); l.info("Project "+pid+" metadata successfully imported."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Creates a new user * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void createUser(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Creating new user."); String domain = c.getParamMandatory("domain"); GdcRESTApiWrapper.GdcUser user = new GdcRESTApiWrapper.GdcUser(); user.setLogin(c.getParamMandatory("username")); user.setPassword(c.getParamMandatory("password")); user.setVerifyPassword(c.getParamMandatory("password")); user.setFirstName(c.getParamMandatory("firstName")); user.setLastName(c.getParamMandatory("lastName")); user.setCompanyName(c.getParam("company")); user.setPosition(c.getParam("position")); user.setCountry(c.getParam("country")); user.setPhoneNumber(c.getParam("phone")); user.setSsoProvider(c.getParam("ssoProvider")); String usersFile = c.getParam("usersFile"); String appnd = c.getParam("append"); c.paramsProcessed(); final boolean append = (appnd != null && "true".equalsIgnoreCase(appnd)); String r = ctx.getRestApi(p).createUser(domain, user); if(r!=null && r.length()>0 && usersFile != null && usersFile.length() > 0) { FileUtil.writeStringToFile(r+"\n", usersFile, append); } l.info("User "+user.getLogin()+"' successfully created. User URI: "+r); } /** * Adds a new user to project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void addUsersToProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Adding users to project."); String pid = ctx.getProjectIdMandatory(); String usersFile = c.getParamMandatory("usersFile"); List<String> uris = new ArrayList<String>(); BufferedReader r = FileUtil.createBufferedUtf8Reader(usersFile); String uri = r.readLine(); while (uri != null && uri.trim().length()>0) { uris.add(uri.trim()); uri = r.readLine(); } String role = c.getParam("role"); c.paramsProcessed(); ctx.getRestApi(p).addUsersToProject(pid, uris, role); l.info("Users "+uris+"' successfully added to project "+pid); } /** * Adds a new user to project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void disableUsersInProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { l.info("Disabling users in project."); String pid = ctx.getProjectIdMandatory(); String usersFile = c.getParamMandatory("usersFile"); c.paramsProcessed(); List<String> uris = new ArrayList<String>(); BufferedReader r = FileUtil.createBufferedUtf8Reader(usersFile); String uri = r.readLine(); while (uri != null && uri.trim().length()>0) { uris.add(uri.trim()); uri = r.readLine(); } ctx.getRestApi(p).disableUsersInProject(pid, uris); l.info("Users "+uris+"' successfully disabled in project "+pid); } /** * Adds a new user to project * @param c command * @param p cli parameters * @param ctx current context * @throws IOException IO issues */ private void getProjectUsers(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); l.info("Getting users from project "+pid); String usersFile = c.getParamMandatory("usersFile"); String field = c.getParamMandatory("field"); String activeOnlys = c.getParam("activeOnly"); c.paramsProcessed(); final boolean activeOnly = (activeOnlys != null && "true".equalsIgnoreCase(activeOnlys)); if("email".equalsIgnoreCase(field) || "uri".equalsIgnoreCase(field)) { List<GdcRESTApiWrapper.GdcUser> users = ctx.getRestApi(p).getProjectUsers(pid,activeOnly); for(GdcRESTApiWrapper.GdcUser user : users) { if("email".equalsIgnoreCase(field)) { FileUtil.writeStringToFile(user.getLogin()+"\n", usersFile, true); } if("uri".equalsIgnoreCase(field)) { FileUtil.writeStringToFile(user.getUri()+"\n", usersFile, true); } l.info("User "+user.getLogin()+"' successfully added. User URI: "+user.getUri()); } } else { l.error("Invalid field parameter. Only values 'email' and 'uri' are currently supported."); } } /** * Create new project command processor * @param c command * @param p cli parameters * @param ctx current context */ private void createProject(Command c, CliParams p, ProcessingContext ctx) { try { String name = c.getParamMandatory("name"); String desc = c.getParam("desc"); String pTempUri = c.getParam("templateUri"); c.paramsProcessed(); if(desc == null || desc.length() <= 0) desc = name; ctx.setProjectId(ctx.getRestApi(p).createProject(StringUtil.toTitle(name), StringUtil.toTitle(desc), pTempUri)); String pid = ctx.getProjectIdMandatory(); checkProjectCreationStatus(pid, p, ctx); l.info("Project id = '"+pid+"' created."); } catch (InterruptedException e) { throw new InternalErrorException(e); } } /** * Exports all DB tables to CSV * @param c command * @param p cli parameters * @param ctx current context */ private void exportJdbcToCsv(Command c, CliParams p, ProcessingContext ctx) throws IOException { try { String usr = null; if(c.checkParam("username")) usr = c.getParam("username"); String psw = null; if(c.checkParam("password")) psw = c.getParam("password"); String drv = c.getParamMandatory("driver"); String url = c.getParamMandatory("url"); String fl = c.getParamMandatory("dir"); c.paramsProcessed(); File dir = new File(fl); if(!dir.exists() || !dir.isDirectory()) { throw new InvalidParameterException("The dir parameter in the ExportJdbcToCsv command must be an existing directory."); } DatabaseToCsv d = new DatabaseToCsv(drv, url, usr, psw); d.export(dir.getAbsolutePath()); l.info("All tables successfully exported to "+dir.getAbsolutePath()); } catch (SQLException e) { throw new IOException(e); } } /** * Checks the project status. Waits till the status is LOADING * @param projectId project ID * @param p cli parameters * @param ctx current context * @throws InterruptedException internal problem with making file writable */ private void checkProjectCreationStatus(String projectId, CliParams p, ProcessingContext ctx) throws InterruptedException { l.debug("Checking project "+projectId+" loading status."); String status = "LOADING"; while("LOADING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getProjectStatus(projectId); l.debug("Project "+projectId+" loading status = "+status); Thread.sleep(500); } } /** * Drop project command processor * @param c command * @param p cli parameters * @param ctx current context */ private void dropProject(Command c, CliParams p, ProcessingContext ctx) { String id = ctx.getProjectId(); if (id == null) { id = c.getParamMandatory("id"); } else { String override = c.getParam("id"); if (override != null) id = override; } c.paramsProcessed(); ctx.getRestApi(p).dropProject(id); l.info("Project id = '"+id+"' dropped."); } /** * Invite user to a project * @param c command * @param p cli parameters * @param ctx current context */ private void inviteUser(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String email = c.getParamMandatory("email"); String msg = c.getParam("msg"); String role = c.getParam("role"); c.paramsProcessed(); ctx.getRestApi(p).inviteUser(pid, email, (msg != null)?(msg):(""), role); l.info("Successfully invited user "+email+" to the project "+pid); } /** * Migrate specified datasets * @param c command * @param p cli parameters * @param ctx current context */ private void migrateDatasets(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); l.info("Migrating project "+pid); String configFiles = c.getParamMandatory("configFiles"); c.paramsProcessed(); if(configFiles != null && configFiles.length() >0) { String[] schemas = configFiles.split(","); if(schemas != null && schemas.length >0) { List<String> manifests = new ArrayList<String>(); for(String schema : schemas) { File sf = new File(schema); if(sf.exists()) { SourceSchema srcSchema = SourceSchema.createSchema(sf); String ssn = srcSchema.getName(); List<Column> columns = AbstractConnector.populateColumnsFromSchema(srcSchema); SLI sli = ctx.getRestApi(p).getSLIById("dataset." + ssn, pid); String manifest = sli.getSLIManifest(columns); manifests.add(manifest); } else { l.debug("The configFile "+schema+" doesn't exists!"); l.error("The configFile "+schema+" doesn't exists!"); throw new InvalidParameterException("The configFile "+schema+" doesn't exists!"); } } String taskUri = ctx.getRestApi(p).migrateDataSets(pid, manifests); if(taskUri != null && taskUri.length() > 0) { l.debug("Checking migration status."); String status = ""; while(!"OK".equalsIgnoreCase(status) && !"ERROR".equalsIgnoreCase(status) && !"WARNING".equalsIgnoreCase(status)) { status = ctx.getRestApi(p).getMigrationStatus(taskUri); l.debug("Migration status = "+status); Thread.sleep(500); } l.info("Migration finished with status "+status); } else { l.info("No migration needed anymore."); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } /** * Generate manifests for specified datasets * @param c command * @param p cli parameters * @param ctx current context */ private void generateManifests(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); l.info("Generating manifests for project "+pid); String configFiles = c.getParamMandatory("configFiles"); String dir = c.getParamMandatory("dir"); c.paramsProcessed(); if(dir != null && dir.length()>0) { File targetDir = new File(dir); if(targetDir.exists() && targetDir.isDirectory()) { if(configFiles != null && configFiles.length() >0) { String[] schemas = configFiles.split(","); if(schemas != null && schemas.length >0) { for(String schema : schemas) { File sf = new File(schema); if(sf.exists()) { SourceSchema srcSchema = SourceSchema.createSchema(sf); String ssn = srcSchema.getName(); List<Column> columns = AbstractConnector.populateColumnsFromSchema(srcSchema); SLI sli = ctx.getRestApi(p).getSLIById("dataset." + ssn, pid); String manifest = sli.getSLIManifest(columns); FileUtil.writeStringToFile(manifest,targetDir.getAbsolutePath()+ System.getProperty("file.separator")+ssn+".json"); } else { l.debug("The configFile "+schema+" doesn't exists!"); l.error("The configFile "+schema+" doesn't exists!"); throw new InvalidParameterException("The configFile "+schema+" doesn't exists!"); } } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The configFiles parameter must contain a comma separated list of schema configuration files!"); l.error("The configFiles parameter must contain a comma separated list of schema configuration files!"); throw new InvalidParameterException("The configFiles parameter must contain a comma separated list of schema configuration files!"); } } else { l.debug("The `dir` parameter must point to a valid directory."); l.error("The `dir` parameter must point to a valid directory."); throw new InvalidParameterException("The `dir` parameter must point to a valid directory."); } } else { l.debug("Please specify a valid `dir` parameter for the GenerateManifests command."); l.error("Please specify a valid `dir` parameter for the GenerateManifests command."); throw new InvalidParameterException("Please specify a valid `dir` parameter for the GenerateManifests command."); } } /** * Retrieves a MD object * @param c command * @param p cli parameters * @param ctx current context */ private void getMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String ids = c.getParamMandatory("id"); String fl = c.getParamMandatory("file"); c.paramsProcessed(); int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in getMetadataObject must be an integer."); } MetadataObject ret = ctx.getRestApi(p).getMetadataObject(pid,id); FileUtil.writeJSONToFile(ret, fl); l.info("Retrieved metadata object "+id+" from the project "+pid+" and stored it in file "+fl); } /** * Stores a MD object * @param c command * @param p cli parameters * @param ctx current context */ private void storeMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String fl = c.getParamMandatory("file"); String ids = c.getParam("id"); c.paramsProcessed(); if(ids != null && ids.length() > 0) { int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in storeMetadataObject must be an integer."); } ctx.getRestApi(p).modifyMetadataObject(pid,id, FileUtil.readJSONFromFile(fl)); l.info("Modified metadata object "+id+" to the project "+pid); } else { ctx.getRestApi(p).createMetadataObject(pid, FileUtil.readJSONFromFile(fl)); l.info("Created a new metadata object in the project "+pid); } } /** * Drops a MD object * @param c command * @param p cli parameters * @param ctx current context */ private void dropMdObject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String ids = c.getParamMandatory("id"); c.paramsProcessed(); int id; try { id = Integer.parseInt(ids); } catch (NumberFormatException e) { throw new InvalidParameterException("The id in dropMetadataObject must be an integer."); } ctx.getRestApi(p).deleteMetadataObject(pid,id); l.info("Dropped metadata object "+id+" from the project "+pid); } /** * Enumerate reports * @param c command * @param p cli parameters * @param ctx current context */ private void getReports(Command c, CliParams p, ProcessingContext ctx) throws IOException { String pid = ctx.getProjectIdMandatory(); String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); List<String> uris = ctx.getRestApi(p).enumerateReports(pid); String result = ""; for(String uri : uris) { if(result.length() > 0) result += "\n" + uri; else result += uri; } FileUtil.writeStringToFile(result, fileName); l.info("Reports written into "+fileName); } /** * Enumerate reports * @param c command * @param p cli parameters * @param ctx current context */ private void executeReports(Command c, CliParams p, ProcessingContext ctx) throws IOException, InterruptedException { String pid = ctx.getProjectIdMandatory(); String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); String result = FileUtil.readStringFromFile(fileName).trim(); if(result != null && result.length()>0) { String[] uris = result.split("\n"); for(String uri : uris) { try { String defUri = ctx.getRestApi(p).getReportDefinition(uri.trim()); l.info("Executing report uri="+defUri); String task = ctx.getRestApi(p).executeReportDefinition(defUri.trim()); l.info("Report " +defUri+ " execution finished: " + task); } catch (GdcRestApiException e) { l.debug("The report uri="+uri+" can't be computed!"); l.info("The report uri="+uri+" can't be computed!"); } } } else { throw new IOException("There are no reports to execute."); } l.info("All reports executed."); } /** * Store project command processor * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void storeProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); String pid = ctx.getProjectIdMandatory(); FileUtil.writeStringToFile(pid, fileName); l.debug("Stored project id="+pid+" to "+fileName); l.info("Stored project id="+pid+" to "+fileName); } /** * Retrieve project command processor * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void retrieveProject(Command c, CliParams p, ProcessingContext ctx) throws IOException { String fileName = c.getParamMandatory("fileName"); c.paramsProcessed(); ctx.setProjectId(FileUtil.readStringFromFile(fileName).trim()); l.debug("Retrieved project id="+ctx.getProjectId()+" from "+fileName); l.info("Retrieved project id="+ctx.getProjectId()+" from "+fileName); } /** * Lock project command processor * @param c command * @param p cli parameters * @param ctx current context * @throws IOException in case of an IO issue */ private void lock(Command c, CliParams p, ProcessingContext ctx) throws IOException { final String path = c.getParamMandatory( "path"); c.paramsProcessed(); final File lock = new File(path); if (!lock.createNewFile()) { if (System.currentTimeMillis() - lock.lastModified() > LOCK_EXPIRATION_TIME) { lock.delete(); if (!lock.exists()) { lock(c, p, ctx); // retry } } l.debug("A concurrent process found using the " + path + " lock file."); throw new IOException("A concurrent process found using the " + path + " lock file."); } lock.deleteOnExit(); } /** * Instantiate all known connectors * TODO: this should be automated * @return array of all active connectors * @throws IOException in case of IO issues */ private Connector[] instantiateConnectors() throws IOException { return new Connector[] { CsvConnector.createConnector(), GaConnector.createConnector(), SfdcConnector.createConnector(), JdbcConnector.createConnector(), PtConnector.createConnector(), DateDimensionConnector.createConnector(), FacebookConnector.createConnector(), FacebookInsightsConnector.createConnector(), MsDynamicsConnector.createConnector(), SugarCrmConnector.createConnector(), ChargifyConnector.createConnector() }; } /** * Loads default values of common parameters from a properties file searching * the working directory and user's home. * @return default configuration */ private static Properties loadDefaults() { final String[] dirs = new String[]{ "user.dir", "user.home" }; final Properties props = new Properties(); for (final String d : dirs) { String path = System.getProperty(d) + File.separator + DEFAULT_PROPERTIES; File f = new File(path); if (f.exists() && f.canRead()) { try { FileInputStream is = new FileInputStream(f); props.load(is); l.debug("Successfully red the gdi configuration from '" + f.getAbsolutePath() + "'."); return props; } catch (IOException e) { l.warn("Readable gdi configuration '" + f.getAbsolutePath() + "' found be error occurred reading it."); l.debug("Error reading gdi configuration '" + f.getAbsolutePath() + "': ", e); } } } return props; } }
true
true
private GdcDI(CommandLine ln, Properties defaults) { try { cliParams = parse(ln, defaults); cliParams.setHttpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); cliParams.setFtpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_FTP_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); connectors = instantiateConnectors(); String execute = cliParams.get(CLI_PARAM_EXECUTE[0]); String scripts = cliParams.get(CLI_PARAM_SCRIPT); if(execute!= null && scripts != null && execute.length()>0 && scripts.length()>0) { throw new InvalidArgumentException("You can't execute a script and use the -e command line parameter at the same time."); } if(execute!= null && execute.length() > 0) { l.debug("Executing arg="+execute); execute(execute); } if(scripts!= null && scripts.length() > 0) { String[] sas = scripts.split(","); for(String script : sas) { l.debug("Executing file="+script); execute(new File(script)); } } if(cliParams.containsKey(CLI_PARAM_HELP[0])) l.info(commandsHelp()); finishedSucessfuly = true; } catch (InvalidArgumentException e) { l.error("Invalid or missing argument: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gooddata-cli [<options> ...] -H|--help|<script>|-e <command>", ops); finishedSucessfuly = false; } catch (InvalidCommandException e) { l.error("Invalid command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InvalidParameterException e) { l.error("Invalid command parameter: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (SfdcException e) { l.error("Error communicating with SalesForce: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ProcessingException e) { l.error("Error processing command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ModelException e) { l.error("Model issue: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (IOException e) { l.error("Encountered an IO problem. Please check that all files that you use in your command line arguments and commands exist." + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InternalErrorException e) { Throwable c = e.getCause(); if( c != null && c instanceof SQLException) { l.error("Error extracting data. Can't process the incoming data. Please check the CSV file " + "separator and consistency (same number of columns in each row). Also, please make sure " + "that the number of columns in your XML config file matches the number of rows in your " + "data source. Make sure that your file is readable by other users (particularly the mysql user). " + "More info: ", c); } else { l.error("Internal error: " + e.getMessage()); l.debug(e); c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } } finishedSucessfuly = false; } catch (HttpMethodException e) { l.debug("Error executing GoodData REST API: " + e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } String msg = e.getMessage(); String requestId = e.getRequestId(); if (requestId != null) { msg += "\n\n" + "If you believe this is not your fault, good people from support\n" + "portal (http://support.gooddata.com) may help you.\n\n" + "Show them this error ID: " + requestId; } l.error(msg); finishedSucessfuly = false; } catch (GdcRestApiException e) { l.error("REST API invocation error: " + e.getMessage()); l.debug(e, e); Throwable c = e.getCause(); while(c!=null) { if(c instanceof HttpMethodException) { HttpMethodException ex = (HttpMethodException)c; String msg = ex.getMessage(); if(msg != null && msg.length()>0 && msg.indexOf("/ldm/manage")>0) { l.error("Error creating/updating logical data model (executing MAQL DDL)."); if(msg.indexOf(".date")>0) { l.error("Bad time dimension schemaReference."); } else { l.error("You are either trying to create a data object that already exists " + "(executing the same MAQL multiple times) or providing a wrong reference " + "or schemaReference in your XML configuration."); } } } l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (GdcException e) { l.error("Unrecognized error: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } finally { context.getRestApi(cliParams).logout(); } }
private GdcDI(CommandLine ln, Properties defaults) { try { cliParams = parse(ln, defaults); cliParams.setHttpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); cliParams.setFtpConfig(new NamePasswordConfiguration( cliParams.containsKey(CLI_PARAM_INSECURE[0]) ? "http" : "https", cliParams.get(CLI_PARAM_FTP_HOST[0]), cliParams.get(CLI_PARAM_USERNAME[0]), cliParams.get(CLI_PARAM_PASSWORD[0]))); connectors = instantiateConnectors(); String execute = cliParams.get(CLI_PARAM_EXECUTE[0]); String scripts = cliParams.get(CLI_PARAM_SCRIPT); if(execute!= null && scripts != null && execute.length()>0 && scripts.length()>0) { throw new InvalidArgumentException("You can't execute a script and use the -e command line parameter at the same time."); } if(execute!= null && execute.length() > 0) { l.debug("Executing arg="+execute); execute(execute); } if(scripts!= null && scripts.length() > 0) { String[] sas = scripts.split(","); for(String script : sas) { l.debug("Executing file="+script); execute(new File(script)); } } if(cliParams.containsKey(CLI_PARAM_HELP[0])) l.info(commandsHelp()); finishedSucessfuly = true; } catch (InvalidArgumentException e) { l.error("Invalid or missing argument: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("gooddata-cli [<options> ...] -H|--help|<script>|-e <command>", ops); finishedSucessfuly = false; } catch (InvalidCommandException e) { l.error("Invalid command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InvalidParameterException e) { l.error("Invalid command parameter: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (SfdcException e) { l.error("Error communicating with SalesForce: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ProcessingException e) { l.error("Error processing command: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (ModelException e) { l.error("Model issue: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (IOException e) { l.error("Encountered an IO problem. Please check that all files that you use in your command line arguments and commands exist." + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } finishedSucessfuly = false; } catch (InternalErrorException e) { Throwable c = e.getCause(); if( c != null && c instanceof SQLException) { l.error("Error extracting data. Can't process the incoming data. Please check the CSV file " + "separator and consistency (same number of columns in each row). Also, please make sure " + "that the number of columns in your XML config file matches the number of rows in your " + "data source. Make sure that your file is readable by other users (particularly the mysql user). " + "More info: ", c); } else { l.error("Internal error: " + e.getMessage()); l.debug(e); c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } } finishedSucessfuly = false; } catch (HttpMethodException e) { l.debug("Error executing GoodData REST API: " + e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ",c); c = c.getCause(); } String msg = e.getMessage(); String requestId = e.getRequestId(); if (requestId != null) { msg += "\n\n" + "If you believe this is not your fault, good people from support\n" + "portal (http://support.gooddata.com) may help you.\n\n" + "Show them this error ID: " + requestId; } l.error(msg); finishedSucessfuly = false; } catch (GdcRestApiException e) { l.error("REST API invocation error: " + e.getMessage()); l.debug(e, e); Throwable c = e.getCause(); while(c!=null) { if(c instanceof HttpMethodException) { HttpMethodException ex = (HttpMethodException)c; String msg = ex.getMessage(); if(msg != null && msg.length()>0 && msg.indexOf("/ldm/manage")>0) { l.error("Error creating/updating logical data model (executing MAQL DDL)."); if(msg.indexOf(".date")>0) { l.error("Bad time dimension schemaReference."); } else { l.error("You are either trying to create a data object that already exists " + "(executing the same MAQL multiple times) or providing a wrong reference " + "or schemaReference in your XML configuration."); } } } l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } catch (GdcException e) { l.error("Unrecognized error: " + e.getMessage()); l.debug(e); Throwable c = e.getCause(); while(c!=null) { l.debug("Caused by: ", c); c = c.getCause(); } finishedSucessfuly = false; } finally { if(cliParams != null) context.getRestApi(cliParams).logout(); } }
diff --git a/src/main/java/com/ctb/pilot/study/algorithm/controller/AlgorithmContestController.java b/src/main/java/com/ctb/pilot/study/algorithm/controller/AlgorithmContestController.java index 5f3a2bb..40f1a30 100644 --- a/src/main/java/com/ctb/pilot/study/algorithm/controller/AlgorithmContestController.java +++ b/src/main/java/com/ctb/pilot/study/algorithm/controller/AlgorithmContestController.java @@ -1,84 +1,84 @@ package com.ctb.pilot.study.algorithm.controller; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.ctb.pilot.gamification.model.Leaderboard; import com.ctb.pilot.study.algorithm.model.AlgorithmContestHistory; import com.ctb.pilot.study.algorithm.model.AlgorithmProblem; import com.ctb.pilot.study.algorithm.model.ProgrammingLanguage; import com.ctb.pilot.study.algorithm.service.AlgorithmContestService; import com.ctb.pilot.user.model.User; @Controller public class AlgorithmContestController { private static final int INDEX_SUBMIT_ID = 0; private static final int INDEX_SUBMIT_DATE = 1; private static final int INDEX_SUBMIT_TIME = 2; private static final int INDEX_VERDICT = 3; private static final int INDEX_RUNTIME = 4; private static final int INDEX_LANGUAGE = 6; private ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yy/MM/dd HH:mm"); } }; @Resource private AlgorithmContestService algorithmContestService; @RequestMapping("/services/study/algorithm_contest/addHistory.do") public String addHistory(@RequestParam int contestSequence, @RequestParam String problemId, @RequestParam String submissionHistory, HttpServletRequest req) throws ParseException { String[] splitSubmissionHistory = submissionHistory.split("[\t ]+"); String submitId = splitSubmissionHistory[INDEX_SUBMIT_ID].trim(); Date submitTime = dateFormat.get().parse( splitSubmissionHistory[INDEX_SUBMIT_DATE].trim() + " " + splitSubmissionHistory[INDEX_SUBMIT_TIME].trim()); if (!splitSubmissionHistory[INDEX_VERDICT].trim().equals("Solved")) { throw new IllegalArgumentException(submissionHistory); } float runtime = Float.parseFloat(splitSubmissionHistory[INDEX_RUNTIME] .trim()); ProgrammingLanguage language = ProgrammingLanguage .valueOf(splitSubmissionHistory[INDEX_LANGUAGE].trim()); HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); int userSequence = user.getSequence(); String sourceUrl = "http://www.programming-challenges.com/pg.php?page=viewsubmission&subid=" + submitId; AlgorithmContestHistory history = new AlgorithmContestHistory( userSequence, contestSequence, problemId, submitId, submitTime, runtime, language.getSequence(), sourceUrl); algorithmContestService.addhistory(history); - return "redirect:/common/web_template.jsp?body_path=/services/study/algorithm_contest/index.html"; + return "redirect:/common/web_template.jsp?body_path=/services/study/algorithm_contest/show.do"; } @RequestMapping("/services/study/algorithm_contest/show.do") public String show(Model model) { Leaderboard leaderboard = algorithmContestService.getLeaderboard(); model.addAttribute("leaderboardEntries", leaderboard.getEntries()); List<AlgorithmProblem> problemList = algorithmContestService .getAllProblems(); model.addAttribute("problemList", problemList); return "services/study/algorithm_contest/show_algorithm_contest"; } }
true
true
public String addHistory(@RequestParam int contestSequence, @RequestParam String problemId, @RequestParam String submissionHistory, HttpServletRequest req) throws ParseException { String[] splitSubmissionHistory = submissionHistory.split("[\t ]+"); String submitId = splitSubmissionHistory[INDEX_SUBMIT_ID].trim(); Date submitTime = dateFormat.get().parse( splitSubmissionHistory[INDEX_SUBMIT_DATE].trim() + " " + splitSubmissionHistory[INDEX_SUBMIT_TIME].trim()); if (!splitSubmissionHistory[INDEX_VERDICT].trim().equals("Solved")) { throw new IllegalArgumentException(submissionHistory); } float runtime = Float.parseFloat(splitSubmissionHistory[INDEX_RUNTIME] .trim()); ProgrammingLanguage language = ProgrammingLanguage .valueOf(splitSubmissionHistory[INDEX_LANGUAGE].trim()); HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); int userSequence = user.getSequence(); String sourceUrl = "http://www.programming-challenges.com/pg.php?page=viewsubmission&subid=" + submitId; AlgorithmContestHistory history = new AlgorithmContestHistory( userSequence, contestSequence, problemId, submitId, submitTime, runtime, language.getSequence(), sourceUrl); algorithmContestService.addhistory(history); return "redirect:/common/web_template.jsp?body_path=/services/study/algorithm_contest/index.html"; }
public String addHistory(@RequestParam int contestSequence, @RequestParam String problemId, @RequestParam String submissionHistory, HttpServletRequest req) throws ParseException { String[] splitSubmissionHistory = submissionHistory.split("[\t ]+"); String submitId = splitSubmissionHistory[INDEX_SUBMIT_ID].trim(); Date submitTime = dateFormat.get().parse( splitSubmissionHistory[INDEX_SUBMIT_DATE].trim() + " " + splitSubmissionHistory[INDEX_SUBMIT_TIME].trim()); if (!splitSubmissionHistory[INDEX_VERDICT].trim().equals("Solved")) { throw new IllegalArgumentException(submissionHistory); } float runtime = Float.parseFloat(splitSubmissionHistory[INDEX_RUNTIME] .trim()); ProgrammingLanguage language = ProgrammingLanguage .valueOf(splitSubmissionHistory[INDEX_LANGUAGE].trim()); HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); int userSequence = user.getSequence(); String sourceUrl = "http://www.programming-challenges.com/pg.php?page=viewsubmission&subid=" + submitId; AlgorithmContestHistory history = new AlgorithmContestHistory( userSequence, contestSequence, problemId, submitId, submitTime, runtime, language.getSequence(), sourceUrl); algorithmContestService.addhistory(history); return "redirect:/common/web_template.jsp?body_path=/services/study/algorithm_contest/show.do"; }
diff --git a/src/main/java/hudson/plugins/warnings/WarningsResultBuilder.java b/src/main/java/hudson/plugins/warnings/WarningsResultBuilder.java index f9032ec1..e0af59d2 100644 --- a/src/main/java/hudson/plugins/warnings/WarningsResultBuilder.java +++ b/src/main/java/hudson/plugins/warnings/WarningsResultBuilder.java @@ -1,36 +1,37 @@ package hudson.plugins.warnings; import hudson.model.AbstractBuild; import hudson.plugins.warnings.util.model.JavaProject; /** * Creates a new warnings result based on the values of a previous build and the * current project. * * @author Ulli Hafner */ public class WarningsResultBuilder { /** * Creates a result that persists the warnings information for the * specified build. * * @param build * the build to create the action for * @param project * the project containing the annotations * @return the result action */ public WarningsResult build(final AbstractBuild<?, ?> build, final JavaProject project) { Object previous = build.getPreviousBuild(); - if (previous instanceof AbstractBuild<?, ?>) { + while (previous instanceof AbstractBuild<?, ?> && previous != null) { AbstractBuild<?, ?> previousBuild = (AbstractBuild<?, ?>)previous; WarningsResultAction previousAction = previousBuild.getAction(WarningsResultAction.class); if (previousAction != null) { return new WarningsResult(build, project, previousAction.getResult().getProject(), previousAction.getResult().getZeroWarningsHighScore()); } + previous = previousBuild.getPreviousBuild(); } return new WarningsResult(build, project); } }
false
true
public WarningsResult build(final AbstractBuild<?, ?> build, final JavaProject project) { Object previous = build.getPreviousBuild(); if (previous instanceof AbstractBuild<?, ?>) { AbstractBuild<?, ?> previousBuild = (AbstractBuild<?, ?>)previous; WarningsResultAction previousAction = previousBuild.getAction(WarningsResultAction.class); if (previousAction != null) { return new WarningsResult(build, project, previousAction.getResult().getProject(), previousAction.getResult().getZeroWarningsHighScore()); } } return new WarningsResult(build, project); }
public WarningsResult build(final AbstractBuild<?, ?> build, final JavaProject project) { Object previous = build.getPreviousBuild(); while (previous instanceof AbstractBuild<?, ?> && previous != null) { AbstractBuild<?, ?> previousBuild = (AbstractBuild<?, ?>)previous; WarningsResultAction previousAction = previousBuild.getAction(WarningsResultAction.class); if (previousAction != null) { return new WarningsResult(build, project, previousAction.getResult().getProject(), previousAction.getResult().getZeroWarningsHighScore()); } previous = previousBuild.getPreviousBuild(); } return new WarningsResult(build, project); }
diff --git a/src/com/android/settings/DevelopmentSettings.java b/src/com/android/settings/DevelopmentSettings.java index 38a34b7a..dc352e9a 100644 --- a/src/com/android/settings/DevelopmentSettings.java +++ b/src/com/android/settings/DevelopmentSettings.java @@ -1,1166 +1,1166 @@ /* * 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.settings; import static android.Manifest.permission.READ_EXTERNAL_STORAGE; import android.app.ActionBar; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.ActivityThread; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.admin.DevicePolicyManager; import android.app.backup.IBackupManager; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.wifi.IWifiManager; import android.net.wifi.WifiInfo; import android.os.AsyncTask; import android.os.BatteryManager; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; import android.os.RemoteException; import android.os.ServiceManager; import android.os.StrictMode; import android.os.SystemProperties; import android.os.Trace; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.MultiCheckPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; import android.provider.Settings; import android.text.TextUtils; import android.view.Gravity; import android.view.HardwareRenderer; import android.view.IWindowManager; import android.view.View; import android.widget.CompoundButton; import android.widget.Switch; import java.util.ArrayList; import java.util.HashSet; /* * Displays preferences for application developers. */ public class DevelopmentSettings extends PreferenceFragment implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener, OnPreferenceChangeListener, CompoundButton.OnCheckedChangeListener { private static final String ENABLE_ADB = "enable_adb"; private static final String ADB_TCPIP = "adb_over_network"; private static final String KEEP_SCREEN_ON = "keep_screen_on"; private static final String ALLOW_MOCK_LOCATION = "allow_mock_location"; private static final String HDCP_CHECKING_KEY = "hdcp_checking"; private static final String HDCP_CHECKING_PROPERTY = "persist.sys.hdcp_checking"; private static final String ENFORCE_READ_EXTERNAL = "enforce_read_external"; private static final String LOCAL_BACKUP_PASSWORD = "local_backup_password"; private static final String HARDWARE_UI_PROPERTY = "persist.sys.ui.hw"; private static final String DEBUG_APP_KEY = "debug_app"; private static final String WAIT_FOR_DEBUGGER_KEY = "wait_for_debugger"; private static final String STRICT_MODE_KEY = "strict_mode"; private static final String POINTER_LOCATION_KEY = "pointer_location"; private static final String SHOW_TOUCHES_KEY = "show_touches"; private static final String SHOW_SCREEN_UPDATES_KEY = "show_screen_updates"; private static final String DISABLE_OVERLAYS_KEY = "disable_overlays"; private static final String SHOW_CPU_USAGE_KEY = "show_cpu_usage"; private static final String FORCE_HARDWARE_UI_KEY = "force_hw_ui"; private static final String TRACK_FRAME_TIME_KEY = "track_frame_time"; private static final String SHOW_HW_SCREEN_UPDATES_KEY = "show_hw_screen_udpates"; private static final String DEBUG_LAYOUT_KEY = "debug_layout"; private static final String WINDOW_ANIMATION_SCALE_KEY = "window_animation_scale"; private static final String TRANSITION_ANIMATION_SCALE_KEY = "transition_animation_scale"; private static final String ANIMATOR_DURATION_SCALE_KEY = "animator_duration_scale"; private static final String ROOT_ACCESS_KEY = "root_access"; private static final String ROOT_ACCESS_PROPERTY = "persist.sys.root_access"; private static final String ENABLE_TRACES_KEY = "enable_traces"; private static final String IMMEDIATELY_DESTROY_ACTIVITIES_KEY = "immediately_destroy_activities"; private static final String APP_PROCESS_LIMIT_KEY = "app_process_limit"; private static final String SHOW_ALL_ANRS_KEY = "show_all_anrs"; private static final String TAG_CONFIRM_ENFORCE = "confirm_enforce"; private static final int RESULT_DEBUG_APP = 1000; private IWindowManager mWindowManager; private IBackupManager mBackupManager; private DevicePolicyManager mDpm; private Switch mEnabledSwitch; private boolean mLastEnabledState; private boolean mHaveDebugSettings; private boolean mDontPokeProperties; private CheckBoxPreference mEnableAdb; private CheckBoxPreference mAdbOverNetwork; private CheckBoxPreference mKeepScreenOn; private CheckBoxPreference mEnforceReadExternal; private CheckBoxPreference mAllowMockLocation; private PreferenceScreen mPassword; private String mDebugApp; private Preference mDebugAppPref; private CheckBoxPreference mWaitForDebugger; private CheckBoxPreference mStrictMode; private CheckBoxPreference mPointerLocation; private CheckBoxPreference mShowTouches; private CheckBoxPreference mShowScreenUpdates; private CheckBoxPreference mDisableOverlays; private CheckBoxPreference mShowCpuUsage; private CheckBoxPreference mForceHardwareUi; private CheckBoxPreference mTrackFrameTime; private CheckBoxPreference mShowHwScreenUpdates; private CheckBoxPreference mDebugLayout; private ListPreference mWindowAnimationScale; private ListPreference mTransitionAnimationScale; private ListPreference mAnimatorDurationScale; private MultiCheckPreference mEnableTracesPref; private CheckBoxPreference mImmediatelyDestroyActivities; private ListPreference mAppProcessLimit; private CheckBoxPreference mShowAllANRs; private ListPreference mRootAccess; private Object mSelectedRootValue; private final ArrayList<Preference> mAllPrefs = new ArrayList<Preference>(); private final ArrayList<CheckBoxPreference> mResetCbPrefs = new ArrayList<CheckBoxPreference>(); private final HashSet<Preference> mDisabledPrefs = new HashSet<Preference>(); // To track whether a confirmation dialog was clicked. private boolean mDialogClicked; private Dialog mEnableDialog; private Dialog mAdbDialog; private Dialog mRootDialog; // To track whether Yes was clicked in the adb warning dialog private boolean mOkClicked; private Dialog mOkDialog; private String mCurrentDialog; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); mBackupManager = IBackupManager.Stub.asInterface( ServiceManager.getService(Context.BACKUP_SERVICE)); mDpm = (DevicePolicyManager)getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE); addPreferencesFromResource(R.xml.development_prefs); mEnableAdb = findAndInitCheckboxPref(ENABLE_ADB); mAdbOverNetwork = findAndInitCheckboxPref(ADB_TCPIP); mKeepScreenOn = findAndInitCheckboxPref(KEEP_SCREEN_ON); mEnforceReadExternal = findAndInitCheckboxPref(ENFORCE_READ_EXTERNAL); mAllowMockLocation = findAndInitCheckboxPref(ALLOW_MOCK_LOCATION); mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD); mAllPrefs.add(mPassword); mDebugAppPref = findPreference(DEBUG_APP_KEY); mAllPrefs.add(mDebugAppPref); mWaitForDebugger = findAndInitCheckboxPref(WAIT_FOR_DEBUGGER_KEY); mStrictMode = findAndInitCheckboxPref(STRICT_MODE_KEY); mPointerLocation = findAndInitCheckboxPref(POINTER_LOCATION_KEY); mShowTouches = findAndInitCheckboxPref(SHOW_TOUCHES_KEY); mShowScreenUpdates = findAndInitCheckboxPref(SHOW_SCREEN_UPDATES_KEY); mDisableOverlays = findAndInitCheckboxPref(DISABLE_OVERLAYS_KEY); mShowCpuUsage = findAndInitCheckboxPref(SHOW_CPU_USAGE_KEY); mForceHardwareUi = findAndInitCheckboxPref(FORCE_HARDWARE_UI_KEY); mTrackFrameTime = findAndInitCheckboxPref(TRACK_FRAME_TIME_KEY); mShowHwScreenUpdates = findAndInitCheckboxPref(SHOW_HW_SCREEN_UPDATES_KEY); mDebugLayout = findAndInitCheckboxPref(DEBUG_LAYOUT_KEY); mWindowAnimationScale = (ListPreference) findPreference(WINDOW_ANIMATION_SCALE_KEY); mAllPrefs.add(mWindowAnimationScale); mWindowAnimationScale.setOnPreferenceChangeListener(this); mTransitionAnimationScale = (ListPreference) findPreference(TRANSITION_ANIMATION_SCALE_KEY); mAllPrefs.add(mTransitionAnimationScale); mTransitionAnimationScale.setOnPreferenceChangeListener(this); mAnimatorDurationScale = (ListPreference) findPreference(ANIMATOR_DURATION_SCALE_KEY); mAllPrefs.add(mAnimatorDurationScale); mAnimatorDurationScale.setOnPreferenceChangeListener(this); mEnableTracesPref = (MultiCheckPreference)findPreference(ENABLE_TRACES_KEY); String[] traceValues = new String[Trace.TRACE_TAGS.length]; for (int i=Trace.TRACE_FLAGS_START_BIT; i<traceValues.length; i++) { traceValues[i] = Integer.toString(1<<i); } mEnableTracesPref.setEntries(Trace.TRACE_TAGS); mEnableTracesPref.setEntryValues(traceValues); mAllPrefs.add(mEnableTracesPref); mEnableTracesPref.setOnPreferenceChangeListener(this); mImmediatelyDestroyActivities = (CheckBoxPreference) findPreference( IMMEDIATELY_DESTROY_ACTIVITIES_KEY); mAllPrefs.add(mImmediatelyDestroyActivities); mResetCbPrefs.add(mImmediatelyDestroyActivities); mAppProcessLimit = (ListPreference) findPreference(APP_PROCESS_LIMIT_KEY); mAllPrefs.add(mAppProcessLimit); mAppProcessLimit.setOnPreferenceChangeListener(this); mShowAllANRs = (CheckBoxPreference) findPreference( SHOW_ALL_ANRS_KEY); mAllPrefs.add(mShowAllANRs); mResetCbPrefs.add(mShowAllANRs); Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY); if (hdcpChecking != null) { mAllPrefs.add(hdcpChecking); } removeHdcpOptionsForProduction(); mRootAccess = (ListPreference) findPreference(ROOT_ACCESS_KEY); mRootAccess.setOnPreferenceChangeListener(this); removeRootOptionsIfRequired(); } private CheckBoxPreference findAndInitCheckboxPref(String key) { CheckBoxPreference pref = (CheckBoxPreference) findPreference(key); if (pref == null) { throw new IllegalArgumentException("Cannot find preference with key = " + key); } mAllPrefs.add(pref); mResetCbPrefs.add(pref); return pref; } private void removeRootOptionsIfRequired() { // user builds don't get root, and eng always gets root if (!Build.IS_DEBUGGABLE || "eng".equals(Build.TYPE)) { if (mRootAccess != null) { getPreferenceScreen().removePreference(mRootAccess); } } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Activity activity = getActivity(); mEnabledSwitch = new Switch(activity); final int padding = activity.getResources().getDimensionPixelSize( R.dimen.action_bar_switch_padding); mEnabledSwitch.setPadding(0, 0, padding, 0); mEnabledSwitch.setOnCheckedChangeListener(this); } @Override public void onStart() { super.onStart(); final Activity activity = getActivity(); activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(mEnabledSwitch, new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.RIGHT)); } @Override public void onStop() { super.onStop(); final Activity activity = getActivity(); activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM); activity.getActionBar().setCustomView(null); } private void removeHdcpOptionsForProduction() { if ("user".equals(Build.TYPE)) { Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY); if (hdcpChecking != null) { // Remove the preference getPreferenceScreen().removePreference(hdcpChecking); mAllPrefs.remove(hdcpChecking); } } } private void setPrefsEnabledState(boolean enabled) { for (int i = 0; i < mAllPrefs.size(); i++) { Preference pref = mAllPrefs.get(i); pref.setEnabled(enabled && !mDisabledPrefs.contains(pref)); } updateAllOptions(); } @Override public void onResume() { super.onResume(); if (mDpm.getMaximumTimeToLock(null) > 0) { // A DeviceAdmin has specified a maximum time until the device // will lock... in this case we can't allow the user to turn // on "stay awake when plugged in" because that would defeat the // restriction. mDisabledPrefs.add(mKeepScreenOn); } else { mDisabledPrefs.remove(mKeepScreenOn); } final ContentResolver cr = getActivity().getContentResolver(); mLastEnabledState = Settings.Secure.getInt(cr, Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; mEnabledSwitch.setChecked(mLastEnabledState); setPrefsEnabledState(mLastEnabledState); if (mHaveDebugSettings && !mLastEnabledState) { // Overall debugging is disabled, but there are some debug // settings that are enabled. This is an invalid state. Switch // to debug settings being enabled, so the user knows there is // stuff enabled and can turn it all off if they want. Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, 1); mLastEnabledState = true; setPrefsEnabledState(mLastEnabledState); } } void updateCheckBox(CheckBoxPreference checkBox, boolean value) { checkBox.setChecked(value); mHaveDebugSettings |= value; } private void updateAllOptions() { final Context context = getActivity(); final ContentResolver cr = context.getContentResolver(); mHaveDebugSettings = false; updateCheckBox(mEnableAdb, Settings.Secure.getInt(cr, Settings.Secure.ADB_ENABLED, 0) != 0); updateAdbOverNetwork(); updateCheckBox(mKeepScreenOn, Settings.System.getInt(cr, Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0) != 0); updateCheckBox(mEnforceReadExternal, isPermissionEnforced(context, READ_EXTERNAL_STORAGE)); updateCheckBox(mAllowMockLocation, Settings.Secure.getInt(cr, Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0); updateHdcpValues(); updatePasswordSummary(); updateDebuggerOptions(); updateStrictModeVisualOptions(); updatePointerLocationOptions(); updateShowTouchesOptions(); updateFlingerOptions(); updateCpuUsageOptions(); updateHardwareUiOptions(); updateTrackFrameTimeOptions(); updateShowHwScreenUpdatesOptions(); updateDebugLayoutOptions(); updateAnimationScaleOptions(); updateEnableTracesOptions(); updateImmediatelyDestroyActivitiesOptions(); updateAppProcessLimitOptions(); updateShowAllANRsOptions(); updateRootAccessOptions(); } private void updateAdbOverNetwork() { int mPort = Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.ADB_PORT, 0); boolean mEnabled = mPort > 0; mAdbOverNetwork.setChecked(mEnabled); if (mEnabled) { IWifiManager mWifiManager = IWifiManager.Stub.asInterface( ServiceManager.getService(Context.WIFI_SERVICE)); WifiInfo mWifiInfo = null; try { mWifiInfo = mWifiManager.getConnectionInfo(); } catch (RemoteException ex) { ex.printStackTrace(); } if (mWifiInfo != null) { mAdbOverNetwork.setSummary("Listening: " + android.text.format.Formatter .formatIpAddress(mWifiInfo.getIpAddress()) + ":" + String.valueOf(mPort)); } else { mAdbOverNetwork.setSummary(R.string.adb_over_network_summary); } } else { mAdbOverNetwork.setSummary(R.string.adb_over_network_summary); } } private void resetDangerousOptions() { mDontPokeProperties = true; for (int i=0; i<mResetCbPrefs.size(); i++) { CheckBoxPreference cb = mResetCbPrefs.get(i); if (cb.isChecked()) { cb.setChecked(false); onPreferenceTreeClick(null, cb); } } resetDebuggerOptions(); writeAnimationScaleOption(0, mWindowAnimationScale, null); writeAnimationScaleOption(1, mTransitionAnimationScale, null); writeAnimationScaleOption(2, mAnimatorDurationScale, null); writeEnableTracesOptions(0); writeAppProcessLimitOptions(null); mHaveDebugSettings = false; updateAllOptions(); mDontPokeProperties = false; pokeSystemProperties(); } private void updateRootAccessOptions() { String value = SystemProperties.get(ROOT_ACCESS_PROPERTY, "1"); mRootAccess.setValue(value); mRootAccess.setSummary(getResources() .getStringArray(R.array.root_access_entries)[Integer.valueOf(value)]); } private void writeRootAccessOptions(Object newValue) { String oldValue = SystemProperties.get(ROOT_ACCESS_PROPERTY, "1"); SystemProperties.set(ROOT_ACCESS_PROPERTY, newValue.toString()); if (Integer.valueOf(newValue.toString()) < 2 && !oldValue.equals(newValue) && "1".equals(SystemProperties.get("service.adb.root", "0"))) { SystemProperties.set("service.adb.root", "0"); Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 0); Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 1); } updateRootAccessOptions(); } private void updateHdcpValues() { int index = 1; // Defaults to drm-only. Needs to match with R.array.hdcp_checking_values ListPreference hdcpChecking = (ListPreference) findPreference(HDCP_CHECKING_KEY); if (hdcpChecking != null) { String currentValue = SystemProperties.get(HDCP_CHECKING_PROPERTY); String[] values = getResources().getStringArray(R.array.hdcp_checking_values); String[] summaries = getResources().getStringArray(R.array.hdcp_checking_summaries); for (int i = 0; i < values.length; i++) { if (currentValue.equals(values[i])) { index = i; break; } } hdcpChecking.setValue(values[index]); hdcpChecking.setSummary(summaries[index]); hdcpChecking.setOnPreferenceChangeListener(this); } } private void updatePasswordSummary() { try { if (mBackupManager.hasBackupPassword()) { mPassword.setSummary(R.string.local_backup_password_summary_change); } else { mPassword.setSummary(R.string.local_backup_password_summary_none); } } catch (RemoteException e) { // Not much we can do here } } private void writeDebuggerOptions() { try { ActivityManagerNative.getDefault().setDebugApp( mDebugApp, mWaitForDebugger.isChecked(), true); } catch (RemoteException ex) { } } private static void resetDebuggerOptions() { try { ActivityManagerNative.getDefault().setDebugApp( null, false, true); } catch (RemoteException ex) { } } private void updateDebuggerOptions() { mDebugApp = Settings.System.getString( getActivity().getContentResolver(), Settings.System.DEBUG_APP); updateCheckBox(mWaitForDebugger, Settings.System.getInt( getActivity().getContentResolver(), Settings.System.WAIT_FOR_DEBUGGER, 0) != 0); if (mDebugApp != null && mDebugApp.length() > 0) { String label; try { ApplicationInfo ai = getActivity().getPackageManager().getApplicationInfo(mDebugApp, PackageManager.GET_DISABLED_COMPONENTS); CharSequence lab = getActivity().getPackageManager().getApplicationLabel(ai); label = lab != null ? lab.toString() : mDebugApp; } catch (PackageManager.NameNotFoundException e) { label = mDebugApp; } mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_set, label)); mWaitForDebugger.setEnabled(true); mHaveDebugSettings = true; } else { mDebugAppPref.setSummary(getResources().getString(R.string.debug_app_not_set)); mWaitForDebugger.setEnabled(false); } } // Returns the current state of the system property that controls // strictmode flashes. One of: // 0: not explicitly set one way or another // 1: on // 2: off private static int currentStrictModeActiveIndex() { if (TextUtils.isEmpty(SystemProperties.get(StrictMode.VISUAL_PROPERTY))) { return 0; } boolean enabled = SystemProperties.getBoolean(StrictMode.VISUAL_PROPERTY, false); return enabled ? 1 : 2; } private void writeStrictModeVisualOptions() { try { mWindowManager.setStrictModeVisualIndicatorPreference(mStrictMode.isChecked() ? "1" : ""); } catch (RemoteException e) { } } private void updateStrictModeVisualOptions() { updateCheckBox(mStrictMode, currentStrictModeActiveIndex() == 1); } private void writePointerLocationOptions() { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.POINTER_LOCATION, mPointerLocation.isChecked() ? 1 : 0); } private void updatePointerLocationOptions() { updateCheckBox(mPointerLocation, Settings.System.getInt(getActivity().getContentResolver(), Settings.System.POINTER_LOCATION, 0) != 0); } private void writeShowTouchesOptions() { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.SHOW_TOUCHES, mShowTouches.isChecked() ? 1 : 0); } private void updateShowTouchesOptions() { updateCheckBox(mShowTouches, Settings.System.getInt(getActivity().getContentResolver(), Settings.System.SHOW_TOUCHES, 0) != 0); } private void updateFlingerOptions() { // magic communication with surface flinger. try { IBinder flinger = ServiceManager.getService("SurfaceFlinger"); if (flinger != null) { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken("android.ui.ISurfaceComposer"); flinger.transact(1010, data, reply, 0); @SuppressWarnings("unused") int showCpu = reply.readInt(); @SuppressWarnings("unused") int enableGL = reply.readInt(); int showUpdates = reply.readInt(); updateCheckBox(mShowScreenUpdates, showUpdates != 0); @SuppressWarnings("unused") int showBackground = reply.readInt(); int disableOverlays = reply.readInt(); updateCheckBox(mDisableOverlays, disableOverlays != 0); reply.recycle(); data.recycle(); } } catch (RemoteException ex) { } } private void writeShowUpdatesOption() { try { IBinder flinger = ServiceManager.getService("SurfaceFlinger"); if (flinger != null) { Parcel data = Parcel.obtain(); data.writeInterfaceToken("android.ui.ISurfaceComposer"); final int showUpdates = mShowScreenUpdates.isChecked() ? 1 : 0; data.writeInt(showUpdates); flinger.transact(1002, data, null, 0); data.recycle(); updateFlingerOptions(); } } catch (RemoteException ex) { } } private void writeDisableOverlaysOption() { try { IBinder flinger = ServiceManager.getService("SurfaceFlinger"); if (flinger != null) { Parcel data = Parcel.obtain(); data.writeInterfaceToken("android.ui.ISurfaceComposer"); final int disableOverlays = mDisableOverlays.isChecked() ? 1 : 0; data.writeInt(disableOverlays); flinger.transact(1008, data, null, 0); data.recycle(); updateFlingerOptions(); } } catch (RemoteException ex) { } } private void updateHardwareUiOptions() { updateCheckBox(mForceHardwareUi, SystemProperties.getBoolean(HARDWARE_UI_PROPERTY, false)); } private void writeHardwareUiOptions() { SystemProperties.set(HARDWARE_UI_PROPERTY, mForceHardwareUi.isChecked() ? "true" : "false"); pokeSystemProperties(); } private void updateTrackFrameTimeOptions() { updateCheckBox(mTrackFrameTime, SystemProperties.getBoolean(HardwareRenderer.PROFILE_PROPERTY, false)); } private void writeTrackFrameTimeOptions() { SystemProperties.set(HardwareRenderer.PROFILE_PROPERTY, mTrackFrameTime.isChecked() ? "true" : "false"); pokeSystemProperties(); } private void updateShowHwScreenUpdatesOptions() { updateCheckBox(mShowHwScreenUpdates, SystemProperties.getBoolean(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, false)); } private void writeShowHwScreenUpdatesOptions() { SystemProperties.set(HardwareRenderer.DEBUG_DIRTY_REGIONS_PROPERTY, mShowHwScreenUpdates.isChecked() ? "true" : "false"); pokeSystemProperties(); } private void updateDebugLayoutOptions() { updateCheckBox(mDebugLayout, SystemProperties.getBoolean(View.DEBUG_LAYOUT_PROPERTY, false)); } private void writeDebugLayoutOptions() { SystemProperties.set(View.DEBUG_LAYOUT_PROPERTY, mDebugLayout.isChecked() ? "true" : "false"); pokeSystemProperties(); } private void updateCpuUsageOptions() { updateCheckBox(mShowCpuUsage, Settings.System.getInt(getActivity().getContentResolver(), Settings.System.SHOW_PROCESSES, 0) != 0); } private void writeCpuUsageOptions() { boolean value = mShowCpuUsage.isChecked(); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.SHOW_PROCESSES, value ? 1 : 0); Intent service = (new Intent()) .setClassName("com.android.systemui", "com.android.systemui.LoadAverageService"); if (value) { getActivity().startService(service); } else { getActivity().stopService(service); } } private void writeImmediatelyDestroyActivitiesOptions() { try { ActivityManagerNative.getDefault().setAlwaysFinish( mImmediatelyDestroyActivities.isChecked()); } catch (RemoteException ex) { } } private void updateImmediatelyDestroyActivitiesOptions() { updateCheckBox(mImmediatelyDestroyActivities, Settings.System.getInt( getActivity().getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0); } private void updateAnimationScaleValue(int which, ListPreference pref) { try { float scale = mWindowManager.getAnimationScale(which); if (scale != 1) { mHaveDebugSettings = true; } CharSequence[] values = pref.getEntryValues(); for (int i=0; i<values.length; i++) { float val = Float.parseFloat(values[i].toString()); if (scale <= val) { pref.setValueIndex(i); pref.setSummary(pref.getEntries()[i]); return; } } pref.setValueIndex(values.length-1); pref.setSummary(pref.getEntries()[0]); } catch (RemoteException e) { } } private void updateAnimationScaleOptions() { updateAnimationScaleValue(0, mWindowAnimationScale); updateAnimationScaleValue(1, mTransitionAnimationScale); updateAnimationScaleValue(2, mAnimatorDurationScale); } private void writeAnimationScaleOption(int which, ListPreference pref, Object newValue) { try { float scale = newValue != null ? Float.parseFloat(newValue.toString()) : 1; mWindowManager.setAnimationScale(which, scale); updateAnimationScaleValue(which, pref); } catch (RemoteException e) { } } private void updateAppProcessLimitOptions() { try { int limit = ActivityManagerNative.getDefault().getProcessLimit(); CharSequence[] values = mAppProcessLimit.getEntryValues(); for (int i=0; i<values.length; i++) { int val = Integer.parseInt(values[i].toString()); if (val >= limit) { if (i != 0) { mHaveDebugSettings = true; } mAppProcessLimit.setValueIndex(i); mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]); return; } } mAppProcessLimit.setValueIndex(0); mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]); } catch (RemoteException e) { } } private void writeAppProcessLimitOptions(Object newValue) { try { int limit = newValue != null ? Integer.parseInt(newValue.toString()) : -1; ActivityManagerNative.getDefault().setProcessLimit(limit); updateAppProcessLimitOptions(); } catch (RemoteException e) { } } private void writeShowAllANRsOptions() { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, mShowAllANRs.isChecked() ? 1 : 0); } private void updateShowAllANRsOptions() { updateCheckBox(mShowAllANRs, Settings.Secure.getInt( getActivity().getContentResolver(), Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0); } private void updateEnableTracesOptions() { String strValue = SystemProperties.get(Trace.PROPERTY_TRACE_TAG_ENABLEFLAGS); long flags = SystemProperties.getLong(Trace.PROPERTY_TRACE_TAG_ENABLEFLAGS, 0); String[] values = mEnableTracesPref.getEntryValues(); int numSet = 0; for (int i=Trace.TRACE_FLAGS_START_BIT; i<values.length; i++) { boolean set = (flags&(1<<i)) != 0; mEnableTracesPref.setValue(i-Trace.TRACE_FLAGS_START_BIT, set); if (set) { numSet++; } } if (numSet == 0) { mEnableTracesPref.setSummary(R.string.enable_traces_summary_none); } else if (numSet == values.length) { mHaveDebugSettings = true; mEnableTracesPref.setSummary(R.string.enable_traces_summary_all); } else { mHaveDebugSettings = true; mEnableTracesPref.setSummary(getString(R.string.enable_traces_summary_num, numSet)); } } private void writeEnableTracesOptions() { long value = 0; String[] values = mEnableTracesPref.getEntryValues(); for (int i=Trace.TRACE_FLAGS_START_BIT; i<values.length; i++) { if (mEnableTracesPref.getValue(i-Trace.TRACE_FLAGS_START_BIT)) { value |= 1<<i; } } writeEnableTracesOptions(value); // Make sure summary is updated. updateEnableTracesOptions(); } private void writeEnableTracesOptions(long value) { SystemProperties.set(Trace.PROPERTY_TRACE_TAG_ENABLEFLAGS, "0x" + Long.toString(value, 16)); pokeSystemProperties(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView == mEnabledSwitch) { if (isChecked != mLastEnabledState) { if (isChecked) { mDialogClicked = false; if (mEnableDialog != null) dismissDialogs(); mEnableDialog = new AlertDialog.Builder(getActivity()).setMessage( getActivity().getResources().getString( R.string.dev_settings_warning_message)) .setTitle(R.string.dev_settings_warning_title) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mEnableDialog.setOnDismissListener(this); } else { resetDangerousOptions(); Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, 0); mLastEnabledState = isChecked; setPrefsEnabledState(mLastEnabledState); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RESULT_DEBUG_APP) { if (resultCode == Activity.RESULT_OK) { mDebugApp = data.getAction(); writeDebuggerOptions(); updateDebuggerOptions(); } } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference == mEnableAdb) { if (mEnableAdb.isChecked()) { mDialogClicked = false; if (mAdbDialog != null) dismissDialogs(); mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage( getActivity().getResources().getString(R.string.adb_warning_message)) .setTitle(R.string.adb_warning_title) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ENABLE_ADB; - mOkDialog.setOnDismissListener(this); + mAdbDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 0); } } else if (preference == mAdbOverNetwork) { if (mAdbOverNetwork.isChecked()) { mOkClicked = false; if (mOkDialog != null) dismissDialogs(); mOkDialog = new AlertDialog.Builder(getActivity()).setMessage( getResources().getString(R.string.adb_over_network_warning)) .setTitle(R.string.adb_over_network) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ADB_TCPIP; mOkDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_PORT, -1); updateAdbOverNetwork(); } } else if (preference == mKeepScreenOn) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, mKeepScreenOn.isChecked() ? (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB) : 0); } else if (preference == mEnforceReadExternal) { if (mEnforceReadExternal.isChecked()) { ConfirmEnforceFragment.show(this); } else { setPermissionEnforced(getActivity(), READ_EXTERNAL_STORAGE, false); } } else if (preference == mAllowMockLocation) { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, mAllowMockLocation.isChecked() ? 1 : 0); } else if (preference == mDebugAppPref) { startActivityForResult(new Intent(getActivity(), AppPicker.class), RESULT_DEBUG_APP); } else if (preference == mWaitForDebugger) { writeDebuggerOptions(); } else if (preference == mStrictMode) { writeStrictModeVisualOptions(); } else if (preference == mPointerLocation) { writePointerLocationOptions(); } else if (preference == mShowTouches) { writeShowTouchesOptions(); } else if (preference == mShowScreenUpdates) { writeShowUpdatesOption(); } else if (preference == mDisableOverlays) { writeDisableOverlaysOption(); } else if (preference == mShowCpuUsage) { writeCpuUsageOptions(); } else if (preference == mImmediatelyDestroyActivities) { writeImmediatelyDestroyActivitiesOptions(); } else if (preference == mShowAllANRs) { writeShowAllANRsOptions(); } else if (preference == mForceHardwareUi) { writeHardwareUiOptions(); } else if (preference == mTrackFrameTime) { writeTrackFrameTimeOptions(); } else if (preference == mShowHwScreenUpdates) { writeShowHwScreenUpdatesOptions(); } else if (preference == mDebugLayout) { writeDebugLayoutOptions(); } return false; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (HDCP_CHECKING_KEY.equals(preference.getKey())) { SystemProperties.set(HDCP_CHECKING_PROPERTY, newValue.toString()); updateHdcpValues(); pokeSystemProperties(); return true; } else if (preference == mWindowAnimationScale) { writeAnimationScaleOption(0, mWindowAnimationScale, newValue); return true; } else if (preference == mTransitionAnimationScale) { writeAnimationScaleOption(1, mTransitionAnimationScale, newValue); return true; } else if (preference == mAnimatorDurationScale) { writeAnimationScaleOption(2, mAnimatorDurationScale, newValue); return true; } else if (preference == mEnableTracesPref) { writeEnableTracesOptions(); return true; } else if (preference == mAppProcessLimit) { writeAppProcessLimitOptions(newValue); return true; } else if (preference == mRootAccess) { if ("0".equals(SystemProperties.get(ROOT_ACCESS_PROPERTY, "1")) && !"0".equals(newValue)) { mSelectedRootValue = newValue; mDialogClicked = false; if (mRootDialog != null) { dismissDialogs(); } mRootDialog = new AlertDialog.Builder(getActivity()) .setMessage(getResources().getString(R.string.root_access_warning_message)) .setTitle(R.string.root_access_warning_title) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this).show(); mRootDialog.setOnDismissListener(this); } else { writeRootAccessOptions(newValue); } return true; } return false; } private void dismissDialogs() { if (mAdbDialog != null) { mAdbDialog.dismiss(); mAdbDialog = null; } if (mEnableDialog != null) { mEnableDialog.dismiss(); mEnableDialog = null; } if (mRootDialog != null) { mRootDialog.dismiss(); mRootDialog = null; } } public void onClick(DialogInterface dialog, int which) { if (dialog == mAdbDialog) { if (which == DialogInterface.BUTTON_POSITIVE) { mDialogClicked = true; if (mCurrentDialog.equals(ENABLE_ADB)) Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 1); else Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_PORT, 5555); } else { // Reset the toggle mEnableAdb.setChecked(false); } } else if (dialog == mEnableDialog) { if (which == DialogInterface.BUTTON_POSITIVE) { mDialogClicked = true; Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED, 1); mLastEnabledState = true; setPrefsEnabledState(mLastEnabledState); } else { // Reset the toggle mEnabledSwitch.setChecked(false); } } else if (dialog == mRootDialog) { if (which == DialogInterface.BUTTON_POSITIVE) { writeRootAccessOptions(mSelectedRootValue); } else { // Reset the option writeRootAccessOptions("0"); } } } public void onDismiss(DialogInterface dialog) { // Assuming that onClick gets called first if (dialog == mAdbDialog) { if (!mDialogClicked) { if (mCurrentDialog.equals(ENABLE_ADB)) mEnableAdb.setChecked(false); else if (mCurrentDialog.equals(ADB_TCPIP)) { updateAdbOverNetwork(); } } else if (mCurrentDialog.equals(ADB_TCPIP)) { updateAdbOverNetwork(); } mAdbDialog = null; } else if (dialog == mEnableDialog) { if (!mDialogClicked) { mEnabledSwitch.setChecked(false); } mEnableDialog = null; } } @Override public void onDestroy() { dismissDialogs(); super.onDestroy(); } void pokeSystemProperties() { if (!mDontPokeProperties) { (new SystemPropPoker()).execute(); } } static class SystemPropPoker extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { String[] services; try { services = ServiceManager.listServices(); } catch (RemoteException e) { return null; } for (String service : services) { IBinder obj = ServiceManager.checkService(service); if (obj != null) { Parcel data = Parcel.obtain(); try { obj.transact(IBinder.SYSPROPS_TRANSACTION, data, null, 0); } catch (RemoteException e) { } data.recycle(); } } return null; } } /** * Dialog to confirm enforcement of {@link #READ_EXTERNAL_STORAGE}. */ public static class ConfirmEnforceFragment extends DialogFragment { public static void show(DevelopmentSettings parent) { final ConfirmEnforceFragment dialog = new ConfirmEnforceFragment(); dialog.setTargetFragment(parent, 0); dialog.show(parent.getFragmentManager(), TAG_CONFIRM_ENFORCE); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Context context = getActivity(); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.enforce_read_external_confirm_title); builder.setMessage(R.string.enforce_read_external_confirm_message); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setPermissionEnforced(context, READ_EXTERNAL_STORAGE, true); ((DevelopmentSettings) getTargetFragment()).updateAllOptions(); } }); builder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((DevelopmentSettings) getTargetFragment()).updateAllOptions(); } }); return builder.create(); } } private static boolean isPermissionEnforced(Context context, String permission) { try { return ActivityThread.getPackageManager().isPermissionEnforced(READ_EXTERNAL_STORAGE); } catch (RemoteException e) { throw new RuntimeException("Problem talking with PackageManager", e); } } private static void setPermissionEnforced( Context context, String permission, boolean enforced) { try { // TODO: offload to background thread ActivityThread.getPackageManager() .setPermissionEnforced(READ_EXTERNAL_STORAGE, enforced); } catch (RemoteException e) { throw new RuntimeException("Problem talking with PackageManager", e); } } }
true
true
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference == mEnableAdb) { if (mEnableAdb.isChecked()) { mDialogClicked = false; if (mAdbDialog != null) dismissDialogs(); mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage( getActivity().getResources().getString(R.string.adb_warning_message)) .setTitle(R.string.adb_warning_title) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ENABLE_ADB; mOkDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 0); } } else if (preference == mAdbOverNetwork) { if (mAdbOverNetwork.isChecked()) { mOkClicked = false; if (mOkDialog != null) dismissDialogs(); mOkDialog = new AlertDialog.Builder(getActivity()).setMessage( getResources().getString(R.string.adb_over_network_warning)) .setTitle(R.string.adb_over_network) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ADB_TCPIP; mOkDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_PORT, -1); updateAdbOverNetwork(); } } else if (preference == mKeepScreenOn) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, mKeepScreenOn.isChecked() ? (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB) : 0); } else if (preference == mEnforceReadExternal) { if (mEnforceReadExternal.isChecked()) { ConfirmEnforceFragment.show(this); } else { setPermissionEnforced(getActivity(), READ_EXTERNAL_STORAGE, false); } } else if (preference == mAllowMockLocation) { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, mAllowMockLocation.isChecked() ? 1 : 0); } else if (preference == mDebugAppPref) { startActivityForResult(new Intent(getActivity(), AppPicker.class), RESULT_DEBUG_APP); } else if (preference == mWaitForDebugger) { writeDebuggerOptions(); } else if (preference == mStrictMode) { writeStrictModeVisualOptions(); } else if (preference == mPointerLocation) { writePointerLocationOptions(); } else if (preference == mShowTouches) { writeShowTouchesOptions(); } else if (preference == mShowScreenUpdates) { writeShowUpdatesOption(); } else if (preference == mDisableOverlays) { writeDisableOverlaysOption(); } else if (preference == mShowCpuUsage) { writeCpuUsageOptions(); } else if (preference == mImmediatelyDestroyActivities) { writeImmediatelyDestroyActivitiesOptions(); } else if (preference == mShowAllANRs) { writeShowAllANRsOptions(); } else if (preference == mForceHardwareUi) { writeHardwareUiOptions(); } else if (preference == mTrackFrameTime) { writeTrackFrameTimeOptions(); } else if (preference == mShowHwScreenUpdates) { writeShowHwScreenUpdatesOptions(); } else if (preference == mDebugLayout) { writeDebugLayoutOptions(); } return false; }
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference == mEnableAdb) { if (mEnableAdb.isChecked()) { mDialogClicked = false; if (mAdbDialog != null) dismissDialogs(); mAdbDialog = new AlertDialog.Builder(getActivity()).setMessage( getActivity().getResources().getString(R.string.adb_warning_message)) .setTitle(R.string.adb_warning_title) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ENABLE_ADB; mAdbDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_ENABLED, 0); } } else if (preference == mAdbOverNetwork) { if (mAdbOverNetwork.isChecked()) { mOkClicked = false; if (mOkDialog != null) dismissDialogs(); mOkDialog = new AlertDialog.Builder(getActivity()).setMessage( getResources().getString(R.string.adb_over_network_warning)) .setTitle(R.string.adb_over_network) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, this) .setNegativeButton(android.R.string.no, this) .show(); mCurrentDialog = ADB_TCPIP; mOkDialog.setOnDismissListener(this); } else { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ADB_PORT, -1); updateAdbOverNetwork(); } } else if (preference == mKeepScreenOn) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STAY_ON_WHILE_PLUGGED_IN, mKeepScreenOn.isChecked() ? (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB) : 0); } else if (preference == mEnforceReadExternal) { if (mEnforceReadExternal.isChecked()) { ConfirmEnforceFragment.show(this); } else { setPermissionEnforced(getActivity(), READ_EXTERNAL_STORAGE, false); } } else if (preference == mAllowMockLocation) { Settings.Secure.putInt(getActivity().getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, mAllowMockLocation.isChecked() ? 1 : 0); } else if (preference == mDebugAppPref) { startActivityForResult(new Intent(getActivity(), AppPicker.class), RESULT_DEBUG_APP); } else if (preference == mWaitForDebugger) { writeDebuggerOptions(); } else if (preference == mStrictMode) { writeStrictModeVisualOptions(); } else if (preference == mPointerLocation) { writePointerLocationOptions(); } else if (preference == mShowTouches) { writeShowTouchesOptions(); } else if (preference == mShowScreenUpdates) { writeShowUpdatesOption(); } else if (preference == mDisableOverlays) { writeDisableOverlaysOption(); } else if (preference == mShowCpuUsage) { writeCpuUsageOptions(); } else if (preference == mImmediatelyDestroyActivities) { writeImmediatelyDestroyActivitiesOptions(); } else if (preference == mShowAllANRs) { writeShowAllANRsOptions(); } else if (preference == mForceHardwareUi) { writeHardwareUiOptions(); } else if (preference == mTrackFrameTime) { writeTrackFrameTimeOptions(); } else if (preference == mShowHwScreenUpdates) { writeShowHwScreenUpdatesOptions(); } else if (preference == mDebugLayout) { writeDebugLayoutOptions(); } return false; }
diff --git a/illagameengine/src/org/illarion/engine/backend/slick/SlickWorldMap.java b/illagameengine/src/org/illarion/engine/backend/slick/SlickWorldMap.java index cfe7b355..7bc2233d 100644 --- a/illagameengine/src/org/illarion/engine/backend/slick/SlickWorldMap.java +++ b/illagameengine/src/org/illarion/engine/backend/slick/SlickWorldMap.java @@ -1,254 +1,257 @@ /* * This file is part of the Illarion Game Engine. * * Copyright © 2013 - Illarion e.V. * * The Illarion Game Engine 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. * * The Illarion Game Engine 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 the Illarion Game Engine. If not, see <http://www.gnu.org/licenses/>. */ package org.illarion.engine.backend.slick; import illarion.common.types.Location; import org.illarion.engine.GameContainer; import org.illarion.engine.graphic.*; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.LinkedList; import java.util.Queue; /** * This is the slick implementation of the world map. * * @author Martin Karing &lt;nitram@illarion.org&gt; */ class SlickWorldMap implements WorldMap, WorldMapDataProviderCallback { /** * The provider that supplies the class with the required data. */ @Nonnull private final WorldMapDataProvider provider; /** * The world map texture that stores the entire world map graphics. */ @Nonnull private final SlickTexture worldMapTexture; /** * Get the Slick2D image the texture is rendered onto. */ private final Image worldMapImage; /** * This is set true in case clearing the map was requested. */ private boolean clearMap; /** * The origin location of the world map. */ @Nonnull private final Location mapOrigin; /** * The last location of the player that was reported. */ @Nonnull private final Location playerLocation; /** * The off screen graphics instance used to update the texture of the world map. */ @Nullable private Graphics offScreenGraphics; /** * This is the location of the last tile that was requested from the provider. */ @Nonnull private final Location lastRequestedLocation; /** * This color instance is used for the drawing operations. */ @Nonnull private final Color tempDrawingColor; /** * This parameter is set {@code true} in case a update of the entire map was requested. */ private boolean fullMapUpdate; /** * The tiles that were marked as dirty and did not receive a update yet. */ @Nonnull private final Queue<Location> dirtyTiles; /** * Create a new instance of the Slick2D implementation of the world map. * * @param provider the provider that supplies the map data * @throws SlickEngineException in case creating the world map fails */ SlickWorldMap(@Nonnull final WorldMapDataProvider provider) throws SlickEngineException { this.provider = provider; try { worldMapImage = Image.createOffscreenImage(WORLD_MAP_WIDTH, WORLD_MAP_HEIGHT); worldMapTexture = new SlickTexture(worldMapImage); } catch (@Nonnull final SlickException e) { throw new SlickEngineException(e); } mapOrigin = new Location(); playerLocation = new Location(); lastRequestedLocation = new Location(); tempDrawingColor = new Color(Color.black); dirtyTiles = new LinkedList<Location>(); } /** * Get the origin location of the map. * * @return the maps origin location */ @Nonnull public Location getMapOrigin() { return mapOrigin; } @Nonnull @Override public Texture getWorldMap() { return worldMapTexture; } @Override public void setTile(final int tileId, final int overlayId, final boolean blocked) { if (offScreenGraphics == null) { throw new IllegalStateException("Callback called while no callback was requested"); } if (lastRequestedLocation.getScZ() != mapOrigin.getScZ()) { return; } final int texPosX = lastRequestedLocation.getScX() - mapOrigin.getScX(); final int texPosY = lastRequestedLocation.getScY() - mapOrigin.getScY(); if ((texPosX < 0) || (texPosX >= WORLD_MAP_WIDTH) || (texPosY < 0) || (texPosY >= WORLD_MAP_HEIGHT)) { return; } if (tileId == NO_TILE) { SlickGraphics.transferColor(MapColor.getColor(NO_TILE), tempDrawingColor); } else { SlickGraphics.transferColor(MapColor.getColor(tileId), tempDrawingColor); if (overlayId != NO_TILE) { final org.illarion.engine.graphic.Color mapColor = MapColor.getColor(tileId); tempDrawingColor.r += mapColor.getRedf(); tempDrawingColor.g += mapColor.getGreenf(); tempDrawingColor.b += mapColor.getBluef(); tempDrawingColor.scale(0.5f); } if (blocked) { tempDrawingColor.scale(0.7f); } } tempDrawingColor.a = 1.f; offScreenGraphics.setColor(tempDrawingColor); offScreenGraphics.fillRect(texPosX, texPosY, 1, 1); } @Override public void setTileChanged(@Nonnull final Location location) { dirtyTiles.offer(new Location(location)); } @Override public void setMapChanged() { clear(); fullMapUpdate = true; } @Override public void setPlayerLocation(@Nonnull final Location location) { playerLocation.set(location); } @Nonnull @Override public Location getPlayerLocation() { return playerLocation; } @Override public void setMapOrigin(@Nonnull final Location location) { mapOrigin.set(location); setMapChanged(); } @Override public void clear() { dirtyTiles.clear(); clearMap = true; } @Override public void render(@Nonnull final GameContainer container) { try { if (clearMap) { clearMap = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } offScreenGraphics.setColor(Color.black); offScreenGraphics.fillRect(0, 0, WORLD_MAP_WIDTH, WORLD_MAP_HEIGHT); } if (fullMapUpdate) { fullMapUpdate = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } for (int x = 0; x < WORLD_MAP_WIDTH; x++) { for (int y = 0; y < WORLD_MAP_HEIGHT; y++) { lastRequestedLocation.set(mapOrigin); lastRequestedLocation.addSC(x, y, 0); provider.requestTile(lastRequestedLocation, this); } } } if (!dirtyTiles.isEmpty()) { + if (offScreenGraphics == null) { + offScreenGraphics = worldMapImage.getGraphics(); + } Location dirtyLocation = dirtyTiles.poll(); while (dirtyLocation != null) { lastRequestedLocation.set(dirtyLocation); provider.requestTile(lastRequestedLocation, this); dirtyLocation = dirtyTiles.poll(); } } if (offScreenGraphics != null) { offScreenGraphics.flush(); offScreenGraphics = null; } } catch (@Nonnull final SlickException e) { // some strange problem } } }
true
true
public void render(@Nonnull final GameContainer container) { try { if (clearMap) { clearMap = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } offScreenGraphics.setColor(Color.black); offScreenGraphics.fillRect(0, 0, WORLD_MAP_WIDTH, WORLD_MAP_HEIGHT); } if (fullMapUpdate) { fullMapUpdate = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } for (int x = 0; x < WORLD_MAP_WIDTH; x++) { for (int y = 0; y < WORLD_MAP_HEIGHT; y++) { lastRequestedLocation.set(mapOrigin); lastRequestedLocation.addSC(x, y, 0); provider.requestTile(lastRequestedLocation, this); } } } if (!dirtyTiles.isEmpty()) { Location dirtyLocation = dirtyTiles.poll(); while (dirtyLocation != null) { lastRequestedLocation.set(dirtyLocation); provider.requestTile(lastRequestedLocation, this); dirtyLocation = dirtyTiles.poll(); } } if (offScreenGraphics != null) { offScreenGraphics.flush(); offScreenGraphics = null; } } catch (@Nonnull final SlickException e) { // some strange problem } }
public void render(@Nonnull final GameContainer container) { try { if (clearMap) { clearMap = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } offScreenGraphics.setColor(Color.black); offScreenGraphics.fillRect(0, 0, WORLD_MAP_WIDTH, WORLD_MAP_HEIGHT); } if (fullMapUpdate) { fullMapUpdate = false; if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } for (int x = 0; x < WORLD_MAP_WIDTH; x++) { for (int y = 0; y < WORLD_MAP_HEIGHT; y++) { lastRequestedLocation.set(mapOrigin); lastRequestedLocation.addSC(x, y, 0); provider.requestTile(lastRequestedLocation, this); } } } if (!dirtyTiles.isEmpty()) { if (offScreenGraphics == null) { offScreenGraphics = worldMapImage.getGraphics(); } Location dirtyLocation = dirtyTiles.poll(); while (dirtyLocation != null) { lastRequestedLocation.set(dirtyLocation); provider.requestTile(lastRequestedLocation, this); dirtyLocation = dirtyTiles.poll(); } } if (offScreenGraphics != null) { offScreenGraphics.flush(); offScreenGraphics = null; } } catch (@Nonnull final SlickException e) { // some strange problem } }
diff --git a/src/Unbxd.java b/src/Unbxd.java index 9d0b325..3ce10e5 100644 --- a/src/Unbxd.java +++ b/src/Unbxd.java @@ -1,225 +1,225 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import models.Product; import models.Query; import tree.BPlusTree; public class Unbxd { public static void main(String[] args) { try { Unbxd unbxd = new Unbxd(); unbxd.ask(); } catch (IOException e) { e.printStackTrace(); } } private final int iMax = 100; private final int lMax = 10000; private BPlusTree<Product> productTreeProductIdIndex; private BPlusTree<Product> productTreeArtistIndex; private BPlusTree<Query> queryTreeProductIdIndex; private BPlusTree<Query> queryTreeQueryIndex; private Scanner in; enum STATES{ WHAT_TO_DO, SEARCH_PRODUCTS, SEARCH_QUERIES, QUIT } public STATES status; public Unbxd() throws IOException { in = new Scanner(System.in); buildProductIndexes(); buildQueryIndexes(); System.out.println(); status = STATES.WHAT_TO_DO; } public void ask(){ if(status == STATES.WHAT_TO_DO){ System.out.println("What do you want to do?"); System.out.println("1) Look for products matching a search string"); System.out.println("2) Look for search strings matching an artist"); System.out.println("Q) Quit"); String input = in.nextLine(); if(input.equals("1")) status = STATES.SEARCH_PRODUCTS; if(input.equals("2")) status = STATES.SEARCH_QUERIES; if(input.equals("Q")) status = STATES.QUIT; }else if(status == STATES.SEARCH_PRODUCTS){ System.out.println("Enter the search string(Q to quit)"); String input = in.nextLine(); if(input.equals("Q")) status = STATES.QUIT; else{ searchProductsForQuery(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.SEARCH_QUERIES){ System.out.println("Enter the artist name(Q to quit)"); String input = in.nextLine(); - if(input.equals("Q")) + if(input.equals("Q") || input.equals("q")) status = STATES.QUIT; else{ searchQueriesForArtist(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.QUIT){ System.exit(0); } ask(); } public void searchProductsForQuery(String searchString){ System.out.println("Looking for products matching Search Query : " + searchString + " ..."); long t = new Date().getTime(); List<Query> queries = queryTreeQueryIndex.search(searchString); List<Product> products = new ArrayList<Product>(); for(Query query : queries){ int productId = query.getProductId(); products.addAll(productTreeProductIdIndex.search(productId)); } long queryTime = new Date().getTime() - t; System.out.println("productId\t| productName\t| artist\t| genre"); System.out.println("_______________________________________________________"); for(Product product : products){ System.out.println(product.toString()); } System.out.println("Rows : " + products.size() + ", Query Time : " + queryTime + " millisecs\n"); } public void searchQueriesForArtist(String artist){ System.out.println("Looking for queries matching Artist : " + artist + " ..."); long t = new Date().getTime(); List<Query> queries = new ArrayList<Query>(); List<Product> products = productTreeArtistIndex.search(artist); for(Product product : products){ int productId = product.getId(); queries.addAll(queryTreeProductIdIndex.search(productId)); } long queryTime = new Date().getTime() - t; System.out.println("query"); System.out.println("_____"); for(Query query : queries){ System.out.println(query.getQuery()); } System.out.println("Rows : " + queries.size() + ", Query Time : " + queryTime + " millisecs\n"); } private void buildProductIndexes() throws IOException{ System.out.println("Enter the path of the file having product info : "); String fileName = in.nextLine(); File f = new File(fileName); while(!f.exists()){ System.out.println("File doesn't exist. Enter the path of the file having product info(Q to quit) : "); fileName = in.nextLine(); if(fileName.equals("Q")) System.exit(0); f = new File(fileName); } System.out.println("Building Product Indexes..."); long t = new Date().getTime(); BufferedReader br = new BufferedReader(new FileReader(f)); productTreeProductIdIndex = new BPlusTree<Product>(iMax, lMax); productTreeArtistIndex = new BPlusTree<Product>(iMax, lMax); while (br.ready()) { String s = br.readLine(); Product product = new Product(s); productTreeProductIdIndex.add(product.getId(), product); productTreeArtistIndex.add(product.getArtist(), product); } br.close(); long indexTime = new Date().getTime() - t; System.out.println("Took " + indexTime + " millisecs to build product indexes\n"); } private void buildQueryIndexes() throws IOException{ System.out.println("Enter the path of the file having query info : "); String fileName = in.nextLine(); File f = new File(fileName); while(!f.exists()){ System.out.println("File doesn't exist. Enter the path of the file having query info(Q to quit) : "); fileName = in.nextLine(); if(fileName.equals("Q")) System.exit(0); f = new File(fileName); } System.out.println("Building Query Indexes..."); long t = new Date().getTime(); BufferedReader br = new BufferedReader(new FileReader(f)); queryTreeProductIdIndex = new BPlusTree<Query>(iMax, lMax); queryTreeQueryIndex = new BPlusTree<Query>(iMax, lMax); while (br.ready()) { String s = br.readLine(); Query query = new Query(s); queryTreeProductIdIndex.add(query.getProductId(), query); queryTreeQueryIndex.add(query.getQuery(), query); } br.close(); long indexTime = new Date().getTime() - t; System.out.println("Took " + indexTime + " millisecs to build query indexes\n"); } public BPlusTree<Product> getProductTreeProductIdIndex() { return productTreeProductIdIndex; } public void setProductTreeProductIdIndex( BPlusTree<Product> productTreeProductIdIndex) { this.productTreeProductIdIndex = productTreeProductIdIndex; } public BPlusTree<Product> getProductTreeArtistIndex() { return productTreeArtistIndex; } public void setProductTreeArtistIndex(BPlusTree<Product> productTreeArtistIndex) { this.productTreeArtistIndex = productTreeArtistIndex; } public BPlusTree<Query> getQueryTreeProductIdIndex() { return queryTreeProductIdIndex; } public void setQueryTreeProductIdIndex(BPlusTree<Query> queryTreeProductIdIndex) { this.queryTreeProductIdIndex = queryTreeProductIdIndex; } public BPlusTree<Query> getQueryTreeQueryIndex() { return queryTreeQueryIndex; } public void setQueryTreeQueryIndex(BPlusTree<Query> queryTreeQueryIndex) { this.queryTreeQueryIndex = queryTreeQueryIndex; } }
true
true
public void ask(){ if(status == STATES.WHAT_TO_DO){ System.out.println("What do you want to do?"); System.out.println("1) Look for products matching a search string"); System.out.println("2) Look for search strings matching an artist"); System.out.println("Q) Quit"); String input = in.nextLine(); if(input.equals("1")) status = STATES.SEARCH_PRODUCTS; if(input.equals("2")) status = STATES.SEARCH_QUERIES; if(input.equals("Q")) status = STATES.QUIT; }else if(status == STATES.SEARCH_PRODUCTS){ System.out.println("Enter the search string(Q to quit)"); String input = in.nextLine(); if(input.equals("Q")) status = STATES.QUIT; else{ searchProductsForQuery(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.SEARCH_QUERIES){ System.out.println("Enter the artist name(Q to quit)"); String input = in.nextLine(); if(input.equals("Q")) status = STATES.QUIT; else{ searchQueriesForArtist(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.QUIT){ System.exit(0); } ask(); }
public void ask(){ if(status == STATES.WHAT_TO_DO){ System.out.println("What do you want to do?"); System.out.println("1) Look for products matching a search string"); System.out.println("2) Look for search strings matching an artist"); System.out.println("Q) Quit"); String input = in.nextLine(); if(input.equals("1")) status = STATES.SEARCH_PRODUCTS; if(input.equals("2")) status = STATES.SEARCH_QUERIES; if(input.equals("Q")) status = STATES.QUIT; }else if(status == STATES.SEARCH_PRODUCTS){ System.out.println("Enter the search string(Q to quit)"); String input = in.nextLine(); if(input.equals("Q")) status = STATES.QUIT; else{ searchProductsForQuery(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.SEARCH_QUERIES){ System.out.println("Enter the artist name(Q to quit)"); String input = in.nextLine(); if(input.equals("Q") || input.equals("q")) status = STATES.QUIT; else{ searchQueriesForArtist(input); status = STATES.WHAT_TO_DO; } }else if(status == STATES.QUIT){ System.exit(0); } ask(); }
diff --git a/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesHelperAction.java b/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesHelperAction.java index 39c2559f..ab4a88b9 100644 --- a/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesHelperAction.java +++ b/content-tool/tool/src/java/org/sakaiproject/content/tool/ResourcesHelperAction.java @@ -1,1028 +1,1028 @@ /********************************************************************************** * $URL: $ * $Id: $ *********************************************************************************** * * Copyright (c) 2006, 2007 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 org.sakaiproject.content.tool; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.cheftool.VelocityPortlet; import org.sakaiproject.cheftool.VelocityPortletPaneledAction; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.content.api.MultiFileUploadPipe; import org.sakaiproject.content.api.ResourceToolAction; import org.sakaiproject.content.api.ResourceToolActionPipe; import org.sakaiproject.content.api.ResourceType; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.content.api.ContentTypeImageService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.api.Time; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.util.FileItem; import org.sakaiproject.util.FormattedText; import org.sakaiproject.util.ParameterParser; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.StringUtil; import org.sakaiproject.util.Validator; public class ResourcesHelperAction extends VelocityPortletPaneledAction { /** the logger for this class */ private static final Log logger = LogFactory.getLog(ResourcesHelperAction.class); /** Resource bundle using current language locale */ private static ResourceLoader rb = new ResourceLoader("types"); protected static final String ACCESS_HTML_TEMPLATE = "resources/sakai_access_html"; protected static final String ACCESS_TEXT_TEMPLATE = "resources/sakai_access_text"; protected static final String ACCESS_UPLOAD_TEMPLATE = "resources/sakai_access_upload"; protected static final String ACCESS_URL_TEMPLATE = "resources/sakai_access_url"; /** copyright path -- MUST have same value as AccessServlet.COPYRIGHT_PATH */ public static final String COPYRIGHT_PATH = Entity.SEPARATOR + "copyright"; private static final String COPYRIGHT_ALERT_URL = ServerConfigurationService.getAccessUrl() + COPYRIGHT_PATH; protected static final String CREATE_FOLDERS_TEMPLATE = "resources/sakai_create_folders"; protected static final String CREATE_HTML_TEMPLATE = "resources/sakai_create_html"; protected static final String CREATE_TEXT_TEMPLATE = "resources/sakai_create_text"; protected static final String CREATE_UPLOAD_TEMPLATE = "resources/sakai_create_upload"; protected static final String CREATE_UPLOADS_TEMPLATE = "resources/sakai_create_uploads"; protected static final String CREATE_URL_TEMPLATE = "resources/sakai_create_url"; protected static final String CREATE_URLS_TEMPLATE = "resources/sakai_create_urls"; public static final String MODE_MAIN = "main"; protected static final String PREFIX = "ResourceTypeHelper."; protected static final String REVISE_HTML_TEMPLATE = "resources/sakai_revise_html"; protected static final String REVISE_TEXT_TEMPLATE = "resources/sakai_revise_text"; protected static final String REVISE_UPLOAD_TEMPLATE = "resources/sakai_revise_upload"; protected static final String REVISE_URL_TEMPLATE = "resources/sakai_revise_url"; protected static final String REPLACE_CONTENT_TEMPLATE = "resources/sakai_replace_file"; /** The content type image lookup service in the State. */ private static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = PREFIX + "content_type_image_service"; private static final String STATE_COPYRIGHT_FAIRUSE_URL = PREFIX + "copyright_fairuse_url"; private static final String STATE_COPYRIGHT_NEW_COPYRIGHT = PREFIX + "new_copyright"; /** copyright related info */ private static final String STATE_COPYRIGHT_TYPES = PREFIX + "copyright_types"; private static final String STATE_DEFAULT_COPYRIGHT = PREFIX + "default_copyright"; private static final String STATE_DEFAULT_COPYRIGHT_ALERT = PREFIX + "default_copyright_alert"; /** The user copyright string */ private static final String STATE_MY_COPYRIGHT = PREFIX + "mycopyright"; private static final String STATE_NEW_COPYRIGHT_INPUT = PREFIX + "new_copyright_input"; /** state attribute indicating whether users in current site should be denied option of making resources public */ private static final String STATE_PREVENT_PUBLIC_DISPLAY = PREFIX + "prevent_public_display"; /** state attribute indicating whether we're using the Creative Commons dialog instead of the "old" copyright dialog */ protected static final String STATE_USING_CREATIVE_COMMONS = PREFIX + "usingCreativeCommons"; /** name of state attribute for the default retract time */ protected static final String STATE_DEFAULT_RETRACT_TIME = PREFIX + "default_retract_time"; public String buildAccessContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = ACCESS_TEXT_TEMPLATE; return template; } public String buildCreateContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = CREATE_UPLOAD_TEMPLATE; ToolSession toolSession = SessionManager.getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); //Reference reference = (Reference) toolSession.getAttribute(ResourceToolAction.COLLECTION_REFERENCE); String typeId = pipe.getAction().getTypeId(); if(ResourceType.TYPE_TEXT.equals(typeId)) { template = CREATE_TEXT_TEMPLATE; } else if(ResourceType.TYPE_HTML.equals(typeId)) { template = CREATE_HTML_TEMPLATE; } else if(ResourceType.TYPE_URL.equals(typeId)) { template = CREATE_URL_TEMPLATE; } else // assume ResourceType.TYPE_UPLOAD { template = CREATE_UPLOAD_TEMPLATE; } return template; } public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { // context.put("sysout", System.out); context.put("tlang", rb); context.put("validator", new Validator()); if(state.getAttribute(ResourcesAction.STATE_MESSAGE) != null) { context.put("itemAlertMessage", state.getAttribute(ResourcesAction.STATE_MESSAGE)); state.removeAttribute(ResourcesAction.STATE_MESSAGE); } ContentTypeImageService contentTypeImageService = (ContentTypeImageService) state.getAttribute(STATE_CONTENT_TYPE_IMAGE_SERVICE); context.put("contentTypeImageService", contentTypeImageService); String mode = (String) state.getAttribute(ResourceToolAction.STATE_MODE); if (mode == null) { initHelper(portlet, context, data, state); } ToolSession toolSession = SessionManager.getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); if(pipe.isActionCompleted()) { return null; } String actionId = pipe.getAction().getId(); String template = ""; switch(pipe.getAction().getActionType()) { case CREATE: template = buildCreateContext(portlet, context, data, state); break; case REVISE_CONTENT: template = buildReviseContext(portlet, context, data, state); break; case REPLACE_CONTENT: template = buildReplaceContext(portlet, context, data, state); break; case NEW_UPLOAD: template = buildUploadFilesContext(portlet, context, data, state); break; case NEW_FOLDER: template = buildNewFoldersContext(portlet, context, data, state); break; case NEW_URLS: template = buildNewUrlsContext(portlet, context, data, state); break; default: // hmmmm break; } return template; } protected String buildNewUrlsContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe pipe = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); List<ResourceToolActionPipe> pipes = pipe.getPipes(); Time defaultRetractDate = (Time) state.getAttribute(STATE_DEFAULT_RETRACT_TIME); if(defaultRetractDate == null) { defaultRetractDate = TimeService.newTime(); state.setAttribute(STATE_DEFAULT_RETRACT_TIME, defaultRetractDate); } Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY); if(preventPublicDisplay == null) { preventPublicDisplay = Boolean.FALSE; state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay); } ListItem parent = new ListItem(pipe.getContentEntity()); parent.setPubviewPossible(! preventPublicDisplay); ListItem model = new ListItem(pipe, parent, defaultRetractDate); model.setPubviewPossible(! preventPublicDisplay); context.put("model", model); context.put("pipes", pipes); if(ContentHostingService.isAvailabilityEnabled()) { context.put("availability_is_enabled", Boolean.TRUE); } ResourcesAction.copyrightChoicesIntoContext(state, context); ResourcesAction.publicDisplayChoicesIntoContext(state, context); return CREATE_URLS_TEMPLATE; } /** * @param portlet * @param context * @param data * @param state * @return */ private String buildNewFoldersContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe pipe = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); List<ResourceToolActionPipe> pipes = pipe.getPipes(); Time defaultRetractDate = (Time) state.getAttribute(STATE_DEFAULT_RETRACT_TIME); if(defaultRetractDate == null) { defaultRetractDate = TimeService.newTime(); state.setAttribute(STATE_DEFAULT_RETRACT_TIME, defaultRetractDate); } Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY); if(preventPublicDisplay == null) { preventPublicDisplay = Boolean.FALSE; state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay); } ListItem parent = new ListItem(pipe.getContentEntity()); parent.setPubviewPossible(! preventPublicDisplay); ListItem model = new ListItem(pipe, parent, defaultRetractDate); model.setPubviewPossible(! preventPublicDisplay); context.put("model", model); context.put("pipes", pipes); if(ContentHostingService.isAvailabilityEnabled()) { context.put("availability_is_enabled", Boolean.TRUE); } ResourcesAction.publicDisplayChoicesIntoContext(state, context); return CREATE_FOLDERS_TEMPLATE; } /** * @param portlet * @param context * @param data * @param state * @return */ protected String buildReplaceContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { ToolSession toolSession = SessionManager.getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY); if(preventPublicDisplay == null) { preventPublicDisplay = Boolean.FALSE; state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay); } ListItem item = new ListItem(pipe.getContentEntity()); item.setPubviewPossible(! preventPublicDisplay); context.put("item", item); return REPLACE_CONTENT_TEMPLATE; } public String buildReviseContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { String template = REVISE_TEXT_TEMPLATE; ToolSession toolSession = SessionManager.getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); //Reference reference = (Reference) toolSession.getAttribute(ResourceToolAction.COLLECTION_REFERENCE); String typeId = pipe.getAction().getTypeId(); String mimetype = pipe.getMimeType(); context.put("pipe", pipe); if(ResourceType.TYPE_TEXT.equals(typeId)) { template = REVISE_TEXT_TEMPLATE; } else if(ResourceType.TYPE_HTML.equals(typeId)) { template = REVISE_HTML_TEMPLATE; } else if(ResourceType.TYPE_URL.equals(typeId)) { template = REVISE_URL_TEMPLATE; } else if(ResourceType.TYPE_UPLOAD.equals(typeId) && mimetype != null && ResourceType.MIME_TYPE_HTML.equals(mimetype)) { template = REVISE_HTML_TEMPLATE; } else if(ResourceType.TYPE_UPLOAD.equals(typeId) && mimetype != null && ResourceType.MIME_TYPE_TEXT.equals(mimetype)) { template = REVISE_TEXT_TEMPLATE; } else // assume ResourceType.TYPE_UPLOAD { template = REVISE_UPLOAD_TEMPLATE; } return template; } /** * @param portlet * @param context * @param data * @param state * @return */ protected String buildUploadFilesContext(VelocityPortlet portlet, Context context, RunData data, SessionState state) { ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe pipe = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); List<ResourceToolActionPipe> pipes = pipe.getPipes(); Time defaultRetractDate = (Time) state.getAttribute(STATE_DEFAULT_RETRACT_TIME); if(defaultRetractDate == null) { defaultRetractDate = TimeService.newTime(); state.setAttribute(STATE_DEFAULT_RETRACT_TIME, defaultRetractDate); } Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY); if(preventPublicDisplay == null) { preventPublicDisplay = Boolean.FALSE; state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay); } ListItem parent = new ListItem(pipe.getContentEntity()); parent.setPubviewPossible(! preventPublicDisplay); ListItem model = new ListItem(pipe, parent, defaultRetractDate); model.setPubviewPossible(! preventPublicDisplay); context.put("model", model); context.put("pipes", pipes); if(ContentHostingService.isAvailabilityEnabled()) { context.put("availability_is_enabled", Boolean.TRUE); } ResourcesAction.copyrightChoicesIntoContext(state, context); ResourcesAction.publicDisplayChoicesIntoContext(state, context); String defaultCopyrightStatus = (String) state.getAttribute(STATE_DEFAULT_COPYRIGHT); if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals("")) { defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright"); state.setAttribute(STATE_DEFAULT_COPYRIGHT, defaultCopyrightStatus); } context.put("defaultCopyrightStatus", defaultCopyrightStatus); return CREATE_UPLOADS_TEMPLATE; } public void doCancel(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); //Tool tool = ToolManager.getCurrentTool(); //String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL); //toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); pipe.setActionCanceled(true); pipe.setErrorEncountered(false); pipe.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } public void doContinue(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); String content = params.getString("content"); if(content == null) { addAlert(state, rb.getString("text.notext")); return; } ToolSession toolSession = SessionManager.getCurrentToolSession(); // Tool tool = ToolManager.getCurrentTool(); // String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL); // toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); String resourceType = pipe.getAction().getTypeId(); String mimetype = pipe.getMimeType(); pipe.setRevisedMimeType(pipe.getMimeType()); if(ResourceType.TYPE_TEXT.equals(resourceType) || ResourceType.MIME_TYPE_TEXT.equals(mimetype)) { pipe.setRevisedMimeType(ResourceType.MIME_TYPE_TEXT); pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); } else if(ResourceType.TYPE_HTML.equals(resourceType) || ResourceType.MIME_TYPE_HTML.equals(mimetype)) { StringBuffer alertMsg = new StringBuffer(); content = FormattedText.processHtmlDocument(content, alertMsg); pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML); pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); if (alertMsg.length() > 0) { addAlert(state, alertMsg.toString()); return; } } else if(ResourceType.TYPE_URL.equals(resourceType)) { pipe.setRevisedMimeType(ResourceType.MIME_TYPE_URL); } else if(ResourceType.TYPE_FOLDER.equals(resourceType)) { MultiFileUploadPipe mfp = (MultiFileUploadPipe) pipe; int count = params.getInt("folderCount"); mfp.setFileCount(count); List<ResourceToolActionPipe> pipes = mfp.getPipes(); for(int i = 0; i < pipes.size(); i++) { ResourceToolActionPipe fp = pipes.get(i); String folderName = params.getString("folder" + (i + 1)); fp.setFileName(folderName); } } pipe.setRevisedContent(content.getBytes()); pipe.setActionCanceled(false); pipe.setErrorEncountered(false); pipe.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } public void doCreateFolders(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe pipe = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); String resourceType = pipe.getAction().getTypeId(); int count = params.getInt("fileCount"); pipe.setFileCount(count); int lastIndex = params.getInt("lastIndex"); List<ResourceToolActionPipe> pipes = pipe.getPipes(); for(int i = 1, c = 0; i <= lastIndex && c < count; i++) { String exists = params.getString("exists." + i); if(exists == null || exists.equals("")) { continue; } ResourceToolActionPipe fp = pipes.get(c); String folderName = params.getString("content." + i); fp.setFileName(folderName); ListItem newFolder = new ListItem(folderName); // capture properties newFolder.captureProperties(params, "." + i); fp.setRevisedListItem(newFolder); c++; } pipe.setActionCanceled(false); pipe.setErrorEncountered(false); pipe.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } public void doReplace(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); FileItem fileitem = null; try { fileitem = params.getFileItem("content"); } catch(Exception e) { logger.warn("Exception ", e); } if(fileitem == null) { String max_file_size_mb = (String) state.getAttribute(ResourcesAction.STATE_FILE_UPLOAD_MAX_SIZE); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } String max_bytes_string = ResourcesAction.getFileSizeString(max_bytes, rb); // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_bytes_string })); //max_file_size_mb + "MB " + rb.getString("exceeded2")); } else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0) { addAlert(state, rb.getString("choosefile7")); } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream stream; stream = fileitem.getInputStream(); if(stream == null) { byte[] bytes = fileitem.get(); pipe.setRevisedContent(bytes); } else { pipe.setRevisedContentStream(stream); } String contentType = fileitem.getContentType(); //pipe.setRevisedContent(bytes); pipe.setRevisedMimeType(contentType); pipe.setFileName(filename); if(ResourceType.MIME_TYPE_HTML.equals(contentType) || ResourceType.MIME_TYPE_TEXT.equals(contentType)) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); } else if(pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING) != null) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, (String) pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING)); } ListItem newFile = new ListItem(filename); pipe.setRevisedListItem(newFile); pipe.setActionCanceled(false); pipe.setErrorEncountered(false); pipe.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } } public void doAddUrls(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe mfp = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); int count = params.getInt("fileCount"); mfp.setFileCount(count); int lastIndex = params.getInt("lastIndex"); List<ResourceToolActionPipe> pipes = mfp.getPipes(); int actualCount = 0; for(int i = 1; i <= lastIndex && actualCount < count; i++) { String exists = params.getString("exists." + i); if(exists == null || exists.equals("")) { continue; } ResourceToolActionPipe pipe = pipes.get(actualCount); String url = params.getString("content." + i ); if(url == null) { continue; } else { try { url = ResourcesAction.validateURL(url); } catch (MalformedURLException e) { addAlert(state, rb.getFormattedMessage("url.invalid", new String[]{url})); continue; } pipe.setRevisedContent(url.getBytes()); } pipe.setFileName(Validator.escapeResourceName(url)); pipe.setRevisedMimeType(ResourceType.MIME_TYPE_URL); ListItem newFile = new ListItem(pipe.getFileName()); // capture properties newFile.captureProperties(params, "." + i); pipe.setRevisedListItem(newFile); actualCount++; } if(actualCount < 1) { addAlert(state, rb.getString("url.noinput")); return; } mfp.setActionCanceled(false); mfp.setErrorEncountered(false); mfp.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } public void doUpload(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe mfp = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); int count = params.getInt("fileCount"); mfp.setFileCount(count); int lastIndex = params.getInt("lastIndex"); List<ResourceToolActionPipe> pipes = mfp.getPipes(); int uploadCount = 0; for(int i = 1, c = 0; i <= lastIndex && c < count; i++) { String exists = params.getString("exists." + i); if(exists == null || exists.equals("")) { continue; } ResourceToolActionPipe pipe = pipes.get(c); FileItem fileitem = null; try { fileitem = params.getFileItem("content." + i ); } catch(Exception e) { logger.warn("Exception ", e); } if(fileitem == null) { String max_file_size_mb = (String) state.getAttribute(ResourcesAction.STATE_FILE_UPLOAD_MAX_SIZE); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } String max_bytes_string = ResourcesAction.getFileSizeString(max_bytes, rb); // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_bytes_string })); //max_file_size_mb + "MB " + rb.getString("exceeded2")); } else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0) { // no file selected -- skip this one } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream stream; stream = fileitem.getInputStream(); if(stream == null) { byte[] bytes = fileitem.get(); pipe.setRevisedContent(bytes); } else { pipe.setRevisedContentStream(stream); } String contentType = fileitem.getContentType(); //pipe.setRevisedContent(bytes); pipe.setRevisedMimeType(contentType); if(ResourceType.MIME_TYPE_HTML.equals(contentType) || ResourceType.MIME_TYPE_TEXT.equals(contentType)) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); } else if(pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING) != null) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, (String) pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING)); } pipe.setFileName(filename); ListItem newFile = new ListItem(filename); // capture properties newFile.captureProperties(params, "." + i); pipe.setRevisedListItem(newFile); uploadCount++; } c++; } - if(uploadCount < 1) + if(uploadCount < 1 && state.getAttribute(ResourcesAction.STATE_MESSAGE) == null) { addAlert(state, rb.getString("choosefile7")); } if(state.getAttribute(ResourcesAction.STATE_MESSAGE) == null) { mfp.setActionCanceled(false); mfp.setErrorEncountered(false); mfp.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } } protected void initHelper(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) { ToolSession toolSession = SessionManager.getCurrentToolSession(); //toolSession.setAttribute(ResourceToolAction.STARTED, Boolean.TRUE); //state.setAttribute(ResourceToolAction.STATE_MODE, MODE_MAIN); if(state.getAttribute(STATE_USING_CREATIVE_COMMONS) == null) { String usingCreativeCommons = ServerConfigurationService.getString("copyright.use_creative_commons"); if( usingCreativeCommons != null && usingCreativeCommons.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.TRUE.toString()); } else { state.setAttribute(STATE_USING_CREATIVE_COMMONS, Boolean.FALSE.toString()); } } if (state.getAttribute(STATE_COPYRIGHT_TYPES) == null) { if (ServerConfigurationService.getStrings("copyrighttype") != null) { state.setAttribute(STATE_COPYRIGHT_TYPES, new ArrayList(Arrays.asList(ServerConfigurationService.getStrings("copyrighttype")))); } } if (state.getAttribute(STATE_DEFAULT_COPYRIGHT) == null) { if (ServerConfigurationService.getString("default.copyright") != null) { state.setAttribute(STATE_DEFAULT_COPYRIGHT, ServerConfigurationService.getString("default.copyright")); } } if (state.getAttribute(STATE_DEFAULT_COPYRIGHT_ALERT) == null) { if (ServerConfigurationService.getString("default.copyright.alert") != null) { state.setAttribute(STATE_DEFAULT_COPYRIGHT_ALERT, ServerConfigurationService.getString("default.copyright.alert")); } } if (state.getAttribute(STATE_NEW_COPYRIGHT_INPUT) == null) { if (ServerConfigurationService.getString("newcopyrightinput") != null) { state.setAttribute(STATE_NEW_COPYRIGHT_INPUT, ServerConfigurationService.getString("newcopyrightinput")); } } if (state.getAttribute(STATE_COPYRIGHT_FAIRUSE_URL) == null) { if (ServerConfigurationService.getString("fairuse.url") != null) { state.setAttribute(STATE_COPYRIGHT_FAIRUSE_URL, ServerConfigurationService.getString("fairuse.url")); } } if (state.getAttribute(STATE_COPYRIGHT_NEW_COPYRIGHT) == null) { if (ServerConfigurationService.getString("copyrighttype.new") != null) { state.setAttribute(STATE_COPYRIGHT_NEW_COPYRIGHT, ServerConfigurationService.getString("copyrighttype.new")); } } state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.FALSE); String[] siteTypes = ServerConfigurationService.getStrings("prevent.public.resources"); String siteType = null; Site site; try { site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext()); siteType = site.getType(); if(siteTypes != null) { for(int i = 0; i < siteTypes.length; i++) { if ((StringUtil.trimToNull(siteTypes[i])).equals(siteType)) { state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, Boolean.TRUE); break; } } } } catch (IdUnusedException e) { // allow public display } catch(NullPointerException e) { // allow public display } state.setAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE, org.sakaiproject.content.cover.ContentTypeImageService.getInstance()); } protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res) throws ToolException { SessionState sstate = getState(req); ToolSession toolSession = SessionManager.getCurrentToolSession(); //String mode = (String) sstate.getAttribute(ResourceToolAction.STATE_MODE); //Object started = toolSession.getAttribute(ResourceToolAction.STARTED); Object done = toolSession.getAttribute(ResourceToolAction.DONE); if (done != null) { toolSession.removeAttribute(ResourceToolAction.STARTED); Tool tool = ToolManager.getCurrentTool(); String url = (String) SessionManager.getCurrentToolSession().getAttribute(tool.getId() + Tool.HELPER_DONE_URL); SessionManager.getCurrentToolSession().removeAttribute(tool.getId() + Tool.HELPER_DONE_URL); try { res.sendRedirect(url); } catch (IOException e) { // Log.warn("chef", this + " : ", e); } return; } super.toolModeDispatch(methodBase, methodExt, req, res); } }
true
true
public void doUpload(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe mfp = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); int count = params.getInt("fileCount"); mfp.setFileCount(count); int lastIndex = params.getInt("lastIndex"); List<ResourceToolActionPipe> pipes = mfp.getPipes(); int uploadCount = 0; for(int i = 1, c = 0; i <= lastIndex && c < count; i++) { String exists = params.getString("exists." + i); if(exists == null || exists.equals("")) { continue; } ResourceToolActionPipe pipe = pipes.get(c); FileItem fileitem = null; try { fileitem = params.getFileItem("content." + i ); } catch(Exception e) { logger.warn("Exception ", e); } if(fileitem == null) { String max_file_size_mb = (String) state.getAttribute(ResourcesAction.STATE_FILE_UPLOAD_MAX_SIZE); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } String max_bytes_string = ResourcesAction.getFileSizeString(max_bytes, rb); // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_bytes_string })); //max_file_size_mb + "MB " + rb.getString("exceeded2")); } else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0) { // no file selected -- skip this one } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream stream; stream = fileitem.getInputStream(); if(stream == null) { byte[] bytes = fileitem.get(); pipe.setRevisedContent(bytes); } else { pipe.setRevisedContentStream(stream); } String contentType = fileitem.getContentType(); //pipe.setRevisedContent(bytes); pipe.setRevisedMimeType(contentType); if(ResourceType.MIME_TYPE_HTML.equals(contentType) || ResourceType.MIME_TYPE_TEXT.equals(contentType)) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); } else if(pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING) != null) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, (String) pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING)); } pipe.setFileName(filename); ListItem newFile = new ListItem(filename); // capture properties newFile.captureProperties(params, "." + i); pipe.setRevisedListItem(newFile); uploadCount++; } c++; } if(uploadCount < 1) { addAlert(state, rb.getString("choosefile7")); } if(state.getAttribute(ResourcesAction.STATE_MESSAGE) == null) { mfp.setActionCanceled(false); mfp.setErrorEncountered(false); mfp.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } }
public void doUpload(RunData data) { SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ()); ParameterParser params = data.getParameters (); ToolSession toolSession = SessionManager.getCurrentToolSession(); MultiFileUploadPipe mfp = (MultiFileUploadPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE); int count = params.getInt("fileCount"); mfp.setFileCount(count); int lastIndex = params.getInt("lastIndex"); List<ResourceToolActionPipe> pipes = mfp.getPipes(); int uploadCount = 0; for(int i = 1, c = 0; i <= lastIndex && c < count; i++) { String exists = params.getString("exists." + i); if(exists == null || exists.equals("")) { continue; } ResourceToolActionPipe pipe = pipes.get(c); FileItem fileitem = null; try { fileitem = params.getFileItem("content." + i ); } catch(Exception e) { logger.warn("Exception ", e); } if(fileitem == null) { String max_file_size_mb = (String) state.getAttribute(ResourcesAction.STATE_FILE_UPLOAD_MAX_SIZE); int max_bytes = 1024 * 1024; try { max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024; } catch(Exception e) { // if unable to parse an integer from the value // in the properties file, use 1 MB as a default max_file_size_mb = "1"; max_bytes = 1024 * 1024; } String max_bytes_string = ResourcesAction.getFileSizeString(max_bytes, rb); // "The user submitted a file to upload but it was too big!" addAlert(state, rb.getFormattedMessage("size.exceeded", new Object[]{ max_bytes_string })); //max_file_size_mb + "MB " + rb.getString("exceeded2")); } else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0) { // no file selected -- skip this one } else if (fileitem.getFileName().length() > 0) { String filename = Validator.getFileName(fileitem.getFileName()); InputStream stream; stream = fileitem.getInputStream(); if(stream == null) { byte[] bytes = fileitem.get(); pipe.setRevisedContent(bytes); } else { pipe.setRevisedContentStream(stream); } String contentType = fileitem.getContentType(); //pipe.setRevisedContent(bytes); pipe.setRevisedMimeType(contentType); if(ResourceType.MIME_TYPE_HTML.equals(contentType) || ResourceType.MIME_TYPE_TEXT.equals(contentType)) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, ResourcesAction.UTF_8_ENCODING); } else if(pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING) != null) { pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_ENCODING, (String) pipe.getPropertyValue(ResourceProperties.PROP_CONTENT_ENCODING)); } pipe.setFileName(filename); ListItem newFile = new ListItem(filename); // capture properties newFile.captureProperties(params, "." + i); pipe.setRevisedListItem(newFile); uploadCount++; } c++; } if(uploadCount < 1 && state.getAttribute(ResourcesAction.STATE_MESSAGE) == null) { addAlert(state, rb.getString("choosefile7")); } if(state.getAttribute(ResourcesAction.STATE_MESSAGE) == null) { mfp.setActionCanceled(false); mfp.setErrorEncountered(false); mfp.setActionCompleted(true); toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE); } }
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java index ba909f0..75f82c1 100644 --- a/src/com/android/settings/DisplaySettings.java +++ b/src/com/android/settings/DisplaySettings.java @@ -1,488 +1,481 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT; import android.app.ActivityManagerNative; import android.app.Dialog; import android.app.admin.DevicePolicyManager; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.content.res.Resources; import android.database.ContentObserver; import android.hardware.display.DisplayManager; import android.hardware.display.WifiDisplayStatus; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.provider.Settings; import android.util.Log; import com.android.internal.view.RotationPolicy; import com.android.settings.cyanogenmod.DisplayRotation; import java.util.ArrayList; public class DisplaySettings extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener, OnPreferenceClickListener { private static final String TAG = "DisplaySettings"; /** If there is no setting in the provider, use this. */ private static final int FALLBACK_SCREEN_TIMEOUT_VALUE = 30000; private static final String KEY_SCREEN_TIMEOUT = "screen_timeout"; private static final String KEY_FONT_SIZE = "font_size"; private static final String KEY_NOTIFICATION_PULSE = "notification_pulse"; private static final String KEY_SCREEN_SAVER = "screensaver"; private static final String KEY_WIFI_DISPLAY = "wifi_display"; private static final String KEY_BATTERY_LIGHT = "battery_light"; private static final String KEY_DISPLAY_ROTATION = "display_rotation"; private static final String KEY_WAKEUP_CATEGORY = "category_wakeup_options"; private static final String KEY_VOLUME_WAKE = "pref_volume_wake"; // Strings used for building the summary private static final String ROTATION_ANGLE_0 = "0"; private static final String ROTATION_ANGLE_90 = "90"; private static final String ROTATION_ANGLE_180 = "180"; private static final String ROTATION_ANGLE_270 = "270"; private static final String ROTATION_ANGLE_DELIM = ", "; private static final String ROTATION_ANGLE_DELIM_FINAL = " & "; private static final int DLG_GLOBAL_CHANGE_WARNING = 1; private DisplayManager mDisplayManager; private CheckBoxPreference mVolumeWake; private PreferenceScreen mNotificationPulse; private PreferenceScreen mBatteryPulse; private PreferenceScreen mDisplayRotationPreference; private WarnedListPreference mFontSizePref; private final Configuration mCurConfig = new Configuration(); private ListPreference mScreenTimeoutPreference; private Preference mScreenSaverPreference; private WifiDisplayStatus mWifiDisplayStatus; private Preference mWifiDisplayPreference; private ContentObserver mAccelerometerRotationObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { updateDisplayRotationPreferenceDescription(); } }; private final RotationPolicy.RotationPolicyListener mRotationPolicyListener = new RotationPolicy.RotationPolicyListener() { @Override public void onChange() { updateDisplayRotationPreferenceDescription(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); - if (mDisplayRotationPreference != null - && RotationPolicy.isRotationLockToggleSupported(getActivity())) { - // If rotation lock is supported, then we do not provide this option in - // Display settings. However, is still available in Accessibility settings. - getPreferenceScreen().removePreference(mDisplayRotationPreference); - mDisplayRotationPreference = null; - } mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mNotificationPulse = (PreferenceScreen) findPreference(KEY_NOTIFICATION_PULSE); if (mNotificationPulse != null) { if (!getResources().getBoolean(com.android.internal.R.bool.config_intrusiveNotificationLed)) { getPreferenceScreen().removePreference(mNotificationPulse); } else { updateLightPulseDescription(); } } mBatteryPulse = (PreferenceScreen) findPreference(KEY_BATTERY_LIGHT); if (mBatteryPulse != null) { if (getResources().getBoolean( com.android.internal.R.bool.config_intrusiveBatteryLed) == false) { getPreferenceScreen().removePreference(mBatteryPulse); } else { updateBatteryPulseDescription(); } } mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake)) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } } private void updateDisplayRotationPreferenceDescription() { if (mDisplayRotationPreference == null) { // The preference was removed, do nothing return; } // We have a preference, lets update the summary StringBuilder summary = new StringBuilder(); Boolean rotationEnabled = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) != 0; int mode = Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION_ANGLES, DisplayRotation.ROTATION_0_MODE|DisplayRotation.ROTATION_90_MODE|DisplayRotation.ROTATION_270_MODE); if (!rotationEnabled) { summary.append(getString(R.string.display_rotation_disabled)); } else { ArrayList<String> rotationList = new ArrayList<String>(); String delim = ""; summary.append(getString(R.string.display_rotation_enabled) + " "); if ((mode & DisplayRotation.ROTATION_0_MODE) != 0) { rotationList.add(ROTATION_ANGLE_0); } if ((mode & DisplayRotation.ROTATION_90_MODE) != 0) { rotationList.add(ROTATION_ANGLE_90); } if ((mode & DisplayRotation.ROTATION_180_MODE) != 0) { rotationList.add(ROTATION_ANGLE_180); } if ((mode & DisplayRotation.ROTATION_270_MODE) != 0) { rotationList.add(ROTATION_ANGLE_270); } for(int i=0;i<rotationList.size();i++) { summary.append(delim).append(rotationList.get(i)); if (rotationList.size() >= 2 && (rotationList.size() - 2) == i) { delim = " " + ROTATION_ANGLE_DELIM_FINAL + " "; } else { delim = ROTATION_ANGLE_DELIM + " "; } } summary.append(" " + getString(R.string.display_rotation_unit)); } mDisplayRotationPreference.setSummary(summary); } private void updateTimeoutPreferenceDescription(long currentTimeout) { ListPreference preference = mScreenTimeoutPreference; String summary; if (currentTimeout < 0) { // Unsupported value summary = ""; } else { final CharSequence[] entries = preference.getEntries(); final CharSequence[] values = preference.getEntryValues(); if (entries == null || entries.length == 0) { summary = ""; } else { int best = 0; for (int i = 0; i < values.length; i++) { long timeout = Long.parseLong(values[i].toString()); if (currentTimeout >= timeout) { best = i; } } summary = preference.getContext().getString(R.string.screen_timeout_summary, entries[best]); } } preference.setSummary(summary); } private void disableUnusableTimeouts(ListPreference screenTimeoutPreference) { final DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService( Context.DEVICE_POLICY_SERVICE); final long maxTimeout = dpm != null ? dpm.getMaximumTimeToLock(null) : 0; if (maxTimeout == 0) { return; // policy not enforced } final CharSequence[] entries = screenTimeoutPreference.getEntries(); final CharSequence[] values = screenTimeoutPreference.getEntryValues(); ArrayList<CharSequence> revisedEntries = new ArrayList<CharSequence>(); ArrayList<CharSequence> revisedValues = new ArrayList<CharSequence>(); for (int i = 0; i < values.length; i++) { long timeout = Long.parseLong(values[i].toString()); if (timeout <= maxTimeout) { revisedEntries.add(entries[i]); revisedValues.add(values[i]); } } if (revisedEntries.size() != entries.length || revisedValues.size() != values.length) { screenTimeoutPreference.setEntries( revisedEntries.toArray(new CharSequence[revisedEntries.size()])); screenTimeoutPreference.setEntryValues( revisedValues.toArray(new CharSequence[revisedValues.size()])); final int userPreference = Integer.parseInt(screenTimeoutPreference.getValue()); if (userPreference <= maxTimeout) { screenTimeoutPreference.setValue(String.valueOf(userPreference)); } else { // There will be no highlighted selection since nothing in the list matches // maxTimeout. The user can still select anything less than maxTimeout. // TODO: maybe append maxTimeout to the list and mark selected. } } screenTimeoutPreference.setEnabled(revisedEntries.size() > 0); } private void updateLightPulseDescription() { if (Settings.System.getInt(getActivity().getContentResolver(), Settings.System.NOTIFICATION_LIGHT_PULSE, 0) == 1) { mNotificationPulse.setSummary(getString(R.string.notification_light_enabled)); } else { mNotificationPulse.setSummary(getString(R.string.notification_light_disabled)); } } private void updateBatteryPulseDescription() { if (Settings.System.getInt(getActivity().getContentResolver(), Settings.System.BATTERY_LIGHT_ENABLED, 1) == 1) { mBatteryPulse.setSummary(getString(R.string.notification_light_enabled)); } else { mBatteryPulse.setSummary(getString(R.string.notification_light_disabled)); } } int floatToIndex(float val) { String[] indices = getResources().getStringArray(R.array.entryvalues_font_size); float lastVal = Float.parseFloat(indices[0]); for (int i=1; i<indices.length; i++) { float thisVal = Float.parseFloat(indices[i]); if (val < (lastVal + (thisVal-lastVal)*.5f)) { return i-1; } lastVal = thisVal; } return indices.length-1; } public void readFontSizePreference(ListPreference pref) { try { mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration()); } catch (RemoteException e) { Log.w(TAG, "Unable to retrieve font size"); } // mark the appropriate item in the preferences list int index = floatToIndex(mCurConfig.fontScale); pref.setValueIndex(index); // report the current size in the summary text final Resources res = getResources(); String[] fontSizeNames = res.getStringArray(R.array.entries_font_size); pref.setSummary(String.format(res.getString(R.string.summary_font_size), fontSizeNames[index])); } @Override public void onResume() { super.onResume(); updateDisplayRotationPreferenceDescription(); updateLightPulseDescription(); updateBatteryPulseDescription(); RotationPolicy.registerRotationPolicyListener(getActivity(), mRotationPolicyListener); // Display rotation observer getContentResolver().registerContentObserver( Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION), true, mAccelerometerRotationObserver); if (mWifiDisplayPreference != null) { getActivity().registerReceiver(mReceiver, new IntentFilter( DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); } updateState(); } @Override public void onPause() { super.onPause(); RotationPolicy.unregisterRotationPolicyListener(getActivity(), mRotationPolicyListener); // Display rotation observer getContentResolver().unregisterContentObserver(mAccelerometerRotationObserver); if (mWifiDisplayPreference != null) { getActivity().unregisterReceiver(mReceiver); } } @Override public Dialog onCreateDialog(int dialogId) { if (dialogId == DLG_GLOBAL_CHANGE_WARNING) { return Utils.buildGlobalChangeWarningDialog(getActivity(), R.string.global_font_change_title, new Runnable() { public void run() { mFontSizePref.click(); } }); } return null; } private void updateState() { readFontSizePreference(mFontSizePref); updateScreenSaverSummary(); updateWifiDisplaySummary(); } private void updateScreenSaverSummary() { if (mScreenSaverPreference != null) { mScreenSaverPreference.setSummary( DreamSettings.getSummaryTextWithDreamName(getActivity())); } } private void updateWifiDisplaySummary() { if (mWifiDisplayPreference != null) { switch (mWifiDisplayStatus.getFeatureState()) { case WifiDisplayStatus.FEATURE_STATE_OFF: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_off); break; case WifiDisplayStatus.FEATURE_STATE_ON: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_on); break; case WifiDisplayStatus.FEATURE_STATE_DISABLED: default: mWifiDisplayPreference.setSummary(R.string.wifi_display_summary_disabled); break; } } } public void writeFontSizePreference(Object objValue) { try { mCurConfig.fontScale = Float.parseFloat(objValue.toString()); ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig); } catch (RemoteException e) { Log.w(TAG, "Unable to save font size"); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mVolumeWake) { Settings.System.putInt(getContentResolver(), Settings.System.VOLUME_WAKE_SCREEN, mVolumeWake.isChecked() ? 1 : 0); return true; } return super.onPreferenceTreeClick(preferenceScreen, preference); } public boolean onPreferenceChange(Preference preference, Object objValue) { final String key = preference.getKey(); if (KEY_SCREEN_TIMEOUT.equals(key)) { int value = Integer.parseInt((String) objValue); try { Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, value); updateTimeoutPreferenceDescription(value); } catch (NumberFormatException e) { Log.e(TAG, "could not persist screen timeout setting", e); } } if (KEY_FONT_SIZE.equals(key)) { writeFontSizePreference(objValue); } return true; } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED)) { mWifiDisplayStatus = (WifiDisplayStatus)intent.getParcelableExtra( DisplayManager.EXTRA_WIFI_DISPLAY_STATUS); updateWifiDisplaySummary(); } } }; @Override public boolean onPreferenceClick(Preference preference) { if (preference == mFontSizePref) { if (Utils.hasMultipleUsers(getActivity())) { showDialog(DLG_GLOBAL_CHANGE_WARNING); return true; } else { mFontSizePref.click(); } } return false; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); if (mDisplayRotationPreference != null && RotationPolicy.isRotationLockToggleSupported(getActivity())) { // If rotation lock is supported, then we do not provide this option in // Display settings. However, is still available in Accessibility settings. getPreferenceScreen().removePreference(mDisplayRotationPreference); mDisplayRotationPreference = null; } mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mNotificationPulse = (PreferenceScreen) findPreference(KEY_NOTIFICATION_PULSE); if (mNotificationPulse != null) { if (!getResources().getBoolean(com.android.internal.R.bool.config_intrusiveNotificationLed)) { getPreferenceScreen().removePreference(mNotificationPulse); } else { updateLightPulseDescription(); } } mBatteryPulse = (PreferenceScreen) findPreference(KEY_BATTERY_LIGHT); if (mBatteryPulse != null) { if (getResources().getBoolean( com.android.internal.R.bool.config_intrusiveBatteryLed) == false) { getPreferenceScreen().removePreference(mBatteryPulse); } else { updateBatteryPulseDescription(); } } mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake)) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ContentResolver resolver = getActivity().getContentResolver(); addPreferencesFromResource(R.xml.display_settings); mDisplayRotationPreference = (PreferenceScreen) findPreference(KEY_DISPLAY_ROTATION); mScreenSaverPreference = findPreference(KEY_SCREEN_SAVER); if (mScreenSaverPreference != null && getResources().getBoolean( com.android.internal.R.bool.config_dreamsSupported) == false) { getPreferenceScreen().removePreference(mScreenSaverPreference); } mScreenTimeoutPreference = (ListPreference) findPreference(KEY_SCREEN_TIMEOUT); final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT, FALLBACK_SCREEN_TIMEOUT_VALUE); mScreenTimeoutPreference.setValue(String.valueOf(currentTimeout)); mScreenTimeoutPreference.setOnPreferenceChangeListener(this); disableUnusableTimeouts(mScreenTimeoutPreference); updateTimeoutPreferenceDescription(currentTimeout); updateDisplayRotationPreferenceDescription(); mFontSizePref = (WarnedListPreference) findPreference(KEY_FONT_SIZE); mFontSizePref.setOnPreferenceChangeListener(this); mFontSizePref.setOnPreferenceClickListener(this); mNotificationPulse = (PreferenceScreen) findPreference(KEY_NOTIFICATION_PULSE); if (mNotificationPulse != null) { if (!getResources().getBoolean(com.android.internal.R.bool.config_intrusiveNotificationLed)) { getPreferenceScreen().removePreference(mNotificationPulse); } else { updateLightPulseDescription(); } } mBatteryPulse = (PreferenceScreen) findPreference(KEY_BATTERY_LIGHT); if (mBatteryPulse != null) { if (getResources().getBoolean( com.android.internal.R.bool.config_intrusiveBatteryLed) == false) { getPreferenceScreen().removePreference(mBatteryPulse); } else { updateBatteryPulseDescription(); } } mDisplayManager = (DisplayManager)getActivity().getSystemService( Context.DISPLAY_SERVICE); mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus(); mWifiDisplayPreference = (Preference)findPreference(KEY_WIFI_DISPLAY); if (mWifiDisplayStatus.getFeatureState() == WifiDisplayStatus.FEATURE_STATE_UNAVAILABLE) { getPreferenceScreen().removePreference(mWifiDisplayPreference); mWifiDisplayPreference = null; } mVolumeWake = (CheckBoxPreference) findPreference(KEY_VOLUME_WAKE); if (mVolumeWake != null) { if (!getResources().getBoolean(R.bool.config_show_volumeRockerWake)) { getPreferenceScreen().removePreference(mVolumeWake); getPreferenceScreen().removePreference((PreferenceCategory) findPreference(KEY_WAKEUP_CATEGORY)); } else { mVolumeWake.setChecked(Settings.System.getInt(resolver, Settings.System.VOLUME_WAKE_SCREEN, 0) == 1); } } }
diff --git a/src/com/android/mms/transaction/MessagingNotification.java b/src/com/android/mms/transaction/MessagingNotification.java index 3c8b8ba7..c2cfd334 100644 --- a/src/com/android/mms/transaction/MessagingNotification.java +++ b/src/com/android/mms/transaction/MessagingNotification.java @@ -1,1358 +1,1361 @@ /* * Copyright (C) 2008 Esmertec AG. * 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.mms.transaction; import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND; import static com.google.android.mms.pdu.PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF; import com.android.mms.R; import com.android.mms.LogTag; import com.android.mms.data.Contact; import com.android.mms.data.Conversation; import com.android.mms.data.WorkingMessage; import com.android.mms.model.SlideModel; import com.android.mms.model.SlideshowModel; import com.android.mms.ui.ComposeMessageActivity; import com.android.mms.ui.ConversationList; import com.android.mms.ui.MessagingPreferenceActivity; import com.android.mms.util.AddressUtils; import com.android.mms.util.DownloadManager; import com.android.mms.widget.MmsWidgetProvider; import com.google.android.mms.MmsException; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.pdu.GenericPdu; import com.google.android.mms.pdu.MultimediaMessagePdu; import com.google.android.mms.pdu.PduHeaders; import com.google.android.mms.pdu.PduPersister; import android.database.sqlite.SqliteWrapper; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.media.AudioManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.Telephony.Mms; import android.provider.Telephony.Sms; import android.telephony.TelephonyManager; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.StyleSpan; import android.text.style.TextAppearanceSpan; import android.util.Log; import android.widget.Toast; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; /** * This class is used to update the notification indicator. It will check whether * there are unread messages. If yes, it would show the notification indicator, * otherwise, hide the indicator. */ public class MessagingNotification { private static final String TAG = LogTag.APP; private static final boolean DEBUG = false; // TODO turn off before ship private static final int NOTIFICATION_ID = 123; public static final int MESSAGE_FAILED_NOTIFICATION_ID = 789; public static final int DOWNLOAD_FAILED_NOTIFICATION_ID = 531; /** * This is the volume at which to play the in-conversation notification sound, * expressed as a fraction of the system notification volume. */ private static final float IN_CONVERSATION_NOTIFICATION_VOLUME = 0.25f; // This must be consistent with the column constants below. private static final String[] MMS_STATUS_PROJECTION = new String[] { Mms.THREAD_ID, Mms.DATE, Mms._ID, Mms.SUBJECT, Mms.SUBJECT_CHARSET }; // This must be consistent with the column constants below. private static final String[] SMS_STATUS_PROJECTION = new String[] { Sms.THREAD_ID, Sms.DATE, Sms.ADDRESS, Sms.SUBJECT, Sms.BODY }; // These must be consistent with MMS_STATUS_PROJECTION and // SMS_STATUS_PROJECTION. private static final int COLUMN_THREAD_ID = 0; private static final int COLUMN_DATE = 1; private static final int COLUMN_MMS_ID = 2; private static final int COLUMN_SMS_ADDRESS = 2; private static final int COLUMN_SUBJECT = 3; private static final int COLUMN_SUBJECT_CS = 4; private static final int COLUMN_SMS_BODY = 4; private static final String[] SMS_THREAD_ID_PROJECTION = new String[] { Sms.THREAD_ID }; private static final String[] MMS_THREAD_ID_PROJECTION = new String[] { Mms.THREAD_ID }; private static final String NEW_INCOMING_SM_CONSTRAINT = "(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_INBOX + " AND " + Sms.SEEN + " = 0)"; private static final String NEW_DELIVERY_SM_CONSTRAINT = "(" + Sms.TYPE + " = " + Sms.MESSAGE_TYPE_SENT + " AND " + Sms.STATUS + " = "+ Sms.STATUS_COMPLETE +")"; private static final String NEW_INCOMING_MM_CONSTRAINT = "(" + Mms.MESSAGE_BOX + "=" + Mms.MESSAGE_BOX_INBOX + " AND " + Mms.SEEN + "=0" + " AND (" + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_NOTIFICATION_IND + " OR " + Mms.MESSAGE_TYPE + "=" + MESSAGE_TYPE_RETRIEVE_CONF + "))"; private static final NotificationInfoComparator INFO_COMPARATOR = new NotificationInfoComparator(); private static final Uri UNDELIVERED_URI = Uri.parse("content://mms-sms/undelivered"); private final static String NOTIFICATION_DELETED_ACTION = "com.android.mms.NOTIFICATION_DELETED_ACTION"; public static class OnDeletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "[MessagingNotification] clear notification: mark all msgs seen"); } Conversation.markAllConversationsAsSeen(context); } } public static final long THREAD_ALL = -1; public static final long THREAD_NONE = -2; /** * Keeps track of the thread ID of the conversation that's currently displayed to the user */ private static long sCurrentlyDisplayedThreadId; private static final Object sCurrentlyDisplayedThreadLock = new Object(); private static OnDeletedReceiver sNotificationDeletedReceiver = new OnDeletedReceiver(); private static Intent sNotificationOnDeleteIntent; private static Handler sToastHandler = new Handler(); private static PduPersister sPduPersister; private static final int MAX_BITMAP_DIMEN_DP = 360; private static float sScreenDensity; /** * mNotificationSet is kept sorted by the incoming message delivery time, with the * most recent message first. */ private static SortedSet<NotificationInfo> sNotificationSet = new TreeSet<NotificationInfo>(INFO_COMPARATOR); private static final int MAX_MESSAGES_TO_SHOW = 8; // the maximum number of new messages to // show in a single notification. private MessagingNotification() { } public static void init(Context context) { // set up the intent filter for notification deleted action IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(NOTIFICATION_DELETED_ACTION); // TODO: should we unregister when the app gets killed? context.registerReceiver(sNotificationDeletedReceiver, intentFilter); sPduPersister = PduPersister.getPduPersister(context); // initialize the notification deleted action sNotificationOnDeleteIntent = new Intent(NOTIFICATION_DELETED_ACTION); sScreenDensity = context.getResources().getDisplayMetrics().density; } /** * Specifies which message thread is currently being viewed by the user. New messages in that * thread will not generate a notification icon and will play the notification sound at a lower * volume. Make sure you set this to THREAD_NONE when the UI component that shows the thread is * no longer visible to the user (e.g. Activity.onPause(), etc.) * @param threadId The ID of the thread that the user is currently viewing. Pass THREAD_NONE * if the user is not viewing a thread, or THREAD_ALL if the user is viewing the conversation * list (note: that latter one has no effect as of this implementation) */ public static void setCurrentlyDisplayedThreadId(long threadId) { synchronized (sCurrentlyDisplayedThreadLock) { sCurrentlyDisplayedThreadId = threadId; } } /** * Checks to see if there are any "unseen" messages or delivery * reports. Shows the most recent notification if there is one. * Does its work and query in a worker thread. * * @param context the context to use */ public static void nonBlockingUpdateNewMessageIndicator(final Context context, final long newMsgThreadId, final boolean isStatusMessage) { new Thread(new Runnable() { @Override public void run() { blockingUpdateNewMessageIndicator(context, newMsgThreadId, isStatusMessage); } }, "MessagingNotification.nonBlockingUpdateNewMessageIndicator").start(); } /** * Checks to see if there are any "unseen" messages or delivery * reports and builds a sorted (by delivery date) list of unread notifications. * * @param context the context to use * @param newMsgThreadId The thread ID of a new message that we're to notify about; if there's * no new message, use THREAD_NONE. If we should notify about multiple or unknown thread IDs, * use THREAD_ALL. * @param isStatusMessage */ public static void blockingUpdateNewMessageIndicator(Context context, long newMsgThreadId, boolean isStatusMessage) { synchronized (sCurrentlyDisplayedThreadLock) { if (newMsgThreadId > 0 && newMsgThreadId == sCurrentlyDisplayedThreadId) { if (DEBUG) { Log.d(TAG, "blockingUpdateNewMessageIndicator: newMsgThreadId == " + "sCurrentlyDisplayedThreadId so NOT showing notification," + " but playing soft sound. threadId: " + newMsgThreadId); } playInConversationNotificationSound(context); return; } } sNotificationSet.clear(); MmsSmsDeliveryInfo delivery = null; Set<Long> threads = new HashSet<Long>(4); int count = 0; addMmsNotificationInfos(context, threads); addSmsNotificationInfos(context, threads); cancelNotification(context, NOTIFICATION_ID); if (!sNotificationSet.isEmpty()) { if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "blockingUpdateNewMessageIndicator: count=" + count + ", newMsgThreadId=" + newMsgThreadId); } updateNotification(context, newMsgThreadId != THREAD_NONE, threads.size()); } // And deals with delivery reports (which use Toasts). It's safe to call in a worker // thread because the toast will eventually get posted to a handler. delivery = getSmsNewDeliveryInfo(context); if (delivery != null) { delivery.deliver(context, isStatusMessage); } } /** * Play the in-conversation notification sound (it's the regular notification sound, but * played at half-volume */ private static void playInConversationNotificationSound(Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); if (TextUtils.isEmpty(ringtoneStr)) { // Nothing to play return; } Uri ringtoneUri = Uri.parse(ringtoneStr); NotificationPlayer player = new NotificationPlayer(LogTag.APP); player.play(context, ringtoneUri, false, AudioManager.STREAM_NOTIFICATION, IN_CONVERSATION_NOTIFICATION_VOLUME); } /** * Updates all pending notifications, clearing or updating them as * necessary. */ public static void blockingUpdateAllNotifications(final Context context) { nonBlockingUpdateNewMessageIndicator(context, THREAD_NONE, false); nonBlockingUpdateSendFailedNotification(context); updateDownloadFailedNotification(context); MmsWidgetProvider.notifyDatasetChanged(context); } private static final class MmsSmsDeliveryInfo { public CharSequence mTicker; public long mTimeMillis; public MmsSmsDeliveryInfo(CharSequence ticker, long timeMillis) { mTicker = ticker; mTimeMillis = timeMillis; } public void deliver(Context context, boolean isStatusMessage) { updateDeliveryNotification( context, isStatusMessage, mTicker, mTimeMillis); } } private static final class NotificationInfo { public final Intent mClickIntent; public final String mMessage; public final CharSequence mTicker; public final long mTimeMillis; public final String mTitle; public final Bitmap mAttachmentBitmap; public final Contact mSender; public final boolean mIsSms; public final int mAttachmentType; public final String mSubject; public final long mThreadId; /** * @param isSms true if sms, false if mms * @param clickIntent where to go when the user taps the notification * @param message for a single message, this is the message text * @param subject text of mms subject * @param ticker text displayed ticker-style across the notification, typically formatted * as sender: message * @param timeMillis date the message was received * @param title for a single message, this is the sender * @param attachmentBitmap a bitmap of an attachment, such as a picture or video * @param sender contact of the sender * @param attachmentType of the mms attachment * @param threadId thread this message belongs to */ public NotificationInfo(boolean isSms, Intent clickIntent, String message, String subject, CharSequence ticker, long timeMillis, String title, Bitmap attachmentBitmap, Contact sender, int attachmentType, long threadId) { mIsSms = isSms; mClickIntent = clickIntent; mMessage = message; mSubject = subject; mTicker = ticker; mTimeMillis = timeMillis; mTitle = title; mAttachmentBitmap = attachmentBitmap; mSender = sender; mAttachmentType = attachmentType; mThreadId = threadId; } public long getTime() { return mTimeMillis; } // This is the message string used in bigText and bigPicture notifications. public CharSequence formatBigMessage(Context context) { final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (!TextUtils.isEmpty(mSubject)) { spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0); } if (mAttachmentType > WorkingMessage.TEXT) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append('\n'); } spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType)); } if (mMessage != null) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append('\n'); } spannableStringBuilder.append(mMessage); } return spannableStringBuilder; } // This is the message string used in each line of an inboxStyle notification. public CharSequence formatInboxMessage(Context context) { final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationSubjectText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); final String sender = mSender.getName(); if (!TextUtils.isEmpty(sender)) { spannableStringBuilder.append(sender); spannableStringBuilder.setSpan(notificationSenderSpan, 0, sender.length(), 0); } String separator = context.getString(R.string.notification_separator); if (!mIsSms) { if (!TextUtils.isEmpty(mSubject)) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } int start = spannableStringBuilder.length(); spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, start, start + mSubject.length(), 0); } if (mAttachmentType > WorkingMessage.TEXT) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } spannableStringBuilder.append(getAttachmentTypeString(context, mAttachmentType)); } } if (message.length() > 0) { if (spannableStringBuilder.length() > 0) { spannableStringBuilder.append(separator); } int start = spannableStringBuilder.length(); spannableStringBuilder.append(message); spannableStringBuilder.setSpan(notificationSubjectSpan, start, start + message.length(), 0); } return spannableStringBuilder; } // This is the summary string used in bigPicture notifications. public CharSequence formatPictureMessage(Context context) { final TextAppearanceSpan notificationSubjectSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); // Change multiple newlines (with potential white space between), into a single new line final String message = !TextUtils.isEmpty(mMessage) ? mMessage.replaceAll("\\n\\s+", "\n") : ""; // Show the subject or the message (if no subject) SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); if (!TextUtils.isEmpty(mSubject)) { spannableStringBuilder.append(mSubject); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, mSubject.length(), 0); } if (message.length() > 0 && spannableStringBuilder.length() == 0) { spannableStringBuilder.append(message); spannableStringBuilder.setSpan(notificationSubjectSpan, 0, message.length(), 0); } return spannableStringBuilder; } } // Return a formatted string with all the sender names separated by commas. private static CharSequence formatSenders(Context context, ArrayList<NotificationInfo> senders) { final TextAppearanceSpan notificationSenderSpan = new TextAppearanceSpan( context, R.style.NotificationPrimaryText); String separator = context.getString(R.string.enumeration_comma); // ", " SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(); int len = senders.size(); for (int i = 0; i < len; i++) { if (i > 0) { spannableStringBuilder.append(separator); } spannableStringBuilder.append(senders.get(i).mSender.getName()); } spannableStringBuilder.setSpan(notificationSenderSpan, 0, spannableStringBuilder.length(), 0); return spannableStringBuilder; } // Return a formatted string with the attachmentType spelled out as a string. For // no attachment (or just text), return null. private static CharSequence getAttachmentTypeString(Context context, int attachmentType) { final TextAppearanceSpan notificationAttachmentSpan = new TextAppearanceSpan( context, R.style.NotificationSecondaryText); int id = 0; switch (attachmentType) { case WorkingMessage.AUDIO: id = R.string.attachment_audio; break; case WorkingMessage.VIDEO: id = R.string.attachment_video; break; case WorkingMessage.SLIDESHOW: id = R.string.attachment_slideshow; break; case WorkingMessage.IMAGE: id = R.string.attachment_picture; break; } if (id > 0) { final SpannableString spannableString = new SpannableString(context.getString(id)); spannableString.setSpan(notificationAttachmentSpan, 0, spannableString.length(), 0); return spannableString; } return null; } /** * * Sorts by the time a notification was received in descending order -- newer first. * */ private static final class NotificationInfoComparator implements Comparator<NotificationInfo> { @Override public int compare( NotificationInfo info1, NotificationInfo info2) { return Long.signum(info2.getTime() - info1.getTime()); } } private static final void addMmsNotificationInfos( Context context, Set<Long> threads) { ContentResolver resolver = context.getContentResolver(); // This query looks like this when logged: // I/Database( 147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/ // mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1 // AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI, MMS_STATUS_PROJECTION, NEW_INCOMING_MM_CONSTRAINT, null, Mms.DATE + " desc"); if (cursor == null) { return; } try { while (cursor.moveToNext()) { long msgId = cursor.getLong(COLUMN_MMS_ID); Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath( Long.toString(msgId)).build(); String address = AddressUtils.getFrom(context, msgUri); Contact contact = Contact.get(address, false); if (contact.getSendToVoicemail()) { // don't notify, skip this one continue; } String subject = getMmsSubject( cursor.getString(COLUMN_SUBJECT), cursor.getInt(COLUMN_SUBJECT_CS)); long threadId = cursor.getLong(COLUMN_THREAD_ID); long timeMillis = cursor.getLong(COLUMN_DATE) * 1000; if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() + ", addr = " + address + ", thread_id=" + threadId); } // Extract the message and/or an attached picture from the first slide Bitmap attachedPicture = null; String messageBody = null; int attachmentType = WorkingMessage.TEXT; try { GenericPdu pdu = sPduPersister.load(msgUri); if (pdu != null && pdu instanceof MultimediaMessagePdu) { SlideshowModel slideshow = SlideshowModel.createFromPduBody(context, ((MultimediaMessagePdu)pdu).getBody()); attachmentType = getAttachmentType(slideshow); SlideModel firstSlide = slideshow.get(0); if (firstSlide != null) { if (firstSlide.hasImage()) { int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP); attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim); } if (firstSlide.hasText()) { messageBody = firstSlide.getText().getText(); } } } } catch (final MmsException e) { Log.e(TAG, "MmsException loading uri: " + msgUri, e); } NotificationInfo info = getNewMessageNotificationInfo(context, false /* isSms */, address, messageBody, subject, threadId, timeMillis, attachedPicture, contact, attachmentType); sNotificationSet.add(info); threads.add(threadId); } } finally { cursor.close(); } } // Look at the passed in slideshow and determine what type of attachment it is. private static int getAttachmentType(SlideshowModel slideshow) { int slideCount = slideshow.size(); if (slideCount == 0) { return WorkingMessage.TEXT; } else if (slideCount > 1) { return WorkingMessage.SLIDESHOW; } else { SlideModel slide = slideshow.get(0); if (slide.hasImage()) { return WorkingMessage.IMAGE; } else if (slide.hasVideo()) { return WorkingMessage.VIDEO; } else if (slide.hasAudio()) { return WorkingMessage.AUDIO; } } return WorkingMessage.TEXT; } private static final int dp2Pixels(int dip) { return (int) (dip * sScreenDensity + 0.5f); } private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) { ContentResolver resolver = context.getContentResolver(); Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT, null, Sms.DATE); if (cursor == null) { return null; } try { if (!cursor.moveToLast()) { return null; } String address = cursor.getString(COLUMN_SMS_ADDRESS); long timeMillis = 3000; Contact contact = Contact.get(address, false); String name = contact.getNameAndNumber(); return new MmsSmsDeliveryInfo(context.getString(R.string.delivery_toast_body, name), timeMillis); } finally { cursor.close(); } } private static final void addSmsNotificationInfos( Context context, Set<Long> threads) { ContentResolver resolver = context.getContentResolver(); Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION, NEW_INCOMING_SM_CONSTRAINT, null, Sms.DATE + " desc"); if (cursor == null) { return; } try { while (cursor.moveToNext()) { String address = cursor.getString(COLUMN_SMS_ADDRESS); Contact contact = Contact.get(address, false); if (contact.getSendToVoicemail()) { // don't notify, skip this one continue; } String message = cursor.getString(COLUMN_SMS_BODY); long threadId = cursor.getLong(COLUMN_THREAD_ID); long timeMillis = cursor.getLong(COLUMN_DATE); if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) { Log.d(TAG, "addSmsNotificationInfos: count=" + cursor.getCount() + ", addr=" + address + ", thread_id=" + threadId); } NotificationInfo info = getNewMessageNotificationInfo(context, true /* isSms */, address, message, null /* subject */, threadId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT); sNotificationSet.add(info); threads.add(threadId); threads.add(cursor.getLong(COLUMN_THREAD_ID)); } } finally { cursor.close(); } } private static final NotificationInfo getNewMessageNotificationInfo( Context context, boolean isSms, String address, String message, String subject, long threadId, long timeMillis, Bitmap attachmentBitmap, Contact contact, int attachmentType) { Intent clickIntent = ComposeMessageActivity.createIntent(context, threadId); clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); String senderInfo = buildTickerMessage( context, address, null, null).toString(); String senderInfoName = senderInfo.substring( 0, senderInfo.length() - 2); CharSequence ticker = buildTickerMessage( context, address, subject, message); return new NotificationInfo(isSms, clickIntent, message, subject, ticker, timeMillis, senderInfoName, attachmentBitmap, contact, attachmentType, threadId); } public static void cancelNotification(Context context, int notificationId) { NotificationManager nm = (NotificationManager) context.getSystemService( Context.NOTIFICATION_SERVICE); nm.cancel(notificationId); } private static void updateDeliveryNotification(final Context context, boolean isStatusMessage, final CharSequence message, final long timeMillis) { if (!isStatusMessage) { return; } if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { return; } sToastHandler.post(new Runnable() { @Override public void run() { Toast.makeText(context, message, (int)timeMillis).show(); } }); } /** * updateNotification is *the* main function for building the actual notification handed to * the NotificationManager * @param context * @param isNew if we've got a new message, show the ticker * @param uniqueThreadCount */ private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); NotificationInfo mostRecentNotification = sNotificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent( taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } TelephonyManager mTM = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callStateIdle = mTM.getCallState() == TelephonyManager.CALL_STATE_IDLE; boolean vibrateOnCall = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_CALL, true); boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; + boolean shouldVibrate = + audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER); - if ((vibrateAlways || vibrateSilent && nowSilent) && (vibrateOnCall || (!vibrateOnCall && callStateIdle))) { + if (((vibrateAlways && shouldVibrate) || (vibrateSilent && nowSilent)) && + (vibrateOnCall || (!vibrateOnCall && callStateIdle))) { /* WAS: notificationdefaults |= Notification.DEFAULT_VIBRATE;*/ String mVibratePattern = "custom".equals(sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, null)) ? sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN_CUSTOM, "0,1200") : sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if(!mVibratePattern.equals("")) { noti.setVibrate(parseVibratePattern(mVibratePattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1 || uniqueThreadCount == 1) { CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri()); PendingIntent mCallPendingIntent = PendingIntent.getActivity(context, 0, callIntent, 0); noti.addAction(R.drawable.ic_menu_call, callText, mCallPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } nm.notify(NOTIFICATION_ID, notification); } protected static CharSequence buildTickerMessage( Context context, String address, String subject, String body) { String displayAddress = Contact.get(address, true).getName(); StringBuilder buf = new StringBuilder( displayAddress == null ? "" : displayAddress.replace('\n', ' ').replace('\r', ' ')); buf.append(':').append(' '); int offset = buf.length(); if (!TextUtils.isEmpty(subject)) { subject = subject.replace('\n', ' ').replace('\r', ' '); buf.append(subject); buf.append(' '); } if (!TextUtils.isEmpty(body)) { body = body.replace('\n', ' ').replace('\r', ' '); buf.append(body); } SpannableString spanText = new SpannableString(buf.toString()); spanText.setSpan(new StyleSpan(Typeface.BOLD), 0, offset, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return spanText; } private static String getMmsSubject(String sub, int charset) { return TextUtils.isEmpty(sub) ? "" : new EncodedStringValue(charset, PduPersister.getBytes(sub)).getString(); } public static void notifyDownloadFailed(Context context, long threadId) { notifyFailed(context, true, threadId, false); } public static void notifySendFailed(Context context) { notifyFailed(context, false, 0, false); } public static void notifySendFailed(Context context, boolean noisy) { notifyFailed(context, false, 0, noisy); } private static void notifyFailed(Context context, boolean isDownload, long threadId, boolean noisy) { // TODO factor out common code for creating notifications boolean enabled = MessagingPreferenceActivity.getNotificationEnabled(context); if (!enabled) { return; } // Strategy: // a. If there is a single failure notification, tapping on the notification goes // to the compose view. // b. If there are two failure it stays in the thread view. Selecting one undelivered // thread will dismiss one undelivered notification but will still display the // notification.If you select the 2nd undelivered one it will dismiss the notification. long[] msgThreadId = {0, 1}; // Dummy initial values, just to initialize the memory int totalFailedCount = getUndeliveredMessageCount(context, msgThreadId); if (totalFailedCount == 0 && !isDownload) { return; } // The getUndeliveredMessageCount method puts a non-zero value in msgThreadId[1] if all // failures are from the same thread. // If isDownload is true, we're dealing with 1 specific failure; therefore "all failed" are // indeed in the same thread since there's only 1. boolean allFailedInSameThread = (msgThreadId[1] != 0) || isDownload; Intent failedIntent; Notification notification = new Notification(); String title; String description; if (totalFailedCount > 1) { description = context.getString(R.string.notification_failed_multiple, Integer.toString(totalFailedCount)); title = context.getString(R.string.notification_failed_multiple_title); } else { title = isDownload ? context.getString(R.string.message_download_failed_title) : context.getString(R.string.message_send_failed_title); description = context.getString(R.string.message_failed_body); } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); if (allFailedInSameThread) { failedIntent = new Intent(context, ComposeMessageActivity.class); if (isDownload) { // When isDownload is true, the valid threadId is passed into this function. failedIntent.putExtra("failed_download_flag", true); } else { threadId = msgThreadId[0]; failedIntent.putExtra("undelivered_flag", true); } failedIntent.putExtra("thread_id", threadId); taskStackBuilder.addParentStack(ComposeMessageActivity.class); } else { failedIntent = new Intent(context, ConversationList.class); } taskStackBuilder.addNextIntent(failedIntent); notification.icon = R.drawable.stat_notify_sms_failed; notification.tickerText = title; notification.setLatestEventInfo(context, title, description, taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); if (noisy) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); boolean vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false /* don't vibrate by default */); if (vibrate) { notification.defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); notification.sound = TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr); } NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (isDownload) { notificationMgr.notify(DOWNLOAD_FAILED_NOTIFICATION_ID, notification); } else { notificationMgr.notify(MESSAGE_FAILED_NOTIFICATION_ID, notification); } } /** * Query the DB and return the number of undelivered messages (total for both SMS and MMS) * @param context The context * @param threadIdResult A container to put the result in, according to the following rules: * threadIdResult[0] contains the thread id of the first message. * threadIdResult[1] is nonzero if the thread ids of all the messages are the same. * You can pass in null for threadIdResult. * You can pass in a threadIdResult of size 1 to avoid the comparison of each thread id. */ private static int getUndeliveredMessageCount(Context context, long[] threadIdResult) { Cursor undeliveredCursor = SqliteWrapper.query(context, context.getContentResolver(), UNDELIVERED_URI, MMS_THREAD_ID_PROJECTION, "read=0", null, null); if (undeliveredCursor == null) { return 0; } int count = undeliveredCursor.getCount(); try { if (threadIdResult != null && undeliveredCursor.moveToFirst()) { threadIdResult[0] = undeliveredCursor.getLong(0); if (threadIdResult.length >= 2) { // Test to see if all the undelivered messages belong to the same thread. long firstId = threadIdResult[0]; while (undeliveredCursor.moveToNext()) { if (undeliveredCursor.getLong(0) != firstId) { firstId = 0; break; } } threadIdResult[1] = firstId; // non-zero if all ids are the same } } } finally { undeliveredCursor.close(); } return count; } public static void nonBlockingUpdateSendFailedNotification(final Context context) { new AsyncTask<Void, Void, Integer>() { protected Integer doInBackground(Void... none) { return getUndeliveredMessageCount(context, null); } protected void onPostExecute(Integer result) { if (result < 1) { cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID); } else { // rebuild and adjust the message count if necessary. notifySendFailed(context); } } }.execute(); } /** * If all the undelivered messages belong to "threadId", cancel the notification. */ public static void updateSendFailedNotificationForThread(Context context, long threadId) { long[] msgThreadId = {0, 0}; if (getUndeliveredMessageCount(context, msgThreadId) > 0 && msgThreadId[0] == threadId && msgThreadId[1] != 0) { cancelNotification(context, MESSAGE_FAILED_NOTIFICATION_ID); } } private static int getDownloadFailedMessageCount(Context context) { // Look for any messages in the MMS Inbox that are of the type // NOTIFICATION_IND (i.e. not already downloaded) and in the // permanent failure state. If there are none, cancel any // failed download notification. Cursor c = SqliteWrapper.query(context, context.getContentResolver(), Mms.Inbox.CONTENT_URI, null, Mms.MESSAGE_TYPE + "=" + String.valueOf(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) + " AND " + Mms.STATUS + "=" + String.valueOf(DownloadManager.STATE_PERMANENT_FAILURE), null, null); if (c == null) { return 0; } int count = c.getCount(); c.close(); return count; } public static void updateDownloadFailedNotification(Context context) { if (getDownloadFailedMessageCount(context) < 1) { cancelNotification(context, DOWNLOAD_FAILED_NOTIFICATION_ID); } } public static boolean isFailedToDeliver(Intent intent) { return (intent != null) && intent.getBooleanExtra("undelivered_flag", false); } public static boolean isFailedToDownload(Intent intent) { return (intent != null) && intent.getBooleanExtra("failed_download_flag", false); } /** * Get the thread ID of the SMS message with the given URI * @param context The context * @param uri The URI of the SMS message * @return The thread ID, or THREAD_NONE if the URI contains no entries */ public static long getSmsThreadId(Context context, Uri uri) { Cursor cursor = SqliteWrapper.query( context, context.getContentResolver(), uri, SMS_THREAD_ID_PROJECTION, null, null, null); if (cursor == null) { return THREAD_NONE; } try { if (cursor.moveToFirst()) { return cursor.getLong(cursor.getColumnIndex(Sms.THREAD_ID)); } else { return THREAD_NONE; } } finally { cursor.close(); } } /** * Get the thread ID of the MMS message with the given URI * @param context The context * @param uri The URI of the SMS message * @return The thread ID, or THREAD_NONE if the URI contains no entries */ public static long getThreadId(Context context, Uri uri) { Cursor cursor = SqliteWrapper.query( context, context.getContentResolver(), uri, MMS_THREAD_ID_PROJECTION, null, null, null); if (cursor == null) { return THREAD_NONE; } try { if (cursor.moveToFirst()) { return cursor.getLong(cursor.getColumnIndex(Mms.THREAD_ID)); } else { return THREAD_NONE; } } finally { cursor.close(); } } // Parse the user provided custom vibrate pattern into a long[] public static long[] parseVibratePattern(String stringPattern) { ArrayList<Long> arrayListPattern = new ArrayList<Long>(); Long l; String[] splitPattern = stringPattern.split(","); int VIBRATE_PATTERN_MAX_SECONDS = 60000; int VIBRATE_PATTERN_MAX_PATTERN = 100; for (int i = 0; i < splitPattern.length; i++) { try { l = Long.parseLong(splitPattern[i].trim()); } catch (NumberFormatException e) { return null; } if (l > VIBRATE_PATTERN_MAX_SECONDS) { return null; } arrayListPattern.add(l); } int size = arrayListPattern.size(); if (size > 0 && size < VIBRATE_PATTERN_MAX_PATTERN) { long[] pattern = new long[size]; for (int i = 0; i < pattern.length; i++) { pattern[i] = arrayListPattern.get(i); } return pattern; } return null; } }
false
true
private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); NotificationInfo mostRecentNotification = sNotificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent( taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } TelephonyManager mTM = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callStateIdle = mTM.getCallState() == TelephonyManager.CALL_STATE_IDLE; boolean vibrateOnCall = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_CALL, true); boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; if ((vibrateAlways || vibrateSilent && nowSilent) && (vibrateOnCall || (!vibrateOnCall && callStateIdle))) { /* WAS: notificationdefaults |= Notification.DEFAULT_VIBRATE;*/ String mVibratePattern = "custom".equals(sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, null)) ? sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN_CUSTOM, "0,1200") : sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if(!mVibratePattern.equals("")) { noti.setVibrate(parseVibratePattern(mVibratePattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1 || uniqueThreadCount == 1) { CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri()); PendingIntent mCallPendingIntent = PendingIntent.getActivity(context, 0, callIntent, 0); noti.addAction(R.drawable.ic_menu_call, callText, mCallPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } nm.notify(NOTIFICATION_ID, notification); }
private static void updateNotification( Context context, boolean isNew, int uniqueThreadCount) { // If the user has turned off notifications in settings, don't do any notifying. if (!MessagingPreferenceActivity.getNotificationEnabled(context)) { if (DEBUG) { Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing"); } return; } // Figure out what we've got -- whether all sms's, mms's, or a mixture of both. int messageCount = sNotificationSet.size(); NotificationInfo mostRecentNotification = sNotificationSet.first(); final Notification.Builder noti = new Notification.Builder(context) .setWhen(mostRecentNotification.mTimeMillis); if (isNew) { noti.setTicker(mostRecentNotification.mTicker); } TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context); // If we have more than one unique thread, change the title (which would // normally be the contact who sent the message) to a generic one that // makes sense for multiple senders, and change the Intent to take the // user to the conversation list instead of the specific thread. // Cases: // 1) single message from single thread - intent goes to ComposeMessageActivity // 2) multiple messages from single thread - intent goes to ComposeMessageActivity // 3) messages from multiple threads - intent goes to ConversationList final Resources res = context.getResources(); String title = null; Bitmap avatar = null; if (uniqueThreadCount > 1) { // messages from multiple threads Intent mainActivityIntent = new Intent(Intent.ACTION_MAIN); mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); mainActivityIntent.setType("vnd.android-dir/mms-sms"); taskStackBuilder.addNextIntent(mainActivityIntent); title = context.getString(R.string.message_count_notification, messageCount); } else { // same thread, single or multiple messages title = mostRecentNotification.mTitle; BitmapDrawable contactDrawable = (BitmapDrawable)mostRecentNotification.mSender .getAvatar(context, null); if (contactDrawable != null) { // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we // have to scale 'em up to 128x128 to fill the whole notification large icon. avatar = contactDrawable.getBitmap(); if (avatar != null) { final int idealIconHeight = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height); final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width); if (avatar.getHeight() < idealIconHeight) { // Scale this image to fit the intended size avatar = Bitmap.createScaledBitmap( avatar, idealIconWidth, idealIconHeight, true); } if (avatar != null) { noti.setLargeIcon(avatar); } } } taskStackBuilder.addParentStack(ComposeMessageActivity.class); taskStackBuilder.addNextIntent(mostRecentNotification.mClickIntent); } // Always have to set the small icon or the notification is ignored noti.setSmallIcon(R.drawable.stat_notify_sms); NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // Update the notification. noti.setContentTitle(title) .setContentIntent( taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) .addKind(Notification.KIND_MESSAGE) .setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming // from a favorite. int defaults = 0; if (isNew) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String vibrateWhen; if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) { vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null); } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) { vibrateWhen = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false) ? context.getString(R.string.prefDefault_vibrate_true) : context.getString(R.string.prefDefault_vibrate_false); } else { vibrateWhen = context.getString(R.string.prefDefault_vibrateWhen); } TelephonyManager mTM = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); boolean callStateIdle = mTM.getCallState() == TelephonyManager.CALL_STATE_IDLE; boolean vibrateOnCall = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_CALL, true); boolean vibrateAlways = vibrateWhen.equals("always"); boolean vibrateSilent = vibrateWhen.equals("silent"); AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); boolean nowSilent = audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE; boolean shouldVibrate = audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER); if (((vibrateAlways && shouldVibrate) || (vibrateSilent && nowSilent)) && (vibrateOnCall || (!vibrateOnCall && callStateIdle))) { /* WAS: notificationdefaults |= Notification.DEFAULT_VIBRATE;*/ String mVibratePattern = "custom".equals(sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, null)) ? sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN_CUSTOM, "0,1200") : sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_PATTERN, "0,1200"); if(!mVibratePattern.equals("")) { noti.setVibrate(parseVibratePattern(mVibratePattern)); } else { defaults |= Notification.DEFAULT_VIBRATE; } } String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null); noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr)); if (DEBUG) { Log.d(TAG, "updateNotification: new message, adding sound to the notification"); } } defaults |= Notification.DEFAULT_LIGHTS; noti.setDefaults(defaults); // set up delete intent noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0)); final Notification notification; if (messageCount == 1 || uniqueThreadCount == 1) { CharSequence callText = context.getText(R.string.menu_call); Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(mostRecentNotification.mSender.getPhoneUri()); PendingIntent mCallPendingIntent = PendingIntent.getActivity(context, 0, callIntent, 0); noti.addAction(R.drawable.ic_menu_call, callText, mCallPendingIntent); } if (messageCount == 1) { // We've got a single message // This sets the text for the collapsed form: noti.setContentText(mostRecentNotification.formatBigMessage(context)); if (mostRecentNotification.mAttachmentBitmap != null) { // The message has a picture, show that notification = new Notification.BigPictureStyle(noti) .bigPicture(mostRecentNotification.mAttachmentBitmap) // This sets the text for the expanded picture form: .setSummaryText(mostRecentNotification.formatPictureMessage(context)) .build(); } else { // Show a single notification -- big style with the text of the whole message notification = new Notification.BigTextStyle(noti) .bigText(mostRecentNotification.formatBigMessage(context)) .build(); } } else { // We've got multiple messages if (uniqueThreadCount == 1) { // We've got multiple messages for the same thread. // Starting with the oldest new message, display the full text of each message. // Begin a line for each subsequent message. SpannableStringBuilder buf = new SpannableStringBuilder(); NotificationInfo infos[] = sNotificationSet.toArray(new NotificationInfo[sNotificationSet.size()]); int len = infos.length; for (int i = len - 1; i >= 0; i--) { NotificationInfo info = infos[i]; buf.append(info.formatBigMessage(context)); if (i != 0) { buf.append('\n'); } } noti.setContentText(context.getString(R.string.message_count_notification, messageCount)); // Show a single notification -- big style with the text of all the messages notification = new Notification.BigTextStyle(noti) .bigText(buf) // Forcibly show the last line, with the app's smallIcon in it, if we // kicked the smallIcon out with an avatar bitmap .setSummaryText((avatar == null) ? null : " ") .build(); } else { // Build a set of the most recent notification per threadId. HashSet<Long> uniqueThreads = new HashSet<Long>(sNotificationSet.size()); ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>(); Iterator<NotificationInfo> notifications = sNotificationSet.iterator(); while (notifications.hasNext()) { NotificationInfo notificationInfo = notifications.next(); if (!uniqueThreads.contains(notificationInfo.mThreadId)) { uniqueThreads.add(notificationInfo.mThreadId); mostRecentNotifPerThread.add(notificationInfo); } } // When collapsed, show all the senders like this: // Fred Flinstone, Barry Manilow, Pete... noti.setContentText(formatSenders(context, mostRecentNotifPerThread)); Notification.InboxStyle inboxStyle = new Notification.InboxStyle(noti); // We have to set the summary text to non-empty so the content text doesn't show // up when expanded. inboxStyle.setSummaryText(" "); // At this point we've got multiple messages in multiple threads. We only // want to show the most recent message per thread, which are in // mostRecentNotifPerThread. int uniqueThreadMessageCount = mostRecentNotifPerThread.size(); int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount); for (int i = 0; i < maxMessages; i++) { NotificationInfo info = mostRecentNotifPerThread.get(i); inboxStyle.addLine(info.formatInboxMessage(context)); } notification = inboxStyle.build(); if (DEBUG) { Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification"); } } } nm.notify(NOTIFICATION_ID, notification); }
diff --git a/x10.runtime/src-java/x10/rtt/Types.java b/x10.runtime/src-java/x10/rtt/Types.java index 3beacaf0a..40105558b 100644 --- a/x10.runtime/src-java/x10/rtt/Types.java +++ b/x10.runtime/src-java/x10/rtt/Types.java @@ -1,439 +1,439 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.rtt; import x10.core.Any; import x10.core.IndexedMemoryChunk; import x10.core.RefI; import x10.core.fun.Fun_0_1; public class Types { public static boolean instanceof$(Type<?> t, Object o) { return t.instanceof$(o); } public static Object cast$(Type<?> t, Object o) { if (! instanceof$(t, o)) throw new ClassCastException(t.toString()); return o; } // Hack to get around parsing problems for generated Java casts. public static <T> T javacast(Object o) { return (T) o; } public static String typeName(Object obj) { String s; if (obj instanceof Any) { s = ((Any) obj).$getRTT().typeName(obj); } else if (Types.getNativeRepRTT(obj) != null) { s = Types.getNativeRepRTT(obj).typeName(); } else { // Note: for java classes that don't have RTTs s = obj.getClass().toString().substring("class ".length()); } return s; } public static RuntimeType runtimeType(Class<?> c) { return new RuntimeType<Class<?>>(c); } // create rtt of comparable before all types that implement comparable (e.g. int) public static final RuntimeType<?> COMPARABLE = new RuntimeType( Comparable.class, new RuntimeType.Variance[] { RuntimeType.Variance.INVARIANT } ) { @Override public String typeName() { return "x10.lang.Comparable"; } }; public static final RuntimeType<Boolean> BOOLEAN = new BooleanType(); public static final RuntimeType<Byte> BYTE = new ByteType(); public static final RuntimeType<Short> SHORT = new ShortType(); public static final RuntimeType<Character> CHAR = new CharType(); public static final RuntimeType<Integer> INT = new IntType(); public static final RuntimeType<Long> LONG = new LongType(); public static final RuntimeType<Float> FLOAT = new FloatType(); public static final RuntimeType<Double> DOUBLE = new DoubleType(); public static final Object BOOLEAN_ZERO = Boolean.valueOf(false); public static final Object BYTE_ZERO = Byte.valueOf((byte) 0); public static final Object SHORT_ZERO = Short.valueOf((short) 0); public static final Object CHAR_ZERO = Character.valueOf((char) 0); public static final Object INT_ZERO = Integer.valueOf(0); public static final Object LONG_ZERO = Long.valueOf(0L); public static final Object FLOAT_ZERO = Float.valueOf(0.0F); public static final Object DOUBLE_ZERO = Double.valueOf(0.0); public static final RuntimeType<String> STRING = new RuntimeType<String>( String.class, new Type[] { new ParameterizedType(Fun_0_1.$RTT, Types.INT, Types.CHAR), new ParameterizedType(Types.COMPARABLE, new UnresolvedType(-1)) } ) { @Override public String typeName() { return "x10.lang.String"; } }; // Fix for XTENLANG-1916 public static final RuntimeType<RefI> OBJECT = new RuntimeType<RefI>(RefI.class) { @Override public String typeName() { return "x10.lang.Object"; } @Override public boolean isSubtype(x10.rtt.Type<?> o) { return o == OBJECT || o == ANY; }; }; public static final RuntimeType<Object> ANY = new RuntimeType<Object>(Object.class) { @Override public String typeName() { return "x10.lang.Any"; } @Override public boolean isSubtype(x10.rtt.Type<?> o) { return o == ANY; }; }; public static Class<?> UBYTE_CLASS; public static Class<?> USHORT_CLASS; public static Class<?> UINT_CLASS; public static Class<?> ULONG_CLASS; public static RuntimeType<?> UBYTE; public static RuntimeType<?> USHORT; public static RuntimeType<?> UINT; public static RuntimeType<?> ULONG; public static Object UBYTE_ZERO; public static Object USHORT_ZERO; public static Object UINT_ZERO; public static Object ULONG_ZERO; static { try { Class<?> c; java.lang.reflect.Field f; UBYTE_CLASS = c = Class.forName("x10.lang.UByte"); f = c.getDeclaredField("$RTT"); UBYTE = (RuntimeType<?>) f.get(null); UBYTE_ZERO = c.getConstructor(new Class[]{byte.class}).newInstance(new Object[]{(byte)0}); USHORT_CLASS = c = Class.forName("x10.lang.UShort"); f = c.getDeclaredField("$RTT"); USHORT = (RuntimeType<?>) f.get(null); USHORT_ZERO = c.getConstructor(new Class[]{short.class}).newInstance(new Object[]{(short)0}); UINT_CLASS = c = Class.forName("x10.lang.UInt"); f = c.getDeclaredField("$RTT"); UINT = (RuntimeType<?>) f.get(null); UINT_ZERO = c.getConstructor(new Class[]{int.class}).newInstance(new Object[]{0}); ULONG_CLASS = c = Class.forName("x10.lang.ULong"); f = c.getDeclaredField("$RTT"); ULONG = (RuntimeType<?>) f.get(null); ULONG_ZERO = c.getConstructor(new Class[]{long.class}).newInstance(new Object[]{0L}); } catch (Exception e) {} } public static RuntimeType<?> getNativeRepRTT(Object o) { if (o instanceof Byte) return BYTE; if (o instanceof Short) return SHORT; if (o instanceof Integer) return INT; if (o instanceof Long) return LONG; if (o instanceof Float) return FLOAT; if (o instanceof Double) return DOUBLE; if (o instanceof Character) return CHAR; if (o instanceof Boolean) return BOOLEAN; if (o instanceof String) return STRING; return null; } // TODO haszero /* private static boolean isPrimitiveStructType(Type<?> rtt) { if (rtt == BYTE || rtt == SHORT || rtt == INT || rtt == LONG || rtt == UBYTE || rtt == USHORT || rtt == UINT || rtt == ULONG || rtt == FLOAT || rtt == DOUBLE || rtt == CHAR || rtt == BOOLEAN) { return true; } return false; } static boolean isStructType(Type<?> rtt) { return rtt.isSubtype(x10.core.Struct.$RTT) || isPrimitiveStructType(rtt); } */ static boolean isStructType(Type<?> rtt) { if (rtt == BYTE || rtt == SHORT || rtt == INT || rtt == LONG || /*rtt == UBYTE || rtt == USHORT || rtt == UINT || rtt == ULONG ||*/ rtt == FLOAT || rtt == DOUBLE || rtt == CHAR || rtt == BOOLEAN) { return true; } else if (rtt.isSubtype(x10.core.Struct.$RTT)) { return true; } return false; } public static boolean instanceofObject(Object o) { return o != null && !isStruct(o); } public static boolean isStruct(Object o) { return x10.core.Struct.$RTT.instanceof$(o) || BYTE.instanceof$(o) || SHORT.instanceof$(o) || INT.instanceof$(o) || LONG.instanceof$(o) || FLOAT.instanceof$(o) || DOUBLE.instanceof$(o) || CHAR.instanceof$(o) || BOOLEAN.instanceof$(o); } public static boolean asboolean(Object typeParamOrAny) { if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Boolean");} if (typeParamOrAny instanceof java.lang.Boolean) {return (java.lang.Boolean) typeParamOrAny;} throw new ClassCastException("x10.lang.Boolean"); } public static byte asbyte(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Byte");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).byteValue();} throw new ClassCastException("x10.lang.Byte"); } public static short asshort(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Short");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).shortValue();} throw new ClassCastException("x10.lang.Short"); } public static int asint(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Int");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).intValue();} throw new ClassCastException("x10.lang.Int"); } public static long aslong(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Long");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).longValue();} throw new ClassCastException("x10.lang.Long"); } public static float asfloat(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Float");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).floatValue();} throw new ClassCastException("x10.lang.Float"); } public static double asdouble(Object typeParamOrAny){ if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Double");} if (typeParamOrAny instanceof java.lang.Number) {return((java.lang.Number) typeParamOrAny).doubleValue();} throw new ClassCastException("x10.lang.Double"); } public static char aschar(Object typeParamOrAny) { if (typeParamOrAny == null) {nullIsCastedToStruct("x10.lang.Char");} if (typeParamOrAny instanceof java.lang.Character) {return (java.lang.Character) typeParamOrAny;} throw new ClassCastException("x10.lang.Char"); } public static Object asStruct(Type<?> rtt, Object typeParamOrAny) { if (typeParamOrAny == null) {nullIsCastedToStruct(rtt);} if (rtt == UBYTE) { if (UBYTE_CLASS.isInstance(typeParamOrAny)) { return typeParamOrAny;} // if (USHORT_CLASS.isInstance(typeParamOrAny)) { return (UByte)...;} // if (UINT_CLASS.isInstance(typeParamOrAny)) { return (UByte)...;} // if (ULONG_CLASS.isInstance(typeParamOrAny)) { return (UByte)...;} } else if (rtt == USHORT) { if (USHORT_CLASS.isInstance(typeParamOrAny)) { return typeParamOrAny;} } else if (rtt == UINT) { if (UINT_CLASS.isInstance(typeParamOrAny)) { return typeParamOrAny;} } else if (rtt == ULONG) { if (ULONG_CLASS.isInstance(typeParamOrAny)) { return typeParamOrAny;} } else { return typeParamOrAny; } throw new ClassCastException(rtt.typeName()); } // FIXME this should be replaced by virtual method for user defined conversion public static Object conversion(Type<?> rtt, Object primOrTypeParam) { if (primOrTypeParam == null) { if (isStructType(rtt)) { nullIsCastedToStruct(rtt); } else { return null; } } if (rtt == BYTE) { if (primOrTypeParam instanceof java.lang.Byte) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).byteValue(); return primOrTypeParam; } if (rtt == SHORT) { if (primOrTypeParam instanceof java.lang.Short) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).shortValue(); return primOrTypeParam; } if (rtt == INT) { if (primOrTypeParam instanceof java.lang.Integer) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).intValue(); return primOrTypeParam; } if (rtt == LONG) { if (primOrTypeParam instanceof java.lang.Long) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).longValue(); return primOrTypeParam; } if (rtt == FLOAT) { if (primOrTypeParam instanceof java.lang.Float) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).floatValue(); return primOrTypeParam; } if (rtt == DOUBLE) { if (primOrTypeParam instanceof java.lang.Double) return primOrTypeParam; if (primOrTypeParam instanceof java.lang.Number) return ((java.lang.Number) primOrTypeParam).doubleValue(); return primOrTypeParam; } if (rtt == STRING) { if (primOrTypeParam instanceof x10.core.String) return x10.core.String.unbox(primOrTypeParam); return primOrTypeParam; } else if (primOrTypeParam instanceof java.lang.String) { // i.e. rtt==Any|Object|Fun return x10.core.String.box((java.lang.String) primOrTypeParam); } return primOrTypeParam; } public static void nullIsCastedToStruct(Type<?> rtt) {throw new java.lang.ClassCastException(rtt.typeName());} public static void nullIsCastedToStruct(String msg){throw new java.lang.ClassCastException(msg);} public static boolean hasNaturalZero(Type<?> rtt) { if (rtt.isSubtype(OBJECT) || rtt == BYTE || rtt == SHORT || rtt == INT || rtt == LONG || /*rtt == UBYTE || rtt == USHORT || rtt == UINT || rtt == ULONG ||*/ rtt == FLOAT || rtt == DOUBLE || rtt == CHAR || rtt == BOOLEAN) return true; return false; } public static <T> T cast(final java.lang.Object self, x10.rtt.Type<?> rtt) { if (self == null) return null; if (rtt != null && !rtt.instanceof$(self)) throw new x10.lang.ClassCastException(rtt.typeName()); return (T) self; } public static <T> T castConversion(final java.lang.Object self, x10.rtt.Type<?> rtt) { if (self == null) return null; T ret = (T) conversion(rtt, self); if (rtt != null && !rtt.instanceof$(ret)) throw new x10.lang.ClassCastException(rtt.typeName()); return ret; } // TODO haszero /* private static Object zeroValue(Class<?> c) { if (c.equals(BYTE.getJavaClass()) || c.equals(Byte.class)) return BYTE_ZERO; if (c.equals(SHORT.getJavaClass()) || c.equals(Short.class)) return SHORT_ZERO; if (c.equals(INT.getJavaClass()) || c.equals(Integer.class)) return INT_ZERO; if (c.equals(LONG.getJavaClass()) || c.equals(Long.class)) return LONG_ZERO; if (c.equals(UBYTE.getJavaClass())) return UBYTE_ZERO; if (c.equals(USHORT.getJavaClass())) return USHORT_ZERO; if (c.equals(UINT.getJavaClass())) return UINT_ZERO; if (c.equals(ULONG.getJavaClass())) return ULONG_ZERO; if (c.equals(FLOAT.getJavaClass()) || c.equals(Float.class)) return FLOAT_ZERO; if (c.equals(DOUBLE.getJavaClass()) || c.equals(Double.class)) return DOUBLE_ZERO; if (c.equals(CHAR.getJavaClass()) || c.equals(Character.class)) return CHAR_ZERO; if (c.equals(BOOLEAN.getJavaClass()) || c.equals(Boolean.class)) return BOOLEAN_ZERO; // Note: user defined structs is not supported // assert !x10.core.Struct.class.isAssignableFrom(c) : "user defined structs is not supported"; return null; } */ public static Object zeroValue(Type<?> rtt) { Type<?>[] typeParams = null; if (rtt instanceof ParameterizedType) { ParameterizedType<?> pt = (ParameterizedType<?>) rtt; rtt = pt.getRuntimeType(); typeParams = pt.getParams(); } if (isStructType(rtt)) { if (rtt == BYTE) return BYTE_ZERO; if (rtt == SHORT) return SHORT_ZERO; if (rtt == INT) return INT_ZERO; if (rtt == LONG) return LONG_ZERO; if (rtt == UBYTE) return UBYTE_ZERO; if (rtt == USHORT) return USHORT_ZERO; if (rtt == UINT) return UINT_ZERO; if (rtt == ULONG) return ULONG_ZERO; if (rtt == FLOAT) return FLOAT_ZERO; if (rtt == DOUBLE) return DOUBLE_ZERO; if (rtt == CHAR) return CHAR_ZERO; if (rtt == BOOLEAN) return BOOLEAN_ZERO; if (rtt == IndexedMemoryChunk.$RTT) return new IndexedMemoryChunk(typeParams[0]); // if (isPrimitiveStructType(rtt)) return zeroValue(rtt.getJavaClass()); // for user-defined structs, call zero value constructor try { Class<?> c = rtt.getJavaClass(); java.lang.reflect.Constructor<?> ctor = null; Class<?>[] paramTypes = null; for (java.lang.reflect.Constructor<?> ctor0 : c.getConstructors()) { paramTypes = ctor0.getParameterTypes(); - if (paramTypes[paramTypes.length-1].equals(java.lang.System[].class)) { + if (paramTypes[paramTypes.length-1].equals(java.lang.System.class)) { ctor = ctor0; break; } } assert ctor != null; Object[] params = new Object[paramTypes.length]; /* int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } for ( ; i < paramTypes.length; ++i) { // these values are not necessarily zero value params[i] = zeroValue(paramTypes[i]); } */ assert typeParams == null ? paramTypes.length == 1 : paramTypes.length == typeParams.length/*T1,T2,...*/ + 1/*(java.lang.String[])null*/; int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } params[i] = null; return ctor.newInstance(params); } catch (Exception e) { e.printStackTrace(); throw new java.lang.Error(e); } } return null; } }
true
true
public static Object zeroValue(Type<?> rtt) { Type<?>[] typeParams = null; if (rtt instanceof ParameterizedType) { ParameterizedType<?> pt = (ParameterizedType<?>) rtt; rtt = pt.getRuntimeType(); typeParams = pt.getParams(); } if (isStructType(rtt)) { if (rtt == BYTE) return BYTE_ZERO; if (rtt == SHORT) return SHORT_ZERO; if (rtt == INT) return INT_ZERO; if (rtt == LONG) return LONG_ZERO; if (rtt == UBYTE) return UBYTE_ZERO; if (rtt == USHORT) return USHORT_ZERO; if (rtt == UINT) return UINT_ZERO; if (rtt == ULONG) return ULONG_ZERO; if (rtt == FLOAT) return FLOAT_ZERO; if (rtt == DOUBLE) return DOUBLE_ZERO; if (rtt == CHAR) return CHAR_ZERO; if (rtt == BOOLEAN) return BOOLEAN_ZERO; if (rtt == IndexedMemoryChunk.$RTT) return new IndexedMemoryChunk(typeParams[0]); // if (isPrimitiveStructType(rtt)) return zeroValue(rtt.getJavaClass()); // for user-defined structs, call zero value constructor try { Class<?> c = rtt.getJavaClass(); java.lang.reflect.Constructor<?> ctor = null; Class<?>[] paramTypes = null; for (java.lang.reflect.Constructor<?> ctor0 : c.getConstructors()) { paramTypes = ctor0.getParameterTypes(); if (paramTypes[paramTypes.length-1].equals(java.lang.System[].class)) { ctor = ctor0; break; } } assert ctor != null; Object[] params = new Object[paramTypes.length]; /* int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } for ( ; i < paramTypes.length; ++i) { // these values are not necessarily zero value params[i] = zeroValue(paramTypes[i]); } */ assert typeParams == null ? paramTypes.length == 1 : paramTypes.length == typeParams.length/*T1,T2,...*/ + 1/*(java.lang.String[])null*/; int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } params[i] = null; return ctor.newInstance(params); } catch (Exception e) { e.printStackTrace(); throw new java.lang.Error(e); } } return null; }
public static Object zeroValue(Type<?> rtt) { Type<?>[] typeParams = null; if (rtt instanceof ParameterizedType) { ParameterizedType<?> pt = (ParameterizedType<?>) rtt; rtt = pt.getRuntimeType(); typeParams = pt.getParams(); } if (isStructType(rtt)) { if (rtt == BYTE) return BYTE_ZERO; if (rtt == SHORT) return SHORT_ZERO; if (rtt == INT) return INT_ZERO; if (rtt == LONG) return LONG_ZERO; if (rtt == UBYTE) return UBYTE_ZERO; if (rtt == USHORT) return USHORT_ZERO; if (rtt == UINT) return UINT_ZERO; if (rtt == ULONG) return ULONG_ZERO; if (rtt == FLOAT) return FLOAT_ZERO; if (rtt == DOUBLE) return DOUBLE_ZERO; if (rtt == CHAR) return CHAR_ZERO; if (rtt == BOOLEAN) return BOOLEAN_ZERO; if (rtt == IndexedMemoryChunk.$RTT) return new IndexedMemoryChunk(typeParams[0]); // if (isPrimitiveStructType(rtt)) return zeroValue(rtt.getJavaClass()); // for user-defined structs, call zero value constructor try { Class<?> c = rtt.getJavaClass(); java.lang.reflect.Constructor<?> ctor = null; Class<?>[] paramTypes = null; for (java.lang.reflect.Constructor<?> ctor0 : c.getConstructors()) { paramTypes = ctor0.getParameterTypes(); if (paramTypes[paramTypes.length-1].equals(java.lang.System.class)) { ctor = ctor0; break; } } assert ctor != null; Object[] params = new Object[paramTypes.length]; /* int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } for ( ; i < paramTypes.length; ++i) { // these values are not necessarily zero value params[i] = zeroValue(paramTypes[i]); } */ assert typeParams == null ? paramTypes.length == 1 : paramTypes.length == typeParams.length/*T1,T2,...*/ + 1/*(java.lang.String[])null*/; int i = 0; if (typeParams != null) { for ( ; i < typeParams.length; ++i) { // pass type params params[i] = typeParams[i]; } } params[i] = null; return ctor.newInstance(params); } catch (Exception e) { e.printStackTrace(); throw new java.lang.Error(e); } } return null; }
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExpression.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExpression.java index 1d470a223..fd3c44c7e 100644 --- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExpression.java +++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExpression.java @@ -1,1941 +1,1941 @@ /******************************************************************************* * Copyright (c) 2008, 2012 Wind River Systems, Inc. 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: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.internal.debug.ui.model; import java.math.BigInteger; import java.util.LinkedList; import java.util.Map; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IExpressionManager; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IExpression; import org.eclipse.debug.core.model.IWatchExpression; import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenCountUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.IElementEditor; import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate; import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta; import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugModelPresentation; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jface.viewers.CellEditor; import org.eclipse.jface.viewers.ICellModifier; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Composite; import org.eclipse.tcf.debug.ui.ITCFExpression; import org.eclipse.tcf.debug.ui.ITCFPrettyExpressionProvider; import org.eclipse.tcf.internal.debug.model.TCFContextState; import org.eclipse.tcf.internal.debug.ui.Activator; import org.eclipse.tcf.internal.debug.ui.ColorCache; import org.eclipse.tcf.internal.debug.ui.ImageCache; import org.eclipse.tcf.protocol.IChannel; import org.eclipse.tcf.protocol.IToken; import org.eclipse.tcf.protocol.JSON; import org.eclipse.tcf.services.IExpressions; import org.eclipse.tcf.services.IMemory; import org.eclipse.tcf.services.IMemory.MemoryError; import org.eclipse.tcf.services.IRegisters; import org.eclipse.tcf.services.ISymbols; import org.eclipse.tcf.util.TCFDataCache; import org.eclipse.tcf.util.TCFTask; public class TCFNodeExpression extends TCFNode implements IElementEditor, ICastToType, IWatchInExpressions, IDetailsProvider, ITCFExpression { // TODO: User commands: Add Global Variables, Remove Global Variables // TODO: enable Change Value user command private final String script; private final int index; private final boolean deref; private final String field_id; private final String reg_id; private final TCFData<String> base_text; private final TCFData<IExpressions.Expression> var_expression; private final TCFData<IExpressions.Expression> rem_expression; private final TCFData<IExpressions.Value> value; private final TCFData<ISymbols.Symbol> type; private final TCFData<String> type_name; private final TCFData<StyledStringBuffer> string; private final TCFData<String> expression_text; private final TCFChildrenSubExpressions children; private final boolean is_empty; private int sort_pos; private boolean enabled = true; private IExpressions.Value prev_value; private IExpressions.Value next_value; private byte[] parent_value; private String remote_expression_id; private static int expr_cnt; TCFNodeExpression(final TCFNode parent, final String script, final String field_id, final String var_id, final String reg_id, final int index, final boolean deref) { super(parent, var_id != null ? var_id : "Expr" + expr_cnt++); this.script = script; this.field_id = field_id; this.reg_id = reg_id; this.index = index; this.deref = deref; is_empty = script == null && var_id == null && field_id == null && reg_id == null && index < 0; var_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null || var_id == null) { set(null, null, null); return true; } command = exps.getContext(var_id, new IExpressions.DoneGetContext() { public void doneGetContext(IToken token, Exception error, IExpressions.Expression context) { set(token, error, context); } }); return false; } }; base_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute expression script, not including type cast */ parent_value = null; if (is_empty) { set(null, null, null); return true; } if (script != null) { set(null, null, script); return true; } if (var_id != null) { if (!var_expression.validate(this)) return false; Throwable err = null; String exp = null; if (var_expression.getData() == null) { err = var_expression.getError(); } else { exp = var_expression.getData().getExpression(); if (exp == null) err = new Exception("Missing 'Expression' property"); } set(null, err, exp); return true; } if (reg_id != null) { set(null, null, "${" + reg_id + "}"); return true; } String e = null; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; String cast = model.getCastToType(n.id); if (cast == null && deref) { TCFNodeExpression exp = (TCFNodeExpression)n; if (!exp.value.validate(this)) return false; IExpressions.Value v = exp.value.getData(); if (v != null && v.getTypeID() != null) { parent_value = v.getValue(); if (parent_value != null) { e = "(${" + v.getTypeID() + "})0x" + TCFNumberFormat.toBigInteger( parent_value, v.isBigEndian(), false).toString(16); } } } if (e == null) { TCFDataCache<String> t = ((TCFNodeExpression)n).base_text; if (!t.validate(this)) return false; e = t.getData(); if (e == null) { set(null, t.getError(), null); return true; } } if (cast != null) e = "(" + cast + ")(" + e + ")"; if (field_id != null) { e = "(" + e + ")" + (deref ? "->" : ".") + "${" + field_id + "}"; } else if (index == 0) { e = "*(" + e + ")"; } else if (index > 0) { e = "(" + e + ")[" + index + "]"; } set(null, null, e); return true; } }; expression_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute human readable expression script, * including type cast, and using variable names instead of IDs */ String expr_text = null; if (script != null) { expr_text = script; } else if (var_id != null) { if (!var_expression.validate(this)) return false; IExpressions.Expression e = var_expression.getData(); if (e != null) { TCFDataCache<ISymbols.Symbol> var = model.getSymbolInfoCache(e.getSymbolID()); if (var != null) { if (!var.validate(this)) return false; if (var.getData() != null) expr_text = var.getData().getName(); } } } else if (reg_id != null) { if (!model.createNode(reg_id, this)) return false; if (isValid()) return true; TCFNodeRegister reg_node = (TCFNodeRegister)model.getNode(reg_id); for (;;) { TCFDataCache<IRegisters.RegistersContext> ctx_cache = reg_node.getContext(); if (!ctx_cache.validate(this)) return false; IRegisters.RegistersContext ctx_data = ctx_cache.getData(); if (ctx_data == null) { set(null, ctx_cache.getError(), null); return true; } expr_text = expr_text == null ? ctx_data.getName() : ctx_data.getName() + "." + expr_text; if (!(reg_node.parent instanceof TCFNodeRegister)) break; reg_node = (TCFNodeRegister)reg_node.parent; } expr_text = "$" + expr_text; } else { TCFDataCache<?> pending = null; TCFDataCache<ISymbols.Symbol> field = model.getSymbolInfoCache(field_id); if (field != null && !field.validate()) pending = field; if (!base_text.validate()) pending = base_text; if (pending != null) { pending.wait(this); return false; } String parent_text = ""; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; TCFDataCache<String> parent_text_cache = ((TCFNodeExpression)n).expression_text; if (!parent_text_cache.validate(this)) return false; if (parent_text_cache.getData() != null) { parent_text = parent_text_cache.getData(); // surround with parentheses if not a simple identifier if (!parent_text.matches("\\w*")) { parent_text = '(' + parent_text + ')'; } } if (index >= 0) { if (index == 0 && deref) { expr_text = "*" + parent_text; } else { expr_text = parent_text + "[" + index + "]"; } } if (expr_text == null && field != null) { ISymbols.Symbol field_data = field.getData(); if (field_data != null) { if (field_data.getName() != null) { expr_text = parent_text + (deref ? "->" : ".") + field_data.getName(); } else if (field_data.getFlag(ISymbols.SYM_FLAG_INHERITANCE)) { TCFDataCache<ISymbols.Symbol> type = model.getSymbolInfoCache(field_data.getTypeID()); if (type != null) { if (!type.validate(this)) return false; ISymbols.Symbol type_data = type.getData(); if (type_data != null) { String type_name = type_data.getName(); expr_text = "*(" + type_name + "*)" + (deref ? "" : "&") + parent_text; } } } } } if (expr_text == null && base_text.getData() != null) expr_text = base_text.getData(); } if (expr_text != null) { String cast = model.getCastToType(id); if (cast != null) expr_text = "(" + cast + ")(" + expr_text + ")"; } set(null, null, expr_text); return true; } }; rem_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null) { set(null, null, null); return true; } String cast = model.getCastToType(id); if (var_id != null && cast == null) { if (!var_expression.validate(this)) return false; set(null, var_expression.getError(), var_expression.getData()); return true; } if (!base_text.validate(this)) return false; String e = base_text.getData(); if (e == null) { set(null, base_text.getError(), null); return true; } if (cast != null) e = "(" + cast + ")(" + e + ")"; TCFNode n = getRootExpression().parent; if (n instanceof TCFNodeStackFrame && ((TCFNodeStackFrame)n).isEmulated()) n = n.parent; command = exps.create(n.id, null, e, new IExpressions.DoneCreate() { public void doneCreate(IToken token, Exception error, IExpressions.Expression context) { disposeRemoteExpression(); if (context != null) remote_expression_id = context.getID(); if (!isDisposed()) set(token, error, context); else disposeRemoteExpression(); } }); return false; } }; value = new TCFData<IExpressions.Value>(channel) { @Override protected boolean startDataRetrieval() { Boolean b = usePrevValue(this); if (b == null) return false; if (b) { set(null, null, prev_value); return true; } if (!rem_expression.validate(this)) return false; final IExpressions.Expression exp = rem_expression.getData(); if (exp == null) { set(null, rem_expression.getError(), null); return true; } final TCFDataCache<?> cache = this; IExpressions exps = launch.getService(IExpressions.class); command = exps.evaluate(exp.getID(), new IExpressions.DoneEvaluate() { public void doneEvaluate(IToken token, Exception error, IExpressions.Value value) { if (command != token) return; command = null; if (error != null) { Boolean b = usePrevValue(cache); if (b == null) return; if (b) { set(null, null, prev_value); return; } } set(null, error, value); } }); return false; } }; type = new TCFData<ISymbols.Symbol>(channel) { @Override protected boolean startDataRetrieval() { String type_id = null; if (model.getCastToType(id) == null && field_id != null) { TCFDataCache<ISymbols.Symbol> sym_cache = model.getSymbolInfoCache(field_id); if (sym_cache != null) { if (!sym_cache.validate(this)) return false; ISymbols.Symbol sym_data = sym_cache.getData(); if (sym_data != null) type_id = sym_data.getTypeID(); } } if (type_id == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null) type_id = val.getTypeID(); } if (type_id == null) { if (!rem_expression.validate(this)) return false; IExpressions.Expression exp = rem_expression.getData(); if (exp != null) type_id = exp.getTypeID(); } if (type_id == null) { set(null, value.getError(), null); return true; } TCFDataCache<ISymbols.Symbol> type_cache = model.getSymbolInfoCache(type_id); if (type_cache == null) { set(null, null, null); return true; } if (!type_cache.validate(this)) return false; set(null, type_cache.getError(), type_cache.getData()); return true; } }; string = new TCFData<StyledStringBuffer>(channel) { ISymbols.Symbol base_type_data; BigInteger addr; byte[] buf; int size; int offs; @Override @SuppressWarnings("incomplete-switch") protected boolean startDataRetrieval() { if (addr != null) return continueMemRead(); if (!value.validate(this)) return false; if (!type.validate(this)) return false; IExpressions.Value value_data = value.getData(); ISymbols.Symbol type_data = type.getData(); if (value_data != null && value_data.getValue() != null && type_data != null) { switch (type_data.getTypeClass()) { case pointer: case array: TCFDataCache<ISymbols.Symbol> base_type_cache = model.getSymbolInfoCache(type_data.getBaseTypeID()); if (base_type_cache == null) break; if (!base_type_cache.validate(this)) return false; base_type_data = base_type_cache.getData(); if (base_type_data == null) break; size = base_type_data.getSize(); if (size == 0) break; switch (base_type_data.getTypeClass()) { case integer: case cardinal: if (base_type_data.getSize() != 1) break; // c-string: read until character = 0 if (type_data.getTypeClass() == ISymbols.TypeClass.array) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '"'), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } // pointer, read c-string data from memory size = 0; // read until 0 return startMemRead(value_data); case composite: if (type_data.getTypeClass() == ISymbols.TypeClass.array) break; // pointer, read struct data from memory return startMemRead(value_data); } break; case integer: case cardinal: if (type_data.getSize() == 1) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '\''), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } break; case enumeration: TCFDataCache<String[]> type_children_cache = model.getSymbolChildrenCache(type_data.getID()); if (!type_children_cache.validate(this)) return false; String[] type_children_data = type_children_cache.getData(); if (type_children_data == null) break; for (String const_id : type_children_data) { TCFDataCache<ISymbols.Symbol> const_cache = model.getSymbolInfoCache(const_id); if (!const_cache.validate(this)) return false; ISymbols.Symbol const_data = const_cache.getData(); if (const_data != null && const_data.getName() != null) { byte[] const_bytes = const_data.getValue(); if (const_bytes != null) { boolean ok = true; byte[] data = value_data.getValue(); for (int i = 0; ok && i < data.length; i++) { if (i < const_bytes.length) ok = const_bytes[i] == data[i]; else ok = data[i] == 0; } if (ok && const_data.getName() != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(const_data.getName()); set(null, null, bf); return true; } } } } break; } } set(null, null, null); return true; } @Override public void reset() { super.reset(); addr = null; } private boolean startMemRead(IExpressions.Value value_data) { byte[] data = value_data.getValue(); BigInteger a = TCFNumberFormat.toBigInteger(data, value_data.isBigEndian(), false); if (!a.equals(BigInteger.valueOf(0))) { addr = a; offs = 0; return continueMemRead(); } set(null, null, null); return true; } private boolean continueMemRead() { // indirect value, need to read it from memory TCFDataCache<TCFNodeExecContext> mem_node_cache = model.searchMemoryContext(parent); if (mem_node_cache == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (!mem_node_cache.validate(this)) return false; if (mem_node_cache.getError() != null) { set(null, mem_node_cache.getError(), null); return true; } TCFNodeExecContext mem_node = mem_node_cache.getData(); if (mem_node == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } TCFDataCache<IMemory.MemoryContext> mem_ctx_cache = mem_node.getMemoryContext(); if (!mem_ctx_cache.validate(this)) return false; if (mem_ctx_cache.getError() != null) { set(null, mem_ctx_cache.getError(), null); return true; } IMemory.MemoryContext mem_space_data = mem_ctx_cache.getData(); if (mem_space_data == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (size == 0) { // c-string: read until 0 + BigInteger get_addr = addr.add(BigInteger.valueOf(offs)); + final int get_size = 16 - (get_addr.intValue() & 0xf); if (buf == null) buf = new byte[256]; - if (offs >= buf.length) { + if (offs + get_size > buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, buf.length); buf = tmp; } - BigInteger get_addr = addr.add(BigInteger.valueOf(offs)); - final int get_size = 16 - (get_addr.intValue() & 0xf); command = mem_space_data.get(get_addr, 1, buf, offs, get_size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (command != token) return; IMemory.ErrorOffset err_offs = null; if (error instanceof IMemory.ErrorOffset) err_offs = (IMemory.ErrorOffset)error; for (int i = 0; i < get_size; i++) { MemoryError byte_error = null; if (error != null && (err_offs == null || err_offs.getStatus(i) != IMemory.ErrorOffset.BYTE_VALID)) { byte_error = error; if (offs == 0) { set(command, byte_error, null); return; } } if (buf[offs] == 0 || offs >= 2048 || byte_error != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(buf, 0, offs, '"'), StyledStringBuffer.MONOSPACED); set(command, null, bf); return; } offs++; } command = null; run(); } }); return false; } if (offs == 0) { buf = new byte[size]; command = mem_space_data.get(addr, 1, buf, 0, size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (error != null) { set(command, error, null); } else if (command == token) { command = null; offs++; run(); } } }); return false; } StyledStringBuffer bf = new StyledStringBuffer(); bf.append('{'); if (!appendCompositeValueText(bf, 1, base_type_data, TCFNodeExpression.this, true, buf, 0, size, base_type_data.isBigEndian(), this)) return false; bf.append('}'); set(null, null, bf); return true; } }; type_name = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { if (!type.validate(this)) return false; if (type.getData() == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null && val.getValue() != null) { String s = getTypeName(val.getTypeClass(), val.getValue().length); if (s != null) { set(null, null, s); return true; } } } StringBuffer bf = new StringBuffer(); if (!getTypeName(bf, type, this)) return false; set(null, null, bf.toString()); return true; } }; children = new TCFChildrenSubExpressions(this, 0, 0, 0); } private void disposeRemoteExpression() { if (remote_expression_id != null && channel.getState() == IChannel.STATE_OPEN) { IExpressions exps = channel.getRemoteService(IExpressions.class); exps.dispose(remote_expression_id, new IExpressions.DoneDispose() { public void doneDispose(IToken token, Exception error) { if (error == null) return; if (channel.getState() != IChannel.STATE_OPEN) return; Activator.log("Error disposing remote expression evaluator", error); } }); remote_expression_id = null; } } @Override public void dispose() { for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.dispose(this); disposeRemoteExpression(); super.dispose(); } private TCFNodeExpression getRootExpression() { TCFNode n = this; while (n.parent instanceof TCFNodeExpression || n.parent instanceof TCFNodeArrayPartition) n = n.parent; return (TCFNodeExpression)n; } private void postAllChangedDelta() { TCFNodeExpression n = getRootExpression(); for (TCFModelProxy p : model.getModelProxies()) { String id = p.getPresentationContext().getId(); if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(id) && n.script != null || TCFModel.ID_EXPRESSION_HOVER.equals(id) && n.script != null || IDebugUIConstants.ID_VARIABLE_VIEW.equals(id) && n.script == null) { p.addDelta(this, IModelDelta.STATE | IModelDelta.CONTENT); } } } private void resetBaseText() { if (parent_value != null && base_text.isValid()) { base_text.reset(); rem_expression.cancel(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); string.cancel(); value.cancel(); } } void onSuspended(boolean func_call) { if (!func_call) { prev_value = next_value; type.reset(); type_name.reset(); } if (rem_expression.isValid() && rem_expression.getError() != null) rem_expression.reset(); if (!func_call || value.isValid() && value.getError() != null) value.reset(); if (!func_call || string.isValid() && string.getError() != null) string.reset(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); children.onSuspended(func_call); if (!func_call) resetBaseText(); // No need to post delta: parent posted CONTENT } void onRegisterValueChanged() { value.reset(); type.reset(); type_name.reset(); string.reset(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); children.onRegisterValueChanged(); resetBaseText(); postAllChangedDelta(); } void onMemoryChanged() { value.reset(); type.reset(); type_name.reset(); string.reset(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); children.onMemoryChanged(); resetBaseText(); if (parent instanceof TCFNodeExpression) return; if (parent instanceof TCFNodeArrayPartition) return; postAllChangedDelta(); } void onMemoryMapChanged() { value.reset(); type.reset(); type_name.reset(); string.reset(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); children.onMemoryMapChanged(); resetBaseText(); if (parent instanceof TCFNodeExpression) return; if (parent instanceof TCFNodeArrayPartition) return; postAllChangedDelta(); } void onValueChanged() { value.reset(); type.reset(); type_name.reset(); string.reset(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); children.onValueChanged(); resetBaseText(); postAllChangedDelta(); } public void onCastToTypeChanged() { rem_expression.cancel(); value.cancel(); type.cancel(); type_name.cancel(); string.cancel(); for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) p.cancel(this); expression_text.cancel(); children.onCastToTypeChanged(); resetBaseText(); postAllChangedDelta(); } public boolean isEmpty() { return is_empty; } public String getScript() { return script; } String getFieldID() { return field_id; } String getRegisterID() { return reg_id; } int getIndex() { return index; } boolean isDeref() { return deref; } void setSortPosition(int sort_pos) { this.sort_pos = sort_pos; } void setEnabled(boolean enabled) { if (this.enabled == enabled) return; this.enabled = enabled; postAllChangedDelta(); } /** * Get expression properties cache that represents a variable. * The cache is empty if the node does not represent a variable. * @return The expression properties cache. */ public TCFDataCache<IExpressions.Expression> getVariable() { return var_expression; } /** * Get expression properties cache. * If the node represents a variable, return same data same as getVariable(). * @return The expression properties cache. */ public TCFDataCache<IExpressions.Expression> getExpression() { return rem_expression; } /** * Get expression value cache. * @return The expression value cache. */ public TCFDataCache<IExpressions.Value> getValue() { return value; } /** * Get expression type cache. * @return The expression type cache. */ public TCFDataCache<ISymbols.Symbol> getType() { return type; } /** * Get human readable expression script, * including type cast, and using variable names instead of IDs. */ public TCFDataCache<String> getExpressionText() { return expression_text; } private Boolean usePrevValue(Runnable done) { // Check if view should show old value. // Old value is shown if context is running or // stack trace does not contain expression parent frame. // Return null if waiting for cache update. if (prev_value == null) return false; if (parent instanceof TCFNodeStackFrame) { TCFNodeExecContext exe = (TCFNodeExecContext)parent.parent; TCFDataCache<TCFContextState> state_cache = exe.getState(); if (!state_cache.validate(done)) return null; TCFContextState state = state_cache.getData(); if (state == null || !state.is_suspended) return true; TCFChildrenStackTrace stack_trace_cache = exe.getStackTrace(); if (!stack_trace_cache.validate(done)) return null; if (stack_trace_cache.getData().get(parent.id) == null) return true; } else if (parent instanceof TCFNodeExecContext) { TCFNodeExecContext exe = (TCFNodeExecContext)parent; TCFDataCache<TCFContextState> state_cache = exe.getState(); if (!state_cache.validate(done)) return null; TCFContextState state = state_cache.getData(); if (state == null || !state.is_suspended) return true; } return false; } @SuppressWarnings("incomplete-switch") private String getTypeName(ISymbols.TypeClass type_class, int size) { switch (type_class) { case integer: if (size == 0) return "<Void>"; return "<Integer-" + (size * 8) + ">"; case cardinal: if (size == 0) return "<Void>"; return "<Unsigned-" + (size * 8) + ">"; case real: if (size == 0) return null; return "<Float-" + (size * 8) + ">"; } return null; } @SuppressWarnings("incomplete-switch") private boolean getTypeName(StringBuffer bf, TCFDataCache<ISymbols.Symbol> type_cache, Runnable done) { String name = null; for (;;) { String s = null; boolean get_base_type = false; if (!type_cache.validate(done)) return false; ISymbols.Symbol type_symbol = type_cache.getData(); if (type_symbol != null) { int flags = type_symbol.getFlags(); s = type_symbol.getName(); if (s != null) { if ((flags & ISymbols.SYM_FLAG_UNION_TYPE) != 0) s = "union " + s; else if ((flags & ISymbols.SYM_FLAG_CLASS_TYPE) != 0) s = "class " + s; else if ((flags & ISymbols.SYM_FLAG_INTERFACE_TYPE) != 0) s = "interface " + s; else if ((flags & ISymbols.SYM_FLAG_STRUCT_TYPE) != 0) s = "struct " + s; else if ((flags & ISymbols.SYM_FLAG_ENUM_TYPE) != 0) s = "enum " + s; } else if (!type_symbol.getID().equals(type_symbol.getTypeID())) { // modified type without name, like "volatile int" TCFDataCache<ISymbols.Symbol> base_type_cache = model.getSymbolInfoCache(type_symbol.getTypeID()); if (base_type_cache != null) { StringBuffer sb = new StringBuffer(); if (!getTypeName(sb, base_type_cache, done)) return false; s = sb.toString(); } } if (s == null) s = getTypeName(type_symbol.getTypeClass(), type_symbol.getSize()); if (s == null) { switch (type_symbol.getTypeClass()) { case pointer: s = "*"; if ((flags & ISymbols.SYM_FLAG_REFERENCE) != 0) s = "&"; get_base_type = true; break; case member_pointer: { String id = type_symbol.getContainerID(); if (id != null) { TCFDataCache<ISymbols.Symbol> cls_cache = model.getSymbolInfoCache(id); if (!cls_cache.validate(done)) return false; ISymbols.Symbol cls_data = cls_cache.getData(); if (cls_data != null) { String cls_name = cls_data.getName(); if (cls_name != null) s = cls_name + "::*"; } } if (s == null) s = "::*"; } get_base_type = true; break; case array: s = "[" + type_symbol.getLength() + "]"; get_base_type = true; break; case composite: s = "<Structure>"; break; case function: { TCFDataCache<String[]> children_cache = model.getSymbolChildrenCache(type_symbol.getID()); if (!children_cache.validate(done)) return false; String[] children = children_cache.getData(); if (children != null) { StringBuffer args = new StringBuffer(); if (name != null) { args.append('('); args.append(name); args.append(')'); name = null; } args.append('('); for (String id : children) { if (id != children[0]) args.append(','); if (!getTypeName(args, model.getSymbolInfoCache(id), done)) return false; } args.append(')'); s = args.toString(); get_base_type = true; break; } } s = "<Function>"; break; } } if (s != null) { if ((flags & ISymbols.SYM_FLAG_VOLATILE_TYPE) != 0) s = "volatile " + s; if ((flags & ISymbols.SYM_FLAG_CONST_TYPE) != 0) s = "const " + s; } } if (s == null) { name = "N/A"; break; } if (name == null) name = s; else if (!get_base_type) name = s + " " + name; else name = s + name; if (!get_base_type) break; if (name.length() > 0x1000) { /* Must be invalid symbols data */ name = "<Unknown>"; break; } type_cache = model.getSymbolInfoCache(type_symbol.getBaseTypeID()); if (type_cache == null) { name = "<Unknown> " + name; break; } } bf.append(name); return true; } private String toASCIIString(byte[] data, int offs, int size, char quote_char) { StringBuffer bf = new StringBuffer(); bf.append(quote_char); for (int i = 0; i < size; i++) { int ch = data[offs + i] & 0xff; if (ch >= ' ' && ch < 0x7f) { bf.append((char)ch); } else { switch (ch) { case '\r': bf.append("\\r"); break; case '\n': bf.append("\\n"); break; case '\b': bf.append("\\b"); break; case '\t': bf.append("\\t"); break; case '\f': bf.append("\\f"); break; default: bf.append('\\'); bf.append((char)('0' + ch / 64)); bf.append((char)('0' + ch / 8 % 8)); bf.append((char)('0' + ch % 8)); } } } if (data.length <= offs + size || data[offs + size] == 0) bf.append(quote_char); else bf.append("..."); return bf.toString(); } @SuppressWarnings("incomplete-switch") private String toNumberString(int radix, ISymbols.TypeClass t, byte[] data, int offs, int size, boolean big_endian) { if (size <= 0 || size > 16) return ""; if (radix != 16) { switch (t) { case array: case composite: return ""; } } String s = null; if (data == null) s = "N/A"; if (s == null && radix == 10) { switch (t) { case integer: s = TCFNumberFormat.toBigInteger(data, offs, size, big_endian, true).toString(); break; case real: s = TCFNumberFormat.toFPString(data, offs, size, big_endian); break; } } if (s == null) { s = TCFNumberFormat.toBigInteger(data, offs, size, big_endian, false).toString(radix); switch (radix) { case 8: if (!s.startsWith("0")) s = "0" + s; break; case 16: if (s.length() < size * 2) { StringBuffer bf = new StringBuffer(); while (bf.length() + s.length() < size * 2) bf.append('0'); bf.append(s); s = bf.toString(); } break; } } assert s != null; return s; } private String toNumberString(int radix) { String s = null; IExpressions.Value val = value.getData(); if (val != null) { byte[] data = val.getValue(); if (data != null) { ISymbols.TypeClass t = val.getTypeClass(); if (t == ISymbols.TypeClass.unknown && type.getData() != null) t = type.getData().getTypeClass(); s = toNumberString(radix, t, data, 0, data.length, val.isBigEndian()); } } if (s == null) s = "N/A"; return s; } private void setLabel(ILabelUpdate result, String name, int col, int radix) { String s = toNumberString(radix); if (name == null) { result.setLabel(s, col); } else { result.setLabel(name + " = " + s, col); } } private boolean isValueChanged(IExpressions.Value x, IExpressions.Value y) { if (x == null || y == null) return false; byte[] xb = x.getValue(); byte[] yb = y.getValue(); if (xb == null || yb == null) return false; if (xb.length != yb.length) return true; for (int i = 0; i < xb.length; i++) { if (xb[i] != yb[i]) return true; } return false; } // // @param return-value Boolean.TRUE --> Show Types ICON is selected/depressed // @param return-value Boolean.FALSE --> Show Types ICON is not selected/depressed // private Boolean isShowTypeNamesEnabled( IPresentationContext context ) { Boolean attribute = (Boolean) context.getProperty(IDebugModelPresentation.DISPLAY_VARIABLE_TYPE_NAMES); if (attribute != null) { return attribute; } return Boolean.FALSE; } @Override protected boolean getData(ILabelUpdate result, Runnable done) { if (is_empty) { result.setLabel("Add new expression", 0); result.setImageDescriptor(ImageCache.getImageDescriptor(ImageCache.IMG_NEW_EXPRESSION), 0); } else if (enabled || script == null) { TCFDataCache<ISymbols.Symbol> field = model.getSymbolInfoCache(field_id); TCFDataCache<?> pending = null; if (field != null && !field.validate()) pending = field; if (reg_id != null && !expression_text.validate(done)) pending = expression_text; if (!var_expression.validate()) pending = var_expression; if (!base_text.validate()) pending = base_text; if (!value.validate()) pending = value; if (!type.validate()) pending = type; if (pending != null) { pending.wait(done); return false; } String name = null; if (index >= 0) { if (index == 0 && deref) { name = "*"; } else { name = "[" + index + "]"; } } if (name == null && field != null) { ISymbols.Symbol field_data = field.getData(); name = field_data.getName(); if (name == null && field_data.getFlag(ISymbols.SYM_FLAG_INHERITANCE)) { TCFDataCache<ISymbols.Symbol> type = model.getSymbolInfoCache(field_data.getTypeID()); if (type != null) { if (!type.validate(done)) return false; ISymbols.Symbol type_data = type.getData(); if (type_data != null) name = type_data.getName(); } } } if (name == null && reg_id != null && expression_text.getData() != null) { name = expression_text.getData(); } if (name == null && var_expression.getData() != null) { TCFDataCache<ISymbols.Symbol> var = model.getSymbolInfoCache(var_expression.getData().getSymbolID()); if (var != null) { if (!var.validate(done)) return false; ISymbols.Symbol var_data = var.getData(); if (var_data != null) { name = var_data.getName(); if (name == null && var_data.getFlag(ISymbols.SYM_FLAG_VARARG)) name = "<VarArg>"; if (name == null) name = "<" + var_data.getID() + ">"; } } } if (name == null && base_text.getData() != null) { name = base_text.getData(); } if (name != null) { String cast = model.getCastToType(id); if (cast != null) name = "(" + cast + ")(" + name + ")"; } Throwable error = base_text.getError(); if (error == null) error = value.getError(); String[] cols = result.getColumnIds(); if (error != null) { if (cols == null || cols.length <= 1) { result.setForeground(ColorCache.rgb_error, 0); if (isShowTypeNamesEnabled( result.getPresentationContext())) { if (!type_name.validate(done)) return false; result.setLabel(name + ": N/A" + " , Type = " + type_name.getData(), 0); } else { result.setLabel(name + ": N/A", 0); } } else { for (int i = 0; i < cols.length; i++) { String c = cols[i]; if (c.equals(TCFColumnPresentationExpression.COL_NAME)) { result.setLabel(name, i); } else if (c.equals(TCFColumnPresentationExpression.COL_TYPE)) { if (!type_name.validate(done)) return false; result.setLabel(type_name.getData(), i); } else { result.setForeground(ColorCache.rgb_error, i); result.setLabel("N/A", i); } } } } else { if (cols == null) { StyledStringBuffer s = getPrettyExpression(done); if (s == null) return false; if (isShowTypeNamesEnabled( result.getPresentationContext())) { if (!type_name.validate(done)) return false; result.setLabel(name + " = " + s + " , Type = " + type_name.getData(), 0); } else { result.setLabel(name + " = " + s, 0); } } else { for (int i = 0; i < cols.length; i++) { String c = cols[i]; if (c.equals(TCFColumnPresentationExpression.COL_NAME)) { result.setLabel(name, i); } else if (c.equals(TCFColumnPresentationExpression.COL_TYPE)) { if (!type_name.validate(done)) return false; result.setLabel(type_name.getData(), i); } else if (c.equals(TCFColumnPresentationExpression.COL_HEX_VALUE)) { setLabel(result, null, i, 16); } else if (c.equals(TCFColumnPresentationExpression.COL_DEC_VALUE)) { setLabel(result, null, i, 10); } else if (c.equals(TCFColumnPresentationExpression.COL_VALUE)) { StyledStringBuffer s = getPrettyExpression(done); if (s == null) return false; result.setLabel(s.toString(), i); } } } } next_value = value.getData(); if (isValueChanged(prev_value, next_value)) { if (cols != null) { for (int i = 1; i < cols.length; i++) { result.setBackground(ColorCache.rgb_highlight, i); } } else { result.setForeground(ColorCache.rgb_no_columns_color_change, 0); } } ISymbols.TypeClass type_class = ISymbols.TypeClass.unknown; ISymbols.Symbol type_symbol = type.getData(); if (type_symbol != null) { type_class = type_symbol.getTypeClass(); } switch (type_class) { case pointer: result.setImageDescriptor(ImageCache.getImageDescriptor(ImageCache.IMG_VARIABLE_POINTER), 0); break; case composite: case array: result.setImageDescriptor(ImageCache.getImageDescriptor(ImageCache.IMG_VARIABLE_AGGREGATE), 0); break; default: result.setImageDescriptor(ImageCache.getImageDescriptor(ImageCache.IMG_VARIABLE), 0); } } else { String[] cols = result.getColumnIds(); if (cols == null || cols.length <= 1) { result.setForeground(ColorCache.rgb_disabled, 0); result.setLabel(script, 0); } else { for (int i = 0; i < cols.length; i++) { String c = cols[i]; if (c.equals(TCFColumnPresentationExpression.COL_NAME)) { result.setForeground(ColorCache.rgb_disabled, i); result.setLabel(script, i); } } } } return true; } @Override protected void getFontData(ILabelUpdate update, String view_id) { if (is_empty) { update.setFontData(TCFModelFonts.getItalicFontData(view_id), 0); } else { FontData fn = TCFModelFonts.getNormalFontData(view_id); String[] cols = update.getColumnIds(); if (cols == null || cols.length == 0) { update.setFontData(fn, 0); } else { String[] ids = update.getColumnIds(); for (int i = 0; i < cols.length; i++) { if (TCFColumnPresentationExpression.COL_HEX_VALUE.equals(ids[i]) || TCFColumnPresentationExpression.COL_DEC_VALUE.equals(ids[i]) || TCFColumnPresentationExpression.COL_VALUE.equals(ids[i])) { update.setFontData(TCFModelFonts.getMonospacedFontData(view_id), i); } else { update.setFontData(fn, i); } } } } } private StyledStringBuffer getPrettyExpression(Runnable done) { for (ITCFPrettyExpressionProvider p : TCFPrettyExpressionProvider.getProviders()) { TCFDataCache<String> c = p.getText(this); if (c != null) { if (!c.validate(done)) return null; if (c.getError() == null && c.getData() != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(c.getData(), StyledStringBuffer.MONOSPACED); return bf; } } } if (!value.validate(done)) return null; if (!string.validate(done)) return null; StyledStringBuffer bf = new StyledStringBuffer(); if (string.getData() != null) { bf.append(string.getData()); } else { IExpressions.Value v = value.getData(); if (v != null) { byte[] data = v.getValue(); if (data != null) { if (!appendValueText(bf, 1, v.getTypeID(), this, data, 0, data.length, v.isBigEndian(), done)) return null; } } } return bf; } private boolean appendArrayValueText(StyledStringBuffer bf, int level, ISymbols.Symbol type, byte[] data, int offs, int size, boolean big_endian, Runnable done) { assert offs + size <= data.length; int length = type.getLength(); bf.append('['); if (length > 0) { int elem_size = size / length; for (int n = 0; n < length; n++) { if (n >= 100) { bf.append("..."); break; } if (n > 0) bf.append(", "); if (!appendValueText(bf, level + 1, type.getBaseTypeID(), null, data, offs + n * elem_size, elem_size, big_endian, done)) return false; } } bf.append(']'); return true; } private boolean appendCompositeValueText( StyledStringBuffer bf, int level, ISymbols.Symbol type, TCFNodeExpression data_node, boolean data_deref, byte[] data, int offs, int size, boolean big_endian, Runnable done) { TCFDataCache<String[]> children_cache = model.getSymbolChildrenCache(type.getID()); if (children_cache == null) { bf.append("..."); return true; } if (!children_cache.validate(done)) return false; String[] children_data = children_cache.getData(); if (children_data == null) { bf.append("..."); return true; } int cnt = 0; TCFDataCache<?> pending = null; for (String id : children_data) { TCFDataCache<ISymbols.Symbol> field_cache = model.getSymbolInfoCache(id); if (!field_cache.validate()) { pending = field_cache; continue; } ISymbols.Symbol field_props = field_cache.getData(); if (field_props == null) continue; if (field_props.getSymbolClass() != ISymbols.SymbolClass.reference) continue; if (field_props.getFlag(ISymbols.SYM_FLAG_ARTIFICIAL)) continue; String name = field_props.getName(); if (name == null && type != null && field_props.getFlag(ISymbols.SYM_FLAG_INHERITANCE)) { name = type.getName(); } TCFNodeExpression field_node = null; if (data_node != null) field_node = data_node.children.getField(id, data_deref); if (field_props.getProperties().get(ISymbols.PROP_OFFSET) == null) { // Bitfield - use field_node to retrieve the value if (name == null || field_node == null) continue; if (cnt > 0) bf.append(", "); bf.append(name); bf.append('='); if (!field_node.value.validate(done)) return false; IExpressions.Value field_value = field_node.value.getData(); byte[] field_data = field_value != null ? field_value.getValue() : null; if (field_data == null) { bf.append('?'); } else { if (!field_node.appendValueText(bf, level + 1, field_props.getTypeID(), field_node, field_data, 0, field_data.length, big_endian, done)) return false; } cnt++; continue; } int f_offs = field_props.getOffset(); int f_size = field_props.getSize(); if (name == null) { if (offs + f_offs + f_size > data.length) continue; StyledStringBuffer bf1 = new StyledStringBuffer(); if (!appendCompositeValueText(bf1, level, field_props, field_node, false, data, offs + f_offs, f_size, big_endian, done)) return false; if (bf1.length() > 0) { if (cnt > 0) bf.append(", "); bf.append(bf1); cnt++; } } else { if (cnt > 0) bf.append(", "); bf.append(name); bf.append('='); if (offs + f_offs + f_size > data.length) { bf.append('?'); } else { if (!appendValueText(bf, level + 1, field_props.getTypeID(), field_node, data, offs + f_offs, f_size, big_endian, done)) return false; } cnt++; } } if (pending == null) return true; pending.wait(done); return false; } private void appendNumericValueText(StyledStringBuffer bf, ISymbols.TypeClass type_class, byte[] data, int offs, int size, boolean big_endian) { bf.append("Hex: ", SWT.BOLD); bf.append(toNumberString(16, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); bf.append(", "); bf.append("Dec: ", SWT.BOLD); bf.append(toNumberString(10, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); bf.append(", "); bf.append("Oct: ", SWT.BOLD); bf.append(toNumberString(8, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); bf.append('\n'); } @SuppressWarnings("incomplete-switch") private boolean appendValueText( StyledStringBuffer bf, int level, String type_id, TCFNodeExpression data_node, byte[] data, int offs, int size, boolean big_endian, Runnable done) { if (data == null) return true; ISymbols.Symbol type_data = null; if (type_id != null) { TCFDataCache<ISymbols.Symbol> type_cache = model.getSymbolInfoCache(type_id); if (!type_cache.validate(done)) return false; type_data = type_cache.getData(); } if (type_data == null) { ISymbols.TypeClass type_class = ISymbols.TypeClass.unknown; if (!value.validate(done)) return false; if (value.getData() != null) type_class = value.getData().getTypeClass(); if (level == 0) { assert offs == 0; assert size == data.length; if (size > 0) appendNumericValueText(bf, type_class, data, offs, size, big_endian); String s = getTypeName(type_class, size); if (s == null) s = "not available"; bf.append("Size: ", SWT.BOLD); bf.append(size); bf.append(size == 1 ? " byte" : " bytes"); bf.append(", "); bf.append("Type: ", SWT.BOLD); bf.append(s); bf.append('\n'); } else if (type_class == ISymbols.TypeClass.integer || type_class == ISymbols.TypeClass.real) { bf.append(toNumberString(10, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); } else { bf.append(toNumberString(16, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); } return true; } if (level == 0) { StyledStringBuffer s = getPrettyExpression(done); if (s == null) return false; if (s.length() > 0) { bf.append(s); bf.append('\n'); } else if (string.getError() != null) { bf.append("Cannot read pointed value: ", SWT.BOLD, null, ColorCache.rgb_error); bf.append(TCFModel.getErrorMessage(string.getError(), false), SWT.ITALIC, null, ColorCache.rgb_error); bf.append('\n'); } } if (type_data.getSize() > 0) { ISymbols.TypeClass type_class = type_data.getTypeClass(); switch (type_class) { case enumeration: case integer: case cardinal: case real: if (level == 0) { appendNumericValueText(bf, type_class, data, offs, size, big_endian); } else if (type_data.getTypeClass() == ISymbols.TypeClass.cardinal) { bf.append("0x", StyledStringBuffer.MONOSPACED); bf.append(toNumberString(16, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); } else { bf.append(toNumberString(10, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); } break; case pointer: case function: case member_pointer: if (level == 0) { appendNumericValueText(bf, type_class, data, offs, size, big_endian); } else { bf.append("0x", StyledStringBuffer.MONOSPACED); bf.append(toNumberString(16, type_class, data, offs, size, big_endian), StyledStringBuffer.MONOSPACED); } break; case array: if (level > 0) { if (!appendArrayValueText(bf, level, type_data, data, offs, size, big_endian, done)) return false; } break; case composite: if (level > 0) { bf.append('{'); if (!appendCompositeValueText(bf, level, type_data, data_node, false, data, offs, size, big_endian, done)) return false; bf.append('}'); } break; } } if (level == 0) { if (!type_name.validate(done)) return false; bf.append("Size: ", SWT.BOLD); bf.append(type_data.getSize()); bf.append(type_data.getSize() == 1 ? " byte" : " bytes"); String nm = type_name.getData(); if (nm != null) { bf.append(", "); bf.append("Type: ", SWT.BOLD); bf.append(nm); } bf.append('\n'); } return true; } private String getRegisterName(String reg_id, Runnable done) { String name = reg_id; TCFDataCache<?> pending = null; TCFNodeRegister reg_node = null; LinkedList<TCFChildren> queue = new LinkedList<TCFChildren>(); TCFNode n = parent; while (n != null) { if (n instanceof TCFNodeStackFrame) { queue.add(((TCFNodeStackFrame)n).getRegisters()); } if (n instanceof TCFNodeExecContext) { queue.add(((TCFNodeExecContext)n).getRegisters()); break; } n = n.parent; } while (!queue.isEmpty()) { TCFChildren reg_list = queue.removeFirst(); if (!reg_list.validate()) { pending = reg_list; } else { Map<String,TCFNode> reg_map = reg_list.getData(); if (reg_map != null) { reg_node = (TCFNodeRegister)reg_map.get(reg_id); if (reg_node != null) break; for (TCFNode node : reg_map.values()) { queue.add(((TCFNodeRegister)node).getChildren()); } } } } if (pending != null) { pending.wait(done); return null; } if (reg_node != null) { TCFDataCache<IRegisters.RegistersContext> reg_ctx_cache = reg_node.getContext(); if (!reg_ctx_cache.validate(done)) return null; IRegisters.RegistersContext reg_ctx_data = reg_ctx_cache.getData(); if (reg_ctx_data != null && reg_ctx_data.getName() != null) name = reg_ctx_data.getName(); } return name; } public boolean getDetailText(StyledStringBuffer bf, Runnable done) { if (is_empty) return true; if (!enabled) { bf.append("Disabled"); return true; } if (!rem_expression.validate(done)) return false; if (rem_expression.getError() == null) { if (!value.validate(done)) return false; IExpressions.Value v = value.getData(); if (v != null) { if (value.getError() == null) { byte[] data = v.getValue(); if (data != null) { boolean big_endian = v.isBigEndian(); if (!appendValueText(bf, 0, v.getTypeID(), this, data, 0, data.length, big_endian, done)) return false; } } int cnt = 0; String reg_id = v.getRegisterID(); if (reg_id != null) { String nm = getRegisterName(reg_id, done); if (nm == null) return false; bf.append("Register: ", SWT.BOLD); bf.append(nm); cnt++; } TCFDataCache<ISymbols.Symbol> field_cache = model.getSymbolInfoCache(field_id); if (field_cache != null) { if (!field_cache.validate(done)) return false; ISymbols.Symbol field_props = field_cache.getData(); if (field_props != null && field_props.getProperties().get(ISymbols.PROP_OFFSET) != null) { if (cnt > 0) bf.append(", "); bf.append("Offset: ", SWT.BOLD); bf.append(Integer.toString(field_props.getOffset()), StyledStringBuffer.MONOSPACED); cnt++; } } Number addr = v.getAddress(); if (addr != null) { BigInteger i = JSON.toBigInteger(addr); if (cnt > 0) bf.append(", "); bf.append("Address: ", SWT.BOLD); bf.append("0x", StyledStringBuffer.MONOSPACED); bf.append(i.toString(16), StyledStringBuffer.MONOSPACED); cnt++; } if (cnt > 0) bf.append('\n'); } if (value.getError() != null) { bf.append(value.getError(), ColorCache.rgb_error); } } else { bf.append(rem_expression.getError(), ColorCache.rgb_error); } return true; } public String getValueText(boolean add_error_text, Runnable done) { if (!rem_expression.validate(done)) return null; if (!value.validate(done)) return null; StyledStringBuffer bf = new StyledStringBuffer(); IExpressions.Value v = value.getData(); if (v != null) { byte[] data = v.getValue(); if (data != null) { boolean big_endian = v.isBigEndian(); if (!appendValueText(bf, 1, v.getTypeID(), this, data, 0, data.length, big_endian, done)) return null; } } if (add_error_text) { if (bf.length() == 0 && rem_expression.getError() != null) { bf.append(TCFModel.getErrorMessage(rem_expression.getError(), false)); } if (bf.length() == 0 && value.getError() != null) { bf.append(TCFModel.getErrorMessage(value.getError(), false)); } } return bf.toString(); } @Override protected boolean getData(IChildrenCountUpdate result, Runnable done) { if (!is_empty && enabled) { if (!children.validate(done)) return false; result.setChildCount(children.size()); } else { result.setChildCount(0); } return true; } @Override protected boolean getData(IChildrenUpdate result, Runnable done) { if (is_empty || !enabled) return true; return children.getData(result, done); } @Override protected boolean getData(IHasChildrenUpdate result, Runnable done) { if (!is_empty && enabled) { if (!children.validate(done)) return false; result.setHasChilren(children.size() > 0); } else { result.setHasChilren(false); } return true; } @Override public int compareTo(TCFNode n) { TCFNodeExpression e = (TCFNodeExpression)n; if (sort_pos < e.sort_pos) return -1; if (sort_pos > e.sort_pos) return +1; return 0; } public CellEditor getCellEditor(IPresentationContext context, String column_id, Object element, Composite parent) { assert element == this; if (TCFColumnPresentationExpression.COL_NAME.equals(column_id)) { return new TextCellEditor(parent); } if (TCFColumnPresentationExpression.COL_HEX_VALUE.equals(column_id)) { return new TextCellEditor(parent); } if (TCFColumnPresentationExpression.COL_DEC_VALUE.equals(column_id)) { return new TextCellEditor(parent); } if (TCFColumnPresentationExpression.COL_VALUE.equals(column_id)) { return new TextCellEditor(parent); } return null; } private static final ICellModifier cell_modifier = new ICellModifier() { public boolean canModify(Object element, final String property) { final TCFNodeExpression node = (TCFNodeExpression)element; return new TCFTask<Boolean>(node.channel) { public void run() { if (TCFColumnPresentationExpression.COL_NAME.equals(property)) { done(node.is_empty || node.script != null); return; } if (!node.is_empty && node.enabled) { if (!node.rem_expression.validate(this)) return; IExpressions.Expression exp = node.rem_expression.getData(); if (exp != null && exp.canAssign()) { if (!node.value.validate(this)) return; if (!node.type.validate(this)) return; if (TCFColumnPresentationExpression.COL_HEX_VALUE.equals(property)) { done(TCFNumberFormat.isValidHexNumber(node.toNumberString(16)) == null); return; } if (TCFColumnPresentationExpression.COL_DEC_VALUE.equals(property)) { done(TCFNumberFormat.isValidDecNumber(true, node.toNumberString(10)) == null); return; } if (TCFColumnPresentationExpression.COL_VALUE.equals(property)) { StyledStringBuffer bf = node.getPrettyExpression(this); if (bf == null) return; String s = bf.toString(); done(s.startsWith("0x") || TCFNumberFormat.isValidDecNumber(true, s) == null); return; } } } done(Boolean.FALSE); } }.getE(); } public Object getValue(Object element, final String property) { final TCFNodeExpression node = (TCFNodeExpression)element; return new TCFTask<String>() { public void run() { if (node.is_empty) { done(""); return; } if (TCFColumnPresentationExpression.COL_NAME.equals(property)) { done(node.script); return; } if (!node.value.validate(this)) return; if (node.value.getData() != null) { if (TCFColumnPresentationExpression.COL_HEX_VALUE.equals(property)) { done(node.toNumberString(16)); return; } if (TCFColumnPresentationExpression.COL_DEC_VALUE.equals(property)) { done(node.toNumberString(10)); return; } if (TCFColumnPresentationExpression.COL_VALUE.equals(property)) { StyledStringBuffer bf = node.getPrettyExpression(this); if (bf == null) return; done(bf.toString()); return; } } done(null); } }.getE(); } public void modify(Object element, final String property, final Object value) { if (value == null) return; final TCFNodeExpression node = (TCFNodeExpression)element; new TCFTask<Boolean>() { @SuppressWarnings("incomplete-switch") public void run() { try { if (TCFColumnPresentationExpression.COL_NAME.equals(property)) { if (node.is_empty) { if (value instanceof String) { final String s = ((String)value).trim(); if (s.length() > 0) { node.model.getDisplay().asyncExec(new Runnable() { public void run() { IWatchExpression expression = DebugPlugin.getDefault().getExpressionManager().newWatchExpression(s); DebugPlugin.getDefault().getExpressionManager().addExpression(expression); IAdaptable object = DebugUITools.getDebugContext(); IDebugElement context = null; if (object instanceof IDebugElement) { context = (IDebugElement)object; } else if (object instanceof ILaunch) { context = ((ILaunch)object).getDebugTarget(); } expression.setExpressionContext(context); } }); } } } else if (!node.script.equals(value)) { IExpressionManager m = DebugPlugin.getDefault().getExpressionManager(); for (final IExpression e : m.getExpressions()) { if (node.script.equals(e.getExpressionText())) m.removeExpression(e); } IExpression e = m.newWatchExpression((String)value); m.addExpression(e); } done(Boolean.TRUE); return; } if (!node.rem_expression.validate(this)) return; IExpressions.Expression exp = node.rem_expression.getData(); if (exp != null && exp.canAssign()) { byte[] bf = null; int size = exp.getSize(); boolean is_float = false; boolean big_endian = false; boolean signed = false; if (!node.value.validate(this)) return; IExpressions.Value eval = node.value.getData(); if (eval != null) { switch(eval.getTypeClass()) { case real: is_float = true; signed = true; break; case integer: signed = true; break; } big_endian = eval.isBigEndian(); size = eval.getValue().length; } String input = (String)value; String error = null; if (TCFColumnPresentationExpression.COL_HEX_VALUE.equals(property)) { error = TCFNumberFormat.isValidHexNumber(input); if (error == null) bf = TCFNumberFormat.toByteArray(input, 16, false, size, signed, big_endian); } else if (TCFColumnPresentationExpression.COL_DEC_VALUE.equals(property)) { error = TCFNumberFormat.isValidDecNumber(is_float, input); if (error == null) bf = TCFNumberFormat.toByteArray(input, 10, is_float, size, signed, big_endian); } else if (TCFColumnPresentationExpression.COL_VALUE.equals(property)) { if (input.startsWith("0x")) { String s = input.substring(2); error = TCFNumberFormat.isValidHexNumber(s); if (error == null) bf = TCFNumberFormat.toByteArray(s, 16, false, size, signed, big_endian); } else { error = TCFNumberFormat.isValidDecNumber(is_float, input); if (error == null) bf = TCFNumberFormat.toByteArray(input, 10, is_float, size, signed, big_endian); } } if (error != null) throw new Exception("Invalid value: " + value, new Exception(error)); if (bf != null) { IExpressions exps = node.launch.getService(IExpressions.class); exps.assign(exp.getID(), bf, new IExpressions.DoneAssign() { public void doneAssign(IToken token, Exception error) { node.getRootExpression().onValueChanged(); if (error != null) { node.model.showMessageBox("Cannot modify element value", error); done(Boolean.FALSE); } else { done(Boolean.TRUE); } } }); return; } } done(Boolean.FALSE); } catch (Throwable x) { node.model.showMessageBox("Cannot modify element value", x); done(Boolean.FALSE); } } }.getE(); } }; public ICellModifier getCellModifier(IPresentationContext context, Object element) { assert element == this; return cell_modifier; } @SuppressWarnings("rawtypes") @Override public Object getAdapter(Class adapter) { if (script != null) { if (adapter == IExpression.class) { IExpressionManager m = DebugPlugin.getDefault().getExpressionManager(); for (final IExpression e : m.getExpressions()) { if (script.equals(e.getExpressionText())) return e; } } if (adapter == IWatchExpression.class) { IExpressionManager m = DebugPlugin.getDefault().getExpressionManager(); for (final IExpression e : m.getExpressions()) { if (e instanceof IWatchExpression && script.equals(e.getExpressionText())) return e; } } } return super.getAdapter(adapter); } }
false
true
TCFNodeExpression(final TCFNode parent, final String script, final String field_id, final String var_id, final String reg_id, final int index, final boolean deref) { super(parent, var_id != null ? var_id : "Expr" + expr_cnt++); this.script = script; this.field_id = field_id; this.reg_id = reg_id; this.index = index; this.deref = deref; is_empty = script == null && var_id == null && field_id == null && reg_id == null && index < 0; var_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null || var_id == null) { set(null, null, null); return true; } command = exps.getContext(var_id, new IExpressions.DoneGetContext() { public void doneGetContext(IToken token, Exception error, IExpressions.Expression context) { set(token, error, context); } }); return false; } }; base_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute expression script, not including type cast */ parent_value = null; if (is_empty) { set(null, null, null); return true; } if (script != null) { set(null, null, script); return true; } if (var_id != null) { if (!var_expression.validate(this)) return false; Throwable err = null; String exp = null; if (var_expression.getData() == null) { err = var_expression.getError(); } else { exp = var_expression.getData().getExpression(); if (exp == null) err = new Exception("Missing 'Expression' property"); } set(null, err, exp); return true; } if (reg_id != null) { set(null, null, "${" + reg_id + "}"); return true; } String e = null; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; String cast = model.getCastToType(n.id); if (cast == null && deref) { TCFNodeExpression exp = (TCFNodeExpression)n; if (!exp.value.validate(this)) return false; IExpressions.Value v = exp.value.getData(); if (v != null && v.getTypeID() != null) { parent_value = v.getValue(); if (parent_value != null) { e = "(${" + v.getTypeID() + "})0x" + TCFNumberFormat.toBigInteger( parent_value, v.isBigEndian(), false).toString(16); } } } if (e == null) { TCFDataCache<String> t = ((TCFNodeExpression)n).base_text; if (!t.validate(this)) return false; e = t.getData(); if (e == null) { set(null, t.getError(), null); return true; } } if (cast != null) e = "(" + cast + ")(" + e + ")"; if (field_id != null) { e = "(" + e + ")" + (deref ? "->" : ".") + "${" + field_id + "}"; } else if (index == 0) { e = "*(" + e + ")"; } else if (index > 0) { e = "(" + e + ")[" + index + "]"; } set(null, null, e); return true; } }; expression_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute human readable expression script, * including type cast, and using variable names instead of IDs */ String expr_text = null; if (script != null) { expr_text = script; } else if (var_id != null) { if (!var_expression.validate(this)) return false; IExpressions.Expression e = var_expression.getData(); if (e != null) { TCFDataCache<ISymbols.Symbol> var = model.getSymbolInfoCache(e.getSymbolID()); if (var != null) { if (!var.validate(this)) return false; if (var.getData() != null) expr_text = var.getData().getName(); } } } else if (reg_id != null) { if (!model.createNode(reg_id, this)) return false; if (isValid()) return true; TCFNodeRegister reg_node = (TCFNodeRegister)model.getNode(reg_id); for (;;) { TCFDataCache<IRegisters.RegistersContext> ctx_cache = reg_node.getContext(); if (!ctx_cache.validate(this)) return false; IRegisters.RegistersContext ctx_data = ctx_cache.getData(); if (ctx_data == null) { set(null, ctx_cache.getError(), null); return true; } expr_text = expr_text == null ? ctx_data.getName() : ctx_data.getName() + "." + expr_text; if (!(reg_node.parent instanceof TCFNodeRegister)) break; reg_node = (TCFNodeRegister)reg_node.parent; } expr_text = "$" + expr_text; } else { TCFDataCache<?> pending = null; TCFDataCache<ISymbols.Symbol> field = model.getSymbolInfoCache(field_id); if (field != null && !field.validate()) pending = field; if (!base_text.validate()) pending = base_text; if (pending != null) { pending.wait(this); return false; } String parent_text = ""; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; TCFDataCache<String> parent_text_cache = ((TCFNodeExpression)n).expression_text; if (!parent_text_cache.validate(this)) return false; if (parent_text_cache.getData() != null) { parent_text = parent_text_cache.getData(); // surround with parentheses if not a simple identifier if (!parent_text.matches("\\w*")) { parent_text = '(' + parent_text + ')'; } } if (index >= 0) { if (index == 0 && deref) { expr_text = "*" + parent_text; } else { expr_text = parent_text + "[" + index + "]"; } } if (expr_text == null && field != null) { ISymbols.Symbol field_data = field.getData(); if (field_data != null) { if (field_data.getName() != null) { expr_text = parent_text + (deref ? "->" : ".") + field_data.getName(); } else if (field_data.getFlag(ISymbols.SYM_FLAG_INHERITANCE)) { TCFDataCache<ISymbols.Symbol> type = model.getSymbolInfoCache(field_data.getTypeID()); if (type != null) { if (!type.validate(this)) return false; ISymbols.Symbol type_data = type.getData(); if (type_data != null) { String type_name = type_data.getName(); expr_text = "*(" + type_name + "*)" + (deref ? "" : "&") + parent_text; } } } } } if (expr_text == null && base_text.getData() != null) expr_text = base_text.getData(); } if (expr_text != null) { String cast = model.getCastToType(id); if (cast != null) expr_text = "(" + cast + ")(" + expr_text + ")"; } set(null, null, expr_text); return true; } }; rem_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null) { set(null, null, null); return true; } String cast = model.getCastToType(id); if (var_id != null && cast == null) { if (!var_expression.validate(this)) return false; set(null, var_expression.getError(), var_expression.getData()); return true; } if (!base_text.validate(this)) return false; String e = base_text.getData(); if (e == null) { set(null, base_text.getError(), null); return true; } if (cast != null) e = "(" + cast + ")(" + e + ")"; TCFNode n = getRootExpression().parent; if (n instanceof TCFNodeStackFrame && ((TCFNodeStackFrame)n).isEmulated()) n = n.parent; command = exps.create(n.id, null, e, new IExpressions.DoneCreate() { public void doneCreate(IToken token, Exception error, IExpressions.Expression context) { disposeRemoteExpression(); if (context != null) remote_expression_id = context.getID(); if (!isDisposed()) set(token, error, context); else disposeRemoteExpression(); } }); return false; } }; value = new TCFData<IExpressions.Value>(channel) { @Override protected boolean startDataRetrieval() { Boolean b = usePrevValue(this); if (b == null) return false; if (b) { set(null, null, prev_value); return true; } if (!rem_expression.validate(this)) return false; final IExpressions.Expression exp = rem_expression.getData(); if (exp == null) { set(null, rem_expression.getError(), null); return true; } final TCFDataCache<?> cache = this; IExpressions exps = launch.getService(IExpressions.class); command = exps.evaluate(exp.getID(), new IExpressions.DoneEvaluate() { public void doneEvaluate(IToken token, Exception error, IExpressions.Value value) { if (command != token) return; command = null; if (error != null) { Boolean b = usePrevValue(cache); if (b == null) return; if (b) { set(null, null, prev_value); return; } } set(null, error, value); } }); return false; } }; type = new TCFData<ISymbols.Symbol>(channel) { @Override protected boolean startDataRetrieval() { String type_id = null; if (model.getCastToType(id) == null && field_id != null) { TCFDataCache<ISymbols.Symbol> sym_cache = model.getSymbolInfoCache(field_id); if (sym_cache != null) { if (!sym_cache.validate(this)) return false; ISymbols.Symbol sym_data = sym_cache.getData(); if (sym_data != null) type_id = sym_data.getTypeID(); } } if (type_id == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null) type_id = val.getTypeID(); } if (type_id == null) { if (!rem_expression.validate(this)) return false; IExpressions.Expression exp = rem_expression.getData(); if (exp != null) type_id = exp.getTypeID(); } if (type_id == null) { set(null, value.getError(), null); return true; } TCFDataCache<ISymbols.Symbol> type_cache = model.getSymbolInfoCache(type_id); if (type_cache == null) { set(null, null, null); return true; } if (!type_cache.validate(this)) return false; set(null, type_cache.getError(), type_cache.getData()); return true; } }; string = new TCFData<StyledStringBuffer>(channel) { ISymbols.Symbol base_type_data; BigInteger addr; byte[] buf; int size; int offs; @Override @SuppressWarnings("incomplete-switch") protected boolean startDataRetrieval() { if (addr != null) return continueMemRead(); if (!value.validate(this)) return false; if (!type.validate(this)) return false; IExpressions.Value value_data = value.getData(); ISymbols.Symbol type_data = type.getData(); if (value_data != null && value_data.getValue() != null && type_data != null) { switch (type_data.getTypeClass()) { case pointer: case array: TCFDataCache<ISymbols.Symbol> base_type_cache = model.getSymbolInfoCache(type_data.getBaseTypeID()); if (base_type_cache == null) break; if (!base_type_cache.validate(this)) return false; base_type_data = base_type_cache.getData(); if (base_type_data == null) break; size = base_type_data.getSize(); if (size == 0) break; switch (base_type_data.getTypeClass()) { case integer: case cardinal: if (base_type_data.getSize() != 1) break; // c-string: read until character = 0 if (type_data.getTypeClass() == ISymbols.TypeClass.array) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '"'), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } // pointer, read c-string data from memory size = 0; // read until 0 return startMemRead(value_data); case composite: if (type_data.getTypeClass() == ISymbols.TypeClass.array) break; // pointer, read struct data from memory return startMemRead(value_data); } break; case integer: case cardinal: if (type_data.getSize() == 1) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '\''), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } break; case enumeration: TCFDataCache<String[]> type_children_cache = model.getSymbolChildrenCache(type_data.getID()); if (!type_children_cache.validate(this)) return false; String[] type_children_data = type_children_cache.getData(); if (type_children_data == null) break; for (String const_id : type_children_data) { TCFDataCache<ISymbols.Symbol> const_cache = model.getSymbolInfoCache(const_id); if (!const_cache.validate(this)) return false; ISymbols.Symbol const_data = const_cache.getData(); if (const_data != null && const_data.getName() != null) { byte[] const_bytes = const_data.getValue(); if (const_bytes != null) { boolean ok = true; byte[] data = value_data.getValue(); for (int i = 0; ok && i < data.length; i++) { if (i < const_bytes.length) ok = const_bytes[i] == data[i]; else ok = data[i] == 0; } if (ok && const_data.getName() != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(const_data.getName()); set(null, null, bf); return true; } } } } break; } } set(null, null, null); return true; } @Override public void reset() { super.reset(); addr = null; } private boolean startMemRead(IExpressions.Value value_data) { byte[] data = value_data.getValue(); BigInteger a = TCFNumberFormat.toBigInteger(data, value_data.isBigEndian(), false); if (!a.equals(BigInteger.valueOf(0))) { addr = a; offs = 0; return continueMemRead(); } set(null, null, null); return true; } private boolean continueMemRead() { // indirect value, need to read it from memory TCFDataCache<TCFNodeExecContext> mem_node_cache = model.searchMemoryContext(parent); if (mem_node_cache == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (!mem_node_cache.validate(this)) return false; if (mem_node_cache.getError() != null) { set(null, mem_node_cache.getError(), null); return true; } TCFNodeExecContext mem_node = mem_node_cache.getData(); if (mem_node == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } TCFDataCache<IMemory.MemoryContext> mem_ctx_cache = mem_node.getMemoryContext(); if (!mem_ctx_cache.validate(this)) return false; if (mem_ctx_cache.getError() != null) { set(null, mem_ctx_cache.getError(), null); return true; } IMemory.MemoryContext mem_space_data = mem_ctx_cache.getData(); if (mem_space_data == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (size == 0) { // c-string: read until 0 if (buf == null) buf = new byte[256]; if (offs >= buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, buf.length); buf = tmp; } BigInteger get_addr = addr.add(BigInteger.valueOf(offs)); final int get_size = 16 - (get_addr.intValue() & 0xf); command = mem_space_data.get(get_addr, 1, buf, offs, get_size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (command != token) return; IMemory.ErrorOffset err_offs = null; if (error instanceof IMemory.ErrorOffset) err_offs = (IMemory.ErrorOffset)error; for (int i = 0; i < get_size; i++) { MemoryError byte_error = null; if (error != null && (err_offs == null || err_offs.getStatus(i) != IMemory.ErrorOffset.BYTE_VALID)) { byte_error = error; if (offs == 0) { set(command, byte_error, null); return; } } if (buf[offs] == 0 || offs >= 2048 || byte_error != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(buf, 0, offs, '"'), StyledStringBuffer.MONOSPACED); set(command, null, bf); return; } offs++; } command = null; run(); } }); return false; } if (offs == 0) { buf = new byte[size]; command = mem_space_data.get(addr, 1, buf, 0, size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (error != null) { set(command, error, null); } else if (command == token) { command = null; offs++; run(); } } }); return false; } StyledStringBuffer bf = new StyledStringBuffer(); bf.append('{'); if (!appendCompositeValueText(bf, 1, base_type_data, TCFNodeExpression.this, true, buf, 0, size, base_type_data.isBigEndian(), this)) return false; bf.append('}'); set(null, null, bf); return true; } }; type_name = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { if (!type.validate(this)) return false; if (type.getData() == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null && val.getValue() != null) { String s = getTypeName(val.getTypeClass(), val.getValue().length); if (s != null) { set(null, null, s); return true; } } } StringBuffer bf = new StringBuffer(); if (!getTypeName(bf, type, this)) return false; set(null, null, bf.toString()); return true; } }; children = new TCFChildrenSubExpressions(this, 0, 0, 0); }
TCFNodeExpression(final TCFNode parent, final String script, final String field_id, final String var_id, final String reg_id, final int index, final boolean deref) { super(parent, var_id != null ? var_id : "Expr" + expr_cnt++); this.script = script; this.field_id = field_id; this.reg_id = reg_id; this.index = index; this.deref = deref; is_empty = script == null && var_id == null && field_id == null && reg_id == null && index < 0; var_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null || var_id == null) { set(null, null, null); return true; } command = exps.getContext(var_id, new IExpressions.DoneGetContext() { public void doneGetContext(IToken token, Exception error, IExpressions.Expression context) { set(token, error, context); } }); return false; } }; base_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute expression script, not including type cast */ parent_value = null; if (is_empty) { set(null, null, null); return true; } if (script != null) { set(null, null, script); return true; } if (var_id != null) { if (!var_expression.validate(this)) return false; Throwable err = null; String exp = null; if (var_expression.getData() == null) { err = var_expression.getError(); } else { exp = var_expression.getData().getExpression(); if (exp == null) err = new Exception("Missing 'Expression' property"); } set(null, err, exp); return true; } if (reg_id != null) { set(null, null, "${" + reg_id + "}"); return true; } String e = null; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; String cast = model.getCastToType(n.id); if (cast == null && deref) { TCFNodeExpression exp = (TCFNodeExpression)n; if (!exp.value.validate(this)) return false; IExpressions.Value v = exp.value.getData(); if (v != null && v.getTypeID() != null) { parent_value = v.getValue(); if (parent_value != null) { e = "(${" + v.getTypeID() + "})0x" + TCFNumberFormat.toBigInteger( parent_value, v.isBigEndian(), false).toString(16); } } } if (e == null) { TCFDataCache<String> t = ((TCFNodeExpression)n).base_text; if (!t.validate(this)) return false; e = t.getData(); if (e == null) { set(null, t.getError(), null); return true; } } if (cast != null) e = "(" + cast + ")(" + e + ")"; if (field_id != null) { e = "(" + e + ")" + (deref ? "->" : ".") + "${" + field_id + "}"; } else if (index == 0) { e = "*(" + e + ")"; } else if (index > 0) { e = "(" + e + ")[" + index + "]"; } set(null, null, e); return true; } }; expression_text = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { /* Compute human readable expression script, * including type cast, and using variable names instead of IDs */ String expr_text = null; if (script != null) { expr_text = script; } else if (var_id != null) { if (!var_expression.validate(this)) return false; IExpressions.Expression e = var_expression.getData(); if (e != null) { TCFDataCache<ISymbols.Symbol> var = model.getSymbolInfoCache(e.getSymbolID()); if (var != null) { if (!var.validate(this)) return false; if (var.getData() != null) expr_text = var.getData().getName(); } } } else if (reg_id != null) { if (!model.createNode(reg_id, this)) return false; if (isValid()) return true; TCFNodeRegister reg_node = (TCFNodeRegister)model.getNode(reg_id); for (;;) { TCFDataCache<IRegisters.RegistersContext> ctx_cache = reg_node.getContext(); if (!ctx_cache.validate(this)) return false; IRegisters.RegistersContext ctx_data = ctx_cache.getData(); if (ctx_data == null) { set(null, ctx_cache.getError(), null); return true; } expr_text = expr_text == null ? ctx_data.getName() : ctx_data.getName() + "." + expr_text; if (!(reg_node.parent instanceof TCFNodeRegister)) break; reg_node = (TCFNodeRegister)reg_node.parent; } expr_text = "$" + expr_text; } else { TCFDataCache<?> pending = null; TCFDataCache<ISymbols.Symbol> field = model.getSymbolInfoCache(field_id); if (field != null && !field.validate()) pending = field; if (!base_text.validate()) pending = base_text; if (pending != null) { pending.wait(this); return false; } String parent_text = ""; TCFNode n = parent; while (n instanceof TCFNodeArrayPartition) n = n.parent; TCFDataCache<String> parent_text_cache = ((TCFNodeExpression)n).expression_text; if (!parent_text_cache.validate(this)) return false; if (parent_text_cache.getData() != null) { parent_text = parent_text_cache.getData(); // surround with parentheses if not a simple identifier if (!parent_text.matches("\\w*")) { parent_text = '(' + parent_text + ')'; } } if (index >= 0) { if (index == 0 && deref) { expr_text = "*" + parent_text; } else { expr_text = parent_text + "[" + index + "]"; } } if (expr_text == null && field != null) { ISymbols.Symbol field_data = field.getData(); if (field_data != null) { if (field_data.getName() != null) { expr_text = parent_text + (deref ? "->" : ".") + field_data.getName(); } else if (field_data.getFlag(ISymbols.SYM_FLAG_INHERITANCE)) { TCFDataCache<ISymbols.Symbol> type = model.getSymbolInfoCache(field_data.getTypeID()); if (type != null) { if (!type.validate(this)) return false; ISymbols.Symbol type_data = type.getData(); if (type_data != null) { String type_name = type_data.getName(); expr_text = "*(" + type_name + "*)" + (deref ? "" : "&") + parent_text; } } } } } if (expr_text == null && base_text.getData() != null) expr_text = base_text.getData(); } if (expr_text != null) { String cast = model.getCastToType(id); if (cast != null) expr_text = "(" + cast + ")(" + expr_text + ")"; } set(null, null, expr_text); return true; } }; rem_expression = new TCFData<IExpressions.Expression>(channel) { @Override protected boolean startDataRetrieval() { IExpressions exps = launch.getService(IExpressions.class); if (exps == null) { set(null, null, null); return true; } String cast = model.getCastToType(id); if (var_id != null && cast == null) { if (!var_expression.validate(this)) return false; set(null, var_expression.getError(), var_expression.getData()); return true; } if (!base_text.validate(this)) return false; String e = base_text.getData(); if (e == null) { set(null, base_text.getError(), null); return true; } if (cast != null) e = "(" + cast + ")(" + e + ")"; TCFNode n = getRootExpression().parent; if (n instanceof TCFNodeStackFrame && ((TCFNodeStackFrame)n).isEmulated()) n = n.parent; command = exps.create(n.id, null, e, new IExpressions.DoneCreate() { public void doneCreate(IToken token, Exception error, IExpressions.Expression context) { disposeRemoteExpression(); if (context != null) remote_expression_id = context.getID(); if (!isDisposed()) set(token, error, context); else disposeRemoteExpression(); } }); return false; } }; value = new TCFData<IExpressions.Value>(channel) { @Override protected boolean startDataRetrieval() { Boolean b = usePrevValue(this); if (b == null) return false; if (b) { set(null, null, prev_value); return true; } if (!rem_expression.validate(this)) return false; final IExpressions.Expression exp = rem_expression.getData(); if (exp == null) { set(null, rem_expression.getError(), null); return true; } final TCFDataCache<?> cache = this; IExpressions exps = launch.getService(IExpressions.class); command = exps.evaluate(exp.getID(), new IExpressions.DoneEvaluate() { public void doneEvaluate(IToken token, Exception error, IExpressions.Value value) { if (command != token) return; command = null; if (error != null) { Boolean b = usePrevValue(cache); if (b == null) return; if (b) { set(null, null, prev_value); return; } } set(null, error, value); } }); return false; } }; type = new TCFData<ISymbols.Symbol>(channel) { @Override protected boolean startDataRetrieval() { String type_id = null; if (model.getCastToType(id) == null && field_id != null) { TCFDataCache<ISymbols.Symbol> sym_cache = model.getSymbolInfoCache(field_id); if (sym_cache != null) { if (!sym_cache.validate(this)) return false; ISymbols.Symbol sym_data = sym_cache.getData(); if (sym_data != null) type_id = sym_data.getTypeID(); } } if (type_id == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null) type_id = val.getTypeID(); } if (type_id == null) { if (!rem_expression.validate(this)) return false; IExpressions.Expression exp = rem_expression.getData(); if (exp != null) type_id = exp.getTypeID(); } if (type_id == null) { set(null, value.getError(), null); return true; } TCFDataCache<ISymbols.Symbol> type_cache = model.getSymbolInfoCache(type_id); if (type_cache == null) { set(null, null, null); return true; } if (!type_cache.validate(this)) return false; set(null, type_cache.getError(), type_cache.getData()); return true; } }; string = new TCFData<StyledStringBuffer>(channel) { ISymbols.Symbol base_type_data; BigInteger addr; byte[] buf; int size; int offs; @Override @SuppressWarnings("incomplete-switch") protected boolean startDataRetrieval() { if (addr != null) return continueMemRead(); if (!value.validate(this)) return false; if (!type.validate(this)) return false; IExpressions.Value value_data = value.getData(); ISymbols.Symbol type_data = type.getData(); if (value_data != null && value_data.getValue() != null && type_data != null) { switch (type_data.getTypeClass()) { case pointer: case array: TCFDataCache<ISymbols.Symbol> base_type_cache = model.getSymbolInfoCache(type_data.getBaseTypeID()); if (base_type_cache == null) break; if (!base_type_cache.validate(this)) return false; base_type_data = base_type_cache.getData(); if (base_type_data == null) break; size = base_type_data.getSize(); if (size == 0) break; switch (base_type_data.getTypeClass()) { case integer: case cardinal: if (base_type_data.getSize() != 1) break; // c-string: read until character = 0 if (type_data.getTypeClass() == ISymbols.TypeClass.array) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '"'), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } // pointer, read c-string data from memory size = 0; // read until 0 return startMemRead(value_data); case composite: if (type_data.getTypeClass() == ISymbols.TypeClass.array) break; // pointer, read struct data from memory return startMemRead(value_data); } break; case integer: case cardinal: if (type_data.getSize() == 1) { byte[] data = value_data.getValue(); StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(data, 0, data.length, '\''), StyledStringBuffer.MONOSPACED); set(null, null, bf); return true; } break; case enumeration: TCFDataCache<String[]> type_children_cache = model.getSymbolChildrenCache(type_data.getID()); if (!type_children_cache.validate(this)) return false; String[] type_children_data = type_children_cache.getData(); if (type_children_data == null) break; for (String const_id : type_children_data) { TCFDataCache<ISymbols.Symbol> const_cache = model.getSymbolInfoCache(const_id); if (!const_cache.validate(this)) return false; ISymbols.Symbol const_data = const_cache.getData(); if (const_data != null && const_data.getName() != null) { byte[] const_bytes = const_data.getValue(); if (const_bytes != null) { boolean ok = true; byte[] data = value_data.getValue(); for (int i = 0; ok && i < data.length; i++) { if (i < const_bytes.length) ok = const_bytes[i] == data[i]; else ok = data[i] == 0; } if (ok && const_data.getName() != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(const_data.getName()); set(null, null, bf); return true; } } } } break; } } set(null, null, null); return true; } @Override public void reset() { super.reset(); addr = null; } private boolean startMemRead(IExpressions.Value value_data) { byte[] data = value_data.getValue(); BigInteger a = TCFNumberFormat.toBigInteger(data, value_data.isBigEndian(), false); if (!a.equals(BigInteger.valueOf(0))) { addr = a; offs = 0; return continueMemRead(); } set(null, null, null); return true; } private boolean continueMemRead() { // indirect value, need to read it from memory TCFDataCache<TCFNodeExecContext> mem_node_cache = model.searchMemoryContext(parent); if (mem_node_cache == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (!mem_node_cache.validate(this)) return false; if (mem_node_cache.getError() != null) { set(null, mem_node_cache.getError(), null); return true; } TCFNodeExecContext mem_node = mem_node_cache.getData(); if (mem_node == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } TCFDataCache<IMemory.MemoryContext> mem_ctx_cache = mem_node.getMemoryContext(); if (!mem_ctx_cache.validate(this)) return false; if (mem_ctx_cache.getError() != null) { set(null, mem_ctx_cache.getError(), null); return true; } IMemory.MemoryContext mem_space_data = mem_ctx_cache.getData(); if (mem_space_data == null) { set(null, new Exception("Context does not provide memory access"), null); return true; } if (size == 0) { // c-string: read until 0 BigInteger get_addr = addr.add(BigInteger.valueOf(offs)); final int get_size = 16 - (get_addr.intValue() & 0xf); if (buf == null) buf = new byte[256]; if (offs + get_size > buf.length) { byte[] tmp = new byte[buf.length * 2]; System.arraycopy(buf, 0, tmp, 0, buf.length); buf = tmp; } command = mem_space_data.get(get_addr, 1, buf, offs, get_size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (command != token) return; IMemory.ErrorOffset err_offs = null; if (error instanceof IMemory.ErrorOffset) err_offs = (IMemory.ErrorOffset)error; for (int i = 0; i < get_size; i++) { MemoryError byte_error = null; if (error != null && (err_offs == null || err_offs.getStatus(i) != IMemory.ErrorOffset.BYTE_VALID)) { byte_error = error; if (offs == 0) { set(command, byte_error, null); return; } } if (buf[offs] == 0 || offs >= 2048 || byte_error != null) { StyledStringBuffer bf = new StyledStringBuffer(); bf.append(toASCIIString(buf, 0, offs, '"'), StyledStringBuffer.MONOSPACED); set(command, null, bf); return; } offs++; } command = null; run(); } }); return false; } if (offs == 0) { buf = new byte[size]; command = mem_space_data.get(addr, 1, buf, 0, size, 0, new IMemory.DoneMemory() { public void doneMemory(IToken token, MemoryError error) { if (error != null) { set(command, error, null); } else if (command == token) { command = null; offs++; run(); } } }); return false; } StyledStringBuffer bf = new StyledStringBuffer(); bf.append('{'); if (!appendCompositeValueText(bf, 1, base_type_data, TCFNodeExpression.this, true, buf, 0, size, base_type_data.isBigEndian(), this)) return false; bf.append('}'); set(null, null, bf); return true; } }; type_name = new TCFData<String>(channel) { @Override protected boolean startDataRetrieval() { if (!type.validate(this)) return false; if (type.getData() == null) { if (!value.validate(this)) return false; IExpressions.Value val = value.getData(); if (val != null && val.getValue() != null) { String s = getTypeName(val.getTypeClass(), val.getValue().length); if (s != null) { set(null, null, s); return true; } } } StringBuffer bf = new StringBuffer(); if (!getTypeName(bf, type, this)) return false; set(null, null, bf.toString()); return true; } }; children = new TCFChildrenSubExpressions(this, 0, 0, 0); }
diff --git a/library/src/com/github/espiandev/showcaseview/ShowcaseView.java b/library/src/com/github/espiandev/showcaseview/ShowcaseView.java index d89d226..048b5c0 100644 --- a/library/src/com/github/espiandev/showcaseview/ShowcaseView.java +++ b/library/src/com/github/espiandev/showcaseview/ShowcaseView.java @@ -1,852 +1,852 @@ package com.github.espiandev.showcaseview; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.DynamicLayout; import android.text.Layout; import android.text.SpannableString; import android.text.TextPaint; import android.text.TextUtils; import android.text.style.TextAppearanceSpan; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.Button; import android.widget.RelativeLayout; import com.github.espiandev.showcaseview.anim.AnimationUtils; import java.lang.reflect.Field; import static com.github.espiandev.showcaseview.anim.AnimationUtils.AnimationEndListener; import static com.github.espiandev.showcaseview.anim.AnimationUtils.AnimationStartListener; /** * A view which allows you to showcase areas of your app with an explanation. */ public class ShowcaseView extends RelativeLayout implements View.OnClickListener, View.OnTouchListener { public static final int TYPE_NO_LIMIT = 0; public static final int TYPE_ONE_SHOT = 1; public static final int INSERT_TO_DECOR = 0; public static final int INSERT_TO_VIEW = 1; public static final int ITEM_ACTION_HOME = 0; public static final int ITEM_TITLE = 1; public static final int ITEM_SPINNER = 2; public static final int ITEM_ACTION_ITEM = 3; public static final int ITEM_ACTION_OVERFLOW = 6; private static final String PREFS_SHOWCASE_INTERNAL = "showcase_internal"; public static final int INNER_CIRCLE_RADIUS = 94; private float showcaseX = -1; private float showcaseY = -1; private float showcaseRadius = -1; private float metricScale = 1.0f; private float legacyShowcaseX = -1; private float legacyShowcaseY = -1; private boolean isRedundant = false; private boolean hasCustomClickListener = false; private ConfigOptions mOptions; private Paint mEraser; private TextPaint mPaintDetail, mPaintTitle; private int backColor; private Drawable showcase; private View mHandy; private final Button mEndButton; private OnShowcaseEventListener mEventListener; private Rect voidedArea; private CharSequence mTitleText, mSubText; private DynamicLayout mDynamicTitleLayout; private DynamicLayout mDynamicDetailLayout; private float[] mBestTextPosition; private boolean mAlteredText = false; private TextAppearanceSpan mDetailSpan, mTitleSpan; private final String buttonText; private float scaleMultiplier = 1f; private Bitmap mBleachedCling; private int mShowcaseColor; protected ShowcaseView(Context context) { this(context, null, R.styleable.CustomTheme_showcaseViewStyle); } protected ShowcaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Get the attributes for the ShowcaseView final TypedArray styled = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ShowcaseView, R.attr.showcaseViewStyle, R.style.ShowcaseView); backColor = styled.getInt(R.styleable.ShowcaseView_sv_backgroundColor, Color.argb(128, 80, 80, 80)); mShowcaseColor = styled.getColor(R.styleable.ShowcaseView_sv_showcaseColor, Color.parseColor("#33B5E5")); int titleTextAppearance = styled.getResourceId(R.styleable.ShowcaseView_sv_titleTextAppearance, R.style.TextAppearance_ShowcaseView_Title); int detailTextAppearance = styled.getResourceId(R.styleable.ShowcaseView_sv_detailTextAppearance, R.style.TextAppearance_ShowcaseView_Detail); mTitleSpan = new TextAppearanceSpan(context, titleTextAppearance); mDetailSpan = new TextAppearanceSpan(context, detailTextAppearance); buttonText = styled.getString(R.styleable.ShowcaseView_sv_buttonText); styled.recycle(); metricScale = getContext().getResources().getDisplayMetrics().density; mEndButton = (Button) LayoutInflater.from(context).inflate(R.layout.showcase_button, null); ConfigOptions options = new ConfigOptions(); options.showcaseId = getId(); setConfigOptions(options); } private void init() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setLayerType(LAYER_TYPE_SOFTWARE, null); } else { setDrawingCacheEnabled(true); } boolean hasShot = getContext().getSharedPreferences(PREFS_SHOWCASE_INTERNAL, Context.MODE_PRIVATE) .getBoolean("hasShot" + getConfigOptions().showcaseId, false); if (hasShot && mOptions.shotType == TYPE_ONE_SHOT) { // The showcase has already been shot once, so we don't need to do anything setVisibility(View.GONE); isRedundant = true; return; } showcase = getContext().getResources().getDrawable(R.drawable.cling_bleached); showcase.setColorFilter(mShowcaseColor, PorterDuff.Mode.MULTIPLY); showcaseRadius = metricScale * INNER_CIRCLE_RADIUS; PorterDuffXfermode mBlender = new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY); setOnTouchListener(this); mPaintTitle = new TextPaint(); mPaintTitle.setAntiAlias(true); mPaintDetail = new TextPaint(); mPaintDetail.setAntiAlias(true); mEraser = new Paint(); mEraser.setColor(0xFFFFFF); mEraser.setAlpha(0); mEraser.setXfermode(mBlender); mEraser.setAntiAlias(true); if (!mOptions.noButton && mEndButton.getParent() == null) { RelativeLayout.LayoutParams lps = getConfigOptions().buttonLayoutParams; if (lps == null) { lps = (LayoutParams) generateDefaultLayoutParams(); lps.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); lps.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); int margin = ((Number) (metricScale * 12)).intValue(); lps.setMargins(margin, margin, margin, margin); } mEndButton.setLayoutParams(lps); mEndButton.setText(buttonText != null ? buttonText : getResources().getString(R.string.ok)); if (!hasCustomClickListener) mEndButton.setOnClickListener(this); addView(mEndButton); } } public void setShowcaseNoView() { setShowcasePosition(1000000, 1000000); } /** * Set the view to showcase * * @param view The {@link View} to showcase. */ public void setShowcaseView(final View view) { if (isRedundant || view == null) { isRedundant = true; return; } isRedundant = false; view.post(new Runnable() { @Override public void run() { init(); if (mOptions.insert == INSERT_TO_VIEW) { showcaseX = (float) (view.getLeft() + view.getWidth() / 2); showcaseY = (float) (view.getTop() + view.getHeight() / 2); } else { int[] coordinates = new int[2]; view.getLocationInWindow(coordinates); showcaseX = (float) (coordinates[0] + view.getWidth() / 2); showcaseY = (float) (coordinates[1] + view.getHeight() / 2); } invalidate(); } }); } /** * Set a specific position to showcase * * @param x X co-ordinate * @param y Y co-ordinate */ public void setShowcasePosition(float x, float y) { if (isRedundant) { return; } showcaseX = x; showcaseY = y; init(); invalidate(); } public void setShowcaseItem(final int itemType, final int actionItemId, final Activity activity) { post(new Runnable() { @Override public void run() { View homeButton = activity.findViewById(android.R.id.home); if (homeButton == null) { // Thanks to @hameno for this int homeId = activity.getResources().getIdentifier("abs__home", "id", activity.getPackageName()); if (homeId == 0) { homeId = activity.getResources().getIdentifier("home", "id", activity.getPackageName()); } if (homeId != 0) { homeButton = activity.findViewById(homeId); } } if (homeButton == null) throw new RuntimeException("insertShowcaseViewWithType cannot be used when the theme " + "has no ActionBar"); ViewParent p = homeButton.getParent().getParent(); //ActionBarView if (!p.getClass().getName().contains("ActionBarView")) { String previousP = p.getClass().getName(); p = p.getParent(); String throwP = p.getClass().getName(); if (!p.getClass().getName().contains("ActionBarView")) throw new IllegalStateException("Cannot find ActionBarView for " + "Activity, instead found " + previousP + " and " + throwP); } Class abv = p.getClass(); //ActionBarView class Class absAbv = abv.getSuperclass(); //AbsActionBarView class switch (itemType) { case ITEM_ACTION_HOME: setShowcaseView(homeButton); break; case ITEM_SPINNER: showcaseSpinner(p, abv); break; case ITEM_TITLE: showcaseTitle(p, abv); break; case ITEM_ACTION_ITEM: case ITEM_ACTION_OVERFLOW: showcaseActionItem(p, absAbv, itemType, actionItemId); break; default: Log.e("TAG", "Unknown item type"); } } }); } private void showcaseActionItem(ViewParent p, Class absAbv, int itemType, int actionItemId) { try { Field mAmpField = absAbv.getDeclaredField("mActionMenuPresenter"); mAmpField.setAccessible(true); Object mAmp = mAmpField.get(p); if (itemType == ITEM_ACTION_OVERFLOW) { // Finds the overflow button associated with the ActionMenuPresenter Field mObField = mAmp.getClass().getDeclaredField("mOverflowButton"); mObField.setAccessible(true); View mOb = (View) mObField.get(mAmp); if (mOb != null) setShowcaseView(mOb); } else { // Want an ActionItem, so find it Field mAmvField = mAmp.getClass().getSuperclass().getDeclaredField("mMenuView"); mAmvField.setAccessible(true); Object mAmv = mAmvField.get(mAmp); Field mChField; if (mAmv.getClass().toString().contains("com.actionbarsherlock")) { // There are thousands of superclasses to traverse up // Have to get superclasses because mChildren is private mChField = mAmv.getClass().getSuperclass().getSuperclass() .getSuperclass().getSuperclass().getDeclaredField("mChildren"); } else if(mAmv.getClass().toString().contains("android.support.v7")) { mChField = mAmv.getClass().getSuperclass().getSuperclass() .getSuperclass().getDeclaredField("mChildren"); } else mChField = mAmv.getClass().getSuperclass().getSuperclass().getDeclaredField("mChildren"); mChField.setAccessible(true); Object[] mChs = (Object[]) mChField.get(mAmv); for (Object mCh : mChs) { if (mCh != null) { View v = (View) mCh; if (v.getId() == actionItemId) setShowcaseView(v); } } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NullPointerException npe) { throw new RuntimeException("insertShowcaseViewWithType() must be called " + "after or during onCreateOptionsMenu() of the host Activity"); } } private void showcaseSpinner(ViewParent p, Class abv) { try { Field mSpinnerField = abv.getDeclaredField("mSpinner"); mSpinnerField.setAccessible(true); View mSpinnerView = (View) mSpinnerField.get(p); if (mSpinnerView != null) { setShowcaseView(mSpinnerView); } } catch (NoSuchFieldException e) { Log.e("TAG", "Failed to find actionbar spinner", e); } catch (IllegalAccessException e) { Log.e("TAG", "Failed to access actionbar spinner", e); } } private void showcaseTitle(ViewParent p, Class abv) { try { Field mTitleViewField = abv.getDeclaredField("mTitleView"); mTitleViewField.setAccessible(true); View titleView = (View) mTitleViewField.get(p); if (titleView != null) { setShowcaseView(titleView); } } catch (NoSuchFieldException e) { Log.e("TAG", "Failed to find actionbar title", e); } catch (IllegalAccessException e) { Log.e("TAG", "Failed to access actionbar title", e); } } /** * Set the shot method of the showcase - only once or no limit * * @param shotType either TYPE_ONE_SHOT or TYPE_NO_LIMIT * @deprecated Use the option in {@link ConfigOptions} instead. */ @Deprecated public void setShotType(int shotType) { if (shotType == TYPE_NO_LIMIT || shotType == TYPE_ONE_SHOT) { mOptions.shotType = shotType; } } /** * Decide whether touches outside the showcased circle should be ignored or not * * @param block true to block touches, false otherwise. By default, this is true. * @deprecated Use the option in {@link ConfigOptions} instead. */ @Deprecated public void blockNonShowcasedTouches(boolean block) { mOptions.block = block; } /** * Override the standard button click event * * @param listener Listener to listen to on click events */ public void overrideButtonClick(OnClickListener listener) { if (isRedundant) { return; } if (mEndButton != null) { mEndButton.setOnClickListener(listener != null ? listener : this); } hasCustomClickListener = true; } public void setOnShowcaseEventListener(OnShowcaseEventListener listener) { mEventListener = listener; } @Override protected void dispatchDraw(Canvas canvas) { if (showcaseX < 0 || showcaseY < 0 || isRedundant) { super.dispatchDraw(canvas); return; } //Draw the semi-transparent background canvas.drawColor(backColor); //Draw to the scale specified Matrix mm = new Matrix(); mm.postScale(scaleMultiplier, scaleMultiplier, showcaseX, showcaseY); canvas.setMatrix(mm); //Erase the area for the ring canvas.drawCircle(showcaseX, showcaseY, showcaseRadius, mEraser); boolean recalculateText = makeVoidedRect() || mAlteredText; mAlteredText = false; showcase.setBounds(voidedArea); showcase.draw(canvas); canvas.setMatrix(new Matrix()); if (!TextUtils.isEmpty(mTitleText) || !TextUtils.isEmpty(mSubText)) { if (recalculateText) mBestTextPosition = getBestTextPosition(canvas.getWidth(), canvas.getHeight()); if (!TextUtils.isEmpty(mTitleText)) { canvas.save(); if (recalculateText) { mDynamicTitleLayout = new DynamicLayout(mTitleText, mPaintTitle, (int) mBestTextPosition[2], Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, true); } canvas.translate(mBestTextPosition[0], mBestTextPosition[1] - 24 * metricScale); mDynamicTitleLayout.draw(canvas); canvas.restore(); } if (!TextUtils.isEmpty(mSubText)) { canvas.save(); if (recalculateText) { mDynamicDetailLayout = new DynamicLayout(mSubText, mPaintDetail, ((Number) mBestTextPosition[2]).intValue(), Layout.Alignment.ALIGN_NORMAL, 1.2f, 1.0f, true); } - canvas.translate(mBestTextPosition[0], mBestTextPosition[1] + 12 * metricScale); + canvas.translate(mBestTextPosition[0] , mBestTextPosition[1] + 12 * metricScale + (mDynamicTitleLayout.getLineBottom(mDynamicTitleLayout.getLineCount()-1)-mDynamicTitleLayout.getLineBottom(0))); mDynamicDetailLayout.draw(canvas); canvas.restore(); } } super.dispatchDraw(canvas); } /** * Calculates the best place to position text * * @param canvasW width of the screen * @param canvasH height of the screen * @return */ private float[] getBestTextPosition(int canvasW, int canvasH) { //if the width isn't much bigger than the voided area, just consider top & bottom float spaceTop = voidedArea.top; float spaceBottom = canvasH - voidedArea.bottom - 64 * metricScale; //64dip considers the OK button //float spaceLeft = voidedArea.left; //float spaceRight = canvasW - voidedArea.right; //TODO: currently only considers above or below showcase, deal with left or right return new float[]{24 * metricScale, spaceTop > spaceBottom ? 128 * metricScale : 24 * metricScale + voidedArea.bottom, canvasW - 48 * metricScale}; } /** * Creates a {@link Rect} which represents the area the showcase covers. Used to calculate * where best to place the text * * @return true if voidedArea has changed, false otherwise. */ private boolean makeVoidedRect() { // This if statement saves resources by not recalculating voidedArea // if the X & Y coordinates haven't changed if (voidedArea == null || (showcaseX != legacyShowcaseX || showcaseY != legacyShowcaseY)) { int cx = (int) showcaseX, cy = (int) showcaseY; int dw = showcase.getIntrinsicWidth(); int dh = showcase.getIntrinsicHeight(); voidedArea = new Rect(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2); legacyShowcaseX = showcaseX; legacyShowcaseY = showcaseY; return true; } return false; } public void animateGesture(float offsetStartX, float offsetStartY, float offsetEndX, float offsetEndY) { mHandy = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.handy, null); addView(mHandy); moveHand(offsetStartX, offsetStartY, offsetEndX, offsetEndY, new AnimationEndListener() { @Override public void onAnimationEnd() { removeView(mHandy); } }); } private void moveHand(float offsetStartX, float offsetStartY, float offsetEndX, float offsetEndY, AnimationEndListener listener) { AnimationUtils.createMovementAnimation(mHandy, showcaseX, showcaseY, offsetStartX, offsetStartY, offsetEndX, offsetEndY, listener).start(); } @Override public void onClick(View view) { // If the type is set to one-shot, store that it has shot if (mOptions.shotType == TYPE_ONE_SHOT) { SharedPreferences internal = getContext().getSharedPreferences(PREFS_SHOWCASE_INTERNAL, Context.MODE_PRIVATE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { internal.edit().putBoolean("hasShot" + getConfigOptions().showcaseId, true).apply(); } else { internal.edit().putBoolean("hasShot" + getConfigOptions().showcaseId, true).commit(); } } hide(); } public void hide() { if (mEventListener != null) { mEventListener.onShowcaseViewHide(this); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && getConfigOptions().fadeOutDuration > 0) { fadeOutShowcase(); } else { setVisibility(View.GONE); } } private void fadeOutShowcase() { AnimationUtils.createFadeOutAnimation(this, getConfigOptions().fadeOutDuration, new AnimationEndListener() { @Override public void onAnimationEnd() { setVisibility(View.GONE); } }).start(); } public void show() { if (mEventListener != null) { mEventListener.onShowcaseViewShow(this); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && getConfigOptions().fadeInDuration > 0) { fadeInShowcase(); } else { setVisibility(View.VISIBLE); } } private void fadeInShowcase() { AnimationUtils.createFadeInAnimation(this, getConfigOptions().fadeInDuration, new AnimationStartListener() { @Override public void onAnimationStart() { setVisibility(View.VISIBLE); } }).start(); } @Override public boolean onTouch(View view, MotionEvent motionEvent) { float xDelta = Math.abs(motionEvent.getRawX() - showcaseX); float yDelta = Math.abs(motionEvent.getRawY() - showcaseY); double distanceFromFocus = Math.sqrt(Math.pow(xDelta, 2) + Math.pow(yDelta, 2)); if (mOptions.hideOnClickOutside && distanceFromFocus > showcaseRadius) { this.hide(); return true; } return mOptions.block && distanceFromFocus > showcaseRadius; } public void setShowcaseIndicatorScale(float scaleMultiplier) { this.scaleMultiplier = scaleMultiplier; } public interface OnShowcaseEventListener { public void onShowcaseViewHide(ShowcaseView showcaseView); public void onShowcaseViewShow(ShowcaseView showcaseView); } public void setText(int titleTextResId, int subTextResId) { String titleText = getContext().getResources().getString(titleTextResId); String subText = getContext().getResources().getString(subTextResId); setText(titleText, subText); } public void setText(String titleText, String subText) { SpannableString ssbTitle = new SpannableString(titleText); ssbTitle.setSpan(mTitleSpan, 0, ssbTitle.length(), 0); mTitleText = ssbTitle; SpannableString ssbDetail = new SpannableString(subText); ssbDetail.setSpan(mDetailSpan, 0, ssbDetail.length(), 0); mSubText = ssbDetail; mAlteredText = true; invalidate(); } /** * Get the ghostly gesture hand for custom gestures * * @return a View representing the ghostly hand */ public View getHand() { final View mHandy = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.handy, null); addView(mHandy); AnimationUtils.hide(mHandy); return mHandy; } /** * Point to a specific view * * @param view The {@link View} to Showcase */ public void pointTo(View view) { float x = AnimationUtils.getX(view) + view.getWidth() / 2; float y = AnimationUtils.getY(view) + view.getHeight() / 2; pointTo(x, y); } /** * Point to a specific point on the screen * * @param x X-coordinate to point to * @param y Y-coordinate to point to */ public void pointTo(float x, float y) { final View mHandy = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.handy, null); AnimationUtils.createMovementAnimation(mHandy, x, y).start(); } private void setConfigOptions(ConfigOptions options) { mOptions = options; } private ConfigOptions getConfigOptions() { // Make sure that this method never returns null if (mOptions == null) return mOptions = new ConfigOptions(); return mOptions; } /** * Quick method to insert a ShowcaseView into an Activity * * @param viewToShowcase View to showcase * @param activity Activity to insert into * @param title Text to show as a title. Can be null. * @param detailText More detailed text. Can be null. * @param options A set of options to customise the ShowcaseView * @return the created ShowcaseView instance */ public static ShowcaseView insertShowcaseView(View viewToShowcase, Activity activity, String title, String detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcaseView(viewToShowcase); sv.setText(title, detailText); return sv; } /** * Quick method to insert a ShowcaseView into an Activity * * @param viewToShowcase View to showcase * @param activity Activity to insert into * @param title Text to show as a title. Can be null. * @param detailText More detailed text. Can be null. * @param options A set of options to customise the ShowcaseView * @return the created ShowcaseView instance */ public static ShowcaseView insertShowcaseView(View viewToShowcase, Activity activity, int title, int detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcaseView(viewToShowcase); sv.setText(title, detailText); return sv; } public static ShowcaseView insertShowcaseView(int showcaseViewId, Activity activity, String title, String detailText, ConfigOptions options) { View v = activity.findViewById(showcaseViewId); if (v != null) { return insertShowcaseView(v, activity, title, detailText, options); } return null; } public static ShowcaseView insertShowcaseView(int showcaseViewId, Activity activity, int title, int detailText, ConfigOptions options) { View v = activity.findViewById(showcaseViewId); if (v != null) { return insertShowcaseView(v, activity, title, detailText, options); } return null; } public static ShowcaseView insertShowcaseView(float x, float y, Activity activity, String title, String detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcasePosition(x, y); sv.setText(title, detailText); return sv; } public static ShowcaseView insertShowcaseView(float x, float y, Activity activity, int title, int detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcasePosition(x, y); sv.setText(title, detailText); return sv; } public static ShowcaseView insertShowcaseView(View showcase, Activity activity) { return insertShowcaseView(showcase, activity, null, null, null); } /** * Quickly insert a ShowcaseView into an Activity, highlighting an item. * * @param type the type of item to showcase (can be ITEM_ACTION_HOME, ITEM_TITLE_OR_SPINNER, ITEM_ACTION_ITEM or ITEM_ACTION_OVERFLOW) * @param itemId the ID of an Action item to showcase (only required for ITEM_ACTION_ITEM * @param activity Activity to insert the ShowcaseView into * @param title Text to show as a title. Can be null. * @param detailText More detailed text. Can be null. * @param options A set of options to customise the ShowcaseView * @return the created ShowcaseView instance */ public static ShowcaseView insertShowcaseViewWithType(int type, int itemId, Activity activity, String title, String detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcaseItem(type, itemId, activity); sv.setText(title, detailText); return sv; } /** * Quickly insert a ShowcaseView into an Activity, highlighting an item. * * @param type the type of item to showcase (can be ITEM_ACTION_HOME, ITEM_TITLE_OR_SPINNER, ITEM_ACTION_ITEM or ITEM_ACTION_OVERFLOW) * @param itemId the ID of an Action item to showcase (only required for ITEM_ACTION_ITEM * @param activity Activity to insert the ShowcaseView into * @param title Text to show as a title. Can be null. * @param detailText More detailed text. Can be null. * @param options A set of options to customise the ShowcaseView * @return the created ShowcaseView instance */ public static ShowcaseView insertShowcaseViewWithType(int type, int itemId, Activity activity, int title, int detailText, ConfigOptions options) { ShowcaseView sv = new ShowcaseView(activity); if (options != null) sv.setConfigOptions(options); if (sv.getConfigOptions().insert == INSERT_TO_DECOR) { ((ViewGroup) activity.getWindow().getDecorView()).addView(sv); } else { ((ViewGroup) activity.findViewById(android.R.id.content)).addView(sv); } sv.setShowcaseItem(type, itemId, activity); sv.setText(title, detailText); return sv; } public static ShowcaseView insertShowcaseView(float x, float y, Activity activity) { return insertShowcaseView(x, y, activity, null, null, null); } public static class ConfigOptions { public boolean block = true, noButton = false; public int insert = INSERT_TO_DECOR; public boolean hideOnClickOutside = false; /** * If you want to use more than one Showcase with the {@link ConfigOptions#shotType} {@link ShowcaseView#TYPE_ONE_SHOT} in one Activity, set a unique value for every different Showcase you want to use. */ public int showcaseId = 0; /** * If you want to use more than one Showcase with {@link ShowcaseView#TYPE_ONE_SHOT} in one Activity, set a unique {@link ConfigOptions#showcaseId} value for every different Showcase you want to use. */ public int shotType = TYPE_NO_LIMIT; /** * Default duration for fade in animation. Set to 0 to disable. */ public int fadeInDuration = AnimationUtils.DEFAULT_DURATION; /** * Default duration for fade out animation. Set to 0 to disable. */ public int fadeOutDuration = AnimationUtils.DEFAULT_DURATION; /** Allow custom positioning of the button within the showcase view. */ public LayoutParams buttonLayoutParams = null; } }
true
true
protected void dispatchDraw(Canvas canvas) { if (showcaseX < 0 || showcaseY < 0 || isRedundant) { super.dispatchDraw(canvas); return; } //Draw the semi-transparent background canvas.drawColor(backColor); //Draw to the scale specified Matrix mm = new Matrix(); mm.postScale(scaleMultiplier, scaleMultiplier, showcaseX, showcaseY); canvas.setMatrix(mm); //Erase the area for the ring canvas.drawCircle(showcaseX, showcaseY, showcaseRadius, mEraser); boolean recalculateText = makeVoidedRect() || mAlteredText; mAlteredText = false; showcase.setBounds(voidedArea); showcase.draw(canvas); canvas.setMatrix(new Matrix()); if (!TextUtils.isEmpty(mTitleText) || !TextUtils.isEmpty(mSubText)) { if (recalculateText) mBestTextPosition = getBestTextPosition(canvas.getWidth(), canvas.getHeight()); if (!TextUtils.isEmpty(mTitleText)) { canvas.save(); if (recalculateText) { mDynamicTitleLayout = new DynamicLayout(mTitleText, mPaintTitle, (int) mBestTextPosition[2], Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, true); } canvas.translate(mBestTextPosition[0], mBestTextPosition[1] - 24 * metricScale); mDynamicTitleLayout.draw(canvas); canvas.restore(); } if (!TextUtils.isEmpty(mSubText)) { canvas.save(); if (recalculateText) { mDynamicDetailLayout = new DynamicLayout(mSubText, mPaintDetail, ((Number) mBestTextPosition[2]).intValue(), Layout.Alignment.ALIGN_NORMAL, 1.2f, 1.0f, true); } canvas.translate(mBestTextPosition[0], mBestTextPosition[1] + 12 * metricScale); mDynamicDetailLayout.draw(canvas); canvas.restore(); } } super.dispatchDraw(canvas); }
protected void dispatchDraw(Canvas canvas) { if (showcaseX < 0 || showcaseY < 0 || isRedundant) { super.dispatchDraw(canvas); return; } //Draw the semi-transparent background canvas.drawColor(backColor); //Draw to the scale specified Matrix mm = new Matrix(); mm.postScale(scaleMultiplier, scaleMultiplier, showcaseX, showcaseY); canvas.setMatrix(mm); //Erase the area for the ring canvas.drawCircle(showcaseX, showcaseY, showcaseRadius, mEraser); boolean recalculateText = makeVoidedRect() || mAlteredText; mAlteredText = false; showcase.setBounds(voidedArea); showcase.draw(canvas); canvas.setMatrix(new Matrix()); if (!TextUtils.isEmpty(mTitleText) || !TextUtils.isEmpty(mSubText)) { if (recalculateText) mBestTextPosition = getBestTextPosition(canvas.getWidth(), canvas.getHeight()); if (!TextUtils.isEmpty(mTitleText)) { canvas.save(); if (recalculateText) { mDynamicTitleLayout = new DynamicLayout(mTitleText, mPaintTitle, (int) mBestTextPosition[2], Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, true); } canvas.translate(mBestTextPosition[0], mBestTextPosition[1] - 24 * metricScale); mDynamicTitleLayout.draw(canvas); canvas.restore(); } if (!TextUtils.isEmpty(mSubText)) { canvas.save(); if (recalculateText) { mDynamicDetailLayout = new DynamicLayout(mSubText, mPaintDetail, ((Number) mBestTextPosition[2]).intValue(), Layout.Alignment.ALIGN_NORMAL, 1.2f, 1.0f, true); } canvas.translate(mBestTextPosition[0] , mBestTextPosition[1] + 12 * metricScale + (mDynamicTitleLayout.getLineBottom(mDynamicTitleLayout.getLineCount()-1)-mDynamicTitleLayout.getLineBottom(0))); mDynamicDetailLayout.draw(canvas); canvas.restore(); } } super.dispatchDraw(canvas); }
diff --git a/yoga-core/src/main/java/org/skyscreamer/yoga/view/XmlYogaViewUtil.java b/yoga-core/src/main/java/org/skyscreamer/yoga/view/XmlYogaViewUtil.java index 651fa74..a585771 100644 --- a/yoga-core/src/main/java/org/skyscreamer/yoga/view/XmlYogaViewUtil.java +++ b/yoga-core/src/main/java/org/skyscreamer/yoga/view/XmlYogaViewUtil.java @@ -1,20 +1,22 @@ package org.skyscreamer.yoga.view; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; public class XmlYogaViewUtil { public static void write( Element rootElement, OutputStream outputStream ) throws IOException { DOMDocument domDocument = new DOMDocument(); domDocument.setRootElement( rootElement ); - domDocument.write( new OutputStreamWriter( outputStream ) ); - outputStream.flush(); + OutputStreamWriter out = new OutputStreamWriter( outputStream ); + domDocument.write( out ); + out.flush(); + out.close(); } }
true
true
public static void write( Element rootElement, OutputStream outputStream ) throws IOException { DOMDocument domDocument = new DOMDocument(); domDocument.setRootElement( rootElement ); domDocument.write( new OutputStreamWriter( outputStream ) ); outputStream.flush(); }
public static void write( Element rootElement, OutputStream outputStream ) throws IOException { DOMDocument domDocument = new DOMDocument(); domDocument.setRootElement( rootElement ); OutputStreamWriter out = new OutputStreamWriter( outputStream ); domDocument.write( out ); out.flush(); out.close(); }
diff --git a/classes/com/sapienter/jbilling/client/util/GenericMaintainAction.java b/classes/com/sapienter/jbilling/client/util/GenericMaintainAction.java index f20a823c..2cdece99 100644 --- a/classes/com/sapienter/jbilling/client/util/GenericMaintainAction.java +++ b/classes/com/sapienter/jbilling/client/util/GenericMaintainAction.java @@ -1,2045 +1,2045 @@ /* The contents of this file are subject to the Jbilling Public License Version 1.1 (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.jbilling.com/JPL/ 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. The Original Code is jbilling. The Initial Developer of the Original Code is Emiliano Conde. Portions created by Sapienter Billing Software Corp. are Copyright (C) Sapienter Billing Software Corp. All Rights Reserved. Contributor(s): ______________________________________. */ package com.sapienter.jbilling.client.util; import java.rmi.RemoteException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Vector; import javax.ejb.EJBObject; import javax.ejb.FinderException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.apache.struts.Globals; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.ActionServlet; import org.apache.struts.config.ModuleConfig; import org.apache.struts.util.RequestUtils; import org.apache.struts.validator.DynaValidatorForm; import org.apache.struts.validator.Resources; import com.sapienter.jbilling.common.JNDILookup; import com.sapienter.jbilling.common.SessionInternalError; import com.sapienter.jbilling.common.Util; import com.sapienter.jbilling.interfaces.BillingProcessSession; import com.sapienter.jbilling.interfaces.ItemSession; import com.sapienter.jbilling.interfaces.ItemSessionHome; import com.sapienter.jbilling.interfaces.NewOrderSession; import com.sapienter.jbilling.interfaces.NotificationSession; import com.sapienter.jbilling.interfaces.OrderSession; import com.sapienter.jbilling.interfaces.OrderSessionHome; import com.sapienter.jbilling.interfaces.PaymentSession; import com.sapienter.jbilling.interfaces.PaymentSessionHome; import com.sapienter.jbilling.interfaces.UserSession; import com.sapienter.jbilling.interfaces.UserSessionHome; import com.sapienter.jbilling.server.entity.AchDTO; import com.sapienter.jbilling.server.entity.BillingProcessConfigurationDTO; import com.sapienter.jbilling.server.entity.CreditCardDTO; import com.sapienter.jbilling.server.entity.InvoiceDTO; import com.sapienter.jbilling.server.entity.PartnerRangeDTO; import com.sapienter.jbilling.server.entity.PaymentInfoChequeDTO; import com.sapienter.jbilling.server.item.ItemDTOEx; import com.sapienter.jbilling.server.item.ItemPriceDTOEx; import com.sapienter.jbilling.server.item.ItemTypeDTOEx; import com.sapienter.jbilling.server.item.ItemUserPriceDTOEx; import com.sapienter.jbilling.server.item.PromotionDTOEx; import com.sapienter.jbilling.server.notification.MessageDTO; import com.sapienter.jbilling.server.notification.MessageSection; import com.sapienter.jbilling.server.order.NewOrderDTO; import com.sapienter.jbilling.server.order.OrderDTOEx; import com.sapienter.jbilling.server.order.OrderPeriodDTOEx; import com.sapienter.jbilling.server.payment.PaymentDTOEx; import com.sapienter.jbilling.server.pluggableTask.PluggableTaskDTOEx; import com.sapienter.jbilling.server.pluggableTask.PluggableTaskParameterDTOEx; import com.sapienter.jbilling.server.pluggableTask.PluggableTaskSession; import com.sapienter.jbilling.server.user.ContactDTOEx; import com.sapienter.jbilling.server.user.PartnerDTOEx; import com.sapienter.jbilling.server.user.UserDTOEx; import com.sapienter.jbilling.server.util.MapPeriodToCalendar; import com.sapienter.jbilling.server.util.OptionDTO; public class GenericMaintainAction { private ActionMapping mapping = null; private ActionServlet servlet = null; private HttpServletRequest request = null; private ActionErrors errors = null; private ActionMessages messages = null; private Logger log = null; private HttpSession session = null; private DynaValidatorForm myForm = null; private String action = null; private String mode = null; private EJBObject remoteSession = null; private String formName = null; // handy variables private Integer selectedId = null; private Integer languageId = null; private Integer entityId = null; private Integer executorId = null; public GenericMaintainAction(ActionMapping mapping, ActionForm form, HttpServletRequest request) { this.mapping = mapping; this.request = request; log = Logger.getLogger(GenericMaintainAction.class); errors = new ActionErrors(); messages = new ActionMessages(); session = request.getSession(false); myForm = (DynaValidatorForm) form; } public GenericMaintainAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, ActionServlet servlet, EJBObject remoteSession, String formName) throws Exception { this.mapping = mapping; this.request = request; this.remoteSession = remoteSession; this.servlet = servlet; log = Logger.getLogger(GenericMaintainAction.class); errors = new ActionErrors(); messages = new ActionMessages(); session = request.getSession(false); action = request.getParameter("action"); mode = request.getParameter("mode"); this.formName = formName; if (action == null) { throw new Exception("action has to be present in the request"); } if (mode == null || mode.trim().length() == 0) { throw new Exception("mode has to be present"); } if (formName == null || formName.trim().length() == 0) { throw new Exception("formName has to be present"); } selectedId = (Integer) session.getAttribute( Constants.SESSION_LIST_ID_SELECTED); languageId = (Integer) session.getAttribute( Constants.SESSION_LANGUAGE); executorId = (Integer) session.getAttribute( Constants.SESSION_LOGGED_USER_ID); entityId = (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY); myForm = (DynaValidatorForm) form; } public ActionForward process() { String forward = null; log.debug("processing action : " + action); try { if (action.equals("edit")) { try { String reset = (String) myForm.get("reset"); if (reset != null && reset.length() > 0) { forward = reset(); } } catch (IllegalArgumentException e) { } if (forward == null) { forward = edit(); } } else if(action.equals("setup")) { forward = setup(); } else if(action.equals("delete")) { forward = delete(); } else { log.error("Invalid action:" + action); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("all.internal")); } } catch (Exception e) { log.error("Exception ", e); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("all.internal")); } // Remove any error messages attribute if none are required if ((errors == null) || errors.isEmpty()) { request.removeAttribute(Globals.ERROR_KEY); } else { // Save the error messages we need request.setAttribute(Globals.ERROR_KEY, errors); } // Remove any messages attribute if none are required if ((messages == null) || messages.isEmpty()) { request.removeAttribute(Globals.MESSAGE_KEY); } else { // Save the messages we need request.setAttribute(Globals.MESSAGE_KEY, messages); } log.debug("forwarding to " + mode + "_" + forward); return mapping.findForward(mode + "_" + forward); } private String edit() throws SessionInternalError, RemoteException { String retValue = "edit"; String messageKey = null; // create a dto with the info from the form and call // the remote session ItemTypeDTOEx typeDto = null; ItemDTOEx itemDto = null; ItemUserPriceDTOEx priceDto = null; PromotionDTOEx promotionDto = null; PaymentDTOEx paymentDto = null; CreditCardDTO creditCardDto = null; AchDTO achDto = null; Boolean automaticPaymentType = null; BillingProcessConfigurationDTO configurationDto = null; MessageDTO messageDto = null; PluggableTaskDTOEx taskDto = null; String[] brandingData = null; PartnerDTOEx partnerDto = null; Object[] partnerDefaultData = null; Integer[] notificationPreferenceData = null; String[] numberingData = null; PartnerRangeDTO[] partnerRangesData = null; // do the validation, before moving any info to the dto errors = new ActionErrors(myForm.validate(mapping, request)); // this is a hack for items created for promotions if (mode.equals("item") && ((String) myForm.get("create")).equals( "promotion")) { retValue = "promotion"; log.debug("Processing an item for a promotion"); } if (mode.equals("payment") && ((String) myForm.get("direct")).equals( "yes")) { retValue = "fromOrder"; } if (!errors.isEmpty()) { return(retValue); } if (mode.equals("type")) { typeDto = new ItemTypeDTOEx(); typeDto.setDescription((String) myForm.get("name")); typeDto.setOrderLineTypeId((Integer) myForm.get("order_line_type")); typeDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); } else if (mode.equals("item")) { // an item if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } itemDto = new ItemDTOEx(); itemDto.setDescription((String) myForm.get("description")); itemDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); itemDto.setNumber((String) myForm.get("internalNumber")); itemDto.setPriceManual(new Integer(((Boolean) myForm.get ("chbx_priceManual")).booleanValue() ? 1 : 0)); itemDto.setTypes((Integer[]) myForm.get("types")); if (((String) myForm.get("percentage")).trim().length() > 0) { itemDto.setPercentage(string2float( (String) myForm.get("percentage"))); } // because of the bad idea of using the same bean for item/type/price, // the validation has to be manual if (itemDto.getTypes().length == 0) { String field = Resources.getMessage(request, "item.prompt.types"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.required", field)); } // get the prices. At least one has to be present itemDto.setPrices((Vector) myForm.get("prices")); boolean priceFlag = false; for (int f = 0; f < itemDto.getPrices().size(); f++) { String priceStr = ((ItemPriceDTOEx)itemDto.getPrices().get(f)). getPriceForm(); log.debug("Now processing item price " + f + " data:" + (ItemPriceDTOEx)itemDto.getPrices().get(f)); Float price = null; if (priceStr != null && priceStr.trim().length() > 0) { price = string2float(priceStr.trim()); if (price == null) { String field = Resources.getMessage(request, "item.prompt.price"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.float", field)); break; } else { priceFlag = true; } } ((ItemPriceDTOEx)itemDto.getPrices().get(f)).setPrice( price); } // either is a percentage or a price is required. if (!priceFlag && itemDto.getPercentage() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("item.error.price")); } } else if (mode.equals("price")) { // a price priceDto = new ItemUserPriceDTOEx(); priceDto.setPrice(string2float((String) myForm.get("price"))); priceDto.setCurrencyId((Integer) myForm.get("currencyId")); } else if (mode.equals("promotion")) { promotionDto = new PromotionDTOEx(); promotionDto.setCode((String) myForm.get("code")); promotionDto.setNotes((String) myForm.get("notes")); promotionDto.setOnce(new Integer(((Boolean) myForm.get ("chbx_once")).booleanValue() ? 1 : 0)); promotionDto.setSince(parseDate("since", "promotion.prompt.since")); promotionDto.setUntil(parseDate("until", "promotion.prompt.until")); } else if (mode.equals("payment")) { paymentDto = new PaymentDTOEx(); // the id, only for payment edits paymentDto.setId((Integer) myForm.get("id")); // set the amount paymentDto.setAmount(string2float((String) myForm.get("amount"))); // set the date paymentDto.setPaymentDate(parseDate("date", "payment.date")); if (((String) myForm.get("method")).equals("cheque")) { // create the cheque dto PaymentInfoChequeDTO chequeDto = new PaymentInfoChequeDTO(); chequeDto.setBank((String) myForm.get("bank")); chequeDto.setNumber((String) myForm.get("chequeNumber")); chequeDto.setDate(parseDate("chequeDate", "payment.cheque.date")); // set the cheque paymentDto.setCheque(chequeDto); paymentDto.setMethodId(Constants.PAYMENT_METHOD_CHEQUE); // validate required fields required(chequeDto.getNumber(),"payment.cheque.number"); required(chequeDto.getDate(), "payment.cheque.date"); // cheques now are never process realtime (may be later will support // electronic cheques paymentDto.setResultId(Constants.RESULT_ENTERED); session.setAttribute("tmp_process_now", new Boolean(false)); } else if (((String) myForm.get("method")).equals("cc")) { CreditCardDTO ccDto = new CreditCardDTO(); ccDto.setNumber((String) myForm.get("ccNumber")); ccDto.setName((String) myForm.get("ccName")); myForm.set("ccExpiry_day", "01"); // to complete the date ccDto.setExpiry(parseDate("ccExpiry", "payment.cc.date")); if (ccDto.getExpiry() != null) { // the expiry can't be past today GregorianCalendar cal = new GregorianCalendar(); cal.setTime(ccDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } paymentDto.setCreditCard(ccDto); // this will be checked when the payment is sent session.setAttribute("tmp_process_now", (Boolean) myForm.get("chbx_processNow")); // validate required fields required(ccDto.getNumber(), "payment.cc.number"); required(ccDto.getExpiry(), "payment.cc.date"); required(ccDto.getName(), "payment.cc.name"); // make sure that the cc is valid before trying to get // the payment method from it if (errors.isEmpty()) { paymentDto.setMethodId(Util.getPaymentMethod( ccDto.getNumber())); } } else if (((String) myForm.get("method")).equals("ach")) { AchDTO ach = new AchDTO(); ach.setAbaRouting((String) myForm.get("aba_code")); ach.setBankAccount((String) myForm.get("account_number")); ach.setAccountType((Integer) myForm.get("account_type")); ach.setBankName((String) myForm.get("bank_name")); ach.setAccountName((String) myForm.get("account_name")); paymentDto.setAch(ach); //this will be checked when the payment is sent session.setAttribute("tmp_process_now", new Boolean(true)); // since it is one big form for all methods, we need to // validate the required manually required(ach.getAbaRouting(), "ach.aba.prompt"); required(ach.getBankAccount(), "ach.account_number.prompt"); required(ach.getBankName(), "ach.bank_name.prompt"); required(ach.getAccountName(), "ach.account_name.prompt"); if (errors.isEmpty()) { paymentDto.setMethodId(Constants.PAYMENT_METHOD_ACH); } } // set the customer id selected in the list (not the logged) paymentDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); // specify if this is a normal payment or a refund paymentDto.setIsRefund(session.getAttribute("jsp_is_refund") == null ? new Integer(0) : new Integer(1)); log.debug("refund = " + paymentDto.getIsRefund()); // set the selected payment for refunds if (paymentDto.getIsRefund().intValue() == 1) { PaymentDTOEx refundPayment = (PaymentDTOEx) session.getAttribute( Constants.SESSION_PAYMENT_DTO); /* * Right now, to process a real-time credit card refund it has to be to * refund a previously done credit card payment. This could be * changed, to say, refund using the customer's credit card no matter * how the guy paid initially. But this might be subjet to the * processor features. * */ if (((Boolean) myForm.get("chbx_processNow")).booleanValue() && ((String) myForm.get("method")).equals("cc") && (refundPayment == null || refundPayment.getCreditCard() == null || refundPayment.getAuthorization() == null || !refundPayment.getResultId().equals(Constants.RESULT_OK))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("refund.error.realtimeNoPayment", "payment.cc.processNow")); } else { paymentDto.setPayment(refundPayment); } // refunds, I need to manually delete the list, because // in the end only the LIST_PAYMENT will be removed session.removeAttribute(Constants.SESSION_LIST_KEY + Constants.LIST_TYPE_REFUND); } // last, set the currency //If a related document is // set (invoice/payment) it'll take it from there. Otherwise it // wil inherite the one from the user paymentDto.setCurrencyId((Integer) myForm.get("currencyId")); if (paymentDto.getCurrencyId() == null) { try { paymentDto.setCurrencyId(getUser(paymentDto.getUserId()). getCurrencyId()); } catch (FinderException e) { throw new SessionInternalError(e); } } if (errors.isEmpty()) { // verify that this entity actually accepts this kind of //payment method if (!((PaymentSession) remoteSession).isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), paymentDto.getMethodId())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } // just in case there was an error log.debug("direct = " + (String) myForm.get("direct")); if (((String) myForm.get("direct")).equals("yes")) { retValue = "fromOrder"; } log.debug("now payment methodId = " + paymentDto.getMethodId()); log.debug("now paymentDto = " + paymentDto); log.debug("retValue = " + retValue); } else if (mode.equals("order")) { // this is kind of a wierd case. The dto in the session is all // it is required to edit. NewOrderDTO summary = (NewOrderDTO) session.getAttribute( Constants.SESSION_ORDER_SUMMARY); summary.setPeriod((Integer) myForm.get("period")); summary.setActiveSince(parseDate("since", "order.prompt.activeSince")); summary.setActiveUntil(parseDate("until", "order.prompt.activeUntil")); summary.setBillingTypeId((Integer) myForm.get("billingType")); summary.setPromoCode((String) myForm.get("promotion_code")); summary.setNotify(new Integer(((Boolean) myForm. get("chbx_notify")).booleanValue() ? 1 : 0)); summary.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); summary.setOwnInvoice(new Integer(((Boolean) myForm. get("chbx_own_invoice")).booleanValue() ? 1 : 0)); summary.setNotesInInvoice(new Integer(((Boolean) myForm. get("chbx_notes")).booleanValue() ? 1 : 0)); summary.setNotes((String) myForm.get("notes")); summary.setAnticipatePeriods(getInteger("anticipate_periods")); summary.setPeriodStr(getOptionDescription(summary.getPeriod(), Constants.PAGE_ORDER_PERIODS, session)); summary.setBillingTypeStr(getOptionDescription( summary.getBillingTypeId(), Constants.PAGE_BILLING_TYPE, session)); summary.setDueDateUnitId((Integer) myForm.get("due_date_unit_id")); summary.setDueDateValue(getInteger("due_date_value")); // if she wants notification, we need a date of expiration if (summary.getNotify().intValue() == 1 && summary.getActiveUntil() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.notifyWithoutDate", "order.prompt.notify")); return "edit"; } // validate the dates if there is a date of expiration if (summary.getActiveUntil() != null) { Date start = summary.getActiveSince() != null ? summary.getActiveSince() : Calendar.getInstance().getTime(); + start = Util.truncateDate(start); // it has to be grater than the starting date - if (!summary.getActiveUntil().after(Util.truncateDate(start))) { + if (!summary.getActiveUntil().after(start)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.dates", "order.prompt.activeUntil")); return "edit"; } // only if it is a recurring order if (!summary.getPeriod().equals(new Integer(1))) { // the whole period has to be a multiple of the period unit // This is true, until there is support for prorating. JNDILookup EJBFactory = null; OrderSessionHome orderHome; try { EJBFactory = JNDILookup.getFactory(false); orderHome = (OrderSessionHome) EJBFactory.lookUpHome( OrderSessionHome.class, OrderSessionHome.JNDI_NAME); OrderSession orderSession = orderHome.create(); OrderPeriodDTOEx period = orderSession.getPeriod( languageId, summary.getPeriod()); GregorianCalendar toTest = new GregorianCalendar(); toTest.setTime(start); while (toTest.getTime().before(summary.getActiveUntil())) { toTest.add(MapPeriodToCalendar.map(period.getUnitId()), period.getValue().intValue()); } if (!toTest.getTime().equals(summary.getActiveUntil())) { log.debug("Fraction of a period:" + toTest.getTime() + " until: " + summary.getActiveUntil()); errors.add(ActionErrors.GLOBAL_ERROR, - new ActionError("order.error.period", - "order.prompt.activeUntil")); + new ActionError("order.error.period")); return "edit"; } } catch (Exception e) { throw new SessionInternalError("Validating date periods", GenericMaintainAction.class, e); } } } // now process this promotion if specified if (summary.getPromoCode() != null && summary.getPromoCode().length() > 0) { try { JNDILookup EJBFactory = JNDILookup.getFactory(false); ItemSessionHome itemHome = (ItemSessionHome) EJBFactory.lookUpHome( ItemSessionHome.class, ItemSessionHome.JNDI_NAME); ItemSession itemSession = itemHome.create(); PromotionDTOEx promotion = itemSession.getPromotion( (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), summary.getPromoCode()); if (promotion == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.noExist", "order.prompt.promotion")); return "edit"; } // if this is an update or the promotion hasn't been // used by the user if (summary.getId() != null || itemSession. promotionIsAvailable(promotion.getId(), summary.getUserId(), promotion.getCode()).booleanValue()) { summary = ((NewOrderSession) remoteSession).addItem( promotion.getItemId(), new Integer(1), summary.getUserId(), entityId); session.setAttribute(Constants.SESSION_ORDER_SUMMARY, summary); } else { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.alreadyUsed", "order.prompt.promotion")); return "edit"; } } catch (Exception e) { } } return "items"; } else if (mode.equals("ach")) { achDto = new AchDTO(); achDto.setAbaRouting((String) myForm.get("aba_code")); achDto.setBankAccount((String) myForm.get("account_number")); achDto.setAccountType((Integer) myForm.get("account_type")); achDto.setBankName((String) myForm.get("bank_name")); achDto.setAccountName((String) myForm.get("account_name")); // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Constants.PAYMENT_METHOD_ACH)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } } else if (mode.equals("creditCard")) { creditCardDto = new CreditCardDTO(); creditCardDto.setName((String) myForm.get("name")); creditCardDto.setNumber((String) myForm.get("number")); myForm.set("expiry_day", "01"); // to complete the date creditCardDto.setExpiry(parseDate("expiry", "payment.cc.date")); // validate the expiry date if (creditCardDto.getExpiry() != null) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(creditCardDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Util.getPaymentMethod(creditCardDto.getNumber()))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); } else if (mode.equals("configuration")) { configurationDto = new BillingProcessConfigurationDTO(); configurationDto.setRetries(getInteger("retries")); configurationDto.setNextRunDate(parseDate("run", "process.configuration.prompt.nextRunDate")); configurationDto.setDaysForRetry(getInteger("retries_days")); configurationDto.setDaysForReport(getInteger("report_days")); configurationDto.setGenerateReport(new Integer(((Boolean) myForm. get("chbx_generateReport")).booleanValue() ? 1 : 0)); configurationDto.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); configurationDto.setOnlyRecurring(new Integer(((Boolean) myForm. get("chbx_only_recurring")).booleanValue() ? 1 : 0)); configurationDto.setInvoiceDateProcess(new Integer(((Boolean) myForm. get("chbx_invoice_date")).booleanValue() ? 1 : 0)); configurationDto.setAutoPayment(new Integer(((Boolean) myForm. get("chbx_auto_payment")).booleanValue() ? 1 : 0)); configurationDto.setAutoPaymentApplication(new Integer(((Boolean) myForm. get("chbx_payment_apply")).booleanValue() ? 1 : 0)); configurationDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); configurationDto.setPeriodUnitId(Integer.valueOf((String) myForm. get("period_unit_id"))); configurationDto.setPeriodValue(Integer.valueOf((String) myForm. get("period_unit_value"))); configurationDto.setDueDateUnitId(Integer.valueOf((String) myForm. get("due_date_unit_id"))); configurationDto.setDueDateValue(Integer.valueOf((String) myForm. get("due_date_value"))); configurationDto.setMaximumPeriods(getInteger("maximum_periods")); if (configurationDto.getAutoPayment().intValue() == 0 && configurationDto.getRetries().intValue() > 0) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("process.configuration.error.auto")); } } else if (mode.equals("notification")) { if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } messageDto = new MessageDTO(); messageDto.setLanguageId((Integer) myForm.get("language")); messageDto.setTypeId(selectedId); messageDto.setUseFlag((Boolean) myForm.get("chbx_use_flag")); // set the sections String sections[] = (String[]) myForm.get("sections"); Integer sectionNumbers[] = (Integer[]) myForm.get("sectionNumbers"); for (int f = 0; f < sections.length; f++) { messageDto.addSection(new MessageSection(sectionNumbers[f], sections[f])); log.debug("adding section:" + f + " " + sections[f]); } log.debug("message is " + messageDto); } else if (mode.equals("parameter")) { /// for pluggable task parameters taskDto = (PluggableTaskDTOEx) session.getAttribute( Constants.SESSION_PLUGGABLE_TASK_DTO); String values[] = (String[]) myForm.get("value"); String names[] = (String[]) myForm.get("name"); for (int f = 0; f < values.length; f++) { PluggableTaskParameterDTOEx parameter = (PluggableTaskParameterDTOEx) taskDto.getParameters() .get(f); parameter.setValue(values[f]); try { parameter.expandValue(); } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("task.parameter.prompt.invalid", names[f])); } } } else if (mode.equals("branding")) { brandingData = new String[2]; brandingData[0] = (String) myForm.get("css"); brandingData[1] = (String) myForm.get("logo"); } else if (mode.equals("invoiceNumbering")) { numberingData = new String[2]; numberingData[0] = (String) myForm.get("prefix"); numberingData[1] = (String) myForm.get("number"); } else if (mode.equals("notificationPreference")) { notificationPreferenceData = new Integer[8]; notificationPreferenceData[0] = new Integer(((Boolean) myForm.get("chbx_self_delivery")).booleanValue() ? 1 : 0); notificationPreferenceData[1] = new Integer(((Boolean) myForm.get("chbx_show_notes")).booleanValue() ? 1 : 0); String field = (String) myForm.get("order_days1"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[2] = null; } else { notificationPreferenceData[2] = Integer.valueOf(field); } field = (String) myForm.get("order_days2"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[3] = null; } else { notificationPreferenceData[3] = Integer.valueOf(field); } field = (String) myForm.get("order_days3"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[4] = null; } else { notificationPreferenceData[4] = Integer.valueOf(field); } // validate that the day values are incremental boolean error = false; if (notificationPreferenceData[2] != null) { if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[3].intValue()) { error = true; } } if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[3].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (error) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.orderDays.error")); } // now get the preferences related with the invoice reminders field = (String) myForm.get("first_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[5] = null; } else { notificationPreferenceData[5] = Integer.valueOf(field); } field = (String) myForm.get("next_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[6] = null; } else { notificationPreferenceData[6] = Integer.valueOf(field); } notificationPreferenceData[7] = new Integer(((Boolean) myForm.get("chbx_invoice_reminders")).booleanValue() ? 1 : 0); // validate taht if the remainders are on, the parameters are there if (notificationPreferenceData[7].intValue() == 1 && (notificationPreferenceData[5] == null || notificationPreferenceData[6] == null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.reminders.error")); } } else if (mode.equals("partnerDefault")) { partnerDefaultData = new Object[8]; if (((String) myForm.get("rate")).trim().length() > 0) { partnerDefaultData[0] = string2float((String) myForm.get( "rate")); } else { partnerDefaultData[0] = null; } if (((String) myForm.get("fee")).trim().length() > 0) { partnerDefaultData[1] = string2float((String) myForm.get( "fee")); } else { partnerDefaultData[1] = null; } partnerDefaultData[2] = (Integer) myForm.get("fee_currency"); partnerDefaultData[3] = new Integer(((Boolean) myForm.get("chbx_one_time")).booleanValue() ? 1 : 0); partnerDefaultData[4] = (Integer) myForm.get("period_unit_id"); partnerDefaultData[5] = Integer.valueOf((String) myForm.get("period_value")); partnerDefaultData[6] = new Integer(((Boolean) myForm.get("chbx_process")).booleanValue() ? 1 : 0); partnerDefaultData[7] = Integer.valueOf((String) myForm.get("clerk")); } else if (mode.equals("ranges")) { retValue = "partner"; // goes to the partner screen String from[] = (String[]) myForm.get("range_from"); String to[] = (String[]) myForm.get("range_to"); String percentage[] = (String[]) myForm.get("percentage_rate"); String referral[] = (String[]) myForm.get("referral_fee"); Vector ranges = new Vector(); for (int f = 0; f < from.length; f++) { if (from[f] != null && from[f].trim().length() > 0) { PartnerRangeDTO range = new PartnerRangeDTO(); try { range.setRangeFrom(getInteger2(from[f])); range.setRangeTo(getInteger2(to[f])); range.setPercentageRate(string2float(percentage[f])); range.setReferralFee(string2float(referral[f])); if (range.getRangeFrom() == null || range.getRangeTo() == null || (range.getPercentageRate() == null && range.getReferralFee() == null) || (range.getPercentageRate() != null && range.getReferralFee() != null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } else { ranges.add(range); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } } } partnerRangesData = new PartnerRangeDTO[ranges.size()]; ranges.toArray(partnerRangesData); if (errors.isEmpty()) { PartnerDTOEx p = new PartnerDTOEx(); p.setRanges(partnerRangesData); int ret = p.validateRanges(); if (ret == 2) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.consec")); } else if (ret == 3) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.gap")); } } if (!errors.isEmpty()) { retValue = "edit"; } } else if (mode.equals("partner")) { partnerDto = new PartnerDTOEx(); partnerDto.setBalance(string2float((String) myForm.get( "balance"))); String optField = (String) myForm.get("rate"); if (optField != null && optField.trim().length() > 0) { partnerDto.setPercentageRate(string2float(optField)); } optField = (String) myForm.get("fee"); if (optField != null && optField.trim().length() > 0) { partnerDto.setReferralFee(string2float(optField)); partnerDto.setFeeCurrencyId((Integer) myForm.get( "fee_currency")); } partnerDto.setPeriodUnitId((Integer) myForm.get( "period_unit_id")); partnerDto.setPeriodValue(Integer.valueOf((String) myForm.get( "period_value"))); partnerDto.setNextPayoutDate(parseDate("payout", "partner.prompt.nextPayout")); partnerDto.setAutomaticProcess(new Integer(((Boolean) myForm.get( "chbx_process")).booleanValue() ? 1 : 0)); partnerDto.setOneTime(new Integer(((Boolean) myForm.get( "chbx_one_time")).booleanValue() ? 1 : 0)); try { Integer clerkId = Integer.valueOf((String) myForm.get( "clerk")); UserDTOEx clerk = getUser(clerkId); if (!entityId.equals(clerk.getEntityId()) || clerk.getDeleted().intValue() == 1 || clerk.getMainRoleId().intValue() > Constants.TYPE_CLERK.intValue()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerkinvalid")); } else { partnerDto.setRelatedClerkUserId(clerkId); } } catch (FinderException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerknotfound")); } } else { throw new SessionInternalError("mode is not supported:" + mode); } // some errors could be added during the form->dto copy if (!errors.isEmpty()) { return(retValue); } // if here the validation was successfull, procede to modify the server // information if (((String) myForm.get("create")).length() > 0) { retValue = "create"; if (mode.equals("type")) { ((ItemSession) remoteSession).createType(typeDto); messageKey = "item.type.create.done"; retValue = "list"; } else if (mode.equals("item")) { // we pass a null language, so it'll pick up the one from // the entity Integer newItem = ((ItemSession) remoteSession).create( itemDto, null); messageKey = "item.create.done"; retValue = "list"; // an item can be created to create a promotion if (((String) myForm.get("create")).equals("promotion")) { retValue = "promotion"; // the id of the new item is needed later, when the // promotion record is created session.setAttribute(Constants.SESSION_ITEM_ID, newItem); } } else if (mode.equals("price")) {// a price // an item has just been selected from the generic list priceDto.setItemId((Integer) session.getAttribute( Constants.SESSION_LIST_ID_SELECTED)); // the user has been also selected from a list, but it has // its own key in the session priceDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); if (((ItemSession) remoteSession).createPrice( executorId, priceDto) != null) { messageKey = "item.user.price.create.done"; } else { messageKey = "item.user.price.create.duplicate"; } retValue = "list"; } else if (mode.equals("promotion")) { // this is the item that has been created for this promotion promotionDto.setItemId((Integer) session.getAttribute( Constants.SESSION_ITEM_ID)); ((ItemSession) remoteSession).createPromotion(executorId, (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), promotionDto); messageKey = "promotion.create.done"; retValue = "list"; } else if (mode.equals("payment")) { // this is not an update, it's the previous step of the review // payments have no updates (unmodifiable transactions). if (paymentDto.getIsRefund().intValue() == 1) { session.setAttribute(Constants.SESSION_PAYMENT_DTO_REFUND, paymentDto); } else { session.setAttribute(Constants.SESSION_PAYMENT_DTO, paymentDto); } if (((String) myForm.get("create")).equals("payout")) { retValue = "reviewPayout"; } else { retValue = "review"; } messageKey = "payment.review"; } else if (mode.equals("partner")) { // get the user dto from the session. This is the dto with the // info of the user to create UserDTOEx user = (UserDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_DTO); ContactDTOEx contact = (ContactDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_CONTACT_DTO); // add the partner information just submited to the user to be // created user.setPartnerDto(partnerDto); // make the call Integer newUserID = ((UserSession) remoteSession).create(user, contact); log.debug("Partner created = " + newUserID); session.setAttribute(Constants.SESSION_USER_ID, newUserID); messageKey = "partner.created"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } else { // this is then an update retValue = "list"; if (mode.equals("type")) { typeDto.setId(selectedId); ((ItemSession) remoteSession).updateType(executorId, typeDto); messageKey = "item.type.update.done"; } else if (mode.equals("item")) { itemDto.setId(selectedId); ((ItemSession) remoteSession).update(executorId, itemDto, (Integer) myForm.get("language")); messageKey = "item.update.done"; } else if (mode.equals("price")) { // a price priceDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePrice(executorId, priceDto); messageKey = "item.user.price.update.done"; } else if (mode.equals("promotion")) { promotionDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePromotion(executorId, promotionDto); messageKey = "promotion.update.done"; } else if (mode.equals("configuration")) { ((BillingProcessSession) remoteSession). createUpdateConfiguration(executorId, configurationDto); messageKey = "process.configuration.updated"; retValue = "edit"; } else if (mode.equals("ach")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateACH(userId, executorId, achDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_ACH, automaticPaymentType); messageKey = "ach.update.done"; retValue = "done"; } else if (mode.equals("creditCard")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateCreditCard(executorId, userId, creditCardDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_CC, automaticPaymentType); messageKey = "creditcard.update.done"; retValue = "done"; } else if (mode.equals("notification")) { ((NotificationSession) remoteSession).createUpdate( messageDto, entityId); messageKey = "notification.message.update.done"; retValue = "edit"; } else if (mode.equals("parameter")) { /// for pluggable task parameters ((PluggableTaskSession) remoteSession).updateParameters( executorId, taskDto); messageKey = "task.parameter.update.done"; retValue = "edit"; } else if (mode.equals("invoiceNumbering")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_INVOICE_PREFIX, numberingData[0].trim()); params.put(Constants.PREFERENCE_INVOICE_NUMBER, Integer.valueOf(numberingData[1])); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "invoice.numbering.updated"; retValue = "edit"; } else if (mode.equals("branding")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_CSS_LOCATION, brandingData[0].trim()); params.put(Constants.PREFERENCE_LOGO_LOCATION, brandingData[1].trim()); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "system.branding.updated"; retValue = "edit"; } else if (mode.equals("notificationPreference")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PAPER_SELF_DELIVERY, notificationPreferenceData[0]); params.put(Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE, notificationPreferenceData[1]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1, notificationPreferenceData[2]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S2, notificationPreferenceData[3]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S3, notificationPreferenceData[4]); params.put(Constants.PREFERENCE_FIRST_REMINDER, notificationPreferenceData[5]); params.put(Constants.PREFERENCE_NEXT_REMINDER, notificationPreferenceData[6]); params.put(Constants.PREFERENCE_USE_INVOICE_REMINDERS, notificationPreferenceData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "notification.preference.update"; retValue = "edit"; } else if (mode.equals("partnerDefault")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PART_DEF_RATE, partnerDefaultData[0]); params.put(Constants.PREFERENCE_PART_DEF_FEE, partnerDefaultData[1]); params.put(Constants.PREFERENCE_PART_DEF_FEE_CURR, partnerDefaultData[2]); params.put(Constants.PREFERENCE_PART_DEF_ONE_TIME, partnerDefaultData[3]); params.put(Constants.PREFERENCE_PART_DEF_PER_UNIT, partnerDefaultData[4]); params.put(Constants.PREFERENCE_PART_DEF_PER_VALUE, partnerDefaultData[5]); params.put(Constants.PREFERENCE_PART_DEF_AUTOMATIC, partnerDefaultData[6]); params.put(Constants.PREFERENCE_PART_DEF_CLERK, partnerDefaultData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "partner.default.updated"; retValue = "edit"; } else if (mode.equals("ranges")) { PartnerDTOEx partner = (PartnerDTOEx) session.getAttribute( Constants.SESSION_PARTNER_DTO); partner.setRanges(partnerRangesData); ((UserSession) remoteSession).updatePartnerRanges(executorId, partner.getId(), partnerRangesData); messageKey = "partner.ranges.updated"; retValue = "partner"; } else if (mode.equals("partner")) { partnerDto.setId((Integer) session.getAttribute( Constants.SESSION_PARTNER_ID)); ((UserSession) remoteSession).updatePartner(executorId, partnerDto); messageKey = "partner.updated"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(messageKey)); // remove a possible list so there's no old cached list session.removeAttribute(Constants.SESSION_LIST_KEY + mode); if (retValue.equals("list")) { // remove the form from the session, otherwise it might show up in a later session.removeAttribute(formName); } return retValue; } private String setup() throws SessionInternalError, RemoteException { String retValue = null; // let's create the form bean and initialized it with the // data from the database ModuleConfig moduleConfig = RequestUtils.getModuleConfig(request, servlet.getServletContext()); myForm = (DynaValidatorForm) RequestUtils.createActionForm( request, mapping, moduleConfig, servlet); retValue = "edit"; if (mode.equals("type")) { ItemTypeDTOEx dto = ((ItemSession) remoteSession).getType( selectedId); myForm.set("name", dto.getDescription()); myForm.set("order_line_type", dto.getOrderLineTypeId()); } else if (mode.equals("item")) { // the price is actually irrelevant in this call, since it's going // to be overwirtten by the user's input // in this case the currency doesn't matter, it ItemDTOEx dto = ((ItemSession) remoteSession).get(selectedId, languageId, null, null, entityId); // the prices have to be localized for (int f = 0; f < dto.getPrices().size(); f++) { ItemPriceDTOEx pr = (ItemPriceDTOEx) dto.getPrices().get(f); pr.setPriceForm(float2string(pr.getPrice())); } myForm.set("internalNumber", dto.getNumber()); myForm.set("description", dto.getDescription()); myForm.set("chbx_priceManual", new Boolean(dto. getPriceManual().intValue() > 0 ? true : false)); myForm.set("types", dto.getTypes()); myForm.set("id", dto.getId()); myForm.set("prices", dto.getPrices()); myForm.set("language", languageId); if (dto.getPercentage() != null) { myForm.set("percentage", float2string(dto.getPercentage())); } else { // otherwise it will pickup the percentage of a // previously edited item! myForm.set("percentage", null); } } else if (mode.equals("price")) { // a price // for prices, a setup is needed when creating one, because // the item information is displayed ItemDTOEx itemDto; // to get a price I need the user and the item // the item: it's just been selected from a list, so it is in selectedId // the user: Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); // check if I'm being called from the list of prices or from // a create ItemUserPriceDTOEx dto; if (session.getAttribute(Constants.SESSION_ITEM_PRICE_ID) != null) { // called from the prices list dto = ((ItemSession) remoteSession). getPrice( (Integer) session.getAttribute( Constants.SESSION_ITEM_PRICE_ID)); selectedId = dto.getItemId(); } else { // called from the items list dto = ((ItemSession) remoteSession). getPrice(userId, selectedId); } if (dto != null) { // the combination is found myForm.set("id", dto.getId()); myForm.set("price", float2string(dto.getPrice())); myForm.set("currencyId", dto.getCurrencyId()); // the id of the price is left in the session, so it can // be used later in the delete session.setAttribute(Constants.SESSION_ITEM_PRICE_ID, dto.getId()); // as a currency, as pass just a 1 because I don't care // about the price itemDto = ((ItemSession) remoteSession).get(selectedId, languageId, null, new Integer(1), entityId); } else { // it's a create // this is a create, because there no previous price for this //user-item combination. // I need the currency of the user, because the price will // be defaulted to this item's price UserDTOEx user; try { user = getUser(userId); } catch (FinderException e) { throw new SessionInternalError(e); } itemDto = ((ItemSession) remoteSession).get(selectedId, languageId, null, user.getCurrencyId(), entityId); // We then use this item's current price myForm.set("price", float2string(itemDto.getPrice())); myForm.set("currencyId", user.getCurrencyId()); retValue = "create"; } // the item dto is needed, because its data is just displayed // with <bean>, it is not edited with <html:text> session.setAttribute(Constants.SESSION_ITEM_DTO, itemDto); } else if (mode.equals("promotion")) { PromotionDTOEx dto = ((ItemSession) remoteSession). getPromotion(selectedId); myForm.set("id", dto.getId()); myForm.set("code", dto.getCode()); myForm.set("notes", dto.getNotes()); myForm.set("chbx_once", new Boolean(dto.getOnce().intValue() == 1)); // new parse the dates setFormDate("since", dto.getSince()); setFormDate("until", dto.getUntil()); // the item id will be needed if the user wants to edit the // item related with this promotion. session.setAttribute(Constants.SESSION_LIST_ID_SELECTED, dto.getItemId()); session.setAttribute(Constants.SESSION_PROMOTION_DTO, dto); } else if (mode.equals("payment")) { CreditCardDTO ccDto = null; AchDTO achDto = null; PaymentInfoChequeDTO chequeDto = null; boolean isEdit = request.getParameter("submode") == null ? false : request.getParameter("submode").equals("edit"); // if an invoice was selected, pre-populate the amount field InvoiceDTO invoiceDto = (InvoiceDTO) session.getAttribute( Constants.SESSION_INVOICE_DTO); PaymentDTOEx paymentDto = (PaymentDTOEx) session.getAttribute( Constants.SESSION_PAYMENT_DTO); if (invoiceDto != null) { log.debug("setting payment with invoice:" + invoiceDto.getId()); myForm.set("amount", float2string(invoiceDto.getBalance())); //paypal can't take i18n amounts session.setAttribute("jsp_paypay_amount", invoiceDto.getBalance()); myForm.set("currencyId", invoiceDto.getCurrencyId()); } else if (paymentDto != null) { // this works for both refunds and payouts log.debug("setting form with payment:" + paymentDto.getId()); myForm.set("id", paymentDto.getId()); myForm.set("amount", float2string(paymentDto.getAmount())); setFormDate("date", paymentDto.getPaymentDate()); myForm.set("currencyId", paymentDto.getCurrencyId()); ccDto = paymentDto.getCreditCard(); achDto = paymentDto.getAch(); chequeDto = paymentDto.getCheque(); } else { // this is not an invoice selected, it's the first call log.debug("setting payment without invoice"); // the date might come handy setFormDate("date", Calendar.getInstance().getTime()); // make the default real-time myForm.set("chbx_processNow", new Boolean(true)); // find out if this is a payment or a refund } boolean isRefund = session.getAttribute( "jsp_is_refund") != null; // populate the credit card fields with the cc in file // if this is a payment creation only if (!isRefund && !isEdit && ((String) myForm.get("ccNumber")).length() == 0) { // normal payment, get the selected user cc // if the user has a credit card, put it (this is a waste for // cheques, but it really doesn't hurt) log.debug("getting this user's cc"); UserDTOEx user; try { user = getUser((Integer) session. getAttribute(Constants.SESSION_USER_ID)); } catch (FinderException e) { throw new SessionInternalError(e); } ccDto = user.getCreditCard(); achDto = user.getAch(); } if (ccDto != null) { myForm.set("ccNumber", ccDto.getNumber()); myForm.set("ccName", ccDto.getName()); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(ccDto.getExpiry()); myForm.set("ccExpiry_month", String.valueOf(cal.get( GregorianCalendar.MONTH) + 1)); myForm.set("ccExpiry_year", String.valueOf(cal.get( GregorianCalendar.YEAR))); } if (achDto != null) { myForm.set("aba_code", achDto.getAbaRouting()); myForm.set("account_number", achDto.getBankAccount()); myForm.set("bank_name", achDto.getBankName()); myForm.set("account_name", achDto.getAccountName()); myForm.set("account_type", achDto.getAccountType()); } if (chequeDto != null) { myForm.set("bank", chequeDto.getBank()); myForm.set("chequeNumber", chequeDto.getNumber()); setFormDate("chequeDate", chequeDto.getDate()); } // if this payment is direct from an order, continue with the // page without invoice list if (request.getParameter("direct") != null) { // the date won't be shown, and it has to be initialized setFormDate("date", Calendar.getInstance().getTime()); myForm.set("method", "cc"); // add the message messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("process.invoiceGenerated")); retValue = "fromOrder"; } // if this is a payout, it has its own page if (request.getParameter("payout") != null) { retValue = "payout"; } // payment edition has a different layout if (isEdit) { retValue = "update"; } } else if (mode.equals("order")) { OrderDTOEx dto = (OrderDTOEx) session.getAttribute( Constants.SESSION_ORDER_DTO); myForm.set("period", dto.getPeriodId()); myForm.set("chbx_notify", new Boolean(dto.getNotify() == null ? false : dto.getNotify().intValue() == 1)); setFormDate("since", dto.getActiveSince()); setFormDate("until", dto.getActiveUntil()); myForm.set("due_date_unit_id", dto.getDueDateUnitId()); myForm.set("due_date_value", dto.getDueDateValue() == null ? null : dto.getDueDateValue().toString()); myForm.set("chbx_df_fm", new Boolean(dto.getDfFm() == null ? false : dto.getDfFm().intValue() == 1)); myForm.set("chbx_own_invoice", new Boolean(dto.getOwnInvoice() == null ? false : dto.getOwnInvoice().intValue() == 1)); myForm.set("chbx_notes", new Boolean(dto.getNotesInInvoice() == null ? false : dto.getNotesInInvoice().intValue() == 1)); myForm.set("notes", dto.getNotes()); myForm.set("anticipate_periods", dto.getAnticipatePeriods() == null ? null : dto.getAnticipatePeriods().toString()); myForm.set("billingType", dto.getBillingTypeId()); if (dto.getPromoCode() != null) { myForm.set("promotion_code", dto.getPromoCode()); } } else if (mode.equals("ach")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); // now only one credit card is supported per user AchDTO dto = ((UserSession) remoteSession). getACH(userId); Integer type = ((UserSession) remoteSession).getAuthPaymentType( userId); Boolean use; if (type == null || !type.equals( Constants.AUTO_PAYMENT_TYPE_ACH)) { use = new Boolean(false); } else { use = new Boolean(true); } if (dto != null) { // it could be that the user has no cc yet myForm.set("aba_code", dto.getAbaRouting()); myForm.set("account_number", dto.getBankAccount()); myForm.set("account_type", dto.getAccountType()); myForm.set("bank_name", dto.getBankName()); myForm.set("account_name", dto.getAccountName()); myForm.set("chbx_use_this", use); } else { session.removeAttribute(formName); return retValue; } } else if (mode.equals("creditCard")) { Integer userId = (request.getParameter("userId") == null) ? (Integer) session.getAttribute( Constants.SESSION_USER_ID) : Integer.valueOf(request.getParameter("userId")); // now only one credit card is supported per user CreditCardDTO dto = ((UserSession) remoteSession). getCreditCard(userId); Integer type = ((UserSession) remoteSession).getAuthPaymentType( userId); Boolean use; if (type == null || !type.equals( Constants.AUTO_PAYMENT_TYPE_CC)) { use = new Boolean(false); } else { use = new Boolean(true); } if (dto != null) { // it could be that the user has no cc yet myForm.set("number", dto.getNumber()); setFormDate("expiry", dto.getExpiry()); myForm.set("name", dto.getName()); myForm.set("chbx_use_this", use); } else { session.removeAttribute(formName); return retValue; } } else if (mode.equals("configuration")) { BillingProcessConfigurationDTO dto = ((BillingProcessSession) remoteSession). getConfigurationDto((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); setFormDate("run", dto.getNextRunDate()); myForm.set("chbx_generateReport", new Boolean( dto.getGenerateReport().intValue() == 1)); myForm.set("chbx_df_fm", dto.getDfFm() == null ? null : new Boolean(dto.getDfFm().intValue() == 1)); myForm.set("chbx_only_recurring", dto.getOnlyRecurring() == null ? null : new Boolean(dto.getOnlyRecurring().intValue() == 1)); myForm.set("chbx_invoice_date", dto.getInvoiceDateProcess() == null ? null : new Boolean(dto.getInvoiceDateProcess().intValue() == 1)); myForm.set("chbx_auto_payment", dto.getAutoPayment() == null ? null : new Boolean(dto.getAutoPayment().intValue() == 1)); myForm.set("chbx_payment_apply", dto.getAutoPaymentApplication() == null ? null : new Boolean(dto.getAutoPaymentApplication().intValue() == 1)); myForm.set("retries", dto.getRetries() == null ? null : dto.getRetries().toString()); myForm.set("retries_days", dto.getDaysForRetry() == null ? null: dto.getDaysForRetry().toString()); myForm.set("report_days", dto.getDaysForReport() == null ? null : dto.getDaysForReport().toString()); myForm.set("period_unit_id", dto.getPeriodUnitId().toString()); myForm.set("period_unit_value", dto.getPeriodValue().toString()); myForm.set("due_date_unit_id", dto.getDueDateUnitId().toString()); myForm.set("due_date_value", dto.getDueDateValue().toString()); myForm.set("maximum_periods", dto.getMaximumPeriods() == null ? null: dto.getMaximumPeriods().toString()); } else if (mode.equals("notification")) { MessageDTO dto = ((NotificationSession) remoteSession).getDTO( selectedId, languageId, entityId); myForm.set("language", languageId); myForm.set("chbx_use_flag", dto.getUseFlag()); // now cook the sections for the form's taste String sections[] = new String[dto.getContent().length]; Integer sectionNubmers[] = new Integer[dto.getContent().length]; for (int f = 0; f < sections.length; f++) { sections[f] = dto.getContent()[f].getContent(); sectionNubmers[f] = dto.getContent()[f].getSection(); } myForm.set("sections", sections); myForm.set("sectionNumbers", sectionNubmers); } else if (mode.equals("parameter")) { /// for pluggable task parameters Integer type = null; if (request.getParameter("type").equals("notification")) { type = PluggableTaskDTOEx.TYPE_EMAIL; } PluggableTaskDTOEx dto = ((PluggableTaskSession) remoteSession). getDTO(type, entityId); // show the values in the form String names[] = new String[dto.getParameters().size()]; String values[] = new String[dto.getParameters().size()]; for (int f = 0; f < dto.getParameters().size(); f++) { PluggableTaskParameterDTOEx parameter = (PluggableTaskParameterDTOEx) dto.getParameters(). get(f); names[f] = parameter.getName(); values[f] = parameter.getValue(); } myForm.set("name", names); myForm.set("value", values); // this will be needed for the update session.setAttribute(Constants.SESSION_PLUGGABLE_TASK_DTO, dto); } else if (mode.equals("branding")) { // set up which preferences do we need Integer[] preferenceIds = new Integer[2]; preferenceIds[0] = Constants.PREFERENCE_CSS_LOCATION; preferenceIds[1] = Constants.PREFERENCE_LOGO_LOCATION; // get'em HashMap result = ((UserSession) remoteSession). getEntityParameters(entityId, preferenceIds); String css = (String) result.get(Constants.PREFERENCE_CSS_LOCATION); myForm.set("css", (css == null) ? "" : css); String logo = (String) result.get(Constants.PREFERENCE_LOGO_LOCATION); myForm.set("logo", (logo == null) ? "" : logo); } else if (mode.equals("invoiceNumbering")) { // set up[ which preferences do we need Integer[] preferenceIds = new Integer[2]; preferenceIds[0] = Constants.PREFERENCE_INVOICE_PREFIX; preferenceIds[1] = Constants.PREFERENCE_INVOICE_NUMBER; // get'em HashMap result = ((UserSession) remoteSession). getEntityParameters(entityId, preferenceIds); String prefix = (String) result.get( Constants.PREFERENCE_INVOICE_PREFIX); myForm.set("prefix", (prefix == null) ? "" : prefix); String number = (String) result.get( Constants.PREFERENCE_INVOICE_NUMBER); myForm.set("number", (number == null) ? "" : number); } else if (mode.equals("notificationPreference")) { Integer[] preferenceIds = new Integer[8]; preferenceIds[0] = Constants.PREFERENCE_PAPER_SELF_DELIVERY; preferenceIds[1] = Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE; preferenceIds[2] = Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1; preferenceIds[3] = Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S2; preferenceIds[4] = Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S3; preferenceIds[5] = Constants.PREFERENCE_FIRST_REMINDER; preferenceIds[6] = Constants.PREFERENCE_NEXT_REMINDER; preferenceIds[7] = Constants.PREFERENCE_USE_INVOICE_REMINDERS; // get'em HashMap result = ((UserSession) remoteSession). getEntityParameters(entityId, preferenceIds); String value = (String) result.get( Constants.PREFERENCE_PAPER_SELF_DELIVERY); myForm.set("chbx_self_delivery", new Boolean(value.equals("1") ? true : false)); value = (String) result.get( Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE); myForm.set("chbx_show_notes", new Boolean(value.equals("1") ? true : false)); value = (String) result.get( Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1); myForm.set("order_days1", value); value = (String) result.get( Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S2); myForm.set("order_days2", value); value = (String) result.get( Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S3); myForm.set("order_days3", value); value = (String) result.get( Constants.PREFERENCE_FIRST_REMINDER); myForm.set("first_reminder", value); value = (String) result.get( Constants.PREFERENCE_NEXT_REMINDER); myForm.set("next_reminder", value); value = (String) result.get( Constants.PREFERENCE_USE_INVOICE_REMINDERS); myForm.set("chbx_invoice_reminders", new Boolean(value.equals("1") ? true : false)); } else if (mode.equals("partnerDefault")) { // set up[ which preferences do we need Integer[] preferenceIds = new Integer[8]; preferenceIds[0] = Constants.PREFERENCE_PART_DEF_RATE; preferenceIds[1] = Constants.PREFERENCE_PART_DEF_FEE; preferenceIds[2] = Constants.PREFERENCE_PART_DEF_FEE_CURR; preferenceIds[3] = Constants.PREFERENCE_PART_DEF_ONE_TIME; preferenceIds[4] = Constants.PREFERENCE_PART_DEF_PER_UNIT; preferenceIds[5] = Constants.PREFERENCE_PART_DEF_PER_VALUE; preferenceIds[6] = Constants.PREFERENCE_PART_DEF_AUTOMATIC; preferenceIds[7] = Constants.PREFERENCE_PART_DEF_CLERK; // get'em HashMap result = ((UserSession) remoteSession). getEntityParameters(entityId, preferenceIds); String value; value = (String) result.get(Constants.PREFERENCE_PART_DEF_RATE); myForm.set("rate", (value == null) ? "" : value); value = (String) result.get(Constants.PREFERENCE_PART_DEF_FEE); myForm.set("fee", (value == null) ? "" : value); value = (String) result.get(Constants.PREFERENCE_PART_DEF_FEE_CURR); myForm.set("fee_currency", Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_ONE_TIME); myForm.set("chbx_one_time", new Boolean(value.equals("1") ? true : false)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_PER_UNIT); myForm.set("period_unit_id", Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_PER_VALUE); myForm.set("period_value", (value == null) ? "" : value); value = (String) result.get(Constants.PREFERENCE_PART_DEF_AUTOMATIC); myForm.set("chbx_process", new Boolean(value.equals("1") ? true : false)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_CLERK); myForm.set("clerk", (value == null) ? "" : value); } else if (mode.equals("ranges")) { PartnerDTOEx partner = (PartnerDTOEx) session.getAttribute( Constants.SESSION_PARTNER_DTO); PartnerRangeDTO ranges[] = partner.getRanges(); String arr1[] = new String[20]; String arr2[] = new String[20]; String arr3[] = new String[20]; String arr4[] = new String[20]; // add 20 ranges to the session for edition for (int f = 0; f < 20; f++) { if (ranges != null && ranges.length > f) { arr1[f] = ranges[f].getRangeFrom().toString(); arr2[f] = ranges[f].getRangeTo().toString(); arr3[f] = float2string(ranges[f].getPercentageRate()); arr4[f] = float2string(ranges[f].getReferralFee()); } else { arr1[f] = null; arr2[f] = null; arr3[f] = null; arr4[f] = null; } } myForm.set("range_from", arr1); myForm.set("range_to", arr2); myForm.set("percentage_rate", arr3); myForm.set("referral_fee", arr4); } else if (mode.equals("partner")) { Integer partnerId = (Integer) session.getAttribute( Constants.SESSION_PARTNER_ID); PartnerDTOEx partner; if (partnerId != null) { try { partner = ((UserSession) remoteSession).getPartnerDTO( partnerId); } catch (FinderException e) { throw new SessionInternalError(e); } } else { partner = new PartnerDTOEx(); // set the values from the preferences (defaults) Integer[] preferenceIds = new Integer[8]; preferenceIds[0] = Constants.PREFERENCE_PART_DEF_RATE; preferenceIds[1] = Constants.PREFERENCE_PART_DEF_FEE; preferenceIds[2] = Constants.PREFERENCE_PART_DEF_FEE_CURR; preferenceIds[3] = Constants.PREFERENCE_PART_DEF_ONE_TIME; preferenceIds[4] = Constants.PREFERENCE_PART_DEF_PER_UNIT; preferenceIds[5] = Constants.PREFERENCE_PART_DEF_PER_VALUE; preferenceIds[6] = Constants.PREFERENCE_PART_DEF_AUTOMATIC; preferenceIds[7] = Constants.PREFERENCE_PART_DEF_CLERK; // get'em HashMap result = ((UserSession) remoteSession). getEntityParameters(entityId, preferenceIds); String value; value = (String) result.get(Constants.PREFERENCE_PART_DEF_RATE); if (value != null && value.trim().length() > 0) { partner.setPercentageRate(string2float(value)); } value = (String) result.get(Constants.PREFERENCE_PART_DEF_FEE); if (value != null && value.trim().length() > 0) { partner.setReferralFee(string2float(value)); value = (String) result.get( Constants.PREFERENCE_PART_DEF_FEE_CURR); partner.setFeeCurrencyId(Integer.valueOf(value)); } value = (String) result.get(Constants.PREFERENCE_PART_DEF_ONE_TIME); partner.setOneTime(Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_PER_UNIT); partner.setPeriodUnitId(Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_PER_VALUE); partner.setPeriodValue(Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_AUTOMATIC); partner.setAutomaticProcess(Integer.valueOf(value)); value = (String) result.get(Constants.PREFERENCE_PART_DEF_CLERK); partner.setRelatedClerkUserId(Integer.valueOf(value)); // some that are not preferences partner.setBalance(new Float(0)); retValue = "create"; } myForm.set("balance", float2string(partner.getBalance())); if (partner.getPercentageRate() != null) { myForm.set("rate", float2string(partner.getPercentageRate())); } if (partner.getReferralFee() != null) { myForm.set("fee", float2string(partner.getReferralFee())); } myForm.set("fee_currency", partner.getFeeCurrencyId()); myForm.set("chbx_one_time", new Boolean( partner.getOneTime().intValue() == 1)); myForm.set("period_unit_id", partner.getPeriodUnitId()); myForm.set("period_value", partner.getPeriodValue().toString()); myForm.set("chbx_process", new Boolean( partner.getAutomaticProcess().intValue() == 1)); myForm.set("clerk", partner.getRelatedClerkUserId().toString()); setFormDate("payout", partner.getNextPayoutDate()); } else { throw new SessionInternalError("mode is not supported:" + mode); } log.debug("setup mode=" + mode + " form name=" + formName + " dyna=" + myForm); session.setAttribute(formName, myForm); return retValue; } private String delete() throws SessionInternalError, RemoteException { String retValue = null; if (mode.equals("type")) { ((ItemSession) remoteSession).deleteType(executorId, selectedId); } else if (mode.equals("item")) { ((ItemSession) remoteSession).delete(executorId, selectedId); } else if (mode.equals("price")) { // it's a price ((ItemSession) remoteSession).deletePrice(executorId, (Integer) session.getAttribute( Constants.SESSION_ITEM_PRICE_ID)); } else if (mode.equals("promotion")) { Integer promotionId = ((PromotionDTOEx) session.getAttribute( Constants.SESSION_PROMOTION_DTO)).getId(); ((ItemSession) remoteSession).deletePromotion(executorId, promotionId); } else if (mode.equals("creditCard")) { ((UserSession) remoteSession).deleteCreditCard(executorId, (Integer) session.getAttribute(Constants.SESSION_USER_ID)); // no need to modify the auto payment type. If it is cc and // there's no cc the payment will be bypassed } else if (mode.equals("ach")) { ((UserSession) remoteSession).removeACH( (Integer) session.getAttribute(Constants.SESSION_USER_ID), executorId); } else if (mode.equals("payment")) { PaymentDTOEx paymentDto = (PaymentDTOEx) session .getAttribute(Constants.SESSION_PAYMENT_DTO); Integer id = paymentDto.getId(); ((PaymentSession) (remoteSession)).deletePayment(id); } session.removeAttribute(formName); retValue = "deleted"; // remove a possible list so there's no old cached list session.removeAttribute(Constants.SESSION_LIST_KEY + mode); return retValue; } /* * */ private String reset() throws SessionInternalError { String retValue = "edit"; myForm.initialize(mapping); if (mode.equals("payment")) { session.removeAttribute(Constants.SESSION_INVOICE_DTO); session.removeAttribute(Constants.SESSION_PAYMENT_DTO); } return retValue; } public Date parseDate(String prefix, String prompt) { Date date = null; String year = (String) myForm.get(prefix + "_year"); String month = (String) myForm.get(prefix + "_month"); String day = (String) myForm.get(prefix + "_day"); // if one of the fields have been entered, all should've been if ((year.length() > 0 && (month.length() <= 0 || day.length() <= 0)) || (month.length() > 0 && (year.length() <= 0 || day.length() <= 0)) || (day.length() > 0 && (month.length() <= 0 || year.length() <= 0)) ) { // get the localized name of this field String field = Resources.getMessage(request, prompt); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.incomplete.date", field)); return null; } if (year.length() > 0 && month.length() > 0 && day.length() > 0) { try { date = Util.getDate(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day)); } catch (Exception e) { log.info("Exception when converting the fields to integer", e); date = null; } if (date == null) { // get the localized name of this field String field = Resources.getMessage(request, prompt); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.date", field)); } } return date; } private void setFormDate(String prefix, Date date) { if (date != null) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); myForm.set(prefix + "_month", String.valueOf(cal.get( GregorianCalendar.MONTH) + 1)); myForm.set(prefix + "_day", String.valueOf(cal.get( GregorianCalendar.DAY_OF_MONTH))); myForm.set(prefix + "_year", String.valueOf(cal.get( GregorianCalendar.YEAR))); } else { myForm.set(prefix + "_month", null); myForm.set(prefix + "_day", null); myForm.set(prefix + "_year", null); } } private void required(String field, String key) { if (field == null || field.trim().length() == 0) { String name = Resources.getMessage(request, key); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.required", name)); } } private void required(Date field, String key) { if (field == null) { String name = Resources.getMessage(request, key); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.required", name)); } } public static void cleanUpSession(HttpSession session) { Enumeration entries = session.getAttributeNames(); for (String entry = (String)entries.nextElement(); entries.hasMoreElements(); entry = (String)entries.nextElement()) { if (!entry.startsWith("sys_") && !entry.startsWith("org.apache.struts")) { //Logger.getLogger(GenericMaintainAction.class).debug("removing " + entry); session.removeAttribute(entry); // you can't modify the colleciton and keep iterating with the // same reference (doahhh :p ) entries = session.getAttributeNames(); } } } public static String getOptionDescription(Integer id, String optionType, HttpSession session) throws SessionInternalError { Vector options = (Vector) session.getAttribute("SESSION_" + optionType); if (options == null) { throw new SessionInternalError("can't find the vector of options" + " in the session:" + optionType); } OptionDTO option; for (int f=0; f < options.size(); f++) { option = (OptionDTO) options.get(f); if (option.getCode().compareTo(id.toString()) == 0) { return option.getDescription(); } } throw new SessionInternalError("id " + id + " not found in options " + optionType); } private UserDTOEx getUser(Integer userId) throws SessionInternalError, FinderException { UserDTOEx retValue = null; try { JNDILookup EJBFactory = JNDILookup.getFactory(false); UserSessionHome userHome = (UserSessionHome) EJBFactory.lookUpHome( UserSessionHome.class, UserSessionHome.JNDI_NAME); UserSession userSession = userHome.create(); retValue = userSession.getUserDTOEx(userId); } catch (FinderException e) { throw new FinderException(); } catch (Exception e) { throw new SessionInternalError(e); } return retValue; } private Integer getInteger(String fieldName) { String field = (String) myForm.get(fieldName); return getInteger2(field); } private Integer getInteger2(String str) { Integer retValue; if (str != null && str.trim().length() > 0) { retValue = Integer.valueOf(str); } else { retValue = null; } return retValue; } private String float2string(Float arg) { return float2string(arg,session); } public static String float2string(Float arg, HttpSession sess) { if (arg == null) { return null; } UserDTOEx user = (UserDTOEx) sess.getAttribute( Constants.SESSION_USER_DTO); NumberFormat nf = NumberFormat.getInstance(user.getLocale()); if (nf instanceof DecimalFormat) { ((DecimalFormat) nf).applyPattern("0.00"); } return nf.format(arg); } private Float string2float(String arg) { return string2float(arg, session); } public static Float string2float(String arg, HttpSession sess) { if (arg == null || arg.trim().length() == 0) { return null; } UserDTOEx user = (UserDTOEx) sess.getAttribute( Constants.SESSION_USER_DTO); NumberFormat nf = NumberFormat.getInstance(user.getLocale()); try { return new Float(nf.parse(arg).floatValue()); } catch (ParseException e) { return null; } } public ActionErrors getErrors() { return errors; } }
false
true
private String edit() throws SessionInternalError, RemoteException { String retValue = "edit"; String messageKey = null; // create a dto with the info from the form and call // the remote session ItemTypeDTOEx typeDto = null; ItemDTOEx itemDto = null; ItemUserPriceDTOEx priceDto = null; PromotionDTOEx promotionDto = null; PaymentDTOEx paymentDto = null; CreditCardDTO creditCardDto = null; AchDTO achDto = null; Boolean automaticPaymentType = null; BillingProcessConfigurationDTO configurationDto = null; MessageDTO messageDto = null; PluggableTaskDTOEx taskDto = null; String[] brandingData = null; PartnerDTOEx partnerDto = null; Object[] partnerDefaultData = null; Integer[] notificationPreferenceData = null; String[] numberingData = null; PartnerRangeDTO[] partnerRangesData = null; // do the validation, before moving any info to the dto errors = new ActionErrors(myForm.validate(mapping, request)); // this is a hack for items created for promotions if (mode.equals("item") && ((String) myForm.get("create")).equals( "promotion")) { retValue = "promotion"; log.debug("Processing an item for a promotion"); } if (mode.equals("payment") && ((String) myForm.get("direct")).equals( "yes")) { retValue = "fromOrder"; } if (!errors.isEmpty()) { return(retValue); } if (mode.equals("type")) { typeDto = new ItemTypeDTOEx(); typeDto.setDescription((String) myForm.get("name")); typeDto.setOrderLineTypeId((Integer) myForm.get("order_line_type")); typeDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); } else if (mode.equals("item")) { // an item if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } itemDto = new ItemDTOEx(); itemDto.setDescription((String) myForm.get("description")); itemDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); itemDto.setNumber((String) myForm.get("internalNumber")); itemDto.setPriceManual(new Integer(((Boolean) myForm.get ("chbx_priceManual")).booleanValue() ? 1 : 0)); itemDto.setTypes((Integer[]) myForm.get("types")); if (((String) myForm.get("percentage")).trim().length() > 0) { itemDto.setPercentage(string2float( (String) myForm.get("percentage"))); } // because of the bad idea of using the same bean for item/type/price, // the validation has to be manual if (itemDto.getTypes().length == 0) { String field = Resources.getMessage(request, "item.prompt.types"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.required", field)); } // get the prices. At least one has to be present itemDto.setPrices((Vector) myForm.get("prices")); boolean priceFlag = false; for (int f = 0; f < itemDto.getPrices().size(); f++) { String priceStr = ((ItemPriceDTOEx)itemDto.getPrices().get(f)). getPriceForm(); log.debug("Now processing item price " + f + " data:" + (ItemPriceDTOEx)itemDto.getPrices().get(f)); Float price = null; if (priceStr != null && priceStr.trim().length() > 0) { price = string2float(priceStr.trim()); if (price == null) { String field = Resources.getMessage(request, "item.prompt.price"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.float", field)); break; } else { priceFlag = true; } } ((ItemPriceDTOEx)itemDto.getPrices().get(f)).setPrice( price); } // either is a percentage or a price is required. if (!priceFlag && itemDto.getPercentage() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("item.error.price")); } } else if (mode.equals("price")) { // a price priceDto = new ItemUserPriceDTOEx(); priceDto.setPrice(string2float((String) myForm.get("price"))); priceDto.setCurrencyId((Integer) myForm.get("currencyId")); } else if (mode.equals("promotion")) { promotionDto = new PromotionDTOEx(); promotionDto.setCode((String) myForm.get("code")); promotionDto.setNotes((String) myForm.get("notes")); promotionDto.setOnce(new Integer(((Boolean) myForm.get ("chbx_once")).booleanValue() ? 1 : 0)); promotionDto.setSince(parseDate("since", "promotion.prompt.since")); promotionDto.setUntil(parseDate("until", "promotion.prompt.until")); } else if (mode.equals("payment")) { paymentDto = new PaymentDTOEx(); // the id, only for payment edits paymentDto.setId((Integer) myForm.get("id")); // set the amount paymentDto.setAmount(string2float((String) myForm.get("amount"))); // set the date paymentDto.setPaymentDate(parseDate("date", "payment.date")); if (((String) myForm.get("method")).equals("cheque")) { // create the cheque dto PaymentInfoChequeDTO chequeDto = new PaymentInfoChequeDTO(); chequeDto.setBank((String) myForm.get("bank")); chequeDto.setNumber((String) myForm.get("chequeNumber")); chequeDto.setDate(parseDate("chequeDate", "payment.cheque.date")); // set the cheque paymentDto.setCheque(chequeDto); paymentDto.setMethodId(Constants.PAYMENT_METHOD_CHEQUE); // validate required fields required(chequeDto.getNumber(),"payment.cheque.number"); required(chequeDto.getDate(), "payment.cheque.date"); // cheques now are never process realtime (may be later will support // electronic cheques paymentDto.setResultId(Constants.RESULT_ENTERED); session.setAttribute("tmp_process_now", new Boolean(false)); } else if (((String) myForm.get("method")).equals("cc")) { CreditCardDTO ccDto = new CreditCardDTO(); ccDto.setNumber((String) myForm.get("ccNumber")); ccDto.setName((String) myForm.get("ccName")); myForm.set("ccExpiry_day", "01"); // to complete the date ccDto.setExpiry(parseDate("ccExpiry", "payment.cc.date")); if (ccDto.getExpiry() != null) { // the expiry can't be past today GregorianCalendar cal = new GregorianCalendar(); cal.setTime(ccDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } paymentDto.setCreditCard(ccDto); // this will be checked when the payment is sent session.setAttribute("tmp_process_now", (Boolean) myForm.get("chbx_processNow")); // validate required fields required(ccDto.getNumber(), "payment.cc.number"); required(ccDto.getExpiry(), "payment.cc.date"); required(ccDto.getName(), "payment.cc.name"); // make sure that the cc is valid before trying to get // the payment method from it if (errors.isEmpty()) { paymentDto.setMethodId(Util.getPaymentMethod( ccDto.getNumber())); } } else if (((String) myForm.get("method")).equals("ach")) { AchDTO ach = new AchDTO(); ach.setAbaRouting((String) myForm.get("aba_code")); ach.setBankAccount((String) myForm.get("account_number")); ach.setAccountType((Integer) myForm.get("account_type")); ach.setBankName((String) myForm.get("bank_name")); ach.setAccountName((String) myForm.get("account_name")); paymentDto.setAch(ach); //this will be checked when the payment is sent session.setAttribute("tmp_process_now", new Boolean(true)); // since it is one big form for all methods, we need to // validate the required manually required(ach.getAbaRouting(), "ach.aba.prompt"); required(ach.getBankAccount(), "ach.account_number.prompt"); required(ach.getBankName(), "ach.bank_name.prompt"); required(ach.getAccountName(), "ach.account_name.prompt"); if (errors.isEmpty()) { paymentDto.setMethodId(Constants.PAYMENT_METHOD_ACH); } } // set the customer id selected in the list (not the logged) paymentDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); // specify if this is a normal payment or a refund paymentDto.setIsRefund(session.getAttribute("jsp_is_refund") == null ? new Integer(0) : new Integer(1)); log.debug("refund = " + paymentDto.getIsRefund()); // set the selected payment for refunds if (paymentDto.getIsRefund().intValue() == 1) { PaymentDTOEx refundPayment = (PaymentDTOEx) session.getAttribute( Constants.SESSION_PAYMENT_DTO); /* * Right now, to process a real-time credit card refund it has to be to * refund a previously done credit card payment. This could be * changed, to say, refund using the customer's credit card no matter * how the guy paid initially. But this might be subjet to the * processor features. * */ if (((Boolean) myForm.get("chbx_processNow")).booleanValue() && ((String) myForm.get("method")).equals("cc") && (refundPayment == null || refundPayment.getCreditCard() == null || refundPayment.getAuthorization() == null || !refundPayment.getResultId().equals(Constants.RESULT_OK))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("refund.error.realtimeNoPayment", "payment.cc.processNow")); } else { paymentDto.setPayment(refundPayment); } // refunds, I need to manually delete the list, because // in the end only the LIST_PAYMENT will be removed session.removeAttribute(Constants.SESSION_LIST_KEY + Constants.LIST_TYPE_REFUND); } // last, set the currency //If a related document is // set (invoice/payment) it'll take it from there. Otherwise it // wil inherite the one from the user paymentDto.setCurrencyId((Integer) myForm.get("currencyId")); if (paymentDto.getCurrencyId() == null) { try { paymentDto.setCurrencyId(getUser(paymentDto.getUserId()). getCurrencyId()); } catch (FinderException e) { throw new SessionInternalError(e); } } if (errors.isEmpty()) { // verify that this entity actually accepts this kind of //payment method if (!((PaymentSession) remoteSession).isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), paymentDto.getMethodId())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } // just in case there was an error log.debug("direct = " + (String) myForm.get("direct")); if (((String) myForm.get("direct")).equals("yes")) { retValue = "fromOrder"; } log.debug("now payment methodId = " + paymentDto.getMethodId()); log.debug("now paymentDto = " + paymentDto); log.debug("retValue = " + retValue); } else if (mode.equals("order")) { // this is kind of a wierd case. The dto in the session is all // it is required to edit. NewOrderDTO summary = (NewOrderDTO) session.getAttribute( Constants.SESSION_ORDER_SUMMARY); summary.setPeriod((Integer) myForm.get("period")); summary.setActiveSince(parseDate("since", "order.prompt.activeSince")); summary.setActiveUntil(parseDate("until", "order.prompt.activeUntil")); summary.setBillingTypeId((Integer) myForm.get("billingType")); summary.setPromoCode((String) myForm.get("promotion_code")); summary.setNotify(new Integer(((Boolean) myForm. get("chbx_notify")).booleanValue() ? 1 : 0)); summary.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); summary.setOwnInvoice(new Integer(((Boolean) myForm. get("chbx_own_invoice")).booleanValue() ? 1 : 0)); summary.setNotesInInvoice(new Integer(((Boolean) myForm. get("chbx_notes")).booleanValue() ? 1 : 0)); summary.setNotes((String) myForm.get("notes")); summary.setAnticipatePeriods(getInteger("anticipate_periods")); summary.setPeriodStr(getOptionDescription(summary.getPeriod(), Constants.PAGE_ORDER_PERIODS, session)); summary.setBillingTypeStr(getOptionDescription( summary.getBillingTypeId(), Constants.PAGE_BILLING_TYPE, session)); summary.setDueDateUnitId((Integer) myForm.get("due_date_unit_id")); summary.setDueDateValue(getInteger("due_date_value")); // if she wants notification, we need a date of expiration if (summary.getNotify().intValue() == 1 && summary.getActiveUntil() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.notifyWithoutDate", "order.prompt.notify")); return "edit"; } // validate the dates if there is a date of expiration if (summary.getActiveUntil() != null) { Date start = summary.getActiveSince() != null ? summary.getActiveSince() : Calendar.getInstance().getTime(); // it has to be grater than the starting date if (!summary.getActiveUntil().after(Util.truncateDate(start))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.dates", "order.prompt.activeUntil")); return "edit"; } // only if it is a recurring order if (!summary.getPeriod().equals(new Integer(1))) { // the whole period has to be a multiple of the period unit // This is true, until there is support for prorating. JNDILookup EJBFactory = null; OrderSessionHome orderHome; try { EJBFactory = JNDILookup.getFactory(false); orderHome = (OrderSessionHome) EJBFactory.lookUpHome( OrderSessionHome.class, OrderSessionHome.JNDI_NAME); OrderSession orderSession = orderHome.create(); OrderPeriodDTOEx period = orderSession.getPeriod( languageId, summary.getPeriod()); GregorianCalendar toTest = new GregorianCalendar(); toTest.setTime(start); while (toTest.getTime().before(summary.getActiveUntil())) { toTest.add(MapPeriodToCalendar.map(period.getUnitId()), period.getValue().intValue()); } if (!toTest.getTime().equals(summary.getActiveUntil())) { log.debug("Fraction of a period:" + toTest.getTime() + " until: " + summary.getActiveUntil()); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.period", "order.prompt.activeUntil")); return "edit"; } } catch (Exception e) { throw new SessionInternalError("Validating date periods", GenericMaintainAction.class, e); } } } // now process this promotion if specified if (summary.getPromoCode() != null && summary.getPromoCode().length() > 0) { try { JNDILookup EJBFactory = JNDILookup.getFactory(false); ItemSessionHome itemHome = (ItemSessionHome) EJBFactory.lookUpHome( ItemSessionHome.class, ItemSessionHome.JNDI_NAME); ItemSession itemSession = itemHome.create(); PromotionDTOEx promotion = itemSession.getPromotion( (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), summary.getPromoCode()); if (promotion == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.noExist", "order.prompt.promotion")); return "edit"; } // if this is an update or the promotion hasn't been // used by the user if (summary.getId() != null || itemSession. promotionIsAvailable(promotion.getId(), summary.getUserId(), promotion.getCode()).booleanValue()) { summary = ((NewOrderSession) remoteSession).addItem( promotion.getItemId(), new Integer(1), summary.getUserId(), entityId); session.setAttribute(Constants.SESSION_ORDER_SUMMARY, summary); } else { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.alreadyUsed", "order.prompt.promotion")); return "edit"; } } catch (Exception e) { } } return "items"; } else if (mode.equals("ach")) { achDto = new AchDTO(); achDto.setAbaRouting((String) myForm.get("aba_code")); achDto.setBankAccount((String) myForm.get("account_number")); achDto.setAccountType((Integer) myForm.get("account_type")); achDto.setBankName((String) myForm.get("bank_name")); achDto.setAccountName((String) myForm.get("account_name")); // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Constants.PAYMENT_METHOD_ACH)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } } else if (mode.equals("creditCard")) { creditCardDto = new CreditCardDTO(); creditCardDto.setName((String) myForm.get("name")); creditCardDto.setNumber((String) myForm.get("number")); myForm.set("expiry_day", "01"); // to complete the date creditCardDto.setExpiry(parseDate("expiry", "payment.cc.date")); // validate the expiry date if (creditCardDto.getExpiry() != null) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(creditCardDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Util.getPaymentMethod(creditCardDto.getNumber()))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); } else if (mode.equals("configuration")) { configurationDto = new BillingProcessConfigurationDTO(); configurationDto.setRetries(getInteger("retries")); configurationDto.setNextRunDate(parseDate("run", "process.configuration.prompt.nextRunDate")); configurationDto.setDaysForRetry(getInteger("retries_days")); configurationDto.setDaysForReport(getInteger("report_days")); configurationDto.setGenerateReport(new Integer(((Boolean) myForm. get("chbx_generateReport")).booleanValue() ? 1 : 0)); configurationDto.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); configurationDto.setOnlyRecurring(new Integer(((Boolean) myForm. get("chbx_only_recurring")).booleanValue() ? 1 : 0)); configurationDto.setInvoiceDateProcess(new Integer(((Boolean) myForm. get("chbx_invoice_date")).booleanValue() ? 1 : 0)); configurationDto.setAutoPayment(new Integer(((Boolean) myForm. get("chbx_auto_payment")).booleanValue() ? 1 : 0)); configurationDto.setAutoPaymentApplication(new Integer(((Boolean) myForm. get("chbx_payment_apply")).booleanValue() ? 1 : 0)); configurationDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); configurationDto.setPeriodUnitId(Integer.valueOf((String) myForm. get("period_unit_id"))); configurationDto.setPeriodValue(Integer.valueOf((String) myForm. get("period_unit_value"))); configurationDto.setDueDateUnitId(Integer.valueOf((String) myForm. get("due_date_unit_id"))); configurationDto.setDueDateValue(Integer.valueOf((String) myForm. get("due_date_value"))); configurationDto.setMaximumPeriods(getInteger("maximum_periods")); if (configurationDto.getAutoPayment().intValue() == 0 && configurationDto.getRetries().intValue() > 0) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("process.configuration.error.auto")); } } else if (mode.equals("notification")) { if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } messageDto = new MessageDTO(); messageDto.setLanguageId((Integer) myForm.get("language")); messageDto.setTypeId(selectedId); messageDto.setUseFlag((Boolean) myForm.get("chbx_use_flag")); // set the sections String sections[] = (String[]) myForm.get("sections"); Integer sectionNumbers[] = (Integer[]) myForm.get("sectionNumbers"); for (int f = 0; f < sections.length; f++) { messageDto.addSection(new MessageSection(sectionNumbers[f], sections[f])); log.debug("adding section:" + f + " " + sections[f]); } log.debug("message is " + messageDto); } else if (mode.equals("parameter")) { /// for pluggable task parameters taskDto = (PluggableTaskDTOEx) session.getAttribute( Constants.SESSION_PLUGGABLE_TASK_DTO); String values[] = (String[]) myForm.get("value"); String names[] = (String[]) myForm.get("name"); for (int f = 0; f < values.length; f++) { PluggableTaskParameterDTOEx parameter = (PluggableTaskParameterDTOEx) taskDto.getParameters() .get(f); parameter.setValue(values[f]); try { parameter.expandValue(); } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("task.parameter.prompt.invalid", names[f])); } } } else if (mode.equals("branding")) { brandingData = new String[2]; brandingData[0] = (String) myForm.get("css"); brandingData[1] = (String) myForm.get("logo"); } else if (mode.equals("invoiceNumbering")) { numberingData = new String[2]; numberingData[0] = (String) myForm.get("prefix"); numberingData[1] = (String) myForm.get("number"); } else if (mode.equals("notificationPreference")) { notificationPreferenceData = new Integer[8]; notificationPreferenceData[0] = new Integer(((Boolean) myForm.get("chbx_self_delivery")).booleanValue() ? 1 : 0); notificationPreferenceData[1] = new Integer(((Boolean) myForm.get("chbx_show_notes")).booleanValue() ? 1 : 0); String field = (String) myForm.get("order_days1"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[2] = null; } else { notificationPreferenceData[2] = Integer.valueOf(field); } field = (String) myForm.get("order_days2"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[3] = null; } else { notificationPreferenceData[3] = Integer.valueOf(field); } field = (String) myForm.get("order_days3"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[4] = null; } else { notificationPreferenceData[4] = Integer.valueOf(field); } // validate that the day values are incremental boolean error = false; if (notificationPreferenceData[2] != null) { if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[3].intValue()) { error = true; } } if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[3].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (error) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.orderDays.error")); } // now get the preferences related with the invoice reminders field = (String) myForm.get("first_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[5] = null; } else { notificationPreferenceData[5] = Integer.valueOf(field); } field = (String) myForm.get("next_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[6] = null; } else { notificationPreferenceData[6] = Integer.valueOf(field); } notificationPreferenceData[7] = new Integer(((Boolean) myForm.get("chbx_invoice_reminders")).booleanValue() ? 1 : 0); // validate taht if the remainders are on, the parameters are there if (notificationPreferenceData[7].intValue() == 1 && (notificationPreferenceData[5] == null || notificationPreferenceData[6] == null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.reminders.error")); } } else if (mode.equals("partnerDefault")) { partnerDefaultData = new Object[8]; if (((String) myForm.get("rate")).trim().length() > 0) { partnerDefaultData[0] = string2float((String) myForm.get( "rate")); } else { partnerDefaultData[0] = null; } if (((String) myForm.get("fee")).trim().length() > 0) { partnerDefaultData[1] = string2float((String) myForm.get( "fee")); } else { partnerDefaultData[1] = null; } partnerDefaultData[2] = (Integer) myForm.get("fee_currency"); partnerDefaultData[3] = new Integer(((Boolean) myForm.get("chbx_one_time")).booleanValue() ? 1 : 0); partnerDefaultData[4] = (Integer) myForm.get("period_unit_id"); partnerDefaultData[5] = Integer.valueOf((String) myForm.get("period_value")); partnerDefaultData[6] = new Integer(((Boolean) myForm.get("chbx_process")).booleanValue() ? 1 : 0); partnerDefaultData[7] = Integer.valueOf((String) myForm.get("clerk")); } else if (mode.equals("ranges")) { retValue = "partner"; // goes to the partner screen String from[] = (String[]) myForm.get("range_from"); String to[] = (String[]) myForm.get("range_to"); String percentage[] = (String[]) myForm.get("percentage_rate"); String referral[] = (String[]) myForm.get("referral_fee"); Vector ranges = new Vector(); for (int f = 0; f < from.length; f++) { if (from[f] != null && from[f].trim().length() > 0) { PartnerRangeDTO range = new PartnerRangeDTO(); try { range.setRangeFrom(getInteger2(from[f])); range.setRangeTo(getInteger2(to[f])); range.setPercentageRate(string2float(percentage[f])); range.setReferralFee(string2float(referral[f])); if (range.getRangeFrom() == null || range.getRangeTo() == null || (range.getPercentageRate() == null && range.getReferralFee() == null) || (range.getPercentageRate() != null && range.getReferralFee() != null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } else { ranges.add(range); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } } } partnerRangesData = new PartnerRangeDTO[ranges.size()]; ranges.toArray(partnerRangesData); if (errors.isEmpty()) { PartnerDTOEx p = new PartnerDTOEx(); p.setRanges(partnerRangesData); int ret = p.validateRanges(); if (ret == 2) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.consec")); } else if (ret == 3) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.gap")); } } if (!errors.isEmpty()) { retValue = "edit"; } } else if (mode.equals("partner")) { partnerDto = new PartnerDTOEx(); partnerDto.setBalance(string2float((String) myForm.get( "balance"))); String optField = (String) myForm.get("rate"); if (optField != null && optField.trim().length() > 0) { partnerDto.setPercentageRate(string2float(optField)); } optField = (String) myForm.get("fee"); if (optField != null && optField.trim().length() > 0) { partnerDto.setReferralFee(string2float(optField)); partnerDto.setFeeCurrencyId((Integer) myForm.get( "fee_currency")); } partnerDto.setPeriodUnitId((Integer) myForm.get( "period_unit_id")); partnerDto.setPeriodValue(Integer.valueOf((String) myForm.get( "period_value"))); partnerDto.setNextPayoutDate(parseDate("payout", "partner.prompt.nextPayout")); partnerDto.setAutomaticProcess(new Integer(((Boolean) myForm.get( "chbx_process")).booleanValue() ? 1 : 0)); partnerDto.setOneTime(new Integer(((Boolean) myForm.get( "chbx_one_time")).booleanValue() ? 1 : 0)); try { Integer clerkId = Integer.valueOf((String) myForm.get( "clerk")); UserDTOEx clerk = getUser(clerkId); if (!entityId.equals(clerk.getEntityId()) || clerk.getDeleted().intValue() == 1 || clerk.getMainRoleId().intValue() > Constants.TYPE_CLERK.intValue()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerkinvalid")); } else { partnerDto.setRelatedClerkUserId(clerkId); } } catch (FinderException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerknotfound")); } } else { throw new SessionInternalError("mode is not supported:" + mode); } // some errors could be added during the form->dto copy if (!errors.isEmpty()) { return(retValue); } // if here the validation was successfull, procede to modify the server // information if (((String) myForm.get("create")).length() > 0) { retValue = "create"; if (mode.equals("type")) { ((ItemSession) remoteSession).createType(typeDto); messageKey = "item.type.create.done"; retValue = "list"; } else if (mode.equals("item")) { // we pass a null language, so it'll pick up the one from // the entity Integer newItem = ((ItemSession) remoteSession).create( itemDto, null); messageKey = "item.create.done"; retValue = "list"; // an item can be created to create a promotion if (((String) myForm.get("create")).equals("promotion")) { retValue = "promotion"; // the id of the new item is needed later, when the // promotion record is created session.setAttribute(Constants.SESSION_ITEM_ID, newItem); } } else if (mode.equals("price")) {// a price // an item has just been selected from the generic list priceDto.setItemId((Integer) session.getAttribute( Constants.SESSION_LIST_ID_SELECTED)); // the user has been also selected from a list, but it has // its own key in the session priceDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); if (((ItemSession) remoteSession).createPrice( executorId, priceDto) != null) { messageKey = "item.user.price.create.done"; } else { messageKey = "item.user.price.create.duplicate"; } retValue = "list"; } else if (mode.equals("promotion")) { // this is the item that has been created for this promotion promotionDto.setItemId((Integer) session.getAttribute( Constants.SESSION_ITEM_ID)); ((ItemSession) remoteSession).createPromotion(executorId, (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), promotionDto); messageKey = "promotion.create.done"; retValue = "list"; } else if (mode.equals("payment")) { // this is not an update, it's the previous step of the review // payments have no updates (unmodifiable transactions). if (paymentDto.getIsRefund().intValue() == 1) { session.setAttribute(Constants.SESSION_PAYMENT_DTO_REFUND, paymentDto); } else { session.setAttribute(Constants.SESSION_PAYMENT_DTO, paymentDto); } if (((String) myForm.get("create")).equals("payout")) { retValue = "reviewPayout"; } else { retValue = "review"; } messageKey = "payment.review"; } else if (mode.equals("partner")) { // get the user dto from the session. This is the dto with the // info of the user to create UserDTOEx user = (UserDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_DTO); ContactDTOEx contact = (ContactDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_CONTACT_DTO); // add the partner information just submited to the user to be // created user.setPartnerDto(partnerDto); // make the call Integer newUserID = ((UserSession) remoteSession).create(user, contact); log.debug("Partner created = " + newUserID); session.setAttribute(Constants.SESSION_USER_ID, newUserID); messageKey = "partner.created"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } else { // this is then an update retValue = "list"; if (mode.equals("type")) { typeDto.setId(selectedId); ((ItemSession) remoteSession).updateType(executorId, typeDto); messageKey = "item.type.update.done"; } else if (mode.equals("item")) { itemDto.setId(selectedId); ((ItemSession) remoteSession).update(executorId, itemDto, (Integer) myForm.get("language")); messageKey = "item.update.done"; } else if (mode.equals("price")) { // a price priceDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePrice(executorId, priceDto); messageKey = "item.user.price.update.done"; } else if (mode.equals("promotion")) { promotionDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePromotion(executorId, promotionDto); messageKey = "promotion.update.done"; } else if (mode.equals("configuration")) { ((BillingProcessSession) remoteSession). createUpdateConfiguration(executorId, configurationDto); messageKey = "process.configuration.updated"; retValue = "edit"; } else if (mode.equals("ach")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateACH(userId, executorId, achDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_ACH, automaticPaymentType); messageKey = "ach.update.done"; retValue = "done"; } else if (mode.equals("creditCard")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateCreditCard(executorId, userId, creditCardDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_CC, automaticPaymentType); messageKey = "creditcard.update.done"; retValue = "done"; } else if (mode.equals("notification")) { ((NotificationSession) remoteSession).createUpdate( messageDto, entityId); messageKey = "notification.message.update.done"; retValue = "edit"; } else if (mode.equals("parameter")) { /// for pluggable task parameters ((PluggableTaskSession) remoteSession).updateParameters( executorId, taskDto); messageKey = "task.parameter.update.done"; retValue = "edit"; } else if (mode.equals("invoiceNumbering")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_INVOICE_PREFIX, numberingData[0].trim()); params.put(Constants.PREFERENCE_INVOICE_NUMBER, Integer.valueOf(numberingData[1])); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "invoice.numbering.updated"; retValue = "edit"; } else if (mode.equals("branding")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_CSS_LOCATION, brandingData[0].trim()); params.put(Constants.PREFERENCE_LOGO_LOCATION, brandingData[1].trim()); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "system.branding.updated"; retValue = "edit"; } else if (mode.equals("notificationPreference")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PAPER_SELF_DELIVERY, notificationPreferenceData[0]); params.put(Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE, notificationPreferenceData[1]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1, notificationPreferenceData[2]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S2, notificationPreferenceData[3]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S3, notificationPreferenceData[4]); params.put(Constants.PREFERENCE_FIRST_REMINDER, notificationPreferenceData[5]); params.put(Constants.PREFERENCE_NEXT_REMINDER, notificationPreferenceData[6]); params.put(Constants.PREFERENCE_USE_INVOICE_REMINDERS, notificationPreferenceData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "notification.preference.update"; retValue = "edit"; } else if (mode.equals("partnerDefault")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PART_DEF_RATE, partnerDefaultData[0]); params.put(Constants.PREFERENCE_PART_DEF_FEE, partnerDefaultData[1]); params.put(Constants.PREFERENCE_PART_DEF_FEE_CURR, partnerDefaultData[2]); params.put(Constants.PREFERENCE_PART_DEF_ONE_TIME, partnerDefaultData[3]); params.put(Constants.PREFERENCE_PART_DEF_PER_UNIT, partnerDefaultData[4]); params.put(Constants.PREFERENCE_PART_DEF_PER_VALUE, partnerDefaultData[5]); params.put(Constants.PREFERENCE_PART_DEF_AUTOMATIC, partnerDefaultData[6]); params.put(Constants.PREFERENCE_PART_DEF_CLERK, partnerDefaultData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "partner.default.updated"; retValue = "edit"; } else if (mode.equals("ranges")) { PartnerDTOEx partner = (PartnerDTOEx) session.getAttribute( Constants.SESSION_PARTNER_DTO); partner.setRanges(partnerRangesData); ((UserSession) remoteSession).updatePartnerRanges(executorId, partner.getId(), partnerRangesData); messageKey = "partner.ranges.updated"; retValue = "partner"; } else if (mode.equals("partner")) { partnerDto.setId((Integer) session.getAttribute( Constants.SESSION_PARTNER_ID)); ((UserSession) remoteSession).updatePartner(executorId, partnerDto); messageKey = "partner.updated"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(messageKey)); // remove a possible list so there's no old cached list session.removeAttribute(Constants.SESSION_LIST_KEY + mode); if (retValue.equals("list")) { // remove the form from the session, otherwise it might show up in a later session.removeAttribute(formName); } return retValue; }
private String edit() throws SessionInternalError, RemoteException { String retValue = "edit"; String messageKey = null; // create a dto with the info from the form and call // the remote session ItemTypeDTOEx typeDto = null; ItemDTOEx itemDto = null; ItemUserPriceDTOEx priceDto = null; PromotionDTOEx promotionDto = null; PaymentDTOEx paymentDto = null; CreditCardDTO creditCardDto = null; AchDTO achDto = null; Boolean automaticPaymentType = null; BillingProcessConfigurationDTO configurationDto = null; MessageDTO messageDto = null; PluggableTaskDTOEx taskDto = null; String[] brandingData = null; PartnerDTOEx partnerDto = null; Object[] partnerDefaultData = null; Integer[] notificationPreferenceData = null; String[] numberingData = null; PartnerRangeDTO[] partnerRangesData = null; // do the validation, before moving any info to the dto errors = new ActionErrors(myForm.validate(mapping, request)); // this is a hack for items created for promotions if (mode.equals("item") && ((String) myForm.get("create")).equals( "promotion")) { retValue = "promotion"; log.debug("Processing an item for a promotion"); } if (mode.equals("payment") && ((String) myForm.get("direct")).equals( "yes")) { retValue = "fromOrder"; } if (!errors.isEmpty()) { return(retValue); } if (mode.equals("type")) { typeDto = new ItemTypeDTOEx(); typeDto.setDescription((String) myForm.get("name")); typeDto.setOrderLineTypeId((Integer) myForm.get("order_line_type")); typeDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); } else if (mode.equals("item")) { // an item if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } itemDto = new ItemDTOEx(); itemDto.setDescription((String) myForm.get("description")); itemDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); itemDto.setNumber((String) myForm.get("internalNumber")); itemDto.setPriceManual(new Integer(((Boolean) myForm.get ("chbx_priceManual")).booleanValue() ? 1 : 0)); itemDto.setTypes((Integer[]) myForm.get("types")); if (((String) myForm.get("percentage")).trim().length() > 0) { itemDto.setPercentage(string2float( (String) myForm.get("percentage"))); } // because of the bad idea of using the same bean for item/type/price, // the validation has to be manual if (itemDto.getTypes().length == 0) { String field = Resources.getMessage(request, "item.prompt.types"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.required", field)); } // get the prices. At least one has to be present itemDto.setPrices((Vector) myForm.get("prices")); boolean priceFlag = false; for (int f = 0; f < itemDto.getPrices().size(); f++) { String priceStr = ((ItemPriceDTOEx)itemDto.getPrices().get(f)). getPriceForm(); log.debug("Now processing item price " + f + " data:" + (ItemPriceDTOEx)itemDto.getPrices().get(f)); Float price = null; if (priceStr != null && priceStr.trim().length() > 0) { price = string2float(priceStr.trim()); if (price == null) { String field = Resources.getMessage(request, "item.prompt.price"); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.float", field)); break; } else { priceFlag = true; } } ((ItemPriceDTOEx)itemDto.getPrices().get(f)).setPrice( price); } // either is a percentage or a price is required. if (!priceFlag && itemDto.getPercentage() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("item.error.price")); } } else if (mode.equals("price")) { // a price priceDto = new ItemUserPriceDTOEx(); priceDto.setPrice(string2float((String) myForm.get("price"))); priceDto.setCurrencyId((Integer) myForm.get("currencyId")); } else if (mode.equals("promotion")) { promotionDto = new PromotionDTOEx(); promotionDto.setCode((String) myForm.get("code")); promotionDto.setNotes((String) myForm.get("notes")); promotionDto.setOnce(new Integer(((Boolean) myForm.get ("chbx_once")).booleanValue() ? 1 : 0)); promotionDto.setSince(parseDate("since", "promotion.prompt.since")); promotionDto.setUntil(parseDate("until", "promotion.prompt.until")); } else if (mode.equals("payment")) { paymentDto = new PaymentDTOEx(); // the id, only for payment edits paymentDto.setId((Integer) myForm.get("id")); // set the amount paymentDto.setAmount(string2float((String) myForm.get("amount"))); // set the date paymentDto.setPaymentDate(parseDate("date", "payment.date")); if (((String) myForm.get("method")).equals("cheque")) { // create the cheque dto PaymentInfoChequeDTO chequeDto = new PaymentInfoChequeDTO(); chequeDto.setBank((String) myForm.get("bank")); chequeDto.setNumber((String) myForm.get("chequeNumber")); chequeDto.setDate(parseDate("chequeDate", "payment.cheque.date")); // set the cheque paymentDto.setCheque(chequeDto); paymentDto.setMethodId(Constants.PAYMENT_METHOD_CHEQUE); // validate required fields required(chequeDto.getNumber(),"payment.cheque.number"); required(chequeDto.getDate(), "payment.cheque.date"); // cheques now are never process realtime (may be later will support // electronic cheques paymentDto.setResultId(Constants.RESULT_ENTERED); session.setAttribute("tmp_process_now", new Boolean(false)); } else if (((String) myForm.get("method")).equals("cc")) { CreditCardDTO ccDto = new CreditCardDTO(); ccDto.setNumber((String) myForm.get("ccNumber")); ccDto.setName((String) myForm.get("ccName")); myForm.set("ccExpiry_day", "01"); // to complete the date ccDto.setExpiry(parseDate("ccExpiry", "payment.cc.date")); if (ccDto.getExpiry() != null) { // the expiry can't be past today GregorianCalendar cal = new GregorianCalendar(); cal.setTime(ccDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } paymentDto.setCreditCard(ccDto); // this will be checked when the payment is sent session.setAttribute("tmp_process_now", (Boolean) myForm.get("chbx_processNow")); // validate required fields required(ccDto.getNumber(), "payment.cc.number"); required(ccDto.getExpiry(), "payment.cc.date"); required(ccDto.getName(), "payment.cc.name"); // make sure that the cc is valid before trying to get // the payment method from it if (errors.isEmpty()) { paymentDto.setMethodId(Util.getPaymentMethod( ccDto.getNumber())); } } else if (((String) myForm.get("method")).equals("ach")) { AchDTO ach = new AchDTO(); ach.setAbaRouting((String) myForm.get("aba_code")); ach.setBankAccount((String) myForm.get("account_number")); ach.setAccountType((Integer) myForm.get("account_type")); ach.setBankName((String) myForm.get("bank_name")); ach.setAccountName((String) myForm.get("account_name")); paymentDto.setAch(ach); //this will be checked when the payment is sent session.setAttribute("tmp_process_now", new Boolean(true)); // since it is one big form for all methods, we need to // validate the required manually required(ach.getAbaRouting(), "ach.aba.prompt"); required(ach.getBankAccount(), "ach.account_number.prompt"); required(ach.getBankName(), "ach.bank_name.prompt"); required(ach.getAccountName(), "ach.account_name.prompt"); if (errors.isEmpty()) { paymentDto.setMethodId(Constants.PAYMENT_METHOD_ACH); } } // set the customer id selected in the list (not the logged) paymentDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); // specify if this is a normal payment or a refund paymentDto.setIsRefund(session.getAttribute("jsp_is_refund") == null ? new Integer(0) : new Integer(1)); log.debug("refund = " + paymentDto.getIsRefund()); // set the selected payment for refunds if (paymentDto.getIsRefund().intValue() == 1) { PaymentDTOEx refundPayment = (PaymentDTOEx) session.getAttribute( Constants.SESSION_PAYMENT_DTO); /* * Right now, to process a real-time credit card refund it has to be to * refund a previously done credit card payment. This could be * changed, to say, refund using the customer's credit card no matter * how the guy paid initially. But this might be subjet to the * processor features. * */ if (((Boolean) myForm.get("chbx_processNow")).booleanValue() && ((String) myForm.get("method")).equals("cc") && (refundPayment == null || refundPayment.getCreditCard() == null || refundPayment.getAuthorization() == null || !refundPayment.getResultId().equals(Constants.RESULT_OK))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("refund.error.realtimeNoPayment", "payment.cc.processNow")); } else { paymentDto.setPayment(refundPayment); } // refunds, I need to manually delete the list, because // in the end only the LIST_PAYMENT will be removed session.removeAttribute(Constants.SESSION_LIST_KEY + Constants.LIST_TYPE_REFUND); } // last, set the currency //If a related document is // set (invoice/payment) it'll take it from there. Otherwise it // wil inherite the one from the user paymentDto.setCurrencyId((Integer) myForm.get("currencyId")); if (paymentDto.getCurrencyId() == null) { try { paymentDto.setCurrencyId(getUser(paymentDto.getUserId()). getCurrencyId()); } catch (FinderException e) { throw new SessionInternalError(e); } } if (errors.isEmpty()) { // verify that this entity actually accepts this kind of //payment method if (!((PaymentSession) remoteSession).isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), paymentDto.getMethodId())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } // just in case there was an error log.debug("direct = " + (String) myForm.get("direct")); if (((String) myForm.get("direct")).equals("yes")) { retValue = "fromOrder"; } log.debug("now payment methodId = " + paymentDto.getMethodId()); log.debug("now paymentDto = " + paymentDto); log.debug("retValue = " + retValue); } else if (mode.equals("order")) { // this is kind of a wierd case. The dto in the session is all // it is required to edit. NewOrderDTO summary = (NewOrderDTO) session.getAttribute( Constants.SESSION_ORDER_SUMMARY); summary.setPeriod((Integer) myForm.get("period")); summary.setActiveSince(parseDate("since", "order.prompt.activeSince")); summary.setActiveUntil(parseDate("until", "order.prompt.activeUntil")); summary.setBillingTypeId((Integer) myForm.get("billingType")); summary.setPromoCode((String) myForm.get("promotion_code")); summary.setNotify(new Integer(((Boolean) myForm. get("chbx_notify")).booleanValue() ? 1 : 0)); summary.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); summary.setOwnInvoice(new Integer(((Boolean) myForm. get("chbx_own_invoice")).booleanValue() ? 1 : 0)); summary.setNotesInInvoice(new Integer(((Boolean) myForm. get("chbx_notes")).booleanValue() ? 1 : 0)); summary.setNotes((String) myForm.get("notes")); summary.setAnticipatePeriods(getInteger("anticipate_periods")); summary.setPeriodStr(getOptionDescription(summary.getPeriod(), Constants.PAGE_ORDER_PERIODS, session)); summary.setBillingTypeStr(getOptionDescription( summary.getBillingTypeId(), Constants.PAGE_BILLING_TYPE, session)); summary.setDueDateUnitId((Integer) myForm.get("due_date_unit_id")); summary.setDueDateValue(getInteger("due_date_value")); // if she wants notification, we need a date of expiration if (summary.getNotify().intValue() == 1 && summary.getActiveUntil() == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.notifyWithoutDate", "order.prompt.notify")); return "edit"; } // validate the dates if there is a date of expiration if (summary.getActiveUntil() != null) { Date start = summary.getActiveSince() != null ? summary.getActiveSince() : Calendar.getInstance().getTime(); start = Util.truncateDate(start); // it has to be grater than the starting date if (!summary.getActiveUntil().after(start)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.dates", "order.prompt.activeUntil")); return "edit"; } // only if it is a recurring order if (!summary.getPeriod().equals(new Integer(1))) { // the whole period has to be a multiple of the period unit // This is true, until there is support for prorating. JNDILookup EJBFactory = null; OrderSessionHome orderHome; try { EJBFactory = JNDILookup.getFactory(false); orderHome = (OrderSessionHome) EJBFactory.lookUpHome( OrderSessionHome.class, OrderSessionHome.JNDI_NAME); OrderSession orderSession = orderHome.create(); OrderPeriodDTOEx period = orderSession.getPeriod( languageId, summary.getPeriod()); GregorianCalendar toTest = new GregorianCalendar(); toTest.setTime(start); while (toTest.getTime().before(summary.getActiveUntil())) { toTest.add(MapPeriodToCalendar.map(period.getUnitId()), period.getValue().intValue()); } if (!toTest.getTime().equals(summary.getActiveUntil())) { log.debug("Fraction of a period:" + toTest.getTime() + " until: " + summary.getActiveUntil()); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("order.error.period")); return "edit"; } } catch (Exception e) { throw new SessionInternalError("Validating date periods", GenericMaintainAction.class, e); } } } // now process this promotion if specified if (summary.getPromoCode() != null && summary.getPromoCode().length() > 0) { try { JNDILookup EJBFactory = JNDILookup.getFactory(false); ItemSessionHome itemHome = (ItemSessionHome) EJBFactory.lookUpHome( ItemSessionHome.class, ItemSessionHome.JNDI_NAME); ItemSession itemSession = itemHome.create(); PromotionDTOEx promotion = itemSession.getPromotion( (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), summary.getPromoCode()); if (promotion == null) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.noExist", "order.prompt.promotion")); return "edit"; } // if this is an update or the promotion hasn't been // used by the user if (summary.getId() != null || itemSession. promotionIsAvailable(promotion.getId(), summary.getUserId(), promotion.getCode()).booleanValue()) { summary = ((NewOrderSession) remoteSession).addItem( promotion.getItemId(), new Integer(1), summary.getUserId(), entityId); session.setAttribute(Constants.SESSION_ORDER_SUMMARY, summary); } else { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("promotion.error.alreadyUsed", "order.prompt.promotion")); return "edit"; } } catch (Exception e) { } } return "items"; } else if (mode.equals("ach")) { achDto = new AchDTO(); achDto.setAbaRouting((String) myForm.get("aba_code")); achDto.setBankAccount((String) myForm.get("account_number")); achDto.setAccountType((Integer) myForm.get("account_type")); achDto.setBankName((String) myForm.get("bank_name")); achDto.setAccountName((String) myForm.get("account_name")); // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Constants.PAYMENT_METHOD_ACH)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } } else if (mode.equals("creditCard")) { creditCardDto = new CreditCardDTO(); creditCardDto.setName((String) myForm.get("name")); creditCardDto.setNumber((String) myForm.get("number")); myForm.set("expiry_day", "01"); // to complete the date creditCardDto.setExpiry(parseDate("expiry", "payment.cc.date")); // validate the expiry date if (creditCardDto.getExpiry() != null) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(creditCardDto.getExpiry()); cal.add(GregorianCalendar.MONTH, 1); // add 1 month if (Calendar.getInstance().getTime().after(cal.getTime())) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("creditcard.error.expired", "payment.cc.date")); } } // verify that this entity actually accepts this kind of //payment method try { JNDILookup EJBFactory = JNDILookup.getFactory(false); PaymentSessionHome paymentHome = (PaymentSessionHome) EJBFactory.lookUpHome( PaymentSessionHome.class, PaymentSessionHome.JNDI_NAME); PaymentSession paymentSession = paymentHome.create(); if (!paymentSession.isMethodAccepted((Integer) session.getAttribute(Constants.SESSION_ENTITY_ID_KEY), Util.getPaymentMethod(creditCardDto.getNumber()))) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("payment.error.notAccepted", "payment.method")); } } catch (Exception e) { throw new SessionInternalError(e); } // update the autimatic payment type for this customer automaticPaymentType = (Boolean) myForm.get("chbx_use_this"); } else if (mode.equals("configuration")) { configurationDto = new BillingProcessConfigurationDTO(); configurationDto.setRetries(getInteger("retries")); configurationDto.setNextRunDate(parseDate("run", "process.configuration.prompt.nextRunDate")); configurationDto.setDaysForRetry(getInteger("retries_days")); configurationDto.setDaysForReport(getInteger("report_days")); configurationDto.setGenerateReport(new Integer(((Boolean) myForm. get("chbx_generateReport")).booleanValue() ? 1 : 0)); configurationDto.setDfFm(new Integer(((Boolean) myForm. get("chbx_df_fm")).booleanValue() ? 1 : 0)); configurationDto.setOnlyRecurring(new Integer(((Boolean) myForm. get("chbx_only_recurring")).booleanValue() ? 1 : 0)); configurationDto.setInvoiceDateProcess(new Integer(((Boolean) myForm. get("chbx_invoice_date")).booleanValue() ? 1 : 0)); configurationDto.setAutoPayment(new Integer(((Boolean) myForm. get("chbx_auto_payment")).booleanValue() ? 1 : 0)); configurationDto.setAutoPaymentApplication(new Integer(((Boolean) myForm. get("chbx_payment_apply")).booleanValue() ? 1 : 0)); configurationDto.setEntityId((Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY)); configurationDto.setPeriodUnitId(Integer.valueOf((String) myForm. get("period_unit_id"))); configurationDto.setPeriodValue(Integer.valueOf((String) myForm. get("period_unit_value"))); configurationDto.setDueDateUnitId(Integer.valueOf((String) myForm. get("due_date_unit_id"))); configurationDto.setDueDateValue(Integer.valueOf((String) myForm. get("due_date_value"))); configurationDto.setMaximumPeriods(getInteger("maximum_periods")); if (configurationDto.getAutoPayment().intValue() == 0 && configurationDto.getRetries().intValue() > 0) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("process.configuration.error.auto")); } } else if (mode.equals("notification")) { if (request.getParameter("reload") != null) { // this is just a change of language the requires a reload // of the bean languageId = (Integer) myForm.get("language"); return setup(); } messageDto = new MessageDTO(); messageDto.setLanguageId((Integer) myForm.get("language")); messageDto.setTypeId(selectedId); messageDto.setUseFlag((Boolean) myForm.get("chbx_use_flag")); // set the sections String sections[] = (String[]) myForm.get("sections"); Integer sectionNumbers[] = (Integer[]) myForm.get("sectionNumbers"); for (int f = 0; f < sections.length; f++) { messageDto.addSection(new MessageSection(sectionNumbers[f], sections[f])); log.debug("adding section:" + f + " " + sections[f]); } log.debug("message is " + messageDto); } else if (mode.equals("parameter")) { /// for pluggable task parameters taskDto = (PluggableTaskDTOEx) session.getAttribute( Constants.SESSION_PLUGGABLE_TASK_DTO); String values[] = (String[]) myForm.get("value"); String names[] = (String[]) myForm.get("name"); for (int f = 0; f < values.length; f++) { PluggableTaskParameterDTOEx parameter = (PluggableTaskParameterDTOEx) taskDto.getParameters() .get(f); parameter.setValue(values[f]); try { parameter.expandValue(); } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("task.parameter.prompt.invalid", names[f])); } } } else if (mode.equals("branding")) { brandingData = new String[2]; brandingData[0] = (String) myForm.get("css"); brandingData[1] = (String) myForm.get("logo"); } else if (mode.equals("invoiceNumbering")) { numberingData = new String[2]; numberingData[0] = (String) myForm.get("prefix"); numberingData[1] = (String) myForm.get("number"); } else if (mode.equals("notificationPreference")) { notificationPreferenceData = new Integer[8]; notificationPreferenceData[0] = new Integer(((Boolean) myForm.get("chbx_self_delivery")).booleanValue() ? 1 : 0); notificationPreferenceData[1] = new Integer(((Boolean) myForm.get("chbx_show_notes")).booleanValue() ? 1 : 0); String field = (String) myForm.get("order_days1"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[2] = null; } else { notificationPreferenceData[2] = Integer.valueOf(field); } field = (String) myForm.get("order_days2"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[3] = null; } else { notificationPreferenceData[3] = Integer.valueOf(field); } field = (String) myForm.get("order_days3"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[4] = null; } else { notificationPreferenceData[4] = Integer.valueOf(field); } // validate that the day values are incremental boolean error = false; if (notificationPreferenceData[2] != null) { if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[3].intValue()) { error = true; } } if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[2].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (notificationPreferenceData[3] != null) { if (notificationPreferenceData[4] != null) { if (notificationPreferenceData[3].intValue() <= notificationPreferenceData[4].intValue()) { error = true; } } } if (error) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.orderDays.error")); } // now get the preferences related with the invoice reminders field = (String) myForm.get("first_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[5] = null; } else { notificationPreferenceData[5] = Integer.valueOf(field); } field = (String) myForm.get("next_reminder"); if (field == null || field.trim().length() == 0) { notificationPreferenceData[6] = null; } else { notificationPreferenceData[6] = Integer.valueOf(field); } notificationPreferenceData[7] = new Integer(((Boolean) myForm.get("chbx_invoice_reminders")).booleanValue() ? 1 : 0); // validate taht if the remainders are on, the parameters are there if (notificationPreferenceData[7].intValue() == 1 && (notificationPreferenceData[5] == null || notificationPreferenceData[6] == null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("notification.reminders.error")); } } else if (mode.equals("partnerDefault")) { partnerDefaultData = new Object[8]; if (((String) myForm.get("rate")).trim().length() > 0) { partnerDefaultData[0] = string2float((String) myForm.get( "rate")); } else { partnerDefaultData[0] = null; } if (((String) myForm.get("fee")).trim().length() > 0) { partnerDefaultData[1] = string2float((String) myForm.get( "fee")); } else { partnerDefaultData[1] = null; } partnerDefaultData[2] = (Integer) myForm.get("fee_currency"); partnerDefaultData[3] = new Integer(((Boolean) myForm.get("chbx_one_time")).booleanValue() ? 1 : 0); partnerDefaultData[4] = (Integer) myForm.get("period_unit_id"); partnerDefaultData[5] = Integer.valueOf((String) myForm.get("period_value")); partnerDefaultData[6] = new Integer(((Boolean) myForm.get("chbx_process")).booleanValue() ? 1 : 0); partnerDefaultData[7] = Integer.valueOf((String) myForm.get("clerk")); } else if (mode.equals("ranges")) { retValue = "partner"; // goes to the partner screen String from[] = (String[]) myForm.get("range_from"); String to[] = (String[]) myForm.get("range_to"); String percentage[] = (String[]) myForm.get("percentage_rate"); String referral[] = (String[]) myForm.get("referral_fee"); Vector ranges = new Vector(); for (int f = 0; f < from.length; f++) { if (from[f] != null && from[f].trim().length() > 0) { PartnerRangeDTO range = new PartnerRangeDTO(); try { range.setRangeFrom(getInteger2(from[f])); range.setRangeTo(getInteger2(to[f])); range.setPercentageRate(string2float(percentage[f])); range.setReferralFee(string2float(referral[f])); if (range.getRangeFrom() == null || range.getRangeTo() == null || (range.getPercentageRate() == null && range.getReferralFee() == null) || (range.getPercentageRate() != null && range.getReferralFee() != null)) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } else { ranges.add(range); } } catch (NumberFormatException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error", new Integer(f + 1))); } } } partnerRangesData = new PartnerRangeDTO[ranges.size()]; ranges.toArray(partnerRangesData); if (errors.isEmpty()) { PartnerDTOEx p = new PartnerDTOEx(); p.setRanges(partnerRangesData); int ret = p.validateRanges(); if (ret == 2) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.consec")); } else if (ret == 3) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.ranges.error.gap")); } } if (!errors.isEmpty()) { retValue = "edit"; } } else if (mode.equals("partner")) { partnerDto = new PartnerDTOEx(); partnerDto.setBalance(string2float((String) myForm.get( "balance"))); String optField = (String) myForm.get("rate"); if (optField != null && optField.trim().length() > 0) { partnerDto.setPercentageRate(string2float(optField)); } optField = (String) myForm.get("fee"); if (optField != null && optField.trim().length() > 0) { partnerDto.setReferralFee(string2float(optField)); partnerDto.setFeeCurrencyId((Integer) myForm.get( "fee_currency")); } partnerDto.setPeriodUnitId((Integer) myForm.get( "period_unit_id")); partnerDto.setPeriodValue(Integer.valueOf((String) myForm.get( "period_value"))); partnerDto.setNextPayoutDate(parseDate("payout", "partner.prompt.nextPayout")); partnerDto.setAutomaticProcess(new Integer(((Boolean) myForm.get( "chbx_process")).booleanValue() ? 1 : 0)); partnerDto.setOneTime(new Integer(((Boolean) myForm.get( "chbx_one_time")).booleanValue() ? 1 : 0)); try { Integer clerkId = Integer.valueOf((String) myForm.get( "clerk")); UserDTOEx clerk = getUser(clerkId); if (!entityId.equals(clerk.getEntityId()) || clerk.getDeleted().intValue() == 1 || clerk.getMainRoleId().intValue() > Constants.TYPE_CLERK.intValue()) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerkinvalid")); } else { partnerDto.setRelatedClerkUserId(clerkId); } } catch (FinderException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("partner.error.clerknotfound")); } } else { throw new SessionInternalError("mode is not supported:" + mode); } // some errors could be added during the form->dto copy if (!errors.isEmpty()) { return(retValue); } // if here the validation was successfull, procede to modify the server // information if (((String) myForm.get("create")).length() > 0) { retValue = "create"; if (mode.equals("type")) { ((ItemSession) remoteSession).createType(typeDto); messageKey = "item.type.create.done"; retValue = "list"; } else if (mode.equals("item")) { // we pass a null language, so it'll pick up the one from // the entity Integer newItem = ((ItemSession) remoteSession).create( itemDto, null); messageKey = "item.create.done"; retValue = "list"; // an item can be created to create a promotion if (((String) myForm.get("create")).equals("promotion")) { retValue = "promotion"; // the id of the new item is needed later, when the // promotion record is created session.setAttribute(Constants.SESSION_ITEM_ID, newItem); } } else if (mode.equals("price")) {// a price // an item has just been selected from the generic list priceDto.setItemId((Integer) session.getAttribute( Constants.SESSION_LIST_ID_SELECTED)); // the user has been also selected from a list, but it has // its own key in the session priceDto.setUserId((Integer) session.getAttribute( Constants.SESSION_USER_ID)); if (((ItemSession) remoteSession).createPrice( executorId, priceDto) != null) { messageKey = "item.user.price.create.done"; } else { messageKey = "item.user.price.create.duplicate"; } retValue = "list"; } else if (mode.equals("promotion")) { // this is the item that has been created for this promotion promotionDto.setItemId((Integer) session.getAttribute( Constants.SESSION_ITEM_ID)); ((ItemSession) remoteSession).createPromotion(executorId, (Integer) session.getAttribute( Constants.SESSION_ENTITY_ID_KEY), promotionDto); messageKey = "promotion.create.done"; retValue = "list"; } else if (mode.equals("payment")) { // this is not an update, it's the previous step of the review // payments have no updates (unmodifiable transactions). if (paymentDto.getIsRefund().intValue() == 1) { session.setAttribute(Constants.SESSION_PAYMENT_DTO_REFUND, paymentDto); } else { session.setAttribute(Constants.SESSION_PAYMENT_DTO, paymentDto); } if (((String) myForm.get("create")).equals("payout")) { retValue = "reviewPayout"; } else { retValue = "review"; } messageKey = "payment.review"; } else if (mode.equals("partner")) { // get the user dto from the session. This is the dto with the // info of the user to create UserDTOEx user = (UserDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_DTO); ContactDTOEx contact = (ContactDTOEx) session.getAttribute( Constants.SESSION_CUSTOMER_CONTACT_DTO); // add the partner information just submited to the user to be // created user.setPartnerDto(partnerDto); // make the call Integer newUserID = ((UserSession) remoteSession).create(user, contact); log.debug("Partner created = " + newUserID); session.setAttribute(Constants.SESSION_USER_ID, newUserID); messageKey = "partner.created"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } else { // this is then an update retValue = "list"; if (mode.equals("type")) { typeDto.setId(selectedId); ((ItemSession) remoteSession).updateType(executorId, typeDto); messageKey = "item.type.update.done"; } else if (mode.equals("item")) { itemDto.setId(selectedId); ((ItemSession) remoteSession).update(executorId, itemDto, (Integer) myForm.get("language")); messageKey = "item.update.done"; } else if (mode.equals("price")) { // a price priceDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePrice(executorId, priceDto); messageKey = "item.user.price.update.done"; } else if (mode.equals("promotion")) { promotionDto.setId((Integer) myForm.get("id")); ((ItemSession) remoteSession).updatePromotion(executorId, promotionDto); messageKey = "promotion.update.done"; } else if (mode.equals("configuration")) { ((BillingProcessSession) remoteSession). createUpdateConfiguration(executorId, configurationDto); messageKey = "process.configuration.updated"; retValue = "edit"; } else if (mode.equals("ach")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateACH(userId, executorId, achDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_ACH, automaticPaymentType); messageKey = "ach.update.done"; retValue = "done"; } else if (mode.equals("creditCard")) { Integer userId = (Integer) session.getAttribute( Constants.SESSION_USER_ID); ((UserSession) remoteSession).updateCreditCard(executorId, userId, creditCardDto); ((UserSession) remoteSession).setAuthPaymentType(userId, Constants.AUTO_PAYMENT_TYPE_CC, automaticPaymentType); messageKey = "creditcard.update.done"; retValue = "done"; } else if (mode.equals("notification")) { ((NotificationSession) remoteSession).createUpdate( messageDto, entityId); messageKey = "notification.message.update.done"; retValue = "edit"; } else if (mode.equals("parameter")) { /// for pluggable task parameters ((PluggableTaskSession) remoteSession).updateParameters( executorId, taskDto); messageKey = "task.parameter.update.done"; retValue = "edit"; } else if (mode.equals("invoiceNumbering")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_INVOICE_PREFIX, numberingData[0].trim()); params.put(Constants.PREFERENCE_INVOICE_NUMBER, Integer.valueOf(numberingData[1])); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "invoice.numbering.updated"; retValue = "edit"; } else if (mode.equals("branding")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_CSS_LOCATION, brandingData[0].trim()); params.put(Constants.PREFERENCE_LOGO_LOCATION, brandingData[1].trim()); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "system.branding.updated"; retValue = "edit"; } else if (mode.equals("notificationPreference")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PAPER_SELF_DELIVERY, notificationPreferenceData[0]); params.put(Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE, notificationPreferenceData[1]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1, notificationPreferenceData[2]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S2, notificationPreferenceData[3]); params.put(Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S3, notificationPreferenceData[4]); params.put(Constants.PREFERENCE_FIRST_REMINDER, notificationPreferenceData[5]); params.put(Constants.PREFERENCE_NEXT_REMINDER, notificationPreferenceData[6]); params.put(Constants.PREFERENCE_USE_INVOICE_REMINDERS, notificationPreferenceData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "notification.preference.update"; retValue = "edit"; } else if (mode.equals("partnerDefault")) { HashMap params = new HashMap(); params.put(Constants.PREFERENCE_PART_DEF_RATE, partnerDefaultData[0]); params.put(Constants.PREFERENCE_PART_DEF_FEE, partnerDefaultData[1]); params.put(Constants.PREFERENCE_PART_DEF_FEE_CURR, partnerDefaultData[2]); params.put(Constants.PREFERENCE_PART_DEF_ONE_TIME, partnerDefaultData[3]); params.put(Constants.PREFERENCE_PART_DEF_PER_UNIT, partnerDefaultData[4]); params.put(Constants.PREFERENCE_PART_DEF_PER_VALUE, partnerDefaultData[5]); params.put(Constants.PREFERENCE_PART_DEF_AUTOMATIC, partnerDefaultData[6]); params.put(Constants.PREFERENCE_PART_DEF_CLERK, partnerDefaultData[7]); ((UserSession) remoteSession).setEntityParameters(entityId, params); messageKey = "partner.default.updated"; retValue = "edit"; } else if (mode.equals("ranges")) { PartnerDTOEx partner = (PartnerDTOEx) session.getAttribute( Constants.SESSION_PARTNER_DTO); partner.setRanges(partnerRangesData); ((UserSession) remoteSession).updatePartnerRanges(executorId, partner.getId(), partnerRangesData); messageKey = "partner.ranges.updated"; retValue = "partner"; } else if (mode.equals("partner")) { partnerDto.setId((Integer) session.getAttribute( Constants.SESSION_PARTNER_ID)); ((UserSession) remoteSession).updatePartner(executorId, partnerDto); messageKey = "partner.updated"; if (request.getParameter("ranges") == null) { retValue = "list"; } else { retValue = "ranges"; } } } messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(messageKey)); // remove a possible list so there's no old cached list session.removeAttribute(Constants.SESSION_LIST_KEY + mode); if (retValue.equals("list")) { // remove the form from the session, otherwise it might show up in a later session.removeAttribute(formName); } return retValue; }
diff --git a/src/ca/wacos/NametagUtils.java b/src/ca/wacos/NametagUtils.java index 9feb5b1..f0ff659 100644 --- a/src/ca/wacos/NametagUtils.java +++ b/src/ca/wacos/NametagUtils.java @@ -1,215 +1,227 @@ package ca.wacos; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.UUID; import net.minecraft.server.v1_5_R2.NBTCompressedStreamTools; import net.minecraft.server.v1_5_R2.NBTTagCompound; import net.minecraft.server.v1_5_R2.NBTTagDouble; import net.minecraft.server.v1_5_R2.NBTTagFloat; import net.minecraft.server.v1_5_R2.NBTTagList; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; public class NametagUtils { static String formatColors(String str) { char[] chars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'n', 'r', 'l', 'k', 'o', 'm'}; char[] array = str.toCharArray(); for (int t = 0; t < array.length - 1; t++) { if (array[t] == '&') { for (char c : chars) { if (c == array[t + 1]) array[t] = '§'; } } } return new String(array); } static void box(String [] paragraph, String title) { ArrayList<String> buffer = new ArrayList<String>(); String at = ""; int side1 = (int) Math.round(25 - ((title.length() + 4) / 2d)); int side2 = (int) (26 - ((title.length() + 4) / 2d)); at += '+'; for (int t = 0; t < side1; t++) at += '-'; at += "{ "; at += title; at += " }"; for (int t = 0; t < side2; t++) at += '-'; at += '+'; buffer.add(at); at = ""; buffer.add("| |"); for (String s : paragraph) { at += "| "; int left = 49; for (int t = 0; t < s.length(); t++) { at += s.charAt(t); left--; if (left == 0) { at += " |"; buffer.add(at); at = ""; at += "| "; left = 49; } } while (left-- > 0) { at += ' '; } at += " |"; buffer.add(at); at = ""; } buffer.add("| |"); buffer.add("+---------------------------------------------------+"); System.out.println(" "); for (String line : buffer.toArray(new String[buffer.size()])) { System.out.println(line); } System.out.println(" "); } static String trim(String input) { if (input.length() > 16) { String temp = input; input = ""; for (int t = 0; t < 16; t++) input += temp.charAt(t); } return input; } static String getValue(String rawValue) { if (!(rawValue.startsWith("\"") && rawValue.endsWith("\""))) { return rawValue; } rawValue = rawValue.trim(); String f1 = ""; for (int t = 1; t < rawValue.length() - 1; t++) { f1 += rawValue.charAt(t); } return f1; } static Location getOfflineLoc(String s) { File file = new File(Bukkit.getWorlds().get(0).getName() + "/players/" + s + ".dat"); if (!file.exists()) return null; try { NBTTagCompound compound = NBTCompressedStreamTools.a(new FileInputStream(file)); World w = Bukkit.getWorld(new UUID(compound.getLong("WorldUUIDMost"), compound.getLong("WorldUUIDLeast"))); NBTTagList list = compound.getList("Pos"); double x = ((NBTTagDouble)list.get(0)).data; double y = ((NBTTagDouble)list.get(1)).data; double z =((NBTTagDouble)list.get(2)).data; list = compound.getList("Rotation"); float yaw = ((NBTTagFloat)list.get(0)).data; float pitch = ((NBTTagFloat)list.get(1)).data; if (GroupLoader.DEBUG) System.out.println("Loaded location from player file: " + w.getName() + ", " + x + ", " + y + ", " + z + ", " + yaw + ", " + pitch); Location loc = new Location(w, x, y, z, yaw, pitch); return loc; } catch (FileNotFoundException e) { e.printStackTrace(); return null; } } static void setOfflineLoc(String s, Location l) { File file = new File(Bukkit.getWorlds().get(0).getName() + "/players/" + s + ".dat"); if (!file.exists()) return; try { NBTTagCompound compound = NBTCompressedStreamTools.a(new FileInputStream(file)); compound.set("Pos", new NBTTagList()); compound.getList("Pos").add(new NBTTagDouble("", l.getX())); compound.getList("Pos").add(new NBTTagDouble("", l.getY())); compound.getList("Pos").add(new NBTTagDouble("", l.getZ())); compound.set("Rotation", new NBTTagList()); compound.getList("Rotation").add(new NBTTagFloat("", l.getYaw())); compound.getList("Rotation").add(new NBTTagFloat("", l.getPitch())); compound.setLong("WorldUUIDLeast", l.getWorld().getUID().getLeastSignificantBits()); compound.setLong("WorldUUIDMost", l.getWorld().getUID().getMostSignificantBits()); NBTCompressedStreamTools.a(compound, new FileOutputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } } static boolean compareVersion(String old, String newer) { ArrayList<Integer> oldValues = new ArrayList<Integer>(); ArrayList<Integer> newValues = new ArrayList<Integer>(); String at = ""; for (char c : old.toCharArray()) { if (c != '.') { at += c; } else { try { oldValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } + try { + oldValues.add(Integer.parseInt(at)); + } + catch (Exception e) { + return false; + } at = ""; for (char c : newer.toCharArray()) { if (c != '.') { at += c; } else { try { newValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } + try { + newValues.add(Integer.parseInt(at)); + } + catch (Exception e) { + return false; + } int size = oldValues.size(); boolean defaultToOld = true; if (newValues.size() < size) { size = newValues.size(); defaultToOld = false; } for (int t = 0; t < size; t++) { if (oldValues.get(t) < newValues.get(t)) { return true; } else if (oldValues.get(t) > newValues.get(t)) { return false; } } if (oldValues.size() == newValues.size()) return false; if (defaultToOld) return true; else return false; } }
false
true
static boolean compareVersion(String old, String newer) { ArrayList<Integer> oldValues = new ArrayList<Integer>(); ArrayList<Integer> newValues = new ArrayList<Integer>(); String at = ""; for (char c : old.toCharArray()) { if (c != '.') { at += c; } else { try { oldValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } at = ""; for (char c : newer.toCharArray()) { if (c != '.') { at += c; } else { try { newValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } int size = oldValues.size(); boolean defaultToOld = true; if (newValues.size() < size) { size = newValues.size(); defaultToOld = false; } for (int t = 0; t < size; t++) { if (oldValues.get(t) < newValues.get(t)) { return true; } else if (oldValues.get(t) > newValues.get(t)) { return false; } } if (oldValues.size() == newValues.size()) return false; if (defaultToOld) return true; else return false; }
static boolean compareVersion(String old, String newer) { ArrayList<Integer> oldValues = new ArrayList<Integer>(); ArrayList<Integer> newValues = new ArrayList<Integer>(); String at = ""; for (char c : old.toCharArray()) { if (c != '.') { at += c; } else { try { oldValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } try { oldValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; for (char c : newer.toCharArray()) { if (c != '.') { at += c; } else { try { newValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } at = ""; } } try { newValues.add(Integer.parseInt(at)); } catch (Exception e) { return false; } int size = oldValues.size(); boolean defaultToOld = true; if (newValues.size() < size) { size = newValues.size(); defaultToOld = false; } for (int t = 0; t < size; t++) { if (oldValues.get(t) < newValues.get(t)) { return true; } else if (oldValues.get(t) > newValues.get(t)) { return false; } } if (oldValues.size() == newValues.size()) return false; if (defaultToOld) return true; else return false; }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/AbstractTaskListFilter.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/AbstractTaskListFilter.java index 3e14895fa..683b3a214 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/AbstractTaskListFilter.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasklist/ui/AbstractTaskListFilter.java @@ -1,33 +1,34 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia 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: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.tasklist.ui; import org.eclipse.mylar.internal.tasklist.ui.actions.NewLocalTaskAction; import org.eclipse.mylar.provisional.tasklist.ITask; import org.eclipse.mylar.provisional.tasklist.MylarTaskListPlugin; /** * Custom filters are used so that the "Find:" filter can 'see through' * any filters that may have been applied. * * @author Mik Kersten */ public abstract class AbstractTaskListFilter { public abstract boolean select(Object element); protected boolean shouldAlwaysShow(ITask task) { return task.isActive() || (MylarTaskListPlugin.getTaskListManager().isReminderToday(task) && !task.isCompleted()) + || (MylarTaskListPlugin.getTaskListManager().isCompletedToday(task)) || (task.isPastReminder() && !task.isCompleted()) || NewLocalTaskAction.DESCRIPTION_DEFAULT.equals(task.getDescription()); } }
true
true
protected boolean shouldAlwaysShow(ITask task) { return task.isActive() || (MylarTaskListPlugin.getTaskListManager().isReminderToday(task) && !task.isCompleted()) || (task.isPastReminder() && !task.isCompleted()) || NewLocalTaskAction.DESCRIPTION_DEFAULT.equals(task.getDescription()); }
protected boolean shouldAlwaysShow(ITask task) { return task.isActive() || (MylarTaskListPlugin.getTaskListManager().isReminderToday(task) && !task.isCompleted()) || (MylarTaskListPlugin.getTaskListManager().isCompletedToday(task)) || (task.isPastReminder() && !task.isCompleted()) || NewLocalTaskAction.DESCRIPTION_DEFAULT.equals(task.getDescription()); }
diff --git a/karaf/gshell/gshell-admin/src/main/java/org/apache/felix/karaf/gshell/admin/internal/AdminServiceImpl.java b/karaf/gshell/gshell-admin/src/main/java/org/apache/felix/karaf/gshell/admin/internal/AdminServiceImpl.java index b072805dd..2e7ec983b 100644 --- a/karaf/gshell/gshell-admin/src/main/java/org/apache/felix/karaf/gshell/admin/internal/AdminServiceImpl.java +++ b/karaf/gshell/gshell-admin/src/main/java/org/apache/felix/karaf/gshell/admin/internal/AdminServiceImpl.java @@ -1,302 +1,302 @@ /* * 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.felix.karaf.gshell.admin.internal; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.io.FileInputStream; import java.net.ServerSocket; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.Properties; import org.apache.felix.karaf.gshell.admin.AdminService; import org.apache.felix.karaf.gshell.admin.Instance; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import org.fusesource.jansi.Ansi; public class AdminServiceImpl implements AdminService { private static final Logger LOGGER = LoggerFactory.getLogger(AdminServiceImpl.class); private Map<String, Instance> instances = new HashMap<String, Instance>(); private int defaultPortStart = 8101; private File storageLocation; public File getStorageLocation() { return storageLocation; } public void setStorageLocation(File storage) { this.storageLocation = storage; } private Properties loadStorage(File location) throws IOException { InputStream is = null; try { is = new FileInputStream(location); Properties props = new Properties(); props.load(is); return props; } finally { if (is != null) { is.close(); } } } private void saveStorage(Properties props, File location) throws IOException { OutputStream os = null; try { os = new FileOutputStream(location); props.store(os, "Admin Service storage"); } finally { if (os != null) { os.close(); } } } public synchronized void init() throws Exception { try { Properties storage = loadStorage(storageLocation); int count = Integer.parseInt(storage.getProperty("count", "0")); defaultPortStart = Integer.parseInt(storage.getProperty("port", Integer.toString(defaultPortStart))); Map<String, Instance> newInstances = new HashMap<String, Instance>(); for (int i = 0; i < count; i++) { String name = storage.getProperty("item." + i + ".name", null); String loc = storage.getProperty("item." + i + ".loc", null); int pid = Integer.parseInt(storage.getProperty("item." + i + ".pid", "0")); if (name != null) { InstanceImpl instance = new InstanceImpl(this, name, loc); if (pid > 0) { try { instance.attach(pid); } catch (IOException e) { // Ignore } } newInstances.put(name, instance); } } instances = newInstances; } catch (Exception e) { LOGGER.warn("Unable to reload Karaf instance list", e); } } public synchronized Instance createInstance(String name, int port, String location) throws Exception { if (instances.get(name) != null) { throw new IllegalArgumentException("Instance '" + name + "' already exists"); } File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile(); int sshPort = port; if (sshPort <= 0) { sshPort = ++defaultPortStart; } - println("Creating new instance on port " + sshPort + " at: @|bold " + serviceMixBase + "|"); + println(Ansi.ansi().a("Creating new instance on port ").a(sshPort).a(" at: ").a(Ansi.Attribute.INTENSITY_BOLD).a(serviceMixBase).a(Ansi.Attribute.RESET).toString()); mkdir(serviceMixBase, "bin"); mkdir(serviceMixBase, "etc"); mkdir(serviceMixBase, "system"); mkdir(serviceMixBase, "deploy"); mkdir(serviceMixBase, "data"); copyResourceToDir(serviceMixBase, "etc/config.properties", true); copyResourceToDir(serviceMixBase, "etc/java.util.logging.properties", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.log.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.features.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.management.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true); copyResourceToDir(serviceMixBase, "etc/startup.properties", true); copyResourceToDir(serviceMixBase, "etc/users.properties", true); HashMap<String, String> props = new HashMap<String, String>(); props.put("${karaf.name}", name); props.put("${karaf.home}", System.getProperty("karaf.home")); props.put("${karaf.base}", serviceMixBase.getPath()); props.put("${karaf.sshPort}", Integer.toString(sshPort)); copyFilteredResourceToDir(serviceMixBase, "etc/system.properties", props); copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.shell.cfg", props); if( System.getProperty("os.name").startsWith("Win") ) { copyFilteredResourceToDir(serviceMixBase, "bin/karaf.bat", props); } else { copyFilteredResourceToDir(serviceMixBase, "bin/karaf", props); chmod(new File(serviceMixBase, "bin/karaf"), "a+x"); } Instance instance = new InstanceImpl(this, name, serviceMixBase.toString()); instances.put(name, instance); saveState(); return instance; } public synchronized Instance[] getInstances() { return instances.values().toArray(new Instance[0]); } public synchronized Instance getInstance(String name) { return instances.get(name); } synchronized void forget(String name) { instances.remove(name); } synchronized void saveState() throws IOException { Properties storage = new Properties(); Instance[] data = getInstances(); storage.setProperty("port", Integer.toString(defaultPortStart)); storage.setProperty("count", Integer.toString(data.length)); for (int i = 0; i < data.length; i++) { storage.setProperty("item." + i + ".name", data[i].getName()); storage.setProperty("item." + i + ".loc", data[i].getLocation()); storage.setProperty("item." + i + ".pid", Integer.toString(data[i].getPid())); } saveStorage(storage, storageLocation); } private void copyResourceToDir(File target, String resource, boolean text) throws Exception { File outFile = new File(target, resource); if( !outFile.exists() ) { println(Ansi.ansi().a("Creating file: ").a(Ansi.Attribute.INTENSITY_BOLD).a(outFile.getPath()).a(Ansi.Attribute.RESET).toString()); InputStream is = getClass().getClassLoader().getResourceAsStream("/org/apache/felix/karaf/gshell/admin/" + resource); try { if( text ) { // Read it line at a time so that we can use the platform line ending when we write it out. PrintStream out = new PrintStream(new FileOutputStream(outFile)); try { Scanner scanner = new Scanner(is); while (scanner.hasNextLine() ) { String line = scanner.nextLine(); out.println(line); } } finally { safeClose(out); } } else { // Binary so just write it out the way it came in. FileOutputStream out = new FileOutputStream(new File(target, resource)); try { int c=0; while((c=is.read())>=0) { out.write(c); } } finally { safeClose(out); } } } finally { safeClose(is); } } } private void println(String st) { System.out.println(st); } private void copyFilteredResourceToDir(File target, String resource, HashMap<String, String> props) throws Exception { File outFile = new File(target, resource); if( !outFile.exists() ) { println(Ansi.ansi().a("Creating file: ").a(Ansi.Attribute.INTENSITY_BOLD).a(outFile.getPath()).a(Ansi.Attribute.RESET).toString()); InputStream is = getClass().getClassLoader().getResourceAsStream("/org/apache/felix/karaf/gshell/admin/" + resource); try { // Read it line at a time so that we can use the platform line ending when we write it out. PrintStream out = new PrintStream(new FileOutputStream(outFile)); try { Scanner scanner = new Scanner(is); while (scanner.hasNextLine() ) { String line = scanner.nextLine(); line = filter(line, props); out.println(line); } } finally { safeClose(out); } } finally { safeClose(is); } } } private void safeClose(InputStream is) throws IOException { if (is == null) { return; } try { is.close(); } catch (Throwable ignore) { } } private void safeClose(OutputStream is) throws IOException { if (is == null) { return; } try { is.close(); } catch (Throwable ignore) { } } private String filter(String line, HashMap<String, String> props) { for (Map.Entry<String, String> i : props.entrySet()) { int p1 = line.indexOf(i.getKey()); if( p1 >= 0 ) { String l1 = line.substring(0, p1); String l2 = line.substring(p1+i.getKey().length()); line = l1+i.getValue()+l2; } } return line; } private void mkdir(File serviceMixBase, String path) { File file = new File(serviceMixBase, path); if( !file.exists() ) { println(Ansi.ansi().a("Creating dir: ").a(Ansi.Attribute.INTENSITY_BOLD).a(file.getPath()).a(Ansi.Attribute.RESET).toString()); file.mkdirs(); } } private int chmod(File serviceFile, String mode) throws Exception { ProcessBuilder builder = new ProcessBuilder(); builder.command("chmod", mode, serviceFile.getCanonicalPath()); Process p = builder.start(); // gnodet: Fix SMX4KNL-46: cpu goes to 100% after running the 'admin create' command // Not sure exactly what happens, but commenting the process io redirection seems // to work around the problem. // //PumpStreamHandler handler = new PumpStreamHandler(io.inputStream, io.outputStream, io.errorStream); //handler.attach(p); //handler.start(); int status = p.waitFor(); //handler.stop(); return status; } }
true
true
public synchronized Instance createInstance(String name, int port, String location) throws Exception { if (instances.get(name) != null) { throw new IllegalArgumentException("Instance '" + name + "' already exists"); } File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile(); int sshPort = port; if (sshPort <= 0) { sshPort = ++defaultPortStart; } println("Creating new instance on port " + sshPort + " at: @|bold " + serviceMixBase + "|"); mkdir(serviceMixBase, "bin"); mkdir(serviceMixBase, "etc"); mkdir(serviceMixBase, "system"); mkdir(serviceMixBase, "deploy"); mkdir(serviceMixBase, "data"); copyResourceToDir(serviceMixBase, "etc/config.properties", true); copyResourceToDir(serviceMixBase, "etc/java.util.logging.properties", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.log.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.features.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.management.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true); copyResourceToDir(serviceMixBase, "etc/startup.properties", true); copyResourceToDir(serviceMixBase, "etc/users.properties", true); HashMap<String, String> props = new HashMap<String, String>(); props.put("${karaf.name}", name); props.put("${karaf.home}", System.getProperty("karaf.home")); props.put("${karaf.base}", serviceMixBase.getPath()); props.put("${karaf.sshPort}", Integer.toString(sshPort)); copyFilteredResourceToDir(serviceMixBase, "etc/system.properties", props); copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.shell.cfg", props); if( System.getProperty("os.name").startsWith("Win") ) { copyFilteredResourceToDir(serviceMixBase, "bin/karaf.bat", props); } else { copyFilteredResourceToDir(serviceMixBase, "bin/karaf", props); chmod(new File(serviceMixBase, "bin/karaf"), "a+x"); } Instance instance = new InstanceImpl(this, name, serviceMixBase.toString()); instances.put(name, instance); saveState(); return instance; }
public synchronized Instance createInstance(String name, int port, String location) throws Exception { if (instances.get(name) != null) { throw new IllegalArgumentException("Instance '" + name + "' already exists"); } File serviceMixBase = new File(location != null ? location : ("instances/" + name)).getCanonicalFile(); int sshPort = port; if (sshPort <= 0) { sshPort = ++defaultPortStart; } println(Ansi.ansi().a("Creating new instance on port ").a(sshPort).a(" at: ").a(Ansi.Attribute.INTENSITY_BOLD).a(serviceMixBase).a(Ansi.Attribute.RESET).toString()); mkdir(serviceMixBase, "bin"); mkdir(serviceMixBase, "etc"); mkdir(serviceMixBase, "system"); mkdir(serviceMixBase, "deploy"); mkdir(serviceMixBase, "data"); copyResourceToDir(serviceMixBase, "etc/config.properties", true); copyResourceToDir(serviceMixBase, "etc/java.util.logging.properties", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.log.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.features.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.management.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.logging.cfg", true); copyResourceToDir(serviceMixBase, "etc/org.ops4j.pax.url.mvn.cfg", true); copyResourceToDir(serviceMixBase, "etc/startup.properties", true); copyResourceToDir(serviceMixBase, "etc/users.properties", true); HashMap<String, String> props = new HashMap<String, String>(); props.put("${karaf.name}", name); props.put("${karaf.home}", System.getProperty("karaf.home")); props.put("${karaf.base}", serviceMixBase.getPath()); props.put("${karaf.sshPort}", Integer.toString(sshPort)); copyFilteredResourceToDir(serviceMixBase, "etc/system.properties", props); copyFilteredResourceToDir(serviceMixBase, "etc/org.apache.felix.karaf.shell.cfg", props); if( System.getProperty("os.name").startsWith("Win") ) { copyFilteredResourceToDir(serviceMixBase, "bin/karaf.bat", props); } else { copyFilteredResourceToDir(serviceMixBase, "bin/karaf", props); chmod(new File(serviceMixBase, "bin/karaf"), "a+x"); } Instance instance = new InstanceImpl(this, name, serviceMixBase.toString()); instances.put(name, instance); saveState(); return instance; }
diff --git a/ini/trakem2/display/Tree.java b/ini/trakem2/display/Tree.java index 479c4b86..47686766 100644 --- a/ini/trakem2/display/Tree.java +++ b/ini/trakem2/display/Tree.java @@ -1,2265 +1,2266 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2009 Albert Cardona. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.display; import ij.ImagePlus; import ij.measure.Calibration; import ij.measure.ResultsTable; import ini.trakem2.imaging.LayerStack; import ini.trakem2.Project; import ini.trakem2.utils.Bureaucrat; import ini.trakem2.utils.IJError; import ini.trakem2.utils.M; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; import ini.trakem2.utils.Worker; import ini.trakem2.vector.VectorString3D; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.Dimension; import java.util.ArrayList; import java.util.LinkedList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.Arrays; import java.util.TreeMap; import java.util.regex.Pattern; import java.util.concurrent.Callable; import java.util.concurrent.Future; import javax.vecmath.Point3f; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JFrame; import javax.swing.JTabbedPane; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import java.awt.event.KeyAdapter; import java.awt.event.MouseAdapter; import fiji.geom.AreaCalculations; // Ideally, this class would use a linked list of node points, where each node could have a list of branches, which would be in themselves linked lists of nodes and so on. // That would make sense, and would make re-rooting and removing nodes (with their branches) trivial and fast. // In practice, I want to reuse Polyline's semiautomatic tracing and thus I am using Polylines for each slab. /** A sequence of points ordered in a set of connected branches. */ public abstract class Tree extends ZDisplayable implements VectorData { static private final Comparator<Layer> COMP_LAYERS = new Comparator<Layer>() { public final int compare(final Layer l1, final Layer l2) { if (l1 == l2) return 0; // the same layer if (l1.getZ() < l2.getZ()) return -1; return 1; // even if same Z, prefer the second } public final boolean equals(Object ob) { return this == ob; } }; protected final TreeMap<Layer,Set<Node>> node_layer_map = new TreeMap<Layer,Set<Node>>(COMP_LAYERS); protected final Set<Node> end_nodes = new HashSet<Node>(); protected Node root = null; protected Tree(Project project, String title) { super(project, title, 0, 0); } /** Reconstruct from XML. */ protected Tree(final Project project, final long id, final HashMap ht_attr, final HashMap ht_links) { super(project, id, ht_attr, ht_links); } /** For cloning purposes, does not call addToDatabase(), neither creates any root node. */ protected Tree(final Project project, final long id, final String title, final double width, final double height, final float alpha, final boolean visible, final Color color, final boolean locked, final AffineTransform at) { super(project, id, title, locked, at, width, height); this.alpha = alpha; this.visible = visible; this.color = color; } final protected Set<Node> getNodesToPaint(final Layer active_layer) { // Determine which layers to paint final Set<Node> nodes; if (layer_set.color_cues) { nodes = new HashSet<Node>(); if (-1 == layer_set.n_layers_color_cue) { // All layers for (final Set<Node> ns : node_layer_map.values()) nodes.addAll(ns); } else { for (final Layer la : layer_set.getColorCueLayerRange(active_layer)) { Set<Node> ns = node_layer_map.get(la); if (null != ns) nodes.addAll(ns); } } } else { // Just the active layer nodes = node_layer_map.get(active_layer); } return nodes; } final public void paint(final Graphics2D g, final Rectangle srcRect, final double magnification, final boolean active, final int channels, final Layer active_layer) { paint(g, srcRect, magnification, active, channels, active_layer, layer_set.paint_arrows); } final public void paint(final Graphics2D g, final Rectangle srcRect, final double magnification, final boolean active, final int channels, final Layer active_layer, final boolean with_arrows) { if (null == root) { setupForDisplay(); if (null == root) return; } //arrange transparency Composite original_composite = null; if (alpha != 1.0f) { original_composite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } AffineTransform gt = null; Stroke stroke = null; synchronized (node_layer_map) { // Determine which layers to paint final Set<Node> nodes = getNodesToPaint(active_layer); if (null != nodes) { Object antialias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images Object text_antialias = g.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Object render_quality = g.getRenderingHint(RenderingHints.KEY_RENDERING); g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); // Clear transform and stroke gt = g.getTransform(); g.setTransform(DisplayCanvas.DEFAULT_AFFINE); stroke = g.getStroke(); g.setStroke(DisplayCanvas.DEFAULT_STROKE); for (final Node nd : nodes) { nd.paintData(g, active_layer, active, srcRect, magnification, nodes, this); nd.paintSlabs(g, active_layer, active, srcRect, magnification, nodes, this.at, this.color, with_arrows, layer_set.paint_edge_confidence_boxes); if (nd == marked) { if (null == MARKED_CHILD) createMarks(); Composite c = g.getComposite(); g.setXORMode(Color.green); float[] fps = new float[]{nd.x, nd.y}; this.at.transform(fps, 0, fps, 0, 1); AffineTransform aff = new AffineTransform(); aff.translate((fps[0] - srcRect.x) * magnification, (fps[1] - srcRect.y) * magnification); g.fill(aff.createTransformedShape(active ? MARKED_PARENT : MARKED_CHILD)); g.setComposite(c); } if (active && active_layer == nd.la) nd.paintHandle(g, srcRect, magnification, this); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, antialias); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, text_antialias); g.setRenderingHint(RenderingHints.KEY_RENDERING, render_quality); } } // restore if (null != gt) { g.setTransform(gt); g.setStroke(stroke); } //Transparency: fix alpha composite back to original. if (null != original_composite) { g.setComposite(original_composite); } } protected Rectangle getPaintingBounds() { Rectangle box = null; synchronized (node_layer_map) { for (final Collection<Node> nodes : node_layer_map.values()) { for (final Node nd : nodes) { if (null == box) box = new Rectangle((int)nd.x, (int)nd.y, 1, 1); else box.add((int)nd.x, (int)nd.y); } } } return box; } protected boolean calculateBoundingBox() { if (null == root) { this.at.setToIdentity(); this.width = 0; this.height = 0; return true; } final Rectangle box = getPaintingBounds(); this.width = box.width; this.height = box.height; // now readjust points to make min_x,min_y be the x,y for (final Collection<Node> nodes : node_layer_map.values()) { for (final Node nd : nodes) { nd.translate(-box.x, -box.y); }} this.at.translate(box.x, box.y); // not using super.translate(...) because a preConcatenation is not needed; here we deal with the data. if (null != layer_set) layer_set.updateBucket(this); return true; } public void repaint() { repaint(true); } /**Repaints in the given ImageCanvas only the area corresponding to the bounding box of this Pipe. */ public void repaint(boolean repaint_navigator) { //TODO: this could be further optimized to repaint the bounding box of the last modified segments, i.e. the previous and next set of interpolated points of any given backbone point. This would be trivial if each segment of the Bezier curve was an object. Rectangle box = getBoundingBox(null); calculateBoundingBox(); box.add(getBoundingBox(null)); Display.repaint(layer_set, this, box, 10, repaint_navigator); } /**Make this object ready to be painted.*/ synchronized private void setupForDisplay() { // TODO } public boolean intersects(final Area area, final double z_first, final double z_last) { if (null == root) return false; synchronized (node_layer_map) { // Area to local coords try { final Area a = area.createTransformedArea(this.at.createInverse()); // find layers between z_first and z_last for (final Map.Entry<Layer,Set<Node>> e : node_layer_map.entrySet()) { final double z = e.getKey().getZ(); if (z >= z_first && z <= z_last) { for (final Node nd : e.getValue()) { if (a.contains(nd.x, nd.y)) return true; } } } } catch (Exception e) { IJError.print(e); } } return false; } public Layer getFirstLayer() { if (null == root) return null; synchronized (node_layer_map) { return node_layer_map.firstKey(); } } private final List<Node> tolink = new ArrayList<Node>(); protected final void addToLinkLater(final Node nd) { synchronized (tolink) { tolink.add(nd); } } protected final void removeFromLinkLater(final Node nd) { synchronized (tolink) { tolink.remove(nd); } } public boolean linkPatches() { if (null == root) return false; // Obtain local copy and clear 'tolink': final ArrayList<Node> tolink; synchronized (this.tolink) { tolink = new ArrayList<Node>(this.tolink); this.tolink.clear(); } if (tolink.isEmpty()) return true; boolean must_lock = false; AffineTransform aff; try { aff = this.at.createInverse(); } catch (Exception e) { IJError.print(e); return false; } for (final Node nd : tolink) { for (final Patch patch : (Collection<Patch>) (Collection) nd.findLinkTargets(aff)) { link(patch); if (patch.locked) must_lock = true; } } if (must_lock && !locked) { setLocked(true); return true; } return false; } /** Create a new instance, intialized with same ZDisplayable-level parameters (affine, color, title, etc.). */ abstract protected Tree newInstance(); abstract protected Node newNode(float lx, float ly, Layer layer, Node modelNode); /** To reconstruct from XML. */ abstract public Node newNode(HashMap ht_attr); public boolean isDeletable() { return null == root; } /** Exports to type t2_treeline. */ static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) { String type = "t2_node"; if (hs.contains(type)) return; hs.add(type); sb_header.append(indent).append("<!ELEMENT t2_tag EMPTY>\n"); sb_header.append(indent).append(TAG_ATTR1).append("t2_tag name").append(TAG_ATTR2); sb_header.append(indent).append(TAG_ATTR1).append("t2_tag key").append(TAG_ATTR2); sb_header.append(indent).append("<!ELEMENT t2_node (t2_area*,t2_tag*)>\n"); sb_header.append(indent).append(TAG_ATTR1).append("t2_node x").append(TAG_ATTR2) .append(indent).append(TAG_ATTR1).append("t2_node y").append(TAG_ATTR2) .append(indent).append(TAG_ATTR1).append("t2_node lid").append(TAG_ATTR2) .append(indent).append(TAG_ATTR1).append("t2_node c").append(TAG_ATTR2) .append(indent).append(TAG_ATTR1).append("t2_node r NMTOKEN #IMPLIED>\n") ; } public void exportXML(StringBuffer sb_body, String indent, Object any) { String name = getClass().getName().toLowerCase(); String type = "t2_" + name.substring(name.lastIndexOf('.') + 1); sb_body.append(indent).append("<").append(type).append('\n'); final String in = indent + "\t"; super.exportXML(sb_body, in, any); String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("style=\"fill:none;stroke-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";stroke-width:1.0px;stroke-opacity:1.0\"\n"); super.restXML(sb_body, in, any); sb_body.append(indent).append(">\n"); if (null != root) exportXML(this, in, sb_body, root); sb_body.append(indent).append("</").append(type).append(">\n"); } /** One day, java will get tail-call optimization (i.e. no more stack overflow errors) and I will laugh at this function. */ static private void exportXML(final Tree tree, final String indent_base, final StringBuffer sb, final Node root) { // Simulating recursion // // write depth-first, closing as children get written final LinkedList<Node> list = new LinkedList<Node>(); list.add(root); final Map<Node,Integer> table = new HashMap<Node,Integer>(); while (!list.isEmpty()) { Node node = list.getLast(); if (null == node.children) { // Processing end point dataNodeXML(tree, getIndents(indent_base, list.size()), sb, node); list.removeLast(); continue; } else { final Integer ii = table.get(node); if (null == ii) { // Never yet processed a child, add first dataNodeXML(tree, getIndents(indent_base, list.size()), sb, node); table.put(node, 0); list.add(node.children[0]); continue; } else { final int i = ii.intValue(); // Are there any more children to process? if (i == node.children.length -1) { // No more children to process closeNodeXML(getIndents(indent_base, list.size()), sb); list.removeLast(); table.remove(node); continue; } else { // Process the next child list.add(node.children[i+1]); table.put(node, i+1); } } } } } static private StringBuffer getIndents(String base, int more) { final StringBuffer sb = new StringBuffer(base.length() + more); sb.append(base); while (more > 0) { sb.append(' '); more--; } return sb; } static private final void dataNodeXML(final Tree tree, final StringBuffer indent, final StringBuffer sb, final Node node) { sb.append(indent) .append("<t2_node x=\"").append(node.x) .append("\" y=\"").append(node.y) .append("\" lid=\"").append(node.la.getId()).append('\"'); ; if (null != node.parent) sb.append(" c=\"").append(node.parent.getConfidence(node)).append('\"'); tree.exportXMLNodeAttributes(indent, sb, node); // may not add anything sb.append(">\n"); // ... so accumulated potentially extra chars are 3: \">\n indent.append(' '); boolean data = tree.exportXMLNodeData(indent, sb, node); if (data) { if (null != node.tags) exportTags(node, sb, indent); if (null == node.children) { indent.setLength(indent.length() -1); sb.append(indent).append("</t2_node>\n"); return; } } else if (null == node.children) { if (null != node.tags) { exportTags(node, sb, indent); sb.append(indent).append("</t2_node>\n"); } else { sb.setLength(sb.length() -3); // remove "\">\n" sb.append("\" />\n"); } } else if (null != node.tags) { exportTags(node, sb, indent); } indent.setLength(indent.length() -1); } abstract protected boolean exportXMLNodeAttributes(StringBuffer indent, StringBuffer sb, Node node); abstract protected boolean exportXMLNodeData(StringBuffer indent, StringBuffer sb, Node node); static private void exportTags(final Node node, final StringBuffer sb, final StringBuffer indent) { for (final Tag tag : (Collection<Tag>) node.getTags()) { sb.append(indent).append("<t2_tag name=\"").append(Displayable.getXMLSafeValue(tag.toString())) .append("\" key=\"").append((char)tag.getKeyCode()).append("\" />\n"); } } static private final void closeNodeXML(final StringBuffer indent, final StringBuffer sb) { sb.append(indent).append("</t2_node>\n"); } /** @return a CustomLineMesh.PAIRWISE list for a LineMesh. */ public List generateTriangles(double scale_, int parallels, int resample) { if (null == root) return null; final ArrayList list = new ArrayList(); // Simulate recursion final LinkedList<Node> todo = new LinkedList<Node>(); todo.add(root); final float scale = (float)scale_; final Calibration cal = layer_set.getCalibration(); final float pixelWidthScaled = (float) cal.pixelWidth * scale; final float pixelHeightScaled = (float) cal.pixelHeight * scale; final int sign = cal.pixelDepth < 0 ? -1 : 1; final float[] fps = new float[2]; final Map<Node,Point3f> points = new HashMap<Node,Point3f>(); // A few performance tests are needed: // 1 - if the map caching of points helps or recomputing every time is cheaper than lookup // 2 - if removing no-longer-needed points from the map helps lookup or overall slows down // // The method, by the way, is very parallelizable: each is independent. boolean go = true; while (go) { final Node node = todo.removeFirst(); // Add children to todo list if any if (null != node.children) { for (final Node nd : node.children) todo.add(nd); } go = !todo.isEmpty(); // Get node's 3D coordinate Point3f p = points.get(node); if (null == p) { fps[0] = node.x; fps[1] = node.y; this.at.transform(fps, 0, fps, 0, 1); p = new Point3f(fps[0] * pixelWidthScaled, fps[1] * pixelHeightScaled, (float)node.la.getZ() * pixelWidthScaled * sign); points.put(node, p); } if (null != node.parent) { // Create a line to the parent list.add(points.get(node.parent)); list.add(p); if (go && node.parent != todo.getFirst().parent) { // node.parent point no longer needed (last child just processed) points.remove(node.parent); } } } return list; } @Override final Class getInternalDataPackageClass() { return DPTree.class; } @Override synchronized Object getDataPackage() { return new DPTree(this); } static class DPTree extends Displayable.DataPackage { final Node root; DPTree(final Tree t) { super(t); this.root = null == t.root ? null : t.root.clone(); } @Override final boolean to2(final Displayable d) { super.to1(d); final Tree t = (Tree)d; if (null != this.root) { t.root = this.root.clone(); t.clearCache(); t.cacheSubtree(t.root.getSubtreeNodes()); t.updateView(); } return true; } } /** Reroots at the point closest to the x,y,layer_id world coordinate. * @return true on success. */ synchronized public boolean reRoot(float x, float y, Layer layer, double magnification) { if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } synchronized (node_layer_map) { // Search within the nodes in layer Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) { Utils.log("No node at " + x + ", " + y + ", " + layer); return false; } nodes = null; // Find a node near the coordinate Node nd = findNode(x, y, layer, magnification); if (null == nd) { Utils.log("No node near " + x + ", " + y + ", " + layer); return false; } end_nodes.add(this.root); end_nodes.remove(nd); nd.setRoot(); this.root = nd; updateView(); return true; } } /** Split the Tree into new Tree at the point closest to the x,y,layer world coordinate. * @return null if no node was found near the x,y,layer point with precision dependent on magnification. */ synchronized public List<Tree> splitNear(float x, float y, Layer layer, double magnification) { try { if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } synchronized (node_layer_map) { // Search within the nodes in layer Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) { Utils.log("No nodes at " + x + ", " + y + ", " + layer); return null; } nodes = null; // Find a node near the coordinate Node nd = findNode(x, y, layer, magnification); if (null == nd) { Utils.log("No node near " + x + ", " + y + ", " + layer + ", mag=" + magnification); return null; } if (null == nd.parent) { Utils.log("Cannot split at a root point!"); return null; } // Cache the children of 'nd' Collection<Node> subtree_nodes = nd.getSubtreeNodes(); // Remove all children nodes of found node 'nd' from the Tree cache arrays: removeNode(nd, subtree_nodes); // Set the found node 'nd' as a new root: (was done by removeNode/Node.remove anyway) nd.parent = null; // With the found nd, now a root, create a new Tree Tree t = newInstance(); t.addToDatabase(); t.root = nd; // ... and fill its cache arrays t.cacheSubtree(subtree_nodes); // includes nd itself // Recompute bounds -- TODO: must translate the second properly, or apply the transforms and then recalculate bounding boxes and transforms. this.calculateBoundingBox(); t.calculateBoundingBox(); // Done! return Arrays.asList(new Tree[]{this, t}); } } catch (Exception e) { IJError.print(e); } return null; } private void cacheSubtree(final Collection<Node> nodes) { cache(nodes, end_nodes, node_layer_map); } private void clearCache() { end_nodes.clear(); node_layer_map.clear(); setLastAdded(null); setLastEdited(null); setLastMarked(null); setLastVisited(null); } /** Take @param nodes and add them to @param end_nodes and @param node_layer_map as appropriate. */ static private void cache(final Collection<Node> nodes, final Collection<Node> end_nodes, final Map<Layer,Set<Node>> node_layer_map) { for (final Node child : nodes) { if (null == child.children) end_nodes.add(child); Set<Node> nds = node_layer_map.get(child.la); if (null == nds) { nds = new HashSet<Node>(); node_layer_map.put(child.la, nds); } nds.add(child); } } /** Returns true if the given point falls within a certain distance of any of the treeline segments, * where a segment is defined as the line between a clicked point and the next. */ @Override public boolean contains(final Layer layer, final int x, final int y) { if (null == root) return false; synchronized (node_layer_map) { final Set<Node> nodes = node_layer_map.get(layer); if (null == nodes) return false; Display front = Display.getFront(); float radius = 10; if (null != front) { double mag = front.getCanvas().getMagnification(); radius = (float)(10 / mag); if (radius < 2) radius = 2; } final Point2D.Double po = inverseTransformPoint(x, y); radius *= radius; for (final Node nd : nodes) { if (nd.isNear((float)po.x, (float)po.y, radius)) return true; } } return false; } public Node getRoot() { return root; } protected Coordinate<Node> createCoordinate(final Node nd) { if (null == nd) return null; double x = nd.x; double y = nd.y; if (!this.at.isIdentity()) { double[] dps = new double[]{x, y}; this.at.transform(dps, 0, dps, 0, 1); x = dps[0]; y = dps[1]; } return new Coordinate<Node>(x, y, nd.la, nd); } public Coordinate<Node> findPreviousBranchOrRootPoint(float x, float y, Layer layer, double magnification) { Node nd = findNodeNear(x, y, layer, magnification); if (null == nd) return null; return createCoordinate(nd.findPreviousBranchOrRootPoint()); } /** If the node found near x,y,layer is a branch point, returns it; otherwise the next down * the chain; on reaching an end point, returns it. */ public Coordinate<Node> findNextBranchOrEndPoint(float x, float y, Layer layer, double magnification) { Node nd = findNodeNear(x, y, layer, magnification); if (null == nd) return null; return createCoordinate(nd.findNextBranchOrEndPoint()); } protected Coordinate<Node> findNearAndGetNext(float x, float y, Layer layer, double magnification) { Node nd = findNodeNear(x, y, layer, magnification); if (null == nd) nd = last_visited; if (null == nd) return null; int n_children = nd.getChildrenCount(); if (0 == n_children) return null; if (1 == n_children) { setLastVisited(nd.children[0]); return createCoordinate(nd.children[0]); } // else, find the closest child edge if (!this.at.isIdentity()) { Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } nd = findNearestChildEdge(nd, x, y); if (null != nd) setLastVisited(nd); return createCoordinate(nd); } protected Coordinate<Node> findNearAndGetPrevious(float x, float y, Layer layer, double magnification) { Node nd = findNodeNear(x, y, layer, magnification); if (null == nd) nd = last_visited; if (null == nd || null == nd.parent) return null; setLastVisited(nd.parent); return createCoordinate(nd.parent); } public Coordinate<Node> getLastEdited() { return createCoordinate(last_edited); } public Coordinate<Node> getLastAdded() { return createCoordinate(last_added); } /** Find an edge near the world coords x,y,layer with precision depending upon magnification, * and adjust its confidence to @param confidence. * @return the node whose parent edge is altered, or null if none found. */ protected Node setEdgeConfidence(byte confidence, float x, float y, Layer layer, double magnification) { synchronized (node_layer_map) { Node nearest = findNodeConfidenceBox(x, y, layer, magnification); if (null == nearest) return null; if (nearest.parent.setConfidence(nearest, confidence)) return nearest; return null; } } protected Node adjustEdgeConfidence(int inc, float x, float y, Layer layer, double magnification) { if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } synchronized (node_layer_map) { Node nearest = findNode(x, y, layer, magnification); if (null == nearest) nearest = findNodeConfidenceBox(x, y, layer, magnification); if (null != nearest && null != nearest.parent && nearest.parent.adjustConfidence(nearest, inc)) return nearest; return null; } } /** Find the node whose confidence box for the parent edge is closest to x,y,layer, if any. */ private Node findNodeConfidenceBox(float x, float y, Layer layer, double magnification) { final Set<Node> nodes = node_layer_map.get(layer); if (null == nodes) return null; Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; float radius = (float)(10 / magnification); if (radius < 2) radius = 2; radius *= radius; // squared float min_sq_dist = Float.MAX_VALUE; Node nearest = null; for (final Node nd : nodes) { if (null == nd.parent) continue; float d = (float)(Math.pow((nd.parent.x + nd.x)/2 - x, 2) + Math.pow((nd.parent.y + nd.y)/2 - y, 2)); if (d < min_sq_dist && d < radius) { min_sq_dist = d; nearest = nd; } } return nearest; } /** Find a node in @param layer near the local coords lx,ly, with precision depending on magnification. */ public Node findNode(final float lx, final float ly, final Layer layer, final double magnification) { synchronized (node_layer_map) { return findClosestNode(node_layer_map.get(layer), lx, ly, magnification); } } /** Expects world coords; with precision depending on magnification. */ public Node findClosestNodeW(final Collection<Node> nodes, final float wx, final float wy, final double magnification) { float lx = wx, ly = wy; if (!this.at.isIdentity()) { Point2D.Double po = inverseTransformPoint(wx, wy); lx = (float)po.x; ly = (float)po.y; } return findClosestNode(nodes, lx, ly, magnification); } /** Expects local coords; with precision depending on magnification. */ public Node findClosestNode(final Collection<Node> nodes, final float lx, final float ly, final double magnification) { if (null == nodes || nodes.isEmpty()) return null; double d = (10.0D / magnification); if (d < 2) d = 2; float min_dist = Float.MAX_VALUE; Node nd = null; for (final Node node : nodes) { float dist = Math.abs(node.x - lx) + Math.abs(node.y - ly); if (dist < min_dist) { min_dist = dist; nd = node; } } return min_dist < d ? nd : null; } /** Find the spatially closest node, in calibrated coords. */ public Node findNearestNode(final float lx, final float ly, final Layer layer) { synchronized (node_layer_map) { final Set<Node> nodes = node_layer_map.get(layer); if (null == nodes) return null; return findNearestNode(lx, ly, (float)layer.getZ(), layer.getParent().getCalibration(), nodes); } } static private Node findNearestNode(float lx, float ly, float lz, final Calibration cal, final Collection<Node> nodes) { if (null == nodes) return null; // A distance map would help here final float pixelWidth = (float) cal.pixelWidth; final float pixelHeight = (float) cal.pixelHeight; Node nearest = null; float sqdist = Float.MAX_VALUE; for (final Node nd : nodes) { final float d = (float) (Math.pow(pixelWidth * (nd.x - lx), 2) + Math.pow(pixelHeight * (nd.y -ly), 2) + Math.pow(pixelWidth * (nd.la.getZ() - lz), 2)); if (d < sqdist) { sqdist = d; nearest = nd; } } return nearest; } /** Find the spatially closest node, in calibrated coords. */ public Node findNearestEndNode(final float lx, final float ly, final Layer layer) { synchronized (node_layer_map) { return findNearestNode(lx, ly, (float)layer.getZ(), layer.getParent().getCalibration(), end_nodes); } } public boolean insertNode(final Node parent, final Node child, final Node in_between, final byte confidence) { synchronized (node_layer_map) { byte b = parent.getConfidence(child); parent.remove(child); parent.add(in_between, b); in_between.add(child, confidence); // cache Collection<Node> subtree = in_between.getSubtreeNodes(); cacheSubtree(subtree); // If child was in end_nodes, remains there setLastAdded(in_between); updateView(); addToLinkLater(in_between); return true; } } /** Considering only the set of consecutive layers currently painted, find a point near an edge * with accurancy depending upon magnification. * @return null if none of the edges is close enough, or an array of parent and child describing the edge. */ public Node[] findNearestEdge(float x_pl, float y_pl, Layer layer, double magnification) { if (null == root) return null; // Don't traverse all, just look into nodes currently being painted according to layer_set.n_layers_color_cue final Set<Node> nodes = getNodesToPaint(layer); if (null == nodes) return null; // double d = (10.0D / magnification); if (d < 2) d = 2; double min_dist = Double.MAX_VALUE; Node[] ns = new Node[2]; // parent and child // for (final Node node : nodes) { if (null == node.children) continue; // Examine if the point is closer to the 2D-projected edge than any other so far: // TODO it's missing edges with parents beyond the set of painted layers, // and it's doing edges to children beyond the set of painted layers. for (final Node child : node.children) { double dist = M.distancePointToSegment(x_pl, y_pl, node.x, node.y, child.x, child.y); if (dist < min_dist && dist < d) { min_dist = dist; ns[0] = node; ns[1] = child; } } } if (null == ns[0]) return null; return ns; } /** In projected 2D only, since that's the perspective of the user. */ private Node findNearestChildEdge(final Node parent, final float lx, final float ly) { if (null == parent || null == parent.children) return null; Node nd = null; double min_dist = Double.MAX_VALUE; for (final Node child : parent.children) { double dist = M.distancePointToSegment(lx, ly, parent.x, parent.y, child.x, child.y); if (dist < min_dist) { min_dist = dist; nd = child; } } return nd; } public boolean addNode(final Node parent, final Node child, final byte confidence) { //try { synchronized (node_layer_map) { Set<Node> nodes = node_layer_map.get(child.la); if (null == nodes) { nodes = new HashSet<Node>(); node_layer_map.put(child.la, nodes); } if (nodes.add(child)) { if (null != parent) { if (!parent.hasChildren() && !end_nodes.remove(parent)) { Utils.log("WARNING: parent wasn't in end_nodes list!"); } parent.add(child, confidence); } if (null == child.children && !end_nodes.add(child)) { Utils.log("WARNING: child was already in end_nodes list!"); } Collection<Node> subtree = child.getSubtreeNodes(); cacheSubtree(subtree); setLastAdded(child); updateView(); synchronized (tolink) { tolink.addAll(subtree); } return true; } else if (0 == nodes.size()) { node_layer_map.remove(child.la); } return false; } /*} finally { //Utils.log2("new node: " + child + " with parent: " + parent); //Utils.log2("layers with nodes: " + node_layer_map.size() + ", child.la = " + child.la + ", nodes:" + node_layer_map.get(child.la).size()); if (null == parent) { Utils.log2("just added parent: "); Utils.log2(" nodes to paint: " + Utils.toString(getNodesToPaint(Display.getFrontLayer()))); Utils.log2(" nodes in node_layer_map: " + Utils.toString(node_layer_map)); } }*/ } /** Remove a node only (not its subtree). * @return true on success. Will return false when the node has 2 or more children. * The new edge confidence is that of the parent to the @param node. */ public boolean popNode(final Node node) { switch (node.getChildrenCount()) { case 0: // End node: removeNode(node, null); return true; case 1: if (null == node.parent) { // Make its child the new root root = node.children[0]; root.parent = null; } else { node.parent.children[node.parent.indexOf(node)] = node.children[0]; node.children[0].parent = node.parent; } synchronized (node_layer_map) { node_layer_map.get(node.la).remove(node); } fireNodeRemoved(node); updateView(); return true; default: return false; } } /** If the tree is a cyclic graph, it may destroy all. */ public void removeNode(final Node node) { synchronized (node_layer_map) { removeNode(node, node.getSubtreeNodes()); } } // TODO this function is not thread safe. Works well because multiple threads aren't so far calling cache-modifying functions. // Should synchronize on node_layer_map. private void removeNode(final Node node, final Collection<Node> subtree_nodes) { if (null == node.parent) { root = null; clearCache(); } else { // if not an end-point, update cached lists if (null != node.children) { Utils.log2("Removing children of node " + node); for (final Node nd : subtree_nodes) { // includes the node itself node_layer_map.get(nd.la).remove(nd); if (null == nd.children && !end_nodes.remove(nd)) { Utils.log2("WARNING: node to remove doesn't have any children but wasn't in end_nodes list!"); } } } else { Utils.log2("Just removing node " + node); end_nodes.remove(node); node_layer_map.get(node.la).remove(node); } if (1 == node.parent.getChildrenCount()) { end_nodes.add(node.parent); } // Finally, remove from parent node node.parent.remove(node); } synchronized (tolink) { if (null != subtree_nodes) { tolink.removeAll(subtree_nodes); } else tolink.remove(node); } fireNodeRemoved(node); updateView(); } /** Join all given Trees by using the first one as the receiver, and all the others as the ones to be merged into the receiver. * Requires each Tree to have a non-null marked Node; otherwise, returns false. */ public boolean canJoin(final List<? extends Tree> ts) { if (null == marked) { Utils.log("No marked node in to-be parent Tree " + this); return false; } boolean quit = false; for (final Tree tl : ts) { if (this == tl) continue; if (null == tl.marked) { Utils.log("No marked node in to-be child treeline " + tl); quit = true; } } return !quit; } /* Requires each Tree to have a non-null marked Node; otherwise, returns false. */ public boolean join(final List<? extends Tree> ts) { if (!canJoin(ts)) return false; // All Tree in ts have a marked node final AffineTransform at_inv; try { at_inv = this.at.createInverse(); } catch (NoninvertibleTransformException nite) { IJError.print(nite); return false; } for (final Tree tl : ts) { if (this == tl) continue; tl.marked.setRoot(); // transform nodes from there to here final AffineTransform aff = new AffineTransform(tl.at); // 1 - to world coords aff.preConcatenate(at_inv); // 2 - to this local coords final float[] fps = new float[2]; for (final Node nd : (List<Node>) tl.marked.getSubtreeNodes()) { // fails to compile? Why? fps[0] = nd.x; fps[1] = nd.y; aff.transform(fps, 0, fps, 0, 1); nd.x = fps[0]; nd.y = fps[1]; } addNode(this.marked, tl.marked, Node.MAX_EDGE_CONFIDENCE); // Remove from tl pointers tl.root = null; // stolen! tl.setLastMarked(null); // Remove from tl cache tl.node_layer_map.clear(); tl.end_nodes.clear(); } calculateBoundingBox(); // Don't clear this.marked updateView(); return true; } /** Expects world coordinates. If no node is near x,y but there is only one node in the current Display view of the layer, then it returns that node. */ protected Node findNodeNear(float x, float y, final Layer layer, final double magnification) { if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } synchronized (node_layer_map) { // Search within the nodes in layer Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) { Utils.log("No nodes at " + x + ", " + y + ", " + layer); return null; } // Find a node near the coordinate Node nd = findNode(x, y, layer, magnification); // If that fails, try any node show all by itself in the display: if (null == nd) { // Is there only one node within the srcRect? final Area a; try { a = new Area(Display.getFront().getCanvas().getSrcRect()) .createTransformedArea(this.at.createInverse()); } catch (NoninvertibleTransformException nite) { IJError.print(nite); return null; } int count = 0; for (final Node node : nodes) { if (node.intersects(a)) { nd = node; count++; if (count > 1) { nd = null; break; } } } } /* if (null == nd) { Utils.log("No node near " + x + ", " + y + ", " + layer + ", mag=" + magnification); return null; } */ return nd; } } public boolean markNear(float x, float y, final Layer layer, final double magnification) { if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x, y); x = (float)po.x; y = (float)po.y; } synchronized (node_layer_map) { // Search within the nodes in layer Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) { Utils.log("No nodes at " + x + ", " + y + ", " + layer); return false; } nodes = null; // Find a node near the coordinate Node found = findNode(x, y, layer, magnification); if (null == found) { Utils.log("No node near " + x + ", " + y + ", " + layer + ", mag=" + magnification); return false; } setLastMarked(found); return true; } } public boolean unmark() { if (null != marked) { setLastMarked(null); return true; } return false; } protected void setActive(Node nd) { this.active = nd; if (null != nd) setLastVisited(nd); } protected Node getActive() { return active; } protected void setLastEdited(Node nd) { this.last_edited = nd; setLastVisited(nd); } protected void setLastAdded(Node nd) { this.last_added = nd; setLastVisited(nd); } protected void setLastMarked(Node nd) { this.marked = nd; setLastVisited(nd); } protected void setLastVisited(Node nd) { this.last_visited = nd; } protected void fireNodeRemoved(final Node nd) { if (nd == marked) marked = null; if (nd == last_added) last_added = null; if (nd == last_edited) last_edited = null; if (nd == last_visited) last_visited = null; removeFromLinkLater(nd); } /** The Node double-clicked on, for join operations. */ private Node marked = null; /** The Node clicked on, for mouse operations. */ private Node active = null; /** The last added node */ private Node last_added = null; /** The last edited node, which will be the last added as well until some other node is edited. */ private Node last_edited = null; /** The last visited node, either navigating or editing. */ private Node last_visited = null; static private Polygon MARKED_PARENT, MARKED_CHILD; static private final void createMarks() { MARKED_PARENT = new Polygon(new int[]{0, -1, -2, -4, -18, -18, -4, -2, -1}, new int[]{0, -2, -3, -4, -4, 4, 4, 3, 2}, 9); MARKED_CHILD = new Polygon(new int[]{0, 10, 12, 12, 22, 22, 12, 12, 10}, new int[]{0, 10, 10, 4, 4, -4, -4, -10, -10}, 9); } @Override public void mousePressed(MouseEvent me, int x_p, int y_p, double mag) { if (ProjectToolbar.PEN != ProjectToolbar.getToolId()) { return; } final Layer layer = Display.getFrontLayer(this.project); if (null != root) { // transform the x_p, y_p to the local coordinates int x_pl = x_p; int y_pl = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_pl = (int)po.x; y_pl = (int)po.y; } Node found = findNode(x_pl, y_pl, layer, mag); setActive(found); if (null != found) { if (2 == me.getClickCount()) { setLastMarked(found); setActive(null); return; } if (me.isShiftDown() && Utils.isControlDown(me)) { if (me.isAltDown()) { // Remove point and its subtree removeNode(found); } else { // Just remove the slab point, joining parent with child if (!popNode(found)) { Utils.log("Can't pop out branch point!\nUse shift+control+alt+click to remove a branch point and its subtree."); setActive(null); return; } } repaint(false); // keep larger size for repainting, will call calculateBoundingBox on mouseRelesed setActive(null); return; } if (me.isShiftDown() && !me.isAltDown()) { // Create new branch at point, with local coordinates Node child = newNode(x_pl, y_pl, layer, found); addNode(found, child, Node.MAX_EDGE_CONFIDENCE); setActive(child); return; } } else { if (2 == me.getClickCount()) { setLastMarked(null); return; } if (me.isAltDown()) { return; } // Add new point if (me.isShiftDown()) { Node[] ns = findNearestEdge(x_pl, y_pl, layer, mag); if (null != ns) { found = newNode(x_pl, y_pl, layer, ns[0]); insertNode(ns[0], ns[1], found, ns[0].getConfidence(ns[1])); setActive(found); } } else { // Find the point closest to any other starting or ending point in all branches Node nearest = findNearestEndNode(x_pl, y_pl, layer); // at least the root exists, so it has to find a node, any node // append new child; inherits radius from parent found = newNode(x_pl, y_pl, layer, nearest); addNode(nearest, found, Node.MAX_EDGE_CONFIDENCE); setActive(found); repaint(true); } return; } } else { // First point root = newNode(x_p, y_p, layer, null); // world coords, so calculateBoundingBox will do the right thing addNode(null, root, (byte)0); setActive(root); } } @Override public void mouseDragged(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_d_old, int y_d_old) { translateActive(me, x_d, y_d, x_d_old, y_d_old); } @Override public void mouseReleased(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_r, int y_r) { final int tool = ProjectToolbar.getToolId(); translateActive(me, x_r, y_d, x_d, y_d); if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { repaint(true); //needed at least for the removePoint } updateViewData(active); setActive(null); } private final void translateActive(MouseEvent me, int x_d, int y_d, int x_d_old, int y_d_old) { if (null == active || me.isAltDown() || Utils.isControlDown(me)) return; // shiftDown is ok: when dragging a newly branched node. // transform to the local coordinates if (!this.at.isIdentity()) { final Point2D.Double pd = inverseTransformPoint(x_d, y_d); x_d = (int)pd.x; y_d = (int)pd.y; final Point2D.Double pdo = inverseTransformPoint(x_d_old, y_d_old); x_d_old = (int)pdo.x; y_d_old = (int)pdo.y; } active.translate(x_d - x_d_old, y_d - y_d_old); repaint(false); setLastEdited(active); } static private Node to_tag = null; static private Node to_untag = null; static private boolean show_tag_dialogs = false; @Override public void keyPressed(KeyEvent ke) { switch (ProjectToolbar.getToolId()) { case ProjectToolbar.PEN: case ProjectToolbar.BRUSH: break; default: // Reject return; } Object source = ke.getSource(); if (! (source instanceof DisplayCanvas)) return; final int keyCode = ke.getKeyCode(); final DisplayCanvas dc = (DisplayCanvas)source; if (null != to_tag || null != to_untag) { // Can only add a tag for A-Z or numbers! if (! (Character.isLetterOrDigit((char)keyCode) && (Character.isDigit((char)keyCode) || Character.isUpperCase((char)keyCode)))) { // VK_F1, F2 ... are lower case letters! Evil! // Cancel tagging Utils.showStatus("Canceled tagging"); to_tag = null; to_untag = null; ke.consume(); return; } - if (KeyEvent.VK_0 == keyCode) { + if (!show_tag_dialogs && KeyEvent.VK_0 == keyCode) { // force dialogs for next key show_tag_dialogs = true; ke.consume(); return; } final boolean untag = null != to_untag; final Node target = untag ? to_untag : to_tag; try { layer_set.addPreDataEditStep(this); if (show_tag_dialogs) { if (untag) { if (layer_set.askToRemoveTag(keyCode)) { // if removed from tag namespace, it will be removed from all nodes that have it layer_set.addDataEditStep(this); } } else { Tag t = layer_set.askForNewTag(keyCode); if (null != t) { target.addTag(t); Display.repaint(layer_set); layer_set.addDataEditStep(this); // no 'with' macros ... without half a dozen layers of cruft. } } show_tag_dialogs = false; return; } TreeSet<Tag> ts = layer_set.getTags(keyCode); if (ts.isEmpty()) { if (untag) return; if (null == layer_set.askForNewTag(keyCode)) return; ts = layer_set.getTags(keyCode); } // Ask to chose one, if more than one if (ts.size() > 1) { final JPopupMenu popup = new JPopupMenu(); popup.add(new JLabel(untag ? "Untag:" : "Tag:")); int i = 1; for (final Tag tag : ts) { JMenuItem item = new JMenuItem(tag.toString()); popup.add(item); if (i < 10) { item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0 + i, 0, true)); } i++; item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) target.removeTag(tag); else target.addTag(tag); Display.repaint(layer_set); layer_set.addDataEditStep(Tree.this); } }); } popup.addSeparator(); JMenuItem item = new JMenuItem(untag ? "Remove tag..." : "Define new tag..."); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, 0, true)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) { layer_set.askToRemoveTag(keyCode); } else { - if (null == layer_set.askForNewTag(keyCode)) return; - target.addTag(layer_set.getTags(keyCode).last()); + Tag t = layer_set.askForNewTag(keyCode); + if (null == t) return; + target.addTag(t); Display.repaint(layer_set); } layer_set.addDataEditStep(Tree.this); } }); // Show the popup on the Display, under the node final float[] fp = new float[]{target.x, target.y}; this.at.transform(fp, 0, fp, 0, 1); Rectangle srcRect = dc.getSrcRect(); double magnification = dc.getMagnification(); final int x = (int)((fp[0] - srcRect.x) * magnification); final int y = (int)((fp[1] - srcRect.y) * magnification); popup.show(dc, x, y); } else { if (untag) target.removeTag(ts.first()); else target.addTag(ts.first()); Display.repaint(layer_set); layer_set.addDataEditStep(this); } return; } finally { updateViewData(untag ? to_untag : to_tag); to_tag = null; to_untag = null; ke.consume(); } } Layer la = dc.getDisplay().getLayer(); final Point po = dc.getCursorLoc(); // as offscreen coords // assumes Node.MAX_EDGE_CONFIDENCE is <= 9. if (keyCode >= KeyEvent.VK_0 && keyCode <= (KeyEvent.VK_0 + Node.MAX_EDGE_CONFIDENCE)) { // Find an edge near the mouse position, by measuring against the middle of it setEdgeConfidence((byte)(keyCode - KeyEvent.VK_0), po.x, po.y, la, dc.getMagnification()); Display.repaint(layer_set); ke.consume(); return; } final int modifiers = ke.getModifiers(); final Display display = Display.getFront(); final Layer layer = display.getLayer(); Node nd = null; Coordinate<Node> c = null; try { switch (keyCode) { case KeyEvent.VK_T: if (0 == modifiers) { to_tag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } else if (0 == (modifiers ^ KeyEvent.SHIFT_MASK)) { to_untag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } ke.consume(); return; } if (0 == modifiers) { switch (keyCode) { case KeyEvent.VK_R: nd = root; display.center(createCoordinate(root)); ke.consume(); return; case KeyEvent.VK_B: c = findPreviousBranchOrRootPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_N: c = findNextBranchOrEndPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_L: c = getLastAdded(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_E: c = getLastEdited(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_CLOSE_BRACKET: display.animateBrowsingTo(findNearAndGetNext(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_OPEN_BRACKET: display.animateBrowsingTo(findNearAndGetPrevious(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_G: nd = findClosestNodeW(getNodesToPaint(layer), po.x, po.y, dc.getMagnification()); if (null != nd) { display.toLayer(nd.la); ke.consume(); return; } } } } finally { if (null != nd) setLastVisited(nd); } } @Override public void mouseWheelMoved(MouseWheelEvent mwe) { final int modifiers = mwe.getModifiers(); if (0 == (MouseWheelEvent.SHIFT_MASK ^ modifiers)) { Object source = mwe.getSource(); if (! (source instanceof DisplayCanvas)) return; DisplayCanvas dc = (DisplayCanvas)source; Layer la = dc.getDisplay().getLayer(); final int rotation = mwe.getWheelRotation(); final double magnification = dc.getMagnification(); final Rectangle srcRect = dc.getSrcRect(); final float x = (float)((mwe.getX() / magnification) + srcRect.x); final float y = (float)((mwe.getY() / magnification) + srcRect.y); adjustEdgeConfidence(rotation > 0 ? 1 : -1, x, y, la, magnification); Display.repaint(this); mwe.consume(); } } /** Used when reconstructing from XML. */ public void setRoot(final Node new_root) { this.root = new_root; if (null == new_root) clearCache(); else cacheSubtree(new_root.getSubtreeNodes()); } @Override public void paintSnapshot(final Graphics2D g, final Rectangle srcRect, final double mag) { switch (layer_set.getSnapshotsMode()) { case 0: // Paint without arrows paint(g, Display.getFront().getCanvas().getSrcRect(), mag, false, 0xffffffff, layer, false); return; case 1: paintAsBox(g); return; default: return; // case 2: // disabled, no paint } } public Set<Node> getEndNodes() { return new HashSet<Node>(end_nodes); } /** Fly-through image stack from source node to mark node. * @param type is ImagePlus.GRAY8 or .COLOR_RGB */ public ImagePlus flyThroughMarked(final int width, final int height, final double magnification, final int type, final String dir) { if (null == marked) return null; return flyThrough(root, marked, width, height, magnification, type, dir); } /** Fly-through image stack from first to last node. If first is not lower order than last, then start to last is returned. * @param type is ImagePlus.GRAY8 or .COLOR_RGB */ public ImagePlus flyThrough(final Node first, final Node last, final int width, final int height, final double magnification, final int type, final String dir) { // Create regions final LinkedList<Region> regions = new LinkedList<Region>(); Node node = last; float[] fps = new float[2]; while (null != node) { fps[0] = node.x; fps[1] = node.y; this.at.transform(fps, 0, fps, 0, 1); regions.addFirst(new Region(new Rectangle((int)fps[0] - width/2, (int)fps[1] - height/2, width, height), node.la, node)); if (first == node) break; node = node.parent; } return project.getLoader().createFlyThrough(regions, magnification, type, dir); } /** Measures number of branch points and end points, and total cable length. * Cable length is measured as: * Cable length: the sum of all distances between all consecutive pairs of nodes. * Lower-bound cable length: the sum of all distances between all end points to branch points, branch points to other branch points, and first branch point to root. */ public ResultsTable measure(ResultsTable rt) { if (null == root) return rt; double cable = 0, lb_cable = 0; int branch_points = 0; final Calibration cal = layer_set.getCalibration(); final double pixelWidth = cal.pixelWidth; final double pixelHeight = cal.pixelHeight; final float[] fps = new float[4]; final float[] fpp = new float[2]; synchronized (node_layer_map) { for (final Collection<Node> nodes : node_layer_map.values()) { for (final Node nd : nodes) { if (nd.getChildrenCount() > 1) branch_points++; if (null == nd.parent) continue; fps[0] = nd.x; fps[2] = nd.parent.x; fps[1] = nd.y; fps[3] = nd.parent.y; this.at.transform(fps, 0, fps, 0, 2); cable += Math.sqrt(Math.pow( (fps[0] - fps[2]) * pixelWidth, 2) + Math.pow( (fps[1] - fps[3]) * pixelHeight, 2) + Math.pow( (nd.la.getZ() - nd.parent.la.getZ()) * pixelWidth, 2)); // Lower bound cable length: if (1 == nd.getChildrenCount()) continue; else { Node prev = nd.findPreviousBranchOrRootPoint(); if (null == prev) { Utils.log("ERROR: Can't find the previous branch or root point for node " + nd); continue; } fpp[0] = prev.x; fpp[1] = prev.y; this.at.transform(fpp, 0, fpp, 0, 1); lb_cable += Math.sqrt(Math.pow( (fpp[0] - fps[0]) * pixelWidth, 2) + Math.pow( (fpp[1] - fps[1]) * pixelHeight, 2) + Math.pow( (nd.la.getZ() - nd.parent.la.getZ()) * pixelWidth, 2)); } } } } if (null == rt) rt = Utils.createResultsTable("Tree results", new String[]{"id", "N branch points", "N end points", "Cable length", "LB Cable length"}); rt.incrementCounter(); rt.addLabel("units", cal.getUnit()); rt.addValue(0, this.id); rt.addValue(1, branch_points); rt.addValue(2, end_nodes.size()); rt.addValue(3, cable); rt.addValue(4, lb_cable); return rt; } /** Expects Rectangle in world coords. */ public boolean intersects(final Layer layer, final Rectangle r) { Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) return false; try { return null != findFirstIntersectingNode(nodes, new Area(r).createTransformedArea(this.at.createInverse())); } catch (NoninvertibleTransformException e) { IJError.print(e); } return false; } /** Expects Area in world coords. */ public boolean intersects(final Layer layer, final Area area) { Set<Node> nodes = node_layer_map.get(layer); if (null == nodes || nodes.isEmpty()) return false; return null != findFirstIntersectingNode(nodes, area); } /** Expects an Area in local coordinates. */ protected Node findFirstIntersectingNode(final Set<Node> nodes, final Area a) { for (final Node nd : nodes) if (nd.intersects(a)) return nd; return null; } @Override public boolean paintsAt(final Layer layer) { synchronized (node_layer_map) { Collection<Node> nodes = node_layer_map.get(layer); return null != nodes && nodes.size() > 0; } } @Override void removeTag(final Tag tag) { synchronized (node_layer_map) { for (final Map.Entry<Layer,Set<Node>> e : node_layer_map.entrySet()) { for (final Node nd : e.getValue()) { nd.removeTag(tag); } } } } private TreeNodesDataView tndv = null; /** Create a GUI to list, in three tabs: starting point, branch points, end points, and all points. * The table has columns for X, Y, Z, data (radius or area), Layer, and tags. * Double-click on a row positions the front display at that coordinate. * An extra tab has a search field, to list nodes for a given typed-in (regex) tag. */ public Future<JFrame> createMultiTableView() { if (null == root) return null; return project.getLoader().doLater(new Callable<JFrame>() { public JFrame call() { synchronized (Tree.this) { if (null == tndv) { tndv = new TreeNodesDataView(root); return tndv.frame; } else { tndv.show(); return tndv.frame; } } }}); } protected void updateView() { if (null == tndv) return; synchronized (tndv) { tndv.recreate(this.root); } } protected void updateViewData(final Node node) { if (null == tndv) return; synchronized (tndv) { tndv.updateData(node); } } public boolean remove2(boolean check) { if (super.remove2(check)) { synchronized (this) { if (null != tndv) { tndv.frame.dispose(); tndv = null; } } return true; } return false; } private class TreeNodesDataView { private JFrame frame; private List<Node> branchnodes, endnodes, allnodes, searchnodes; private Table table_branchnodes = new Table(), table_endnodes = new Table(), table_allnodes = new Table(), table_searchnodes = new Table(); private NodeTableModel model_branchnodes, model_endnodes, model_allnodes, model_searchnodes; private final HashMap<Node,NodeData> nodedata = new HashMap<Node,NodeData>(); TreeNodesDataView(final Node root) { create(root); createGUI(); } private final class Table extends JTable { Table() { super(); getTableHeader().addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { // mousePressed would fail to repaint due to asynch issues if (2 != me.getClickCount()) return; int viewColumn = getColumnModel().getColumnIndexAtX(me.getX()); int column = convertColumnIndexToModel(viewColumn); if (-1 == column) return; ((NodeTableModel)getModel()).sortByColumn(column, me.isShiftDown()); } }); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { final int row = Table.this.rowAtPoint(me.getPoint()); if (2 == me.getClickCount()) { go(row); } else if (Utils.isPopupTrigger(me)) { JPopupMenu popup = new JPopupMenu(); final JMenuItem go = new JMenuItem("Go"); popup.add(go); // ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent ae) { final Object src = ae.getSource(); if (src == go) go(row); } }; go.addActionListener(listener); popup.show(Table.this, me.getX(), me.getY()); } } }); this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_G) { final int row = getSelectedRow(); if (-1 != row) go(row); } else if (ke.getKeyCode() == KeyEvent.VK_W && (0 == (Utils.getControlModifier() ^ ke.getModifiers()))) { frame.dispose(); } } }); } void go(int row) { Display.centerAt(Tree.this.createCoordinate(((NodeTableModel)this.getModel()).nodes.get(row))); } } void show() { frame.pack(); frame.setVisible(true); frame.toFront(); } private void createGUI() { this.frame = new JFrame("Nodes for " + Tree.this); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { Tree.this.tndv = null; } }); JTabbedPane tabs = new JTabbedPane(); tabs.setPreferredSize(new Dimension(500, 500)); tabs.add("All nodes", new JScrollPane(table_allnodes)); tabs.add("Branch nodes", new JScrollPane(table_branchnodes)); tabs.add("End nodes", new JScrollPane(table_endnodes)); final JTextField search = new JTextField(14); search.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_ENTER) { search(search.getText()); } } }); JButton b = new JButton("Search"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { search(search.getText()); } }); JPanel pane = new JPanel(); GridBagLayout gb = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 0; c.gridwidth = 1; c.anchor = GridBagConstraints.NORTH; gb.setConstraints(search, c); pane.add(search); c.gridx = 1; gb.setConstraints(b, c); pane.add(b); c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.fill = GridBagConstraints.BOTH; pane.add(new JScrollPane(table_searchnodes)); tabs.add("Search", pane); frame.getContentPane().add(tabs); frame.pack(); ij.gui.GUI.center(frame); frame.setVisible(true); } private synchronized void create(final Node root) { this.branchnodes = new ArrayList<Node>(); this.endnodes = new ArrayList<Node>(); this.allnodes = null == root ? new ArrayList<Node>() : new ArrayList<Node>(root.getSubtreeNodes()); this.searchnodes = new ArrayList<Node>(); for (final Node nd : allnodes) { switch (nd.getChildrenCount()) { case 0: endnodes.add(nd); break; case 1: continue; // slab default: branchnodes.add(nd); break; } } this.model_branchnodes = new NodeTableModel(branchnodes, nodedata); this.model_endnodes = new NodeTableModel(endnodes, nodedata); this.model_allnodes = new NodeTableModel(allnodes, nodedata); this.model_searchnodes = new NodeTableModel(searchnodes, nodedata); this.table_branchnodes.setModel(this.model_branchnodes); this.table_endnodes.setModel(this.model_endnodes); this.table_allnodes.setModel(this.model_allnodes); this.table_searchnodes.setModel(this.model_searchnodes); } void recreate(final Node root) { Tree.this.project.getLoader().doLater(new Callable() { public Object call() { create(root); Utils.revalidateComponent(frame); return null; }}); } void updateData(final Node node) { synchronized (nodedata) { nodedata.remove(node); } } private void search(final String regex) { final StringBuilder sb = new StringBuilder(); if (!regex.startsWith("^")) sb.append("^.*"); sb.append(regex); if (!regex.endsWith("$")) sb.append(".*$"); try { final Pattern pat = Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); this.searchnodes = new ArrayList<Node>(); for (final Node nd : allnodes) { final Collection<Tag> tags = (Collection<Tag>) nd.getTags(); if (null == tags) continue; for (final Tag tag : tags) { if (pat.matcher(tag.toString()).matches()) { this.searchnodes.add(nd); break; } } } this.model_searchnodes = new NodeTableModel(this.searchnodes, this.nodedata); this.table_searchnodes.setModel(this.model_searchnodes); this.frame.pack(); } catch (Exception e) { IJError.print(e); } } } private final class NodeData { final double x, y, z; final String data, tags, conf; NodeData(final Node nd) { final float[] fp = new float[]{nd.x, nd.y}; Tree.this.at.transform(fp, 0, fp, 0, 1); final Calibration cal = Tree.this.layer_set.getCalibration(); this.x = fp[0] * cal.pixelHeight; this.y = fp[1] * cal.pixelWidth; this.z = nd.la.getZ() * cal.pixelWidth; // Assumes only RadiusNode and AreaNode exist if (nd.getClass() == AreaTree.AreaNode.class) { this.data = new StringBuilder (Utils.cutNumber (Math.abs (AreaCalculations.area (((AreaTree.AreaNode)nd).getData().getPathIterator(null))) * cal.pixelWidth * cal.pixelHeight, 1)).append(' ').append(cal.getUnits()).append('^').append(2).toString(); } else { this.data = new StringBuilder(Utils.cutNumber(((Treeline.RadiusNode)nd).getData(), 1)).append(' ').append(cal.getUnits()).toString(); } this.conf = null == nd.parent ? "root" : Byte.toString(nd.parent.getEdgeConfidence(nd)); // final Set<Tag> ts = nd.getTags(); if (null != ts) { if (1 == ts.size()) this.tags = ts.iterator().next().toString(); else { final StringBuilder sb = new StringBuilder(); for (final Tag t : ts) sb.append(t.toString()).append(", "); sb.setLength(sb.length() -2); this.tags = sb.toString(); } } else { this.tags = ""; } } } private class NodeTableModel extends AbstractTableModel { final List<Node> nodes; final HashMap<Node,NodeData> nodedata; private NodeTableModel(final List<Node> nodes, final HashMap<Node,NodeData> nodedata) { this.nodes = nodes; this.nodedata = nodedata; // a cache } private String getDataName() { if (nodes.isEmpty()) return "Data"; if (nodes.get(0) instanceof Treeline.RadiusNode) return "Radius"; if (nodes.get(0) instanceof AreaTree.AreaNode) return "Area"; return "Data"; } public String getColumnName(int col) { switch (col) { case 0: return ""; // listing case 1: return "X"; case 2: return "Y"; case 3: return "Z"; case 4: return "Layer"; case 5: return "Edge confidence"; case 6: return getDataName(); case 7: return "Tags"; default: return null; // should be an error } } public int getRowCount() { return nodes.size(); } public int getColumnCount() { return 8; } public Object getRawValueAt(int row, int col) { if (0 == nodes.size()) return null; final Node nd = nodes.get(row); switch (col) { case 0: return row+1; case 1: return getNodeData(nd).x; case 2: return getNodeData(nd).y; case 3: return getNodeData(nd).z; case 4: return nd.la; case 5: return getNodeData(nd).conf; case 6: return getNodeData(nd).data; case 7: return getNodeData(nd).tags; default: return null; } } public Object getValueAt(int row, int col) { final Object o = getRawValueAt(row, col); return o instanceof Double ? Utils.cutNumber(((Double)o).doubleValue(), 1) : o; } private NodeData getNodeData(final Node nd) { synchronized (nodedata) { NodeData ndat = nodedata.get(nd); if (null == ndat) { ndat = new NodeData(nd); nodedata.put(nd, ndat); } return ndat; } } public boolean isCellEditable(int row, int col) { return false; } public void setValueAt(Object value, int row, int col) {} public void sortByColumn(final int col, final boolean descending) { final ArrayList<Node> nodes = new ArrayList<Node>(NodeTableModel.this.nodes); Collections.sort(NodeTableModel.this.nodes, new Comparator<Node>() { public int compare(Node nd1, Node nd2) { if (descending) { Node tmp = nd1; nd1 = nd2; nd2 = tmp; } Object val1 = getRawValueAt(nodes.indexOf(nd1), col); Object val2 = getRawValueAt(nodes.indexOf(nd2), col); if (7 == col) { // Replace empty strings with a row of z val1 = fixStrings(val1); val2 = fixStrings(val2); } return ((Comparable)val1).compareTo((Comparable)val2); } }); fireTableDataChanged(); fireTableStructureChanged(); } private final Object fixStrings(final Object val) { if (val.getClass() == String.class) { if (0 == ((String)val).length()) return "zzzzzz"; else return ((String)val).toLowerCase(); } return val; } } synchronized protected boolean layerRemoved(Layer la) { super.layerRemoved(la); final Set<Node> nodes = node_layer_map.remove(la); if (null == nodes) return true; final List<Tree> siblings = new ArrayList<Tree>(); for (final Iterator<Node> it = nodes.iterator(); it.hasNext(); ) { final Node nd = it.next(); it.remove(); fireNodeRemoved(nd); if (null == nd.parent) { switch (nd.getChildrenCount()) { case 1: this.root = nd.children[0]; nd.children[0] = null; break; case 0: this.root = null; break; default: // split: the first child remains as root: this.root = nd.children[0]; nd.children[0] = null; // ... and the rest of children become a new Tree each when done for (int i=1; i<nd.children.length; i++) { Tree t = newInstance(); t.addToDatabase(); t.root = nd.children[i]; nd.children[i] = null; siblings.add(t); } break; } } else { if (null == nd.children) { end_nodes.remove(nd); } else { // add all its children to the parent for (int i=0; i<nd.children.length; i++) { nd.children[i].parent = null; nd.parent.add(nd.children[i], nd.confidence[i]); } } nd.parent.remove(nd); } } if (!siblings.isEmpty()) { this.clearCache(); if (null != this.root) this.cacheSubtree(root.getSubtreeNodes()); for (Tree t : siblings) { t.cacheSubtree(t.root.getSubtreeNodes()); t.calculateBoundingBox(); layer_set.add(t); project.getProjectTree().addSibling(this, t); } } this.calculateBoundingBox(); return true; } public boolean apply(final Layer la, final Area roi, final mpicbg.models.CoordinateTransform ict) throws Exception { synchronized (node_layer_map) { if (null == root) return true; final Set<Node> nodes = node_layer_map.get(la); if (null == nodes || nodes.isEmpty()) return true; AffineTransform inverse = this.at.createInverse(); final Area localroi = roi.createTransformedArea(inverse); mpicbg.models.CoordinateTransform chain = null; for (final Node nd : nodes) { if (nd.intersects(localroi)) { if (null == chain) { chain = M.wrap(this.at, ict, inverse); } } nd.apply(chain, roi); } if (null != chain) calculateBoundingBox(); } return true; } public boolean apply(final VectorDataTransform vdt) throws Exception { synchronized (node_layer_map) { if (null == root) return true; final Set<Node> nodes = node_layer_map.get(vdt.layer); if (null == nodes || nodes.isEmpty()) return true; final VectorDataTransform vlocal = vdt.makeLocalTo(this); for (final Node nd : nodes) { nd.apply(vlocal); } calculateBoundingBox(); } return true; } }
false
true
public void keyPressed(KeyEvent ke) { switch (ProjectToolbar.getToolId()) { case ProjectToolbar.PEN: case ProjectToolbar.BRUSH: break; default: // Reject return; } Object source = ke.getSource(); if (! (source instanceof DisplayCanvas)) return; final int keyCode = ke.getKeyCode(); final DisplayCanvas dc = (DisplayCanvas)source; if (null != to_tag || null != to_untag) { // Can only add a tag for A-Z or numbers! if (! (Character.isLetterOrDigit((char)keyCode) && (Character.isDigit((char)keyCode) || Character.isUpperCase((char)keyCode)))) { // VK_F1, F2 ... are lower case letters! Evil! // Cancel tagging Utils.showStatus("Canceled tagging"); to_tag = null; to_untag = null; ke.consume(); return; } if (KeyEvent.VK_0 == keyCode) { // force dialogs for next key show_tag_dialogs = true; ke.consume(); return; } final boolean untag = null != to_untag; final Node target = untag ? to_untag : to_tag; try { layer_set.addPreDataEditStep(this); if (show_tag_dialogs) { if (untag) { if (layer_set.askToRemoveTag(keyCode)) { // if removed from tag namespace, it will be removed from all nodes that have it layer_set.addDataEditStep(this); } } else { Tag t = layer_set.askForNewTag(keyCode); if (null != t) { target.addTag(t); Display.repaint(layer_set); layer_set.addDataEditStep(this); // no 'with' macros ... without half a dozen layers of cruft. } } show_tag_dialogs = false; return; } TreeSet<Tag> ts = layer_set.getTags(keyCode); if (ts.isEmpty()) { if (untag) return; if (null == layer_set.askForNewTag(keyCode)) return; ts = layer_set.getTags(keyCode); } // Ask to chose one, if more than one if (ts.size() > 1) { final JPopupMenu popup = new JPopupMenu(); popup.add(new JLabel(untag ? "Untag:" : "Tag:")); int i = 1; for (final Tag tag : ts) { JMenuItem item = new JMenuItem(tag.toString()); popup.add(item); if (i < 10) { item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0 + i, 0, true)); } i++; item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) target.removeTag(tag); else target.addTag(tag); Display.repaint(layer_set); layer_set.addDataEditStep(Tree.this); } }); } popup.addSeparator(); JMenuItem item = new JMenuItem(untag ? "Remove tag..." : "Define new tag..."); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, 0, true)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) { layer_set.askToRemoveTag(keyCode); } else { if (null == layer_set.askForNewTag(keyCode)) return; target.addTag(layer_set.getTags(keyCode).last()); Display.repaint(layer_set); } layer_set.addDataEditStep(Tree.this); } }); // Show the popup on the Display, under the node final float[] fp = new float[]{target.x, target.y}; this.at.transform(fp, 0, fp, 0, 1); Rectangle srcRect = dc.getSrcRect(); double magnification = dc.getMagnification(); final int x = (int)((fp[0] - srcRect.x) * magnification); final int y = (int)((fp[1] - srcRect.y) * magnification); popup.show(dc, x, y); } else { if (untag) target.removeTag(ts.first()); else target.addTag(ts.first()); Display.repaint(layer_set); layer_set.addDataEditStep(this); } return; } finally { updateViewData(untag ? to_untag : to_tag); to_tag = null; to_untag = null; ke.consume(); } } Layer la = dc.getDisplay().getLayer(); final Point po = dc.getCursorLoc(); // as offscreen coords // assumes Node.MAX_EDGE_CONFIDENCE is <= 9. if (keyCode >= KeyEvent.VK_0 && keyCode <= (KeyEvent.VK_0 + Node.MAX_EDGE_CONFIDENCE)) { // Find an edge near the mouse position, by measuring against the middle of it setEdgeConfidence((byte)(keyCode - KeyEvent.VK_0), po.x, po.y, la, dc.getMagnification()); Display.repaint(layer_set); ke.consume(); return; } final int modifiers = ke.getModifiers(); final Display display = Display.getFront(); final Layer layer = display.getLayer(); Node nd = null; Coordinate<Node> c = null; try { switch (keyCode) { case KeyEvent.VK_T: if (0 == modifiers) { to_tag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } else if (0 == (modifiers ^ KeyEvent.SHIFT_MASK)) { to_untag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } ke.consume(); return; } if (0 == modifiers) { switch (keyCode) { case KeyEvent.VK_R: nd = root; display.center(createCoordinate(root)); ke.consume(); return; case KeyEvent.VK_B: c = findPreviousBranchOrRootPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_N: c = findNextBranchOrEndPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_L: c = getLastAdded(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_E: c = getLastEdited(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_CLOSE_BRACKET: display.animateBrowsingTo(findNearAndGetNext(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_OPEN_BRACKET: display.animateBrowsingTo(findNearAndGetPrevious(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_G: nd = findClosestNodeW(getNodesToPaint(layer), po.x, po.y, dc.getMagnification()); if (null != nd) { display.toLayer(nd.la); ke.consume(); return; } } } } finally { if (null != nd) setLastVisited(nd); } }
public void keyPressed(KeyEvent ke) { switch (ProjectToolbar.getToolId()) { case ProjectToolbar.PEN: case ProjectToolbar.BRUSH: break; default: // Reject return; } Object source = ke.getSource(); if (! (source instanceof DisplayCanvas)) return; final int keyCode = ke.getKeyCode(); final DisplayCanvas dc = (DisplayCanvas)source; if (null != to_tag || null != to_untag) { // Can only add a tag for A-Z or numbers! if (! (Character.isLetterOrDigit((char)keyCode) && (Character.isDigit((char)keyCode) || Character.isUpperCase((char)keyCode)))) { // VK_F1, F2 ... are lower case letters! Evil! // Cancel tagging Utils.showStatus("Canceled tagging"); to_tag = null; to_untag = null; ke.consume(); return; } if (!show_tag_dialogs && KeyEvent.VK_0 == keyCode) { // force dialogs for next key show_tag_dialogs = true; ke.consume(); return; } final boolean untag = null != to_untag; final Node target = untag ? to_untag : to_tag; try { layer_set.addPreDataEditStep(this); if (show_tag_dialogs) { if (untag) { if (layer_set.askToRemoveTag(keyCode)) { // if removed from tag namespace, it will be removed from all nodes that have it layer_set.addDataEditStep(this); } } else { Tag t = layer_set.askForNewTag(keyCode); if (null != t) { target.addTag(t); Display.repaint(layer_set); layer_set.addDataEditStep(this); // no 'with' macros ... without half a dozen layers of cruft. } } show_tag_dialogs = false; return; } TreeSet<Tag> ts = layer_set.getTags(keyCode); if (ts.isEmpty()) { if (untag) return; if (null == layer_set.askForNewTag(keyCode)) return; ts = layer_set.getTags(keyCode); } // Ask to chose one, if more than one if (ts.size() > 1) { final JPopupMenu popup = new JPopupMenu(); popup.add(new JLabel(untag ? "Untag:" : "Tag:")); int i = 1; for (final Tag tag : ts) { JMenuItem item = new JMenuItem(tag.toString()); popup.add(item); if (i < 10) { item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0 + i, 0, true)); } i++; item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) target.removeTag(tag); else target.addTag(tag); Display.repaint(layer_set); layer_set.addDataEditStep(Tree.this); } }); } popup.addSeparator(); JMenuItem item = new JMenuItem(untag ? "Remove tag..." : "Define new tag..."); popup.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, 0, true)); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (untag) { layer_set.askToRemoveTag(keyCode); } else { Tag t = layer_set.askForNewTag(keyCode); if (null == t) return; target.addTag(t); Display.repaint(layer_set); } layer_set.addDataEditStep(Tree.this); } }); // Show the popup on the Display, under the node final float[] fp = new float[]{target.x, target.y}; this.at.transform(fp, 0, fp, 0, 1); Rectangle srcRect = dc.getSrcRect(); double magnification = dc.getMagnification(); final int x = (int)((fp[0] - srcRect.x) * magnification); final int y = (int)((fp[1] - srcRect.y) * magnification); popup.show(dc, x, y); } else { if (untag) target.removeTag(ts.first()); else target.addTag(ts.first()); Display.repaint(layer_set); layer_set.addDataEditStep(this); } return; } finally { updateViewData(untag ? to_untag : to_tag); to_tag = null; to_untag = null; ke.consume(); } } Layer la = dc.getDisplay().getLayer(); final Point po = dc.getCursorLoc(); // as offscreen coords // assumes Node.MAX_EDGE_CONFIDENCE is <= 9. if (keyCode >= KeyEvent.VK_0 && keyCode <= (KeyEvent.VK_0 + Node.MAX_EDGE_CONFIDENCE)) { // Find an edge near the mouse position, by measuring against the middle of it setEdgeConfidence((byte)(keyCode - KeyEvent.VK_0), po.x, po.y, la, dc.getMagnification()); Display.repaint(layer_set); ke.consume(); return; } final int modifiers = ke.getModifiers(); final Display display = Display.getFront(); final Layer layer = display.getLayer(); Node nd = null; Coordinate<Node> c = null; try { switch (keyCode) { case KeyEvent.VK_T: if (0 == modifiers) { to_tag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } else if (0 == (modifiers ^ KeyEvent.SHIFT_MASK)) { to_untag = findNodeNear(po.x, po.y, layer, dc.getMagnification()); } ke.consume(); return; } if (0 == modifiers) { switch (keyCode) { case KeyEvent.VK_R: nd = root; display.center(createCoordinate(root)); ke.consume(); return; case KeyEvent.VK_B: c = findPreviousBranchOrRootPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_N: c = findNextBranchOrEndPoint(po.x, po.y, layer, dc.getMagnification()); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_L: c = getLastAdded(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_E: c = getLastEdited(); if (null == c) return; nd = c.object; display.center(c); ke.consume(); return; case KeyEvent.VK_CLOSE_BRACKET: display.animateBrowsingTo(findNearAndGetNext(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_OPEN_BRACKET: display.animateBrowsingTo(findNearAndGetPrevious(po.x, po.y, layer, dc.getMagnification())); ke.consume(); return; case KeyEvent.VK_G: nd = findClosestNodeW(getNodesToPaint(layer), po.x, po.y, dc.getMagnification()); if (null != nd) { display.toLayer(nd.la); ke.consume(); return; } } } } finally { if (null != nd) setLastVisited(nd); } }
diff --git a/src/com/android/contacts/util/PhoneNumberFormatter.java b/src/com/android/contacts/util/PhoneNumberFormatter.java index 6e63aac37..204ac69a8 100644 --- a/src/com/android/contacts/util/PhoneNumberFormatter.java +++ b/src/com/android/contacts/util/PhoneNumberFormatter.java @@ -1,75 +1,73 @@ /* * 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.contacts.util; import com.android.contacts.ContactsUtils; import android.content.Context; import android.os.AsyncTask; import android.telephony.PhoneNumberFormattingTextWatcher; import android.widget.TextView; public final class PhoneNumberFormatter { private PhoneNumberFormatter() {} /** * Load {@link TextWatcherLoadAsyncTask} in a worker thread and set it to a {@link TextView}. */ private static class TextWatcherLoadAsyncTask extends AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher> { private final String mCountryCode; private final TextView mTextView; public TextWatcherLoadAsyncTask(String countryCode, TextView textView) { mCountryCode = countryCode; mTextView = textView; } @Override protected PhoneNumberFormattingTextWatcher doInBackground(Void... params) { return new PhoneNumberFormattingTextWatcher(mCountryCode); } @Override protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) { if (watcher == null || isCancelled()) { return; // May happen if we cancel the task. } - if (mTextView.getHandler() == null) { - return; // View is already detached. - } + // Setting a text changed listener is safe even after the view is detached. mTextView.addTextChangedListener(watcher); // Note changes the user made before onPostExecute() will not be formatted, but // once they type the next letter we format the entire text, so it's not a big deal. // (And loading PhoneNumberFormattingTextWatcher is usually fast enough.) // We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format // the existing content here, but that could cause unwanted results. // (e.g. the contact editor thinks the user changed the content, and would save // when closed even when the user didn't make other changes.) } } /** * Delay-set {@link PhoneNumberFormattingTextWatcher} to a {@link TextView}. */ public static final void setPhoneNumberFormattingTextWatcher(Context context, TextView textView) { new TextWatcherLoadAsyncTask(ContactsUtils.getCurrentCountryIso(context), textView) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null); } }
true
true
protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) { if (watcher == null || isCancelled()) { return; // May happen if we cancel the task. } if (mTextView.getHandler() == null) { return; // View is already detached. } mTextView.addTextChangedListener(watcher); // Note changes the user made before onPostExecute() will not be formatted, but // once they type the next letter we format the entire text, so it's not a big deal. // (And loading PhoneNumberFormattingTextWatcher is usually fast enough.) // We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format // the existing content here, but that could cause unwanted results. // (e.g. the contact editor thinks the user changed the content, and would save // when closed even when the user didn't make other changes.) }
protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) { if (watcher == null || isCancelled()) { return; // May happen if we cancel the task. } // Setting a text changed listener is safe even after the view is detached. mTextView.addTextChangedListener(watcher); // Note changes the user made before onPostExecute() will not be formatted, but // once they type the next letter we format the entire text, so it's not a big deal. // (And loading PhoneNumberFormattingTextWatcher is usually fast enough.) // We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format // the existing content here, but that could cause unwanted results. // (e.g. the contact editor thinks the user changed the content, and would save // when closed even when the user didn't make other changes.) }
diff --git a/runtime/src/org/zaluum/widget/ZSliderWidget.java b/runtime/src/org/zaluum/widget/ZSliderWidget.java index 8476a9b..8efda9b 100644 --- a/runtime/src/org/zaluum/widget/ZSliderWidget.java +++ b/runtime/src/org/zaluum/widget/ZSliderWidget.java @@ -1,38 +1,38 @@ package org.zaluum.widget; import java.util.concurrent.atomic.AtomicReference; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.zaluum.annotation.Apply; import org.zaluum.annotation.Box; /** * * @author frede * */ @Box public class ZSliderWidget extends JSlider { private static final long serialVersionUID = 1L; private AtomicReference<Double> out = new AtomicReference<Double>(); - public ZSliderWidget(int min, int max) { - setMaximum(max); - setMinimum(min); + public ZSliderWidget() { + setMaximum(1000); + setMinimum(0); setValue(0); out.set((double) 0); addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { - out.set((double) getValue()); + out.set((double) getValue()/1000.0); } }); } @Apply public double apply() { return out.get(); } }
false
true
public ZSliderWidget(int min, int max) { setMaximum(max); setMinimum(min); setValue(0); out.set((double) 0); addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { out.set((double) getValue()); } }); }
public ZSliderWidget() { setMaximum(1000); setMinimum(0); setValue(0); out.set((double) 0); addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { out.set((double) getValue()/1000.0); } }); }
diff --git a/src/main/java/net/glowstone/scheduler/GlowScheduler.java b/src/main/java/net/glowstone/scheduler/GlowScheduler.java index 4b6dab8..d33fa64 100644 --- a/src/main/java/net/glowstone/scheduler/GlowScheduler.java +++ b/src/main/java/net/glowstone/scheduler/GlowScheduler.java @@ -1,325 +1,326 @@ package net.glowstone.scheduler; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import net.glowstone.GlowServer; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitWorker; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; /** * A scheduler for managing server ticks, Bukkit tasks, and other synchronization. */ public final class GlowScheduler implements BukkitScheduler { private static class GlowThreadFactory implements ThreadFactory { public static final GlowThreadFactory INSTANCE = new GlowThreadFactory(); private final AtomicInteger threadCounter = new AtomicInteger(); private GlowThreadFactory() { } @Override public Thread newThread(Runnable runnable) { return new Thread(runnable, "Glowstone-scheduler-" + threadCounter.getAndIncrement()); } } /** * The number of milliseconds between pulses. */ static final int PULSE_EVERY = 50; /** * The server this scheduler is managing for. */ private final GlowServer server; /** * The scheduled executor service which backs this worlds. */ private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(GlowThreadFactory.INSTANCE); /** * Executor to handle execution of async tasks */ private final ExecutorService asyncTaskExecutor = Executors.newCachedThreadPool(GlowThreadFactory.INSTANCE); /** * A list of active tasks. */ private final ConcurrentMap<Integer, GlowTask> tasks = new ConcurrentHashMap<Integer, GlowTask>(); /** * The primary worlds thread in which pulse() is called. */ private Thread primaryThread; /** * World tick scheduler */ private final WorldScheduler worlds; /** * Tasks to be executed during the tick */ private final Deque<Runnable> inTickTasks = new ConcurrentLinkedDeque<Runnable>(); /** * Condition to wait on when processing in tick tasks */ private final Object inTickTaskCondition; /** * Runnable to run at end of tick */ private final Runnable tickEndRun; /** * Creates a new task scheduler. */ public GlowScheduler(GlowServer server, WorldScheduler worlds) { this.server = server; this.worlds = worlds; inTickTaskCondition = worlds.getAdvanceCondition(); tickEndRun = new Runnable() { @Override public void run() { GlowScheduler.this.worlds.doTickEnd(); } }; primaryThread = Thread.currentThread(); } public void start() { executor.scheduleAtFixedRate(new Runnable() { public void run() { try { pulse(); } catch (Exception ex) { GlowServer.logger.log(Level.SEVERE, "Error while pulsing", ex); } } }, 0, PULSE_EVERY, TimeUnit.MILLISECONDS); } /** * Stops the scheduler and all tasks. */ public void stop() { cancelAllTasks(); worlds.stop(); executor.shutdownNow(); asyncTaskExecutor.shutdown(); synchronized (inTickTaskCondition) { for (Runnable task : inTickTasks) { if (task instanceof Future) { ((Future) task).cancel(false); } } inTickTasks.clear(); } } /** * Schedules the specified task. * @param task The task. */ private GlowTask schedule(GlowTask task) { tasks.put(task.getTaskId(), task); return task; } /** * Returns true if the current {@link Thread} is the server's primary thread. */ public boolean isPrimaryThread() { return Thread.currentThread() == primaryThread; } public void scheduleInTickExecution(Runnable run) { if (isPrimaryThread() || executor.isShutdown()) { run.run(); } else { synchronized (inTickTaskCondition) { inTickTasks.addFirst(run); inTickTaskCondition.notifyAll(); } } } /** * Adds new tasks and updates existing tasks, removing them if necessary. * <p/> * TODO: Add watchdog system to make sure ticks advance */ private void pulse() { primaryThread = Thread.currentThread(); // Process player packets server.getSessionRegistry().pulse(); // Run the relevant tasks. for (Iterator<GlowTask> it = tasks.values().iterator(); it.hasNext(); ) { GlowTask task = it.next(); switch (task.shouldExecute()) { case RUN: if (task.isSync()) { task.run(); } else { asyncTaskExecutor.submit(task); } + break; case STOP: it.remove(); } } try { int currentTick = worlds.beginTick(); try { asyncTaskExecutor.submit(tickEndRun); } catch (RejectedExecutionException ex) { worlds.stop(); return; } Runnable tickTask; synchronized (inTickTaskCondition) { while (!worlds.isTickComplete(currentTick)) { while ((tickTask = inTickTasks.poll()) != null) { tickTask.run(); } inTickTaskCondition.wait(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public int scheduleSyncDelayedTask(Plugin plugin, Runnable task, long delay) { return scheduleSyncRepeatingTask(plugin, task, delay, -1); } public int scheduleSyncDelayedTask(Plugin plugin, Runnable task) { return scheduleSyncDelayedTask(plugin, task, 0); } public int scheduleSyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period) { return schedule(new GlowTask(plugin, task, true, delay, period)).getTaskId(); } @Deprecated @SuppressWarnings("deprecation") public int scheduleAsyncDelayedTask(Plugin plugin, Runnable task, long delay) { return scheduleAsyncRepeatingTask(plugin, task, delay, -1); } @Deprecated @SuppressWarnings("deprecation") public int scheduleAsyncDelayedTask(Plugin plugin, Runnable task) { return scheduleAsyncRepeatingTask(plugin, task, 0, -1); } @Deprecated public int scheduleAsyncRepeatingTask(Plugin plugin, Runnable task, long delay, long period) { return schedule(new GlowTask(plugin, task, false, delay, period)).getTaskId(); } public <T> Future<T> callSyncMethod(Plugin plugin, Callable<T> task) { FutureTask<T> future = new FutureTask<T>(task); runTask(plugin, future); return future; } public <T> T syncIfNeeded(Callable<T> task) throws Exception { if (isPrimaryThread()) { return task.call(); } else { return callSyncMethod(null, task).get(); } } public BukkitTask runTask(Plugin plugin, Runnable task) throws IllegalArgumentException { return runTaskLater(plugin, task, 0); } public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable task) throws IllegalArgumentException { return runTaskLaterAsynchronously(plugin, task, 0); } public BukkitTask runTaskLater(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException { return runTaskTimer(plugin, task, delay, -1); } public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable task, long delay) throws IllegalArgumentException { return runTaskTimerAsynchronously(plugin, task, delay, -1); } public BukkitTask runTaskTimer(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException { return schedule(new GlowTask(plugin, task, true, delay, period)); } public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable task, long delay, long period) throws IllegalArgumentException { return schedule(new GlowTask(plugin, task, false, delay, period)); } public void cancelTask(int taskId) { tasks.remove(taskId); } public void cancelTasks(Plugin plugin) { for (Iterator<GlowTask> it = tasks.values().iterator(); it.hasNext(); ) { if (it.next().getOwner() == plugin) { it.remove(); } } } public void cancelAllTasks() { tasks.clear(); } public boolean isCurrentlyRunning(int taskId) { GlowTask task = tasks.get(taskId); return task != null && task.getLastExecutionState() == TaskExecutionState.RUN; } public boolean isQueued(int taskId) { return tasks.containsKey(taskId); } /** * Returns active async tasks * @return active async tasks */ public List<BukkitWorker> getActiveWorkers() { return ImmutableList.<BukkitWorker>copyOf(Collections2.filter(tasks.values(), new Predicate<GlowTask>() { @Override public boolean apply(@Nullable GlowTask glowTask) { return glowTask != null && !glowTask.isSync() && glowTask.getLastExecutionState() == TaskExecutionState.RUN; } })); } /** * Returns tasks that still have at least one run remaining * @return the tasks to be run */ public List<BukkitTask> getPendingTasks() { return new ArrayList<BukkitTask>(tasks.values()); } }
true
true
private void pulse() { primaryThread = Thread.currentThread(); // Process player packets server.getSessionRegistry().pulse(); // Run the relevant tasks. for (Iterator<GlowTask> it = tasks.values().iterator(); it.hasNext(); ) { GlowTask task = it.next(); switch (task.shouldExecute()) { case RUN: if (task.isSync()) { task.run(); } else { asyncTaskExecutor.submit(task); } case STOP: it.remove(); } } try { int currentTick = worlds.beginTick(); try { asyncTaskExecutor.submit(tickEndRun); } catch (RejectedExecutionException ex) { worlds.stop(); return; } Runnable tickTask; synchronized (inTickTaskCondition) { while (!worlds.isTickComplete(currentTick)) { while ((tickTask = inTickTasks.poll()) != null) { tickTask.run(); } inTickTaskCondition.wait(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
private void pulse() { primaryThread = Thread.currentThread(); // Process player packets server.getSessionRegistry().pulse(); // Run the relevant tasks. for (Iterator<GlowTask> it = tasks.values().iterator(); it.hasNext(); ) { GlowTask task = it.next(); switch (task.shouldExecute()) { case RUN: if (task.isSync()) { task.run(); } else { asyncTaskExecutor.submit(task); } break; case STOP: it.remove(); } } try { int currentTick = worlds.beginTick(); try { asyncTaskExecutor.submit(tickEndRun); } catch (RejectedExecutionException ex) { worlds.stop(); return; } Runnable tickTask; synchronized (inTickTaskCondition) { while (!worlds.isTickComplete(currentTick)) { while ((tickTask = inTickTasks.poll()) != null) { tickTask.run(); } inTickTaskCondition.wait(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
diff --git a/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/SignatureComposite.java b/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/SignatureComposite.java index 509034b..81c8c5a 100755 --- a/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/SignatureComposite.java +++ b/org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/ui/wizards/SignatureComposite.java @@ -1,110 +1,111 @@ package org.jcryptool.visual.sig.ui.wizards; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Text; public class SignatureComposite extends Composite implements SelectionListener{ private Group grpSignatures; private Text txtDescription; private Button rdo1; private Button rdo2; private Button rdo3; private Button rdo4; //Constructor public SignatureComposite(Composite parent, int style) { super(parent, style); //parent.setSize(600, 400); //Draw the controls initialize(); } /** * Draws all the controls of the composite */ private void initialize() { grpSignatures = new Group(this, SWT.NONE); grpSignatures.setText(Messages.SignatureWizard_grpSignatures); grpSignatures.setBounds(10, 10, 300, 151); rdo1 = new Button(grpSignatures, SWT.RADIO); rdo1.setSelection(true); rdo1.setBounds(10, 19, 118, 18); rdo1.setText(Messages.SignatureWizard_DSA); rdo2 = new Button(grpSignatures, SWT.RADIO); rdo2.setBounds(10, 43, 118, 18); rdo2.setText(Messages.SignatureWizard_RSA); rdo3 = new Button(grpSignatures, SWT.RADIO); rdo3.setEnabled(false); rdo3.setBounds(10, 67, 118, 18); rdo3.setText(Messages.SignatureWizard_ECDSA); rdo4 = new Button(grpSignatures, SWT.RADIO); rdo4.setEnabled(false); rdo4.setBounds(10, 91, 118, 18); rdo4.setText(Messages.SignatureWizard_RSAandMGF1); Group grpDescription = new Group(this, SWT.NONE); grpDescription.setText(Messages.SignatureWizard_grpDescription); grpDescription.setBounds(10, 171, 300, 255); txtDescription = new Text(grpDescription, SWT.WRAP | SWT.TRANSPARENT); txtDescription.setEditable(false); txtDescription.setBounds(10, 15, 275, 213); txtDescription.setBackground(new Color(Display.getCurrent(), 220, 220, 220)); txtDescription.setText(Messages.SignatureWizard_DSA_description); //Add event listeners rdo1.addSelectionListener(this); rdo2.addSelectionListener(this); rdo3.addSelectionListener(this); rdo4.addSelectionListener(this); //rdo5.addSelectionListener(this); //If called by JCT-CA only SHA-256 can be used! Therefore only ECDSA, RSA and RSA with MGF1 will work if (org.jcryptool.visual.sig.algorithm.Input.privateKey != null) { rdo1.setEnabled(false); + rdo1.setSelection(false); rdo2.setSelection(true); rdo3.setEnabled(false); rdo4.setEnabled(false); } } /** * @return the grpSignatures */ public Group getgrpSignatures() { return grpSignatures; } @Override public void widgetSelected(SelectionEvent e) { if (rdo1.getSelection()) txtDescription.setText(Messages.SignatureWizard_DSA_description); else if (rdo2.getSelection()) txtDescription.setText(Messages.SignatureWizard_RSA_description); else if (rdo3.getSelection()) txtDescription.setText(Messages.SignatureWizard_ECDSA_description); else if (rdo4.getSelection()) txtDescription.setText(Messages.SignatureWizard_RSAandMGF1_description); }//end widgetSelected @Override public void widgetDefaultSelected(SelectionEvent e) { // TODO Auto-generated method stub } }
true
true
private void initialize() { grpSignatures = new Group(this, SWT.NONE); grpSignatures.setText(Messages.SignatureWizard_grpSignatures); grpSignatures.setBounds(10, 10, 300, 151); rdo1 = new Button(grpSignatures, SWT.RADIO); rdo1.setSelection(true); rdo1.setBounds(10, 19, 118, 18); rdo1.setText(Messages.SignatureWizard_DSA); rdo2 = new Button(grpSignatures, SWT.RADIO); rdo2.setBounds(10, 43, 118, 18); rdo2.setText(Messages.SignatureWizard_RSA); rdo3 = new Button(grpSignatures, SWT.RADIO); rdo3.setEnabled(false); rdo3.setBounds(10, 67, 118, 18); rdo3.setText(Messages.SignatureWizard_ECDSA); rdo4 = new Button(grpSignatures, SWT.RADIO); rdo4.setEnabled(false); rdo4.setBounds(10, 91, 118, 18); rdo4.setText(Messages.SignatureWizard_RSAandMGF1); Group grpDescription = new Group(this, SWT.NONE); grpDescription.setText(Messages.SignatureWizard_grpDescription); grpDescription.setBounds(10, 171, 300, 255); txtDescription = new Text(grpDescription, SWT.WRAP | SWT.TRANSPARENT); txtDescription.setEditable(false); txtDescription.setBounds(10, 15, 275, 213); txtDescription.setBackground(new Color(Display.getCurrent(), 220, 220, 220)); txtDescription.setText(Messages.SignatureWizard_DSA_description); //Add event listeners rdo1.addSelectionListener(this); rdo2.addSelectionListener(this); rdo3.addSelectionListener(this); rdo4.addSelectionListener(this); //rdo5.addSelectionListener(this); //If called by JCT-CA only SHA-256 can be used! Therefore only ECDSA, RSA and RSA with MGF1 will work if (org.jcryptool.visual.sig.algorithm.Input.privateKey != null) { rdo1.setEnabled(false); rdo2.setSelection(true); rdo3.setEnabled(false); rdo4.setEnabled(false); } }
private void initialize() { grpSignatures = new Group(this, SWT.NONE); grpSignatures.setText(Messages.SignatureWizard_grpSignatures); grpSignatures.setBounds(10, 10, 300, 151); rdo1 = new Button(grpSignatures, SWT.RADIO); rdo1.setSelection(true); rdo1.setBounds(10, 19, 118, 18); rdo1.setText(Messages.SignatureWizard_DSA); rdo2 = new Button(grpSignatures, SWT.RADIO); rdo2.setBounds(10, 43, 118, 18); rdo2.setText(Messages.SignatureWizard_RSA); rdo3 = new Button(grpSignatures, SWT.RADIO); rdo3.setEnabled(false); rdo3.setBounds(10, 67, 118, 18); rdo3.setText(Messages.SignatureWizard_ECDSA); rdo4 = new Button(grpSignatures, SWT.RADIO); rdo4.setEnabled(false); rdo4.setBounds(10, 91, 118, 18); rdo4.setText(Messages.SignatureWizard_RSAandMGF1); Group grpDescription = new Group(this, SWT.NONE); grpDescription.setText(Messages.SignatureWizard_grpDescription); grpDescription.setBounds(10, 171, 300, 255); txtDescription = new Text(grpDescription, SWT.WRAP | SWT.TRANSPARENT); txtDescription.setEditable(false); txtDescription.setBounds(10, 15, 275, 213); txtDescription.setBackground(new Color(Display.getCurrent(), 220, 220, 220)); txtDescription.setText(Messages.SignatureWizard_DSA_description); //Add event listeners rdo1.addSelectionListener(this); rdo2.addSelectionListener(this); rdo3.addSelectionListener(this); rdo4.addSelectionListener(this); //rdo5.addSelectionListener(this); //If called by JCT-CA only SHA-256 can be used! Therefore only ECDSA, RSA and RSA with MGF1 will work if (org.jcryptool.visual.sig.algorithm.Input.privateKey != null) { rdo1.setEnabled(false); rdo1.setSelection(false); rdo2.setSelection(true); rdo3.setEnabled(false); rdo4.setEnabled(false); } }
diff --git a/src/savant/format/FastaFormatter.java b/src/savant/format/FastaFormatter.java index 77a7d78e..5019e9fd 100644 --- a/src/savant/format/FastaFormatter.java +++ b/src/savant/format/FastaFormatter.java @@ -1,95 +1,95 @@ /* * Copyright 2010 University of Toronto * * 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 savant.format; import java.io.*; import savant.format.header.FileType; import savant.util.MiscUtils; public class FastaFormatter extends SavantFileFormatter{ public static final int RECORDS_PER_INTERRUPT_CHECK = 1000; public FastaFormatter(String inFile, String outFile) { super(inFile, outFile, FileType.SEQUENCE_FASTA); } public void format() throws IOException, InterruptedException, SavantFileFormattingException{ // set the input file size (for tracking progress) this.totalBytes = new File(inFilePath).length(); // open the input file inFileReader = this.openInputFile(); DataOutputStream outfile = null; //Read File Line By Line try { String strLine; boolean done = false; while (!done) { for (int i=0; i<RECORDS_PER_INTERRUPT_CHECK; i++) { if ((strLine = inFileReader.readLine()) == null) { done = true; break; } // update bytes read from input this.byteCount += strLine.getBytes().length; // set the correct output stream - if (strLine.charAt(0) == '>') { + if (strLine.length() > 0 && strLine.charAt(0) == '>') { String refname = MiscUtils.removeChar(strLine, '>'); refname = refname.replace(' ', '_'); outfile = this.getFileForReference(refname); } else { if (outfile == null) { throw new SavantFileFormattingException("no FASTA line found."); } // generate output //outfile.writeBytes(strLine); if (strLine.length() > 0 && !strLine.matches("\\s*") && strLine.charAt(0) != '>') { outfile.writeBytes(strLine); } } } // check to see if format has been cancelled if (Thread.interrupted()) throw new InterruptedException(); // update progress property for UI updateProgress(); } // close output streams; // VERY IMPORTANT THAT THIS HAPPENS BEFORE COPY! closeOutputStreams(); // write the output file this.writeOutputFile(); } finally { inFileReader.close(); //closeOutputStreams(); //this.closeOutputFiles(); } } }
true
true
public void format() throws IOException, InterruptedException, SavantFileFormattingException{ // set the input file size (for tracking progress) this.totalBytes = new File(inFilePath).length(); // open the input file inFileReader = this.openInputFile(); DataOutputStream outfile = null; //Read File Line By Line try { String strLine; boolean done = false; while (!done) { for (int i=0; i<RECORDS_PER_INTERRUPT_CHECK; i++) { if ((strLine = inFileReader.readLine()) == null) { done = true; break; } // update bytes read from input this.byteCount += strLine.getBytes().length; // set the correct output stream if (strLine.charAt(0) == '>') { String refname = MiscUtils.removeChar(strLine, '>'); refname = refname.replace(' ', '_'); outfile = this.getFileForReference(refname); } else { if (outfile == null) { throw new SavantFileFormattingException("no FASTA line found."); } // generate output //outfile.writeBytes(strLine); if (strLine.length() > 0 && !strLine.matches("\\s*") && strLine.charAt(0) != '>') { outfile.writeBytes(strLine); } } } // check to see if format has been cancelled if (Thread.interrupted()) throw new InterruptedException(); // update progress property for UI updateProgress(); } // close output streams; // VERY IMPORTANT THAT THIS HAPPENS BEFORE COPY! closeOutputStreams(); // write the output file this.writeOutputFile(); } finally { inFileReader.close(); //closeOutputStreams(); //this.closeOutputFiles(); } }
public void format() throws IOException, InterruptedException, SavantFileFormattingException{ // set the input file size (for tracking progress) this.totalBytes = new File(inFilePath).length(); // open the input file inFileReader = this.openInputFile(); DataOutputStream outfile = null; //Read File Line By Line try { String strLine; boolean done = false; while (!done) { for (int i=0; i<RECORDS_PER_INTERRUPT_CHECK; i++) { if ((strLine = inFileReader.readLine()) == null) { done = true; break; } // update bytes read from input this.byteCount += strLine.getBytes().length; // set the correct output stream if (strLine.length() > 0 && strLine.charAt(0) == '>') { String refname = MiscUtils.removeChar(strLine, '>'); refname = refname.replace(' ', '_'); outfile = this.getFileForReference(refname); } else { if (outfile == null) { throw new SavantFileFormattingException("no FASTA line found."); } // generate output //outfile.writeBytes(strLine); if (strLine.length() > 0 && !strLine.matches("\\s*") && strLine.charAt(0) != '>') { outfile.writeBytes(strLine); } } } // check to see if format has been cancelled if (Thread.interrupted()) throw new InterruptedException(); // update progress property for UI updateProgress(); } // close output streams; // VERY IMPORTANT THAT THIS HAPPENS BEFORE COPY! closeOutputStreams(); // write the output file this.writeOutputFile(); } finally { inFileReader.close(); //closeOutputStreams(); //this.closeOutputFiles(); } }
diff --git a/src/org/flowvisor/config/ConfDBHandler.java b/src/org/flowvisor/config/ConfDBHandler.java index 6ec7a6d..d7db921 100644 --- a/src/org/flowvisor/config/ConfDBHandler.java +++ b/src/org/flowvisor/config/ConfDBHandler.java @@ -1,127 +1,128 @@ package org.flowvisor.config; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp.ConnectionFactory; import org.apache.commons.dbcp.DriverManagerConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.derby.jdbc.EmbeddedDataSource; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; /** * Defines a connection pool to derby. * Guarantees that the status of a returned connection * is valid. * * * @author ash * */ public class ConfDBHandler implements ConfDBSettings { private String protocol = null; private String dbName = null; private String username = null; private String password = null; private ConnectionFactory cf = null; @SuppressWarnings("unused") private PoolableConnectionFactory pcf = null; private GenericObjectPool gop = null; private PoolingDataSource pds = null; private Boolean autoCommit = false; public ConfDBHandler(String protocol, String dbName, String username, String password, Boolean autoCommit) { this.protocol = protocol; this.dbName = System.getProperty("derby.system.home") + "/" + dbName; this.username = username; this.password = password; this.autoCommit = autoCommit; } public ConfDBHandler() { this("jdbc:derby:", "FlowVisorDB", "", "", true); } private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); pcf = new PoolableConnectionFactory(cf, gop, null, null,false, autoCommit); + pcf.setValidationQuery("SELECT 1"); pds = new PoolingDataSource(pcf.getPool()); return pds; } @Override public Connection getConnection() throws SQLException { return getDataSource().getConnection(); } @Override public Connection getConnection(String user, String pass) throws SQLException { return getDataSource().getConnection(user, pass); } @Override public void returnConnection(Connection conn) { try { gop.returnObject(conn); } catch (Exception e) { FVLog.log(LogLevel.CRIT, null, "Unable to return connection"); } } @Override public int getNumActive() { return gop.getNumActive(); } @Override public int getNumIdle() { return gop.getNumIdle(); } @Override public int getMaxActive() { return gop.getMaxActive(); } @Override public int getMaxIdle() { return gop.getMaxIdle(); } @Override public Boolean getDefaultAutoCommit() { return autoCommit; } @Override public void shutdown() { try { gop.close(); ((EmbeddedDataSource) getDataSource()).setShutdownDatabase("shutdown"); } catch (ClassCastException cce) { //Isn't this a derby db? } catch (Exception e) { FVLog.log(LogLevel.WARN, null, "Error on closing connection pool to derby"); } } }
true
true
private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); pcf = new PoolableConnectionFactory(cf, gop, null, null,false, autoCommit); pds = new PoolingDataSource(pcf.getPool()); return pds; }
private DataSource getDataSource() { if (pds != null) return pds; gop = new GenericObjectPool(null); gop.setTestOnBorrow(true); gop.setTestWhileIdle(true); cf = new DriverManagerConnectionFactory(this.protocol + this.dbName, this.username, this.password); pcf = new PoolableConnectionFactory(cf, gop, null, null,false, autoCommit); pcf.setValidationQuery("SELECT 1"); pds = new PoolingDataSource(pcf.getPool()); return pds; }
diff --git a/aether-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java b/aether-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java index abc1544..8a3d206 100644 --- a/aether-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java +++ b/aether-impl/src/main/java/org/eclipse/aether/impl/DefaultServiceLocator.java @@ -1,220 +1,229 @@ /******************************************************************************* * Copyright (c) 2010, 2011 Sonatype, Inc. * 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: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.aether.impl; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.internal.impl.DefaultArtifactResolver; import org.eclipse.aether.internal.impl.DefaultDependencyCollector; import org.eclipse.aether.internal.impl.DefaultDeployer; import org.eclipse.aether.internal.impl.DefaultFileProcessor; import org.eclipse.aether.internal.impl.DefaultInstaller; import org.eclipse.aether.internal.impl.DefaultLocalRepositoryProvider; import org.eclipse.aether.internal.impl.DefaultMetadataResolver; import org.eclipse.aether.internal.impl.DefaultRemoteRepositoryManager; import org.eclipse.aether.internal.impl.DefaultRepositoryEventDispatcher; import org.eclipse.aether.internal.impl.DefaultRepositorySystem; import org.eclipse.aether.internal.impl.DefaultSyncContextFactory; import org.eclipse.aether.internal.impl.DefaultUpdateCheckManager; import org.eclipse.aether.internal.impl.EnhancedLocalRepositoryManagerFactory; import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.spi.io.FileProcessor; import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory; import org.eclipse.aether.spi.locator.Service; import org.eclipse.aether.spi.locator.ServiceLocator; /** * A simple service locator that is already setup with all components from this library. To acquire a complete * repository system, clients need to add an artifact descriptor, a version resolver, a version range resolver and * optionally some repository connectors to access remote repositories. */ public class DefaultServiceLocator implements ServiceLocator { private final Map<Class<?>, Collection<Class<?>>> classes; private final Map<Class<?>, List<?>> instances; /** * Creates a new service locator that already knows about all service implementations included this library. */ public DefaultServiceLocator() { classes = new HashMap<Class<?>, Collection<Class<?>>>(); instances = new HashMap<Class<?>, List<?>>(); addService( RepositorySystem.class, DefaultRepositorySystem.class ); addService( ArtifactResolver.class, DefaultArtifactResolver.class ); addService( DependencyCollector.class, DefaultDependencyCollector.class ); addService( Deployer.class, DefaultDeployer.class ); addService( Installer.class, DefaultInstaller.class ); addService( MetadataResolver.class, DefaultMetadataResolver.class ); addService( RemoteRepositoryManager.class, DefaultRemoteRepositoryManager.class ); addService( UpdateCheckManager.class, DefaultUpdateCheckManager.class ); addService( FileProcessor.class, DefaultFileProcessor.class ); addService( SyncContextFactory.class, DefaultSyncContextFactory.class ); addService( RepositoryEventDispatcher.class, DefaultRepositoryEventDispatcher.class ); addService( LocalRepositoryProvider.class, DefaultLocalRepositoryProvider.class ); addService( LocalRepositoryManagerFactory.class, SimpleLocalRepositoryManagerFactory.class ); addService( LocalRepositoryManagerFactory.class, EnhancedLocalRepositoryManagerFactory.class ); } /** * Sets the implementation class for a service. * * @param <T> The service type. * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @return This locator for chaining, never {@code null}. */ public <T> DefaultServiceLocator setService( Class<T> type, Class<? extends T> impl ) { classes.remove( type ); return addService( type, impl ); } /** * Adds the implementation class for a service. * * @param <T> The service type. * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @return This locator for chaining, never {@code null}. */ public <T> DefaultServiceLocator addService( Class<T> type, Class<? extends T> impl ) { if ( impl == null ) { throw new IllegalArgumentException( "implementation class must not be null" ); } Collection<Class<?>> impls = classes.get( type ); if ( impls == null ) { impls = new LinkedHashSet<Class<?>>(); classes.put( type, impls ); } impls.add( impl ); return this; } /** * Sets the instances for a service. * * @param <T> The service type. * @param type The interface describing the service, must not be {@code null}. * @param services The instances of the service, must not be {@code null}. * @return This locator for chaining, never {@code null}. */ public <T> DefaultServiceLocator setServices( Class<T> type, T... services ) { synchronized ( instances ) { instances.put( type, Arrays.asList( services ) ); } return this; } public <T> T getService( Class<T> type ) { List<T> objs = getServices( type ); return objs.isEmpty() ? null : objs.get( 0 ); } public <T> List<T> getServices( Class<T> type ) { synchronized ( instances ) { @SuppressWarnings( "unchecked" ) List<T> objs = (List<T>) instances.get( type ); if ( objs == null ) { Iterator<T> it; Collection<Class<?>> impls = classes.get( type ); if ( impls == null || impls.isEmpty() ) { objs = Collections.emptyList(); it = objs.iterator(); } else { objs = new ArrayList<T>( impls.size() ); for ( Class<?> impl : impls ) { try { Constructor<?> constr = impl.getDeclaredConstructor(); if ( !Modifier.isPublic( constr.getModifiers() ) ) { constr.setAccessible( true ); } Object obj = constr.newInstance(); objs.add( type.cast( obj ) ); } catch ( Exception e ) { serviceCreationFailed( type, impl, e ); } + catch ( LinkageError e ) + { + serviceCreationFailed( type, impl, e ); + } } it = objs.iterator(); objs = Collections.unmodifiableList( objs ); } instances.put( type, objs ); while ( it.hasNext() ) { T obj = it.next(); if ( obj instanceof Service ) { try { ( (Service) obj ).initService( this ); } catch ( Exception e ) { it.remove(); serviceCreationFailed( type, obj.getClass(), e ); } + catch ( LinkageError e ) + { + it.remove(); + serviceCreationFailed( type, obj.getClass(), e ); + } } } } return objs; } } /** * Handles errors during creation of a service. * * @param type The interface describing the service, must not be {@code null}. * @param impl The implementation class of the service, must not be {@code null}. * @param exception The error that occurred while trying to instantiate the implementation class, must not be * {@code null}. */ protected void serviceCreationFailed( Class<?> type, Class<?> impl, Throwable exception ) { exception.printStackTrace(); } }
false
true
public <T> List<T> getServices( Class<T> type ) { synchronized ( instances ) { @SuppressWarnings( "unchecked" ) List<T> objs = (List<T>) instances.get( type ); if ( objs == null ) { Iterator<T> it; Collection<Class<?>> impls = classes.get( type ); if ( impls == null || impls.isEmpty() ) { objs = Collections.emptyList(); it = objs.iterator(); } else { objs = new ArrayList<T>( impls.size() ); for ( Class<?> impl : impls ) { try { Constructor<?> constr = impl.getDeclaredConstructor(); if ( !Modifier.isPublic( constr.getModifiers() ) ) { constr.setAccessible( true ); } Object obj = constr.newInstance(); objs.add( type.cast( obj ) ); } catch ( Exception e ) { serviceCreationFailed( type, impl, e ); } } it = objs.iterator(); objs = Collections.unmodifiableList( objs ); } instances.put( type, objs ); while ( it.hasNext() ) { T obj = it.next(); if ( obj instanceof Service ) { try { ( (Service) obj ).initService( this ); } catch ( Exception e ) { it.remove(); serviceCreationFailed( type, obj.getClass(), e ); } } } } return objs; } }
public <T> List<T> getServices( Class<T> type ) { synchronized ( instances ) { @SuppressWarnings( "unchecked" ) List<T> objs = (List<T>) instances.get( type ); if ( objs == null ) { Iterator<T> it; Collection<Class<?>> impls = classes.get( type ); if ( impls == null || impls.isEmpty() ) { objs = Collections.emptyList(); it = objs.iterator(); } else { objs = new ArrayList<T>( impls.size() ); for ( Class<?> impl : impls ) { try { Constructor<?> constr = impl.getDeclaredConstructor(); if ( !Modifier.isPublic( constr.getModifiers() ) ) { constr.setAccessible( true ); } Object obj = constr.newInstance(); objs.add( type.cast( obj ) ); } catch ( Exception e ) { serviceCreationFailed( type, impl, e ); } catch ( LinkageError e ) { serviceCreationFailed( type, impl, e ); } } it = objs.iterator(); objs = Collections.unmodifiableList( objs ); } instances.put( type, objs ); while ( it.hasNext() ) { T obj = it.next(); if ( obj instanceof Service ) { try { ( (Service) obj ).initService( this ); } catch ( Exception e ) { it.remove(); serviceCreationFailed( type, obj.getClass(), e ); } catch ( LinkageError e ) { it.remove(); serviceCreationFailed( type, obj.getClass(), e ); } } } } return objs; } }
diff --git a/src/main/java/com/griefcraft/util/ProtectionFinder.java b/src/main/java/com/griefcraft/util/ProtectionFinder.java index 57d4fc86..e71905d6 100644 --- a/src/main/java/com/griefcraft/util/ProtectionFinder.java +++ b/src/main/java/com/griefcraft/util/ProtectionFinder.java @@ -1,397 +1,397 @@ /* * Copyright 2011 Tyler Blair. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. * * The views and conclusions contained in the software and documentation are those of the * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ package com.griefcraft.util; import com.griefcraft.cache.ProtectionCache; import com.griefcraft.lwc.LWC; import com.griefcraft.model.Protection; import com.griefcraft.util.matchers.DoorMatcher; import com.griefcraft.util.matchers.DoubleChestMatcher; import com.griefcraft.util.matchers.GravityMatcher; import com.griefcraft.util.matchers.WallMatcher; import org.bukkit.Material; import org.bukkit.block.Block; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Searches for blocks that can potentially be a protection */ public class ProtectionFinder { /** * The LWC object to work with */ private LWC lwc; /** * The base block to match off of */ private Block baseBlock = null; /** * The matched protection if found */ private Protection matchedProtection = null; /** * If we already checked the database */ private boolean searched = false; /** * All of the matched blocks */ private final List<Block> blocks = new LinkedList<Block>(); /** * All of the blocks that are protectables */ private final List<Block> protectables = new LinkedList<Block>(); public ProtectionFinder(LWC lwc) { this.lwc = lwc; } /** * Try and match blocks using the given base block * * @param baseBlock * @return TRUE if a set of blocks was found */ public boolean matchBlocks(Block baseBlock) { // Did we already find a protection? if (matchedProtection != null) { return true; } // First, reset reset(); this.baseBlock = baseBlock; // Add the base block addBlock(baseBlock); // Check the base-block Result result; if ((result = tryLoadProtection(baseBlock, false)) != Result.E_NOT_FOUND) { return result == Result.E_FOUND; } // Now attempt to use the matchers for (Matcher matcher : getProtectionMatchers()) { boolean matches = matcher.matches(this); if (matches) { // we matched a protection somewhere! return true; } } if (loadProtection() == null) { // Blacklist each block, all of them did not return matches ProtectionCache cache = LWC.getInstance().getProtectionCache(); for (Block block : blocks) { if (cache.getProtection(block) == null) { cache.addNull(block); } } } // No matches searched = true; return false; } /** * Do a full sweeping match of all the blocks for a given protection */ public void fullMatchBlocks() { // Reset the blocks blocks.clear(); // Add the base block blocks.add(baseBlock); // Go through each matcher and execute it for (Matcher matcher : getProtectionMatchers()) { if (matcher.matches(this)) { break; } } } /** * Get the possible protection matchers that can match the protection * * @return */ public Matcher[] getProtectionMatchers() { Material material = baseBlock.getType(); // Double chests if (DoubleChestMatcher.PROTECTABLES_CHESTS.contains(material)) { return new Matcher[] { new DoubleChestMatcher() }; } // Gravity else if (GravityMatcher.PROTECTABLES_POSTS.contains(material)) { return new Matcher[] { new GravityMatcher() }; } // Doors else if (DoorMatcher.PROTECTABLES_DOORS.contains(material)) { return new Matcher[] { new DoorMatcher() }; } // Anything else else { return new Matcher[] { new DoorMatcher(), new GravityMatcher(), new WallMatcher() }; } } /** * Add a block to the matched blocks * * @param block */ public void addBlock(Block block) { if (!blocks.contains(block)) { blocks.add(block); } } /** * Load the protection for the calculated protectables. * Returns NULL if no protection was found. * * @return */ public Protection loadProtection() { return loadProtection(false); } /** * Load the protection for the calculated protectables. * Returns NULL if no protection was found. * * @param noAutoCache if a match is found, don't cache it to be the protection we use * @return */ public Protection loadProtection(boolean noAutoCache) { // Do we have a result already cached? if (searched) { return matchedProtection; } // Calculate the protectables calculateProtectables(); searched = true; for (Block block : protectables) { if (tryLoadProtection(block, noAutoCache) == Result.E_FOUND) { return matchedProtection; } } return null; } /** * Try and load a protection for a given block. If succeded, cache it locally * * @param block * @param noAutoCache if a match is found, don't cache it to be the protection we use * @return */ protected Result tryLoadProtection(Block block, boolean noAutoCache) { if (matchedProtection != null) { return Result.E_FOUND; } LWC lwc = LWC.getInstance(); ProtectionCache cache = lwc.getProtectionCache(); // Check the cache if ((matchedProtection = cache.getProtection(block)) != null) { searched = true; if (matchedProtection.getProtectionFinder() == null) { fullMatchBlocks(); matchedProtection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } return Result.E_FOUND; } // Manual intervention is required if (block.getType() == Material.REDSTONE_WIRE || block.getType() == Material.REDSTONE_TORCH_OFF || block.getType() == Material.REDSTONE_TORCH_ON) { return Result.E_ABORT; } // Null cache if (cache.isKnownToBeNull(block)) { searched = true; return Result.E_ABORT; } // don't bother trying to load it if it is not protectable if (!lwc.isProtectable(block)) { return Result.E_NOT_FOUND; } // Null-check if (block.getWorld() == null) { lwc.log("World is null for the block " + block); return Result.E_NOT_FOUND; } Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { - if (matchedProtection.getProtectionFinder() == null) { + if (protection.getProtectionFinder() == null) { fullMatchBlocks(); - matchedProtection.setProtectionFinder(this); + protection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.isBlockInWorld()) { if (noAutoCache) { return Result.E_FOUND; } this.matchedProtection = protection; searched = true; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null ? Result.E_FOUND : Result.E_NOT_FOUND; } /** * Get the finder's base block * * @return */ public Block getBaseBlock() { return baseBlock; } /** * Get an immutable set of the matched blocks * * @return */ public List<Block> getBlocks() { return Collections.unmodifiableList(blocks); } /** * Get an immutable set of the protectable blocks * * @return */ public List<Block> getProtectables() { return Collections.unmodifiableList(protectables); } /** * Reset the matcher state */ private void reset() { blocks.clear(); protectables.clear(); baseBlock = null; searched = false; } /** * From the matched blocks calculate and store the blocks that are protectable */ private void calculateProtectables() { // reset the matched protectables protectables.clear(); searched = false; // if there's only 1 block it was already checked (the base block) int size = blocks.size(); if (size == 1) { return; } // go through the blocks for (int index = 1; index < size; index++) { Block block = blocks.get(index); // Is it protectable? if (lwc.isProtectable(block)) { protectables.add(block); } } } /** * Matches protections */ public interface Matcher { /** * Check if the block matches any VALID protections. * * @return */ public boolean matches(ProtectionFinder finder); } private enum Result { E_FOUND, E_ABORT, E_NOT_FOUND } }
false
true
protected Result tryLoadProtection(Block block, boolean noAutoCache) { if (matchedProtection != null) { return Result.E_FOUND; } LWC lwc = LWC.getInstance(); ProtectionCache cache = lwc.getProtectionCache(); // Check the cache if ((matchedProtection = cache.getProtection(block)) != null) { searched = true; if (matchedProtection.getProtectionFinder() == null) { fullMatchBlocks(); matchedProtection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } return Result.E_FOUND; } // Manual intervention is required if (block.getType() == Material.REDSTONE_WIRE || block.getType() == Material.REDSTONE_TORCH_OFF || block.getType() == Material.REDSTONE_TORCH_ON) { return Result.E_ABORT; } // Null cache if (cache.isKnownToBeNull(block)) { searched = true; return Result.E_ABORT; } // don't bother trying to load it if it is not protectable if (!lwc.isProtectable(block)) { return Result.E_NOT_FOUND; } // Null-check if (block.getWorld() == null) { lwc.log("World is null for the block " + block); return Result.E_NOT_FOUND; } Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { if (matchedProtection.getProtectionFinder() == null) { fullMatchBlocks(); matchedProtection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.isBlockInWorld()) { if (noAutoCache) { return Result.E_FOUND; } this.matchedProtection = protection; searched = true; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null ? Result.E_FOUND : Result.E_NOT_FOUND; }
protected Result tryLoadProtection(Block block, boolean noAutoCache) { if (matchedProtection != null) { return Result.E_FOUND; } LWC lwc = LWC.getInstance(); ProtectionCache cache = lwc.getProtectionCache(); // Check the cache if ((matchedProtection = cache.getProtection(block)) != null) { searched = true; if (matchedProtection.getProtectionFinder() == null) { fullMatchBlocks(); matchedProtection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } return Result.E_FOUND; } // Manual intervention is required if (block.getType() == Material.REDSTONE_WIRE || block.getType() == Material.REDSTONE_TORCH_OFF || block.getType() == Material.REDSTONE_TORCH_ON) { return Result.E_ABORT; } // Null cache if (cache.isKnownToBeNull(block)) { searched = true; return Result.E_ABORT; } // don't bother trying to load it if it is not protectable if (!lwc.isProtectable(block)) { return Result.E_NOT_FOUND; } // Null-check if (block.getWorld() == null) { lwc.log("World is null for the block " + block); return Result.E_NOT_FOUND; } Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { if (protection.getProtectionFinder() == null) { fullMatchBlocks(); protection.setProtectionFinder(this); lwc.getProtectionCache().add(matchedProtection); } // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.isBlockInWorld()) { if (noAutoCache) { return Result.E_FOUND; } this.matchedProtection = protection; searched = true; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null ? Result.E_FOUND : Result.E_NOT_FOUND; }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java index 94807b653..d9b7966da 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java @@ -1,368 +1,367 @@ /******************************************************************************* * Copyright (c) 2004, 2010 Tasktop Technologies 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: * Eugene Kuleshov - initial API and implementation * Tasktop Technologies - initial API and implementation * Yatta Solutions - fix for bug 327262 *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.workingsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.internal.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.internal.tasks.core.TaskCategory; import org.eclipse.mylyn.internal.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.monitor.ui.MonitorUi; import org.eclipse.mylyn.tasks.core.IRepositoryElement; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetUpdater; import org.eclipse.ui.PlatformUI; /** * @author Eugene Kuleshov * @author Mik Kersten * @author Steffen Pingel * @author Carsten Reckord */ public class TaskWorkingSetUpdater implements IWorkingSetUpdater, ITaskListChangeListener, IResourceChangeListener { public static String ID_TASK_WORKING_SET = "org.eclipse.mylyn.tasks.ui.workingSet"; //$NON-NLS-1$ private final List<IWorkingSet> workingSets = new CopyOnWriteArrayList<IWorkingSet>(); private static TaskWorkingSetUpdater INSTANCE; private static class TaskWorkingSetDelta { private final IWorkingSet workingSet; private final List<Object> elements; private boolean changed; public TaskWorkingSetDelta(IWorkingSet workingSet) { this.workingSet = workingSet; this.elements = new ArrayList<Object>(Arrays.asList(workingSet.getElements())); } public int indexOf(Object element) { return elements.indexOf(element); } public void set(int index, Object element) { elements.set(index, element); changed = true; } public void remove(int index) { if (elements.remove(index) != null) { changed = true; } } public void process() { if (changed) { workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } } } public TaskWorkingSetUpdater() { INSTANCE = this; TasksUiInternal.getTaskList().addChangeListener(this); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } public void dispose() { TasksUiInternal.getTaskList().removeChangeListener(this); } public void add(IWorkingSet workingSet) { checkElementExistence(workingSet); synchronized (workingSets) { workingSets.add(workingSet); } } private void checkElementExistence(IWorkingSet workingSet) { ArrayList<IAdaptable> list = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); boolean changed = false; for (Iterator<IAdaptable> iter = list.iterator(); iter.hasNext();) { IAdaptable adaptable = iter.next(); boolean remove = false; if (adaptable instanceof AbstractTaskContainer) { String handle = ((AbstractTaskContainer) adaptable).getHandleIdentifier(); remove = true; for (IRepositoryElement element : TasksUiPlugin.getTaskList().getRootElements()) { if (element != null && element.getHandleIdentifier().equals(handle)) { - list.add(adaptable); remove = false; break; } } } else if (adaptable instanceof IProject) { IProject project = ResourcesPlugin.getWorkspace() .getRoot() .getProject(((IProject) adaptable).getName()); if (project == null || !project.exists()) { remove = true; } } if (remove) { iter.remove(); changed = true; } } if (changed) { workingSet.setElements(list.toArray(new IAdaptable[list.size()])); } } public boolean contains(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.contains(workingSet); } } public boolean remove(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.remove(workingSet); } } public void containersChanged(Set<TaskContainerDelta> delta) { for (TaskContainerDelta taskContainerDelta : delta) { if (taskContainerDelta.getElement() instanceof TaskCategory || taskContainerDelta.getElement() instanceof IRepositoryQuery) { synchronized (workingSets) { switch (taskContainerDelta.getKind()) { case REMOVED: // Remove from all for (IWorkingSet workingSet : workingSets) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.remove(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; case ADDED: // Add to the active working set for (IWorkingSet workingSet : TaskWorkingSetUpdater.getEnabledSets()) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.add(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; } } } } } // TODO: consider putting back, but evaluate policy and note bug 197257 // public void taskActivated(AbstractTask task) { // Set<AbstractTaskContainer> taskContainers = new HashSet<AbstractTaskContainer>( // TasksUiPlugin.getTaskList().getQueriesForHandle(task.getHandleIdentifier())); // taskContainers.addAll(task.getParentContainers()); // // Set<AbstractTaskContainer> allActiveWorkingSetContainers = new HashSet<AbstractTaskContainer>(); // for (IWorkingSet workingSet : PlatformUI.getWorkbench() // .getActiveWorkbenchWindow() // .getActivePage() // .getWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // allActiveWorkingSetContainers.add((AbstractTaskContainer) adaptable); // } // } // } // boolean isContained = false; // for (AbstractTaskContainer taskContainer : allActiveWorkingSetContainers) { // if (taskContainers.contains(taskContainer)) { // isContained = true; // break; // } // } // // ; // if (!isContained) { // IWorkingSet matchingWorkingSet = null; // for (IWorkingSet workingSet : PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // if (((AbstractTaskContainer)adaptable).contains(task.getHandleIdentifier())) { // matchingWorkingSet = workingSet; // } // } // } // } // // if (matchingWorkingSet != null) { // new ToggleWorkingSetAction(matchingWorkingSet).run(); // } else { // new ToggleAllWorkingSetsAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow()).run(); // } // } // } public static IWorkingSet[] getEnabledSets() { Set<IWorkingSet> workingSets = new HashSet<IWorkingSet>(); Set<IWorkbenchWindow> windows = MonitorUi.getMonitoredWindows(); for (IWorkbenchWindow iWorkbenchWindow : windows) { IWorkbenchPage page = iWorkbenchWindow.getActivePage(); if (page != null) { workingSets.addAll(Arrays.asList(page.getWorkingSets())); } } return workingSets.toArray(new IWorkingSet[workingSets.size()]); } /** * TODO: move */ public static boolean areNoTaskWorkingSetsEnabled() { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets(); for (IWorkingSet workingSet : workingSets) { if (workingSet != null && workingSet.getId().equalsIgnoreCase(ID_TASK_WORKING_SET)) { if (isWorkingSetEnabled(workingSet)) { return false; } } } return true; } public static boolean isWorkingSetEnabled(IWorkingSet set) { IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (IWorkingSet enabledSet : enabledSets) { if (enabledSet.equals(set)) { return true; } } return false; } public static boolean isOnlyTaskWorkingSetEnabled(IWorkingSet set) { if (!TaskWorkingSetUpdater.isWorkingSetEnabled(set)) { return false; } IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (int i = 0; i < enabledSets.length; i++) { if (!enabledSets[i].equals(set) && enabledSets[i].getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { return false; } } return true; } private void processResourceDelta(TaskWorkingSetDelta result, IResourceDelta delta) { IResource resource = delta.getResource(); int type = resource.getType(); int index = result.indexOf(resource); int kind = delta.getKind(); int flags = delta.getFlags(); if (kind == IResourceDelta.CHANGED && type == IResource.PROJECT && index != -1) { if ((flags & IResourceDelta.OPEN) != 0) { result.set(index, resource); } } if (index != -1 && kind == IResourceDelta.REMOVED) { if ((flags & IResourceDelta.MOVED_TO) != 0) { result.set(index, ResourcesPlugin.getWorkspace().getRoot().findMember(delta.getMovedToPath())); } else { result.remove(index); } } // Don't dive into closed or opened projects if (projectGotClosedOrOpened(resource, kind, flags)) { return; } IResourceDelta[] children = delta.getAffectedChildren(); for (IResourceDelta element : children) { processResourceDelta(result, element); } } private boolean projectGotClosedOrOpened(IResource resource, int kind, int flags) { return resource.getType() == IResource.PROJECT && kind == IResourceDelta.CHANGED && (flags & IResourceDelta.OPEN) != 0; } public void resourceChanged(IResourceChangeEvent event) { for (IWorkingSet workingSet : workingSets) { TaskWorkingSetDelta workingSetDelta = new TaskWorkingSetDelta(workingSet); if (event.getDelta() != null) { processResourceDelta(workingSetDelta, event.getDelta()); } workingSetDelta.process(); } } /** * Must be called from the UI thread */ public static void applyWorkingSetsToAllWindows(Collection<IWorkingSet> workingSets) { IWorkingSet[] workingSetArray = workingSets.toArray(new IWorkingSet[workingSets.size()]); for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) { for (IWorkbenchPage page : window.getPages()) { page.setWorkingSets(workingSetArray); } } } public static Set<IWorkingSet> getActiveWorkingSets(IWorkbenchWindow window) { if (window != null && window.getActivePage() != null) { Set<IWorkingSet> allSets = new HashSet<IWorkingSet>(Arrays.asList(window.getActivePage().getWorkingSets())); Set<IWorkingSet> tasksSets = new HashSet<IWorkingSet>(allSets); for (IWorkingSet workingSet : allSets) { if (workingSet.getId() == null || !workingSet.getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { tasksSets.remove(workingSet); } } return tasksSets; } else { return Collections.emptySet(); } } public static TaskWorkingSetUpdater getInstance() { return INSTANCE; } }
true
true
private void checkElementExistence(IWorkingSet workingSet) { ArrayList<IAdaptable> list = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); boolean changed = false; for (Iterator<IAdaptable> iter = list.iterator(); iter.hasNext();) { IAdaptable adaptable = iter.next(); boolean remove = false; if (adaptable instanceof AbstractTaskContainer) { String handle = ((AbstractTaskContainer) adaptable).getHandleIdentifier(); remove = true; for (IRepositoryElement element : TasksUiPlugin.getTaskList().getRootElements()) { if (element != null && element.getHandleIdentifier().equals(handle)) { list.add(adaptable); remove = false; break; } } } else if (adaptable instanceof IProject) { IProject project = ResourcesPlugin.getWorkspace() .getRoot() .getProject(((IProject) adaptable).getName()); if (project == null || !project.exists()) { remove = true; } } if (remove) { iter.remove(); changed = true; } } if (changed) { workingSet.setElements(list.toArray(new IAdaptable[list.size()])); } }
private void checkElementExistence(IWorkingSet workingSet) { ArrayList<IAdaptable> list = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); boolean changed = false; for (Iterator<IAdaptable> iter = list.iterator(); iter.hasNext();) { IAdaptable adaptable = iter.next(); boolean remove = false; if (adaptable instanceof AbstractTaskContainer) { String handle = ((AbstractTaskContainer) adaptable).getHandleIdentifier(); remove = true; for (IRepositoryElement element : TasksUiPlugin.getTaskList().getRootElements()) { if (element != null && element.getHandleIdentifier().equals(handle)) { remove = false; break; } } } else if (adaptable instanceof IProject) { IProject project = ResourcesPlugin.getWorkspace() .getRoot() .getProject(((IProject) adaptable).getName()); if (project == null || !project.exists()) { remove = true; } } if (remove) { iter.remove(); changed = true; } } if (changed) { workingSet.setElements(list.toArray(new IAdaptable[list.size()])); } }
diff --git a/core/plugins/org.eclipse.dltk.console.ui/src/org/eclipse/dltk/console/ui/internal/ScriptConsolePage.java b/core/plugins/org.eclipse.dltk.console.ui/src/org/eclipse/dltk/console/ui/internal/ScriptConsolePage.java index 9cd1d882b..76ba7b93c 100644 --- a/core/plugins/org.eclipse.dltk.console.ui/src/org/eclipse/dltk/console/ui/internal/ScriptConsolePage.java +++ b/core/plugins/org.eclipse.dltk.console.ui/src/org/eclipse/dltk/console/ui/internal/ScriptConsolePage.java @@ -1,103 +1,103 @@ package org.eclipse.dltk.console.ui.internal; import org.eclipse.dltk.console.ScriptConsoleConstants; import org.eclipse.dltk.console.ui.ScriptConsole; import org.eclipse.dltk.console.ui.internal.actions.CloseScriptConsoleAction; import org.eclipse.dltk.console.ui.internal.actions.SaveConsoleSessionAction; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IActionBars; import org.eclipse.ui.console.IConsoleConstants; import org.eclipse.ui.console.IConsoleView; import org.eclipse.ui.console.TextConsolePage; import org.eclipse.ui.console.TextConsoleViewer; import org.eclipse.ui.console.actions.TextViewerAction; public class ScriptConsolePage extends TextConsolePage implements IScriptConsoleContentHandler { protected class ContentAssistProposalsAction extends TextViewerAction { public ContentAssistProposalsAction(ITextViewer viewer) { super(viewer, ISourceViewer.CONTENTASSIST_PROPOSALS); } } protected class ContentAssistContextInfoAction extends TextViewerAction { public ContentAssistContextInfoAction(ITextViewer viewer) { super(viewer, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); } } private SourceViewerConfiguration cfg; private ScriptConsoleViewer viewer; private TextViewerAction proposalsAction; protected void createActions() { super.createActions(); proposalsAction = new ContentAssistProposalsAction(getViewer()); proposalsAction = new ContentAssistProposalsAction(getViewer()); SaveConsoleSessionAction saveSessionAction = new SaveConsoleSessionAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.SaveSessionAction, ScriptConsoleMessages.SaveSessionTooltip); - CloseScriptConsoleAction colseConsoleAction = new CloseScriptConsoleAction( + CloseScriptConsoleAction closeConsoleAction = new CloseScriptConsoleAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.TerminateConsoleAction, ScriptConsoleMessages.TerminateConsoleTooltip); IActionBars bars = getSite().getActionBars(); IToolBarManager toolbarManager = bars.getToolBarManager(); toolbarManager.prependToGroup(IConsoleConstants.LAUNCH_GROUP, new GroupMarker(ScriptConsoleConstants.SCRIPT_GROUP)); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, new Separator()); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, - colseConsoleAction); + closeConsoleAction); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, saveSessionAction); bars.updateActionBars(); } protected TextConsoleViewer createViewer(Composite parent) { viewer = new ScriptConsoleViewer(parent, (ScriptConsole) getConsole(), this); viewer.configure(cfg); return viewer; } public ScriptConsolePage(ScriptConsole console, IConsoleView view, SourceViewerConfiguration cfg) { super(console, view); this.cfg = cfg; } public void clearConsolePage() { viewer.clear(); } public void contentAssistRequired() { proposalsAction.run(); } public void insertText(String text) { viewer.insertText(text); } }
false
true
protected void createActions() { super.createActions(); proposalsAction = new ContentAssistProposalsAction(getViewer()); proposalsAction = new ContentAssistProposalsAction(getViewer()); SaveConsoleSessionAction saveSessionAction = new SaveConsoleSessionAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.SaveSessionAction, ScriptConsoleMessages.SaveSessionTooltip); CloseScriptConsoleAction colseConsoleAction = new CloseScriptConsoleAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.TerminateConsoleAction, ScriptConsoleMessages.TerminateConsoleTooltip); IActionBars bars = getSite().getActionBars(); IToolBarManager toolbarManager = bars.getToolBarManager(); toolbarManager.prependToGroup(IConsoleConstants.LAUNCH_GROUP, new GroupMarker(ScriptConsoleConstants.SCRIPT_GROUP)); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, new Separator()); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, colseConsoleAction); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, saveSessionAction); bars.updateActionBars(); }
protected void createActions() { super.createActions(); proposalsAction = new ContentAssistProposalsAction(getViewer()); proposalsAction = new ContentAssistProposalsAction(getViewer()); SaveConsoleSessionAction saveSessionAction = new SaveConsoleSessionAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.SaveSessionAction, ScriptConsoleMessages.SaveSessionTooltip); CloseScriptConsoleAction closeConsoleAction = new CloseScriptConsoleAction( (ScriptConsole) getConsole(), ScriptConsoleMessages.TerminateConsoleAction, ScriptConsoleMessages.TerminateConsoleTooltip); IActionBars bars = getSite().getActionBars(); IToolBarManager toolbarManager = bars.getToolBarManager(); toolbarManager.prependToGroup(IConsoleConstants.LAUNCH_GROUP, new GroupMarker(ScriptConsoleConstants.SCRIPT_GROUP)); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, new Separator()); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, closeConsoleAction); toolbarManager.appendToGroup(ScriptConsoleConstants.SCRIPT_GROUP, saveSessionAction); bars.updateActionBars(); }
diff --git a/src/com/larsbutler/gamedemo/core/GameState.java b/src/com/larsbutler/gamedemo/core/GameState.java index a9095b8..af92028 100644 --- a/src/com/larsbutler/gamedemo/core/GameState.java +++ b/src/com/larsbutler/gamedemo/core/GameState.java @@ -1,175 +1,170 @@ package com.larsbutler.gamedemo.core; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.geom.Rectangle2D; import java.util.List; import com.larsbutler.gamedemo.math.Acceleration; import com.larsbutler.gamedemo.math.Collision; import com.larsbutler.gamedemo.math.MathUtil; import com.larsbutler.gamedemo.math.RK4; import com.larsbutler.gamedemo.math.State; import com.larsbutler.gamedemo.models.Entity; import com.larsbutler.gamedemo.models.Level; import com.larsbutler.gamedemo.models.Player; public class GameState implements KeyListener { private Level level; private Player player; public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } public Player getPlayer() { return player; } public void setPlayer(Player player) { this.player = player; } /** * Do all physics and entity updates here. * * @param timeStepNanos * Time delta (in ns) to simulate physics. For example, if * timeStepNanos == 1/60 sec, we do physics updates for 1/60 sec. */ public void update(long prevTimeStep, long timeStepNanos) { double t = (double)prevTimeStep / Kernel.NANOS_PER_SECOND; double dt = (double)timeStepNanos / Kernel.NANOS_PER_SECOND; updatePlayer(player, dt); move(player, t, dt); } public static void updatePlayer(Player p, double dt) { State state = p.getXState(); if (p.isLeft() && p.isRight()) { state.v = 0.0; } else if (p.isLeft()) { state.v += -(Player.CEL_PER_SECOND * dt); // Cap the movement speed to the maximum allowed if (state.v <= -Player.MAX_XVEL_PER_UPDATE) { state.v = -Player.MAX_XVEL_PER_UPDATE; } } else if (p.isRight()) { state.v += (Player.CEL_PER_SECOND * dt); // Cap the movement speed to the maximum allowed if (state.v >= Player.MAX_XVEL_PER_UPDATE) { state.v = Player.MAX_XVEL_PER_UPDATE; } } else { // we're moving right // reduce the overall speed if (state.v > 0.0) { state.v += -(Player.CEL_PER_SECOND * dt); if (state.v < 0.0) { state.v = 0.0; } } // we're moving left // reduce the overall speed else if (state.v < 0.0) { state.v += (Player.CEL_PER_SECOND * dt); if (state.v > 0.0) { state.v = 0.0; } } } } public void move(Entity e, double t, double dt) { State currentXState = e.getXState(); State currentYState = e.getYState(); e.setPrevXState(currentXState); e.setPrevYState(currentYState); // All of the solid tiles we can collide with: List<Rectangle2D> levelHitBoxes = level.tileHitBoxes(); double correction = 0.0; // Move one axis at a time, and check for collisions after each. e.setXState( RK4.integrate(currentXState, t, dt, Acceleration.EMPTY)); for (Rectangle2D box : levelHitBoxes) { correction = Collision.getXCorrection(e, box); if (correction != 0.0) { e.getXState().p += correction; // Since we hit something, zero the velocity // on this axis: e.getXState().v = 0.0; } } - System.err.println(); - System.err.println("Before moving: " + e.getY() + ", " + (e.getY() + e.getHeight())); e.setYState( RK4.integrate(currentYState, t, dt, Acceleration.GRAVITY_ONLY)); - System.err.println("After moving: " + e.getY() + ", " + (e.getY() + e.getHeight())); boolean floorColl = false; for (Rectangle2D box : levelHitBoxes) { correction = Collision.getYCorrection(e, box); if (correction != 0.0) { - System.err.println("Correction: " + correction); -// e.getYState().p = (double)(float)(e.getYState().p + correction); - e.getYState().p += correction; + e.getYState().p = (double)(float)(e.getYState().p + correction); +// e.getYState().p += correction; // if we hit a "floor", // reset `canJump` status: if (e.getYState().v > 0.0) { // we were falling floorColl = true; } // Since we hit something, zero the velocity // on this axis: e.getYState().v = 0.0; } } - System.err.println("After correction: " + e.getY() + ", " + (e.getY() + e.getHeight())); e.setCanJump(floorColl); } public void keyPressed(KeyEvent e) { int kc = e.getKeyCode(); switch (kc) { case KeyEvent.VK_LEFT: player.setLeft(true); break; case KeyEvent.VK_RIGHT: player.setRight(true); break; case KeyEvent.VK_SPACE: player.jump(); break; } } public void keyReleased(KeyEvent e) { int kc = e.getKeyCode(); switch (kc) { case KeyEvent.VK_LEFT: player.setLeft(false); break; case KeyEvent.VK_RIGHT: player.setRight(false); break; } } public void keyTyped(KeyEvent e) {} }
false
true
public void move(Entity e, double t, double dt) { State currentXState = e.getXState(); State currentYState = e.getYState(); e.setPrevXState(currentXState); e.setPrevYState(currentYState); // All of the solid tiles we can collide with: List<Rectangle2D> levelHitBoxes = level.tileHitBoxes(); double correction = 0.0; // Move one axis at a time, and check for collisions after each. e.setXState( RK4.integrate(currentXState, t, dt, Acceleration.EMPTY)); for (Rectangle2D box : levelHitBoxes) { correction = Collision.getXCorrection(e, box); if (correction != 0.0) { e.getXState().p += correction; // Since we hit something, zero the velocity // on this axis: e.getXState().v = 0.0; } } System.err.println(); System.err.println("Before moving: " + e.getY() + ", " + (e.getY() + e.getHeight())); e.setYState( RK4.integrate(currentYState, t, dt, Acceleration.GRAVITY_ONLY)); System.err.println("After moving: " + e.getY() + ", " + (e.getY() + e.getHeight())); boolean floorColl = false; for (Rectangle2D box : levelHitBoxes) { correction = Collision.getYCorrection(e, box); if (correction != 0.0) { System.err.println("Correction: " + correction); // e.getYState().p = (double)(float)(e.getYState().p + correction); e.getYState().p += correction; // if we hit a "floor", // reset `canJump` status: if (e.getYState().v > 0.0) { // we were falling floorColl = true; } // Since we hit something, zero the velocity // on this axis: e.getYState().v = 0.0; } } System.err.println("After correction: " + e.getY() + ", " + (e.getY() + e.getHeight())); e.setCanJump(floorColl); }
public void move(Entity e, double t, double dt) { State currentXState = e.getXState(); State currentYState = e.getYState(); e.setPrevXState(currentXState); e.setPrevYState(currentYState); // All of the solid tiles we can collide with: List<Rectangle2D> levelHitBoxes = level.tileHitBoxes(); double correction = 0.0; // Move one axis at a time, and check for collisions after each. e.setXState( RK4.integrate(currentXState, t, dt, Acceleration.EMPTY)); for (Rectangle2D box : levelHitBoxes) { correction = Collision.getXCorrection(e, box); if (correction != 0.0) { e.getXState().p += correction; // Since we hit something, zero the velocity // on this axis: e.getXState().v = 0.0; } } e.setYState( RK4.integrate(currentYState, t, dt, Acceleration.GRAVITY_ONLY)); boolean floorColl = false; for (Rectangle2D box : levelHitBoxes) { correction = Collision.getYCorrection(e, box); if (correction != 0.0) { e.getYState().p = (double)(float)(e.getYState().p + correction); // e.getYState().p += correction; // if we hit a "floor", // reset `canJump` status: if (e.getYState().v > 0.0) { // we were falling floorColl = true; } // Since we hit something, zero the velocity // on this axis: e.getYState().v = 0.0; } } e.setCanJump(floorColl); }
diff --git a/src/mc/lib/network/AsyncFileDownloader.java b/src/mc/lib/network/AsyncFileDownloader.java index 5925980..6fae4e6 100644 --- a/src/mc/lib/network/AsyncFileDownloader.java +++ b/src/mc/lib/network/AsyncFileDownloader.java @@ -1,234 +1,237 @@ /* Copyright 2012 Mikhail Chabanov 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 mc.lib.network; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import mc.lib.interfaces.OnCompleteListener; import mc.lib.interfaces.OnProgressListener; import mc.lib.log.Log; import mc.lib.stream.StreamHelper; import android.os.AsyncTask; public class AsyncFileDownloader extends AsyncTask<Void, Integer, Boolean> { private static final String LOGTAG = AsyncFileDownloader.class.getSimpleName(); private static int id = 1; private static Map<Integer, AsyncFileDownloader> map = new HashMap<Integer, AsyncFileDownloader>(); public static synchronized int downloadFile(String url, String outputFilePath, OnCompleteListener<File> clistener, OnProgressListener plistener) { try { return downloadFile(new URL(url), new File(outputFilePath), clistener, plistener); } catch(MalformedURLException e) { Log.e(LOGTAG, "Wrong url", e); } return -1; } public static synchronized int downloadFile(String url, File output, OnCompleteListener<File> clistener, OnProgressListener plistener) { try { return downloadFile(new URL(url), output, clistener, plistener); } catch(MalformedURLException e) { Log.e(LOGTAG, "Wrong url", e); } return -1; } public static synchronized int downloadFile(URL url, String outputFilePath, OnCompleteListener<File> clistener, OnProgressListener plistener) { return downloadFile(url, new File(outputFilePath), clistener, plistener); } public static synchronized int downloadFile(URL url, File output, OnCompleteListener<File> clistener, OnProgressListener plistener) { if(url != null && output != null) { AsyncFileDownloader afd = new AsyncFileDownloader(url, output, clistener, plistener); id++; map.put(id, afd); afd.execute((Void[])null); return id; } else { Log.e(LOGTAG, "URL or Output file is NULL"); } return -1; } public static synchronized void cancelDownload(int id, boolean callOnCompleteListener) { AsyncFileDownloader afd = map.get(id); if(afd == null) { Log.w(LOGTAG, "Cannot find download task with id" + id); return; } afd.cancel = true; afd.callOnCompleteListener = callOnCompleteListener; } private URL url; private File file; private OnCompleteListener<File> clistener; private OnProgressListener plistener; private boolean callOnCompleteListener; private boolean cancel; private AsyncFileDownloader(URL url, File file, OnCompleteListener<File> clistener, OnProgressListener plistener) { super(); this.url = url; this.file = file; this.clistener = clistener; this.plistener = plistener; this.callOnCompleteListener = true; } @Override protected Boolean doInBackground(Void... v) { InputStream is = null; OutputStream os = null; try { Log.i(LOGTAG, "Srart downloading url(" + url + ") to file(" + file + ")"); URLConnection c = url.openConnection(); c.connect(); is = c.getInputStream(); int readingTimeout = c.getReadTimeout(); if(readingTimeout < StreamHelper.READING_TIMEOUT) { readingTimeout = StreamHelper.READING_TIMEOUT; } int fileSize = c.getContentLength(); if(fileSize > 0) { Log.i(LOGTAG, "Size of file to download:" + fileSize); } int readLast = 0, readTotal = 0; os = new FileOutputStream(file); byte[] buff = new byte[StreamHelper.BUFFER_SIZE]; readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); readLast = is.read(buff); } while(readLast > 0) { os.write(buff, 0, readLast); readTotal += readLast; publishProgress(readTotal, fileSize); if(cancel) { break; } readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); if(cancel) { break; } readLast = is.read(buff); } } publishProgress(Integer.MAX_VALUE, Integer.MAX_VALUE); } catch(IOException e) { Log.e(LOGTAG, "Exception while reading stream", e); file = null; } catch(Exception e) { Log.e(LOGTAG, "Cannot open stream", e); file = null; } finally { StreamHelper.close(os); StreamHelper.close(is); } if(cancel) { Log.i(LOGTAG, "Download task canceled. Id:" + id); - file.delete(); - file = null; + if(file != null) + { + file.delete(); + file = null; + } return false; } return true; } @Override protected void onProgressUpdate(Integer... p) { if(plistener != null && !cancel) { plistener.notifyProgress(p[0], p[1]); } } @Override protected void onPostExecute(Boolean result) { if(result) { Log.i(LOGTAG, "Download complete sucessfully"); } if(clistener != null && callOnCompleteListener) { clistener.complete(file); } } private static void wait(int waitTime) { try { Thread.sleep(waitTime); } catch(InterruptedException e) { Log.w(LOGTAG, "Stream reading timeout interupted"); } } }
true
true
protected Boolean doInBackground(Void... v) { InputStream is = null; OutputStream os = null; try { Log.i(LOGTAG, "Srart downloading url(" + url + ") to file(" + file + ")"); URLConnection c = url.openConnection(); c.connect(); is = c.getInputStream(); int readingTimeout = c.getReadTimeout(); if(readingTimeout < StreamHelper.READING_TIMEOUT) { readingTimeout = StreamHelper.READING_TIMEOUT; } int fileSize = c.getContentLength(); if(fileSize > 0) { Log.i(LOGTAG, "Size of file to download:" + fileSize); } int readLast = 0, readTotal = 0; os = new FileOutputStream(file); byte[] buff = new byte[StreamHelper.BUFFER_SIZE]; readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); readLast = is.read(buff); } while(readLast > 0) { os.write(buff, 0, readLast); readTotal += readLast; publishProgress(readTotal, fileSize); if(cancel) { break; } readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); if(cancel) { break; } readLast = is.read(buff); } } publishProgress(Integer.MAX_VALUE, Integer.MAX_VALUE); } catch(IOException e) { Log.e(LOGTAG, "Exception while reading stream", e); file = null; } catch(Exception e) { Log.e(LOGTAG, "Cannot open stream", e); file = null; } finally { StreamHelper.close(os); StreamHelper.close(is); } if(cancel) { Log.i(LOGTAG, "Download task canceled. Id:" + id); file.delete(); file = null; return false; } return true; }
protected Boolean doInBackground(Void... v) { InputStream is = null; OutputStream os = null; try { Log.i(LOGTAG, "Srart downloading url(" + url + ") to file(" + file + ")"); URLConnection c = url.openConnection(); c.connect(); is = c.getInputStream(); int readingTimeout = c.getReadTimeout(); if(readingTimeout < StreamHelper.READING_TIMEOUT) { readingTimeout = StreamHelper.READING_TIMEOUT; } int fileSize = c.getContentLength(); if(fileSize > 0) { Log.i(LOGTAG, "Size of file to download:" + fileSize); } int readLast = 0, readTotal = 0; os = new FileOutputStream(file); byte[] buff = new byte[StreamHelper.BUFFER_SIZE]; readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); readLast = is.read(buff); } while(readLast > 0) { os.write(buff, 0, readLast); readTotal += readLast; publishProgress(readTotal, fileSize); if(cancel) { break; } readLast = is.read(buff); if(readLast < 0 && readingTimeout > 0) { wait(readingTimeout); if(cancel) { break; } readLast = is.read(buff); } } publishProgress(Integer.MAX_VALUE, Integer.MAX_VALUE); } catch(IOException e) { Log.e(LOGTAG, "Exception while reading stream", e); file = null; } catch(Exception e) { Log.e(LOGTAG, "Cannot open stream", e); file = null; } finally { StreamHelper.close(os); StreamHelper.close(is); } if(cancel) { Log.i(LOGTAG, "Download task canceled. Id:" + id); if(file != null) { file.delete(); file = null; } return false; } return true; }
diff --git a/src/main/java/com/me/tft_02/ghosts/listeners/BlockListener.java b/src/main/java/com/me/tft_02/ghosts/listeners/BlockListener.java index c6a4745..431fefc 100644 --- a/src/main/java/com/me/tft_02/ghosts/listeners/BlockListener.java +++ b/src/main/java/com/me/tft_02/ghosts/listeners/BlockListener.java @@ -1,59 +1,61 @@ package com.me.tft_02.ghosts.listeners; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import com.me.tft_02.ghosts.Ghosts; import com.me.tft_02.ghosts.config.Config; import com.me.tft_02.ghosts.database.DatabaseManager; import com.me.tft_02.ghosts.datatypes.TombBlock; import com.me.tft_02.ghosts.locale.LocaleLoader; import com.me.tft_02.ghosts.managers.TombstoneManager; import com.me.tft_02.ghosts.util.BlockUtils; import com.me.tft_02.ghosts.util.Permissions; public class BlockListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); - if (!BlockUtils.isTombStone(block.getLocation()) && Ghosts.p.ghostManager.isGhost(player)) { - event.setCancelled(true); + if (!BlockUtils.isTombStone(block.getLocation())) { + if (Ghosts.p.ghostManager.isGhost(player)) { + event.setCancelled(true); + } return; } if (block.getType() == Material.WALL_SIGN) { org.bukkit.material.Sign signData = (org.bukkit.material.Sign) block.getState().getData(); TombBlock tBlock = DatabaseManager.tombBlockList.get(block.getRelative(signData.getAttachedFace()).getLocation()); if (tBlock == null) { return; } } if (block.getType() != Material.CHEST && block.getType() != Material.SIGN_POST) { return; } if (Config.getInstance().getPreventDestroy() && !Permissions.breakTombs(player)) { player.sendMessage(LocaleLoader.getString("Tombstone.Cannot_Break")); event.setCancelled(true); return; } TombBlock tombBlock = DatabaseManager.tombBlockList.get(block.getLocation()); TombstoneManager.removeTomb(tombBlock, true); Player owner = Ghosts.p.getServer().getPlayer(tombBlock.getOwner()); if (owner != null) { owner.sendMessage(LocaleLoader.getString("Tombstone.Was_Destroyed", player.getName())); } } }
true
true
public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); if (!BlockUtils.isTombStone(block.getLocation()) && Ghosts.p.ghostManager.isGhost(player)) { event.setCancelled(true); return; } if (block.getType() == Material.WALL_SIGN) { org.bukkit.material.Sign signData = (org.bukkit.material.Sign) block.getState().getData(); TombBlock tBlock = DatabaseManager.tombBlockList.get(block.getRelative(signData.getAttachedFace()).getLocation()); if (tBlock == null) { return; } } if (block.getType() != Material.CHEST && block.getType() != Material.SIGN_POST) { return; } if (Config.getInstance().getPreventDestroy() && !Permissions.breakTombs(player)) { player.sendMessage(LocaleLoader.getString("Tombstone.Cannot_Break")); event.setCancelled(true); return; } TombBlock tombBlock = DatabaseManager.tombBlockList.get(block.getLocation()); TombstoneManager.removeTomb(tombBlock, true); Player owner = Ghosts.p.getServer().getPlayer(tombBlock.getOwner()); if (owner != null) { owner.sendMessage(LocaleLoader.getString("Tombstone.Was_Destroyed", player.getName())); } }
public void onBlockBreak(BlockBreakEvent event) { Block block = event.getBlock(); Player player = event.getPlayer(); if (!BlockUtils.isTombStone(block.getLocation())) { if (Ghosts.p.ghostManager.isGhost(player)) { event.setCancelled(true); } return; } if (block.getType() == Material.WALL_SIGN) { org.bukkit.material.Sign signData = (org.bukkit.material.Sign) block.getState().getData(); TombBlock tBlock = DatabaseManager.tombBlockList.get(block.getRelative(signData.getAttachedFace()).getLocation()); if (tBlock == null) { return; } } if (block.getType() != Material.CHEST && block.getType() != Material.SIGN_POST) { return; } if (Config.getInstance().getPreventDestroy() && !Permissions.breakTombs(player)) { player.sendMessage(LocaleLoader.getString("Tombstone.Cannot_Break")); event.setCancelled(true); return; } TombBlock tombBlock = DatabaseManager.tombBlockList.get(block.getLocation()); TombstoneManager.removeTomb(tombBlock, true); Player owner = Ghosts.p.getServer().getPlayer(tombBlock.getOwner()); if (owner != null) { owner.sendMessage(LocaleLoader.getString("Tombstone.Was_Destroyed", player.getName())); } }
diff --git a/clustermate-service/src/main/java/com/fasterxml/clustermate/service/cleanup/LocalEntryCleaner.java b/clustermate-service/src/main/java/com/fasterxml/clustermate/service/cleanup/LocalEntryCleaner.java index 29628688..1ec9aa0b 100644 --- a/clustermate-service/src/main/java/com/fasterxml/clustermate/service/cleanup/LocalEntryCleaner.java +++ b/clustermate-service/src/main/java/com/fasterxml/clustermate/service/cleanup/LocalEntryCleaner.java @@ -1,137 +1,138 @@ package com.fasterxml.clustermate.service.cleanup; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.*; import com.fasterxml.clustermate.service.SharedServiceStuff; import com.fasterxml.clustermate.service.Stores; import com.fasterxml.clustermate.service.bdb.LastAccessStore; import com.fasterxml.clustermate.service.store.StoredEntry; import com.fasterxml.clustermate.service.store.StoredEntryConverter; import com.fasterxml.storemate.shared.EntryKey; import com.fasterxml.storemate.shared.StorableKey; import com.fasterxml.storemate.store.Storable; import com.fasterxml.storemate.store.StorableStore; import com.fasterxml.storemate.store.StoreException; import com.fasterxml.storemate.store.backend.IterationAction; import com.fasterxml.storemate.store.backend.StorableLastModIterationCallback; /** * Helper class used to keep track of clean up progress * for local BDB cleanup. */ public class LocalEntryCleaner<K extends EntryKey, E extends StoredEntry<K>> extends CleanupTask<LocalCleanupStats> { private final static Logger LOG = LoggerFactory.getLogger(LocalEntryCleaner.class); /** * Time-to-live for tomb stones */ protected final long _tombstoneTTLMsecs; protected final StorableStore _entryStore; protected final LastAccessStore<K, E> _lastAccessStore; protected final StoredEntryConverter<K, E> _entryFactory; protected final boolean _isTesting; public LocalEntryCleaner(SharedServiceStuff stuff, Stores<K, E> stores, AtomicBoolean shutdown) { super(stuff, shutdown); _tombstoneTTLMsecs = stuff.getServiceConfig().cfgTombstoneTTL.getMillis(); _entryFactory = stuff.getEntryConverter(); _entryStore = stores.getEntryStore(); _lastAccessStore = stores.getLastAccessStore(); _isTesting = stuff.isRunningTests(); } @Override protected LocalCleanupStats _cleanUp() throws Exception { final LocalCleanupStats stats = new LocalCleanupStats(); if (_entryStore.isClosed()) { if (!_isTesting) { LOG.warn("LocalEntryCleanup task cancelled: Entry DB has been closed"); } return stats; } final long tombstoneThreshold = _timeMaster.currentTimeMillis() - _tombstoneTTLMsecs; _entryStore.iterateEntriesByModifiedTime(new StorableLastModIterationCallback() { @Override public IterationAction verifyTimestamp(long timestamp) { return IterationAction.PROCESS_ENTRY; } @Override public IterationAction verifyKey(StorableKey key) { // first things first: do we need to quit? // TODO: maybe consider max runtime? if (shouldStop()) { return IterationAction.TERMINATE_ITERATION; } return IterationAction.PROCESS_ENTRY; } @Override public IterationAction processEntry(Storable raw) throws StoreException { // for tombstones easy, common max-TTL: final StoredEntry<K> entry = _entryFactory.entryFromStorable(raw); if (raw.isDeleted()) { if (entry.insertedBefore(tombstoneThreshold)) { + delete(raw.getKey()); stats.addExpiredTombstone(); } else { stats.addRemainingTombstone(); } return IterationAction.PROCESS_ENTRY; } // for other entries bit more complex; basically checking following possibilities: // (a) Entry is older than its maxTTL (which varies entry by entry), can be removed // (b) Entry is younger than its minTTL since creation, can be skipped // (c) Entry does not use access-time: remove // (d) Entry needs to be retained based on local last-access time: skip // (e) Must check global last-access to determine whether to keep or skip final long currentTime = _timeMaster.currentTimeMillis(); if (entry.hasExceededMaxTTL(currentTime)) { // (a) remove stats.addExpiredMaxTTLEntry(); delete(raw.getKey()); } else if (!entry.hasExceededMinTTL(currentTime)) { // (b) skip stats.addRemainingEntry(); } else if (!entry.usesLastAccessTime()) { // (c) remove stats.addExpiredLastAccessEntry(); delete(raw.getKey()); } else if (!entry.hasExceededLastAccessTTL(currentTime, _lastAccessStore.findLastAccessTime(entry.getKey(), entry.getLastAccessUpdateMethod()))) { stats.addRemainingEntry(); // (d) keep } else { // (e): add to list of things to check... // !!! TODO stats.addRemainingEntry(); } return IterationAction.PROCESS_ENTRY; } private void delete(StorableKey key) throws StoreException { try { _entryStore.hardDelete(key, true); } catch (StoreException e) { throw e; } catch (IOException e) { throw new StoreException.IO(key, e); } } }, 0L); return stats; } }
true
true
protected LocalCleanupStats _cleanUp() throws Exception { final LocalCleanupStats stats = new LocalCleanupStats(); if (_entryStore.isClosed()) { if (!_isTesting) { LOG.warn("LocalEntryCleanup task cancelled: Entry DB has been closed"); } return stats; } final long tombstoneThreshold = _timeMaster.currentTimeMillis() - _tombstoneTTLMsecs; _entryStore.iterateEntriesByModifiedTime(new StorableLastModIterationCallback() { @Override public IterationAction verifyTimestamp(long timestamp) { return IterationAction.PROCESS_ENTRY; } @Override public IterationAction verifyKey(StorableKey key) { // first things first: do we need to quit? // TODO: maybe consider max runtime? if (shouldStop()) { return IterationAction.TERMINATE_ITERATION; } return IterationAction.PROCESS_ENTRY; } @Override public IterationAction processEntry(Storable raw) throws StoreException { // for tombstones easy, common max-TTL: final StoredEntry<K> entry = _entryFactory.entryFromStorable(raw); if (raw.isDeleted()) { if (entry.insertedBefore(tombstoneThreshold)) { stats.addExpiredTombstone(); } else { stats.addRemainingTombstone(); } return IterationAction.PROCESS_ENTRY; } // for other entries bit more complex; basically checking following possibilities: // (a) Entry is older than its maxTTL (which varies entry by entry), can be removed // (b) Entry is younger than its minTTL since creation, can be skipped // (c) Entry does not use access-time: remove // (d) Entry needs to be retained based on local last-access time: skip // (e) Must check global last-access to determine whether to keep or skip final long currentTime = _timeMaster.currentTimeMillis(); if (entry.hasExceededMaxTTL(currentTime)) { // (a) remove stats.addExpiredMaxTTLEntry(); delete(raw.getKey()); } else if (!entry.hasExceededMinTTL(currentTime)) { // (b) skip stats.addRemainingEntry(); } else if (!entry.usesLastAccessTime()) { // (c) remove stats.addExpiredLastAccessEntry(); delete(raw.getKey()); } else if (!entry.hasExceededLastAccessTTL(currentTime, _lastAccessStore.findLastAccessTime(entry.getKey(), entry.getLastAccessUpdateMethod()))) { stats.addRemainingEntry(); // (d) keep } else { // (e): add to list of things to check... // !!! TODO stats.addRemainingEntry(); } return IterationAction.PROCESS_ENTRY; } private void delete(StorableKey key) throws StoreException { try { _entryStore.hardDelete(key, true); } catch (StoreException e) { throw e; } catch (IOException e) { throw new StoreException.IO(key, e); } } }, 0L); return stats; }
protected LocalCleanupStats _cleanUp() throws Exception { final LocalCleanupStats stats = new LocalCleanupStats(); if (_entryStore.isClosed()) { if (!_isTesting) { LOG.warn("LocalEntryCleanup task cancelled: Entry DB has been closed"); } return stats; } final long tombstoneThreshold = _timeMaster.currentTimeMillis() - _tombstoneTTLMsecs; _entryStore.iterateEntriesByModifiedTime(new StorableLastModIterationCallback() { @Override public IterationAction verifyTimestamp(long timestamp) { return IterationAction.PROCESS_ENTRY; } @Override public IterationAction verifyKey(StorableKey key) { // first things first: do we need to quit? // TODO: maybe consider max runtime? if (shouldStop()) { return IterationAction.TERMINATE_ITERATION; } return IterationAction.PROCESS_ENTRY; } @Override public IterationAction processEntry(Storable raw) throws StoreException { // for tombstones easy, common max-TTL: final StoredEntry<K> entry = _entryFactory.entryFromStorable(raw); if (raw.isDeleted()) { if (entry.insertedBefore(tombstoneThreshold)) { delete(raw.getKey()); stats.addExpiredTombstone(); } else { stats.addRemainingTombstone(); } return IterationAction.PROCESS_ENTRY; } // for other entries bit more complex; basically checking following possibilities: // (a) Entry is older than its maxTTL (which varies entry by entry), can be removed // (b) Entry is younger than its minTTL since creation, can be skipped // (c) Entry does not use access-time: remove // (d) Entry needs to be retained based on local last-access time: skip // (e) Must check global last-access to determine whether to keep or skip final long currentTime = _timeMaster.currentTimeMillis(); if (entry.hasExceededMaxTTL(currentTime)) { // (a) remove stats.addExpiredMaxTTLEntry(); delete(raw.getKey()); } else if (!entry.hasExceededMinTTL(currentTime)) { // (b) skip stats.addRemainingEntry(); } else if (!entry.usesLastAccessTime()) { // (c) remove stats.addExpiredLastAccessEntry(); delete(raw.getKey()); } else if (!entry.hasExceededLastAccessTTL(currentTime, _lastAccessStore.findLastAccessTime(entry.getKey(), entry.getLastAccessUpdateMethod()))) { stats.addRemainingEntry(); // (d) keep } else { // (e): add to list of things to check... // !!! TODO stats.addRemainingEntry(); } return IterationAction.PROCESS_ENTRY; } private void delete(StorableKey key) throws StoreException { try { _entryStore.hardDelete(key, true); } catch (StoreException e) { throw e; } catch (IOException e) { throw new StoreException.IO(key, e); } } }, 0L); return stats; }
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/software/Quest5a.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/software/Quest5a.java index ca11b59..cecc2ed 100644 --- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/software/Quest5a.java +++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/software/Quest5a.java @@ -1,59 +1,59 @@ package org.akquinet.audit.bsi.httpd.software; import java.util.List; import org.akquinet.audit.FormattedConsole; import org.akquinet.audit.YesNoQuestion; import org.akquinet.audit.FormattedConsole.OutputLevel; import org.akquinet.httpd.ConfigFile; import org.akquinet.httpd.syntax.Directive; public class Quest5a implements YesNoQuestion { private static final String _id = "Quest5a"; private ConfigFile _conf; private static final FormattedConsole _console = FormattedConsole.getDefault(); private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q2; public Quest5a(ConfigFile conf) { _conf = conf; } /** * checks whether there are any Include-directives in the config file */ @Override public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); - List<Directive> incList = _conf.getDirectiveIgnoreCase("Include"); + List<Directive> incList = _conf.getAllDirectivesIgnoreCase("Include"); if(!incList.isEmpty()) { _console.printAnswer(_level, false, "There are Include-directives in your apache configuration:"); for (Directive directive : incList) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } else { _console.printAnswer(OutputLevel.Q2, true, "No Include-directives found."); return true; } } @Override public boolean isCritical() { return true; } @Override public String getID() { return _id; } }
true
true
public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); List<Directive> incList = _conf.getDirectiveIgnoreCase("Include"); if(!incList.isEmpty()) { _console.printAnswer(_level, false, "There are Include-directives in your apache configuration:"); for (Directive directive : incList) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } else { _console.printAnswer(OutputLevel.Q2, true, "No Include-directives found."); return true; } }
public boolean answer() { _console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----"); List<Directive> incList = _conf.getAllDirectivesIgnoreCase("Include"); if(!incList.isEmpty()) { _console.printAnswer(_level, false, "There are Include-directives in your apache configuration:"); for (Directive directive : incList) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } return false; } else { _console.printAnswer(OutputLevel.Q2, true, "No Include-directives found."); return true; } }
diff --git a/tests/src/com/android/music/MusicPlayerStability.java b/tests/src/com/android/music/MusicPlayerStability.java index 5654adb..d84d2f8 100644 --- a/tests/src/com/android/music/MusicPlayerStability.java +++ b/tests/src/com/android/music/MusicPlayerStability.java @@ -1,88 +1,90 @@ /* * Copyright (C) 2009 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.music.tests; import android.app.Instrumentation; import com.android.music.TrackBrowserActivity; import android.view.KeyEvent; import android.widget.ListView; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; /** * Junit / Instrumentation test case for the Music Player */ public class MusicPlayerStability extends ActivityInstrumentationTestCase2 <TrackBrowserActivity>{ private static String TAG = "musicplayerstability"; private static int PLAY_TIME = 30000; private ListView mTrackList; public MusicPlayerStability() { super("com.android.music",TrackBrowserActivity.class); } @Override protected void setUp() throws Exception { getActivity(); super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test case 1: This test case is for the power and general stability * measurment. We don't need to do the validation. This test case simply * play the mp3 for 30 seconds then stop. * The sdcard should have the target mp3 files. */ @LargeTest public void testPlay30sMP3() throws Exception { // Launch the songs list. Pick the fisrt song and play try { Instrumentation inst = getInstrumentation(); + //Make sure the song list shown up + Thread.sleep(2000); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); mTrackList = getActivity().getListView(); - int viewCount = mTrackList.getSelectedItemPosition(); + int scrollCount = mTrackList.getMaxScrollAmount(); //Make sure there is at least one song in the sdcard - if (viewCount != -1) { + if (scrollCount != -1) { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER); } else { assertTrue("testPlayMP3", false); } Thread.sleep(PLAY_TIME); } catch (Exception e) { assertTrue("testPlayMP3", false); } } @LargeTest public void testLaunchMusicPlayer() throws Exception { // Launch music player and sleep for 30 seconds to capture // the music player power usage base line. try { Thread.sleep(PLAY_TIME); } catch (Exception e) { assertTrue("MusicPlayer Do Nothing", false); } assertTrue("MusicPlayer Do Nothing", true); } }
false
true
public void testPlay30sMP3() throws Exception { // Launch the songs list. Pick the fisrt song and play try { Instrumentation inst = getInstrumentation(); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); mTrackList = getActivity().getListView(); int viewCount = mTrackList.getSelectedItemPosition(); //Make sure there is at least one song in the sdcard if (viewCount != -1) { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER); } else { assertTrue("testPlayMP3", false); } Thread.sleep(PLAY_TIME); } catch (Exception e) { assertTrue("testPlayMP3", false); } }
public void testPlay30sMP3() throws Exception { // Launch the songs list. Pick the fisrt song and play try { Instrumentation inst = getInstrumentation(); //Make sure the song list shown up Thread.sleep(2000); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN); mTrackList = getActivity().getListView(); int scrollCount = mTrackList.getMaxScrollAmount(); //Make sure there is at least one song in the sdcard if (scrollCount != -1) { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER); } else { assertTrue("testPlayMP3", false); } Thread.sleep(PLAY_TIME); } catch (Exception e) { assertTrue("testPlayMP3", false); } }
diff --git a/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java b/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java index 3d39bc6..56a8dd0 100755 --- a/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java +++ b/src/com/evervolv/EVParts/Preferences/LockscreenPrefs.java @@ -1,98 +1,99 @@ package com.evervolv.EVParts.Preferences; import com.evervolv.EVParts.R; import com.evervolv.EVParts.R.bool; import com.evervolv.EVParts.R.xml; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.EditTextPreference; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceChangeListener; import android.widget.Toast; import android.util.Log; import android.provider.Settings; public class LockscreenPrefs extends PreferenceActivity implements OnPreferenceChangeListener { private static final String CARRIER_CAP = "pref_carrier_caption"; private static final String LOCKSCREEN_ROTARY_LOCK = "pref_use_rotary_lockscreen"; private static final String TRACKBALL_UNLOCK_PREF = "pref_trackball_unlock"; private static final String GENERAL_CATEGORY = "pref_lockscreen_general_category"; private EditTextPreference mCarrierCaption; private CheckBoxPreference mUseRotaryLockPref; private CheckBoxPreference mTrackballUnlockPref; private static final String TAG = "EVParts"; private static final boolean DEBUG = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.lockscreen_prefs); PreferenceScreen prefSet = getPreferenceScreen(); /* Rotary lockscreen */ mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK); mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1); /* Carrier caption */ mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP); mCarrierCaption.setOnPreferenceChangeListener(this); /* Trackball Unlock */ mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF); mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1); PreferenceCategory generalCategory = (PreferenceCategory) prefSet .findPreference(GENERAL_CATEGORY); if (!getResources().getBoolean(R.bool.has_trackball)) { + if (DEBUG) Log.d(TAG, "does not have trackball!"); generalCategory.removePreference(mTrackballUnlockPref); } } public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { boolean value; if (preference == mUseRotaryLockPref) { value = mUseRotaryLockPref.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.USE_ROTARY_LOCKSCREEN, value ? 1 : 0); //Temporary hack to fix Phone FC's when swapping styles. ActivityManager am = (ActivityManager)getSystemService( Context.ACTIVITY_SERVICE); am.forceStopPackage("com.android.phone"); } else if (preference == mTrackballUnlockPref) { value = mTrackballUnlockPref.isChecked(); Settings.System.putInt(getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN, value ? 1 : 0); return true; } return true; } public boolean onPreferenceChange(Preference preference, Object objValue) { if (preference == mCarrierCaption) { Settings.System.putString(getContentResolver(),Settings.System.CARRIER_CAP, objValue.toString()); //Didn't i say i was learning? ActivityManager am = (ActivityManager)getSystemService( Context.ACTIVITY_SERVICE); am.forceStopPackage("com.android.phone"); } return true; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.lockscreen_prefs); PreferenceScreen prefSet = getPreferenceScreen(); /* Rotary lockscreen */ mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK); mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1); /* Carrier caption */ mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP); mCarrierCaption.setOnPreferenceChangeListener(this); /* Trackball Unlock */ mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF); mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1); PreferenceCategory generalCategory = (PreferenceCategory) prefSet .findPreference(GENERAL_CATEGORY); if (!getResources().getBoolean(R.bool.has_trackball)) { generalCategory.removePreference(mTrackballUnlockPref); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.lockscreen_prefs); PreferenceScreen prefSet = getPreferenceScreen(); /* Rotary lockscreen */ mUseRotaryLockPref = (CheckBoxPreference)prefSet.findPreference(LOCKSCREEN_ROTARY_LOCK); mUseRotaryLockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.USE_ROTARY_LOCKSCREEN, 1) == 1); /* Carrier caption */ mCarrierCaption = (EditTextPreference)prefSet.findPreference(CARRIER_CAP); mCarrierCaption.setOnPreferenceChangeListener(this); /* Trackball Unlock */ mTrackballUnlockPref = (CheckBoxPreference) prefSet.findPreference(TRACKBALL_UNLOCK_PREF); mTrackballUnlockPref.setChecked(Settings.System.getInt(getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1); PreferenceCategory generalCategory = (PreferenceCategory) prefSet .findPreference(GENERAL_CATEGORY); if (!getResources().getBoolean(R.bool.has_trackball)) { if (DEBUG) Log.d(TAG, "does not have trackball!"); generalCategory.removePreference(mTrackballUnlockPref); } }
diff --git a/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java b/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java index 670c495f4..e390d99db 100644 --- a/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java +++ b/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java @@ -1,227 +1,228 @@ /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.frontend; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import java.io.IOException; /** * DataProcessor contains the common elements of all frontend data * processors, namely the name, context, timers, SphinxProperties, * and dumping. It also contains the acoustic properties object from * which acoustic model properties can be queried. */ public abstract class DataProcessor { /** * The name of this DataProcessor. */ private String name; /** * The context of this DataProcessor. */ private String context; /** * A Timer for timing processing. */ private Timer timer; /** * Indicates whether to dump the processed Data */ private boolean dump = false; /** * The SphinxProperties used by this DataProcessor */ private SphinxProperties sphinxProperties; // true if processing Data objects within an Utterance private boolean inUtterance; /** * Constructs a default DataProcessor */ public DataProcessor() {} /** * Constructs a DataProcessor with the given name and context. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor */ public DataProcessor(String name, String context) { initialize(name, context, null); } /** * Constructs a DataProcessor of the given name and at the given context. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor * @param sphinxProperties the sphinx properties used */ public DataProcessor(String name, String context, SphinxProperties sphinxProperties) { initialize(name, context, sphinxProperties); } /** * Initializes this DataProcessor. * * @param name the name of this DataProcessor * @param context the context of this DataProcessor * @param sphinxProperties the SphinxProperties to use */ public void initialize(String name, String context, SphinxProperties sphinxProperties) { this.name = name; this.context = context; this.sphinxProperties = sphinxProperties; this.timer = Timer.getTimer(context, name); } /** * Returns the name of this DataProcessor. * * @return the name of this DataProcessor */ public final String getName() { return name; } /** * Returns the context of this DataProcessor. * * @return the context of this DataProcessor */ public final String getContext() { return context; } /** * Returns the SphinxProperties used by this DataProcessor. * * @return the SphinxProperties */ public final SphinxProperties getSphinxProperties() { if (sphinxProperties != null) { return sphinxProperties; } else { return SphinxProperties.getSphinxProperties(getContext()); } } /** * Sets the SphinxProperties to use. * * @param sphinxProperties the SphinxProperties to use */ public void setSphinxProperties(SphinxProperties sphinxProperties) { this.sphinxProperties = sphinxProperties; } /** * Returns the Timer for metrics collection purposes. * * @return the Timer */ public final Timer getTimer() { return timer; } /** * Determine whether to dump the output for debug purposes. * * @return true to dump, false to not dump */ public final boolean getDump() { return this.dump; } /** * Set whether we should dump the output for debug purposes. * * @param dump true to dump the output; false otherwise */ public void setDump(boolean dump) { this.dump = dump; } /** * Returns the name of this DataProcessor. * * @return the name of this DataProcessor */ public String toString() { return name; } /** * Does sanity check on whether the Signals UTTERANCE_START and * UTTERANCE_END are in sequence. Throws an Error if: * <ol> * <li> We have not received an UTTERANCE_START Signal before * receiving an Signal/Data. * <li> We received an UTTERANCE_START after an UTTERANCE_START * without an intervening UTTERANCE_END; * </ol> * * @throws Error if the UTTERANCE_START and UTTERANCE_END signals * are not in sequence */ protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { - throw new Error(getName() + ": null data"); + throw new Error + (getName() + ": unexpected return of null Data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } } }
true
true
protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { throw new Error(getName() + ": null data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } }
protected void signalCheck(Data data) { if (!inUtterance) { if (data != null) { if (data.hasSignal(Signal.UTTERANCE_START)) { inUtterance = true; } else { throw new Error(getName() + ": no UTTERANCE_START"); } } } else { if (data == null) { throw new Error (getName() + ": unexpected return of null Data"); } else if (data.hasSignal(Signal.UTTERANCE_END)) { inUtterance = false; } else if (data.hasSignal(Signal.UTTERANCE_START)) { throw new Error(getName() + ": too many UTTERANCE_START"); } } }
diff --git a/src/adapter/LEDOutputAdapter.java b/src/adapter/LEDOutputAdapter.java index b5e20f5..562ffc8 100644 --- a/src/adapter/LEDOutputAdapter.java +++ b/src/adapter/LEDOutputAdapter.java @@ -1,37 +1,37 @@ package adapter; import java.awt.Color; import com.IOController; public class LEDOutputAdapter implements OutputAdapter { @Override public void setColor(Color color) { int red = (color.getRed()*100)/255; int green = (color.getGreen()*100)/255; int blue = (color.getBlue()*100)/255; int min = Math.min(Math.min(red, green), blue); - String message = "SC"+1+" R "+(red>min?(int)(red*2):(int)(red*0.5))+"; G "+(green>min?(int)(green*2):(int)(green*0.5))+"; B "+(blue>min?(int)(blue*2):(int)(blue*0.5))+";"; + String message = "SC"+1+" R "+red+"; G "+green+"; B "+blue+";"; //System.out.println(message); IOController controller = IOController.getInstance(); controller.sendMessageToLEDController(message); } public void setColor(Color color, int lineNo) { int red = (color.getRed()*100)/255; int green = (color.getGreen()*100)/255; int blue = (color.getBlue()*100)/255; String message = "SC"+lineNo+" R "+red+"; G "+green+"; B "+blue+";"; IOController controller = IOController.getInstance(); controller.sendMessageToLEDController(message); } @Override public void startTransmission() { IOController.getInstance().openPort(); } @Override public void endTransmission() { IOController.getInstance().closePort(); } }
true
true
public void setColor(Color color) { int red = (color.getRed()*100)/255; int green = (color.getGreen()*100)/255; int blue = (color.getBlue()*100)/255; int min = Math.min(Math.min(red, green), blue); String message = "SC"+1+" R "+(red>min?(int)(red*2):(int)(red*0.5))+"; G "+(green>min?(int)(green*2):(int)(green*0.5))+"; B "+(blue>min?(int)(blue*2):(int)(blue*0.5))+";"; //System.out.println(message); IOController controller = IOController.getInstance(); controller.sendMessageToLEDController(message); }
public void setColor(Color color) { int red = (color.getRed()*100)/255; int green = (color.getGreen()*100)/255; int blue = (color.getBlue()*100)/255; int min = Math.min(Math.min(red, green), blue); String message = "SC"+1+" R "+red+"; G "+green+"; B "+blue+";"; //System.out.println(message); IOController controller = IOController.getInstance(); controller.sendMessageToLEDController(message); }
diff --git a/goobi1.9/WEB-INF/src/org/goobi/api/display/helper/ConfigDispayRules.java b/goobi1.9/WEB-INF/src/org/goobi/api/display/helper/ConfigDispayRules.java index 393ed8366..e442cffbb 100644 --- a/goobi1.9/WEB-INF/src/org/goobi/api/display/helper/ConfigDispayRules.java +++ b/goobi1.9/WEB-INF/src/org/goobi/api/display/helper/ConfigDispayRules.java @@ -1,425 +1,430 @@ package org.goobi.api.display.helper; /** * This file is part of the Goobi Application - a Workflow tool for the support of mass digitization. * * Visit the websites for more information. - http://gdz.sub.uni-goettingen.de - http://www.intranda.com * * Copyright 2009, Center for Retrospective Digitization, Göttingen (GDZ), * * 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 * * Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions * of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to * link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this * library, you may extend this exception to your version of the library, but you are not obliged to do so. If you do not wish to do so, delete this * exception statement from your version. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy; import org.goobi.api.display.Item; import org.goobi.api.display.enums.DisplayType; import de.sub.goobi.helper.Helper; public final class ConfigDispayRules { private static ConfigDispayRules instance = new ConfigDispayRules(); private static XMLConfiguration config; private static String configPfad; private final Helper helper = new Helper(); private final HashMap<String, HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>>> allValues = new HashMap<String, HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>>>(); /** * * reads given xml file into XMLConfiguration * * @throws ConfigurationException */ private ConfigDispayRules() { configPfad = helper.getGoobiConfigDirectory() + "ruleSet.xml"; try { config = new XMLConfiguration(configPfad); config.setReloadingStrategy(new FileChangedReloadingStrategy()); getDisplayItems(); } catch (ConfigurationException e) { /* * no configuration file found, default configuration (textarea) * will be used, nothing to do here */ } } public static ConfigDispayRules getInstance() { return instance; } /** * * creates hierarchical HashMap with values for each element of given data */ private synchronized void getDisplayItems() { if (allValues.isEmpty() && config != null) { int countRuleSet = config.getMaxIndex("ruleSet"); for (int i = 0; i <= countRuleSet; i++) { int projectContext = config.getMaxIndex("ruleSet(" + i + ").context"); for (int j = 0; j <= projectContext; j++) { HashMap<String, HashMap<String, ArrayList<Item>>> itemsByType = new HashMap<String, HashMap<String, ArrayList<Item>>>(); HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>> bindstate = new HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>>(); String projectName = config.getString("ruleSet(" + i + ").context(" + j + ")[@projectName]"); String bind = config.getString("ruleSet(" + i + ").context(" + j + ").bind"); int countSelect1 = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select1"); int countSelect = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select"); int countTextArea = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").textarea"); int countInput = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").input"); HashMap<String, ArrayList<Item>> select1 = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> select = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> input = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> textarea = new HashMap<String, ArrayList<Item>>(); for (int k = 0; k <= countSelect1; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select1(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelect1ByElementName(projectName, bind, elementName); select1.put(elementName, items); } for (int k = 0; k <= countSelect; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelectByElementName(projectName, bind, elementName); select.put(elementName, items); } for (int k = 0; k <= countTextArea; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").textarea(" + k + ")[@tns:ref]"); ArrayList<Item> items = getTextareaByElementName(projectName, bind, elementName); textarea.put(elementName, items); } for (int k = 0; k <= countInput; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").input(" + k + ")[@tns:ref]"); ArrayList<Item> items = getInputByElementName(projectName, bind, elementName); input.put(elementName, items); } itemsByType.put("select1", select1); itemsByType.put("select", select); itemsByType.put("input", input); itemsByType.put("textarea", textarea); - bindstate.put(bind, itemsByType); - allValues.put(projectName, bindstate); + if (allValues.get(projectName) == null) { + bindstate.put(bind, itemsByType); + allValues.put(projectName, bindstate); + } else { + bindstate = allValues.get(projectName); + bindstate.put(bind, itemsByType); + } } } } // for (Entry<String, HashMap<String, HashMap<String, HashMap<String, // ArrayList<Item>>>>> bla : allValues.entrySet()) { // System.out.println("proj:" + bla.getKey()); // for (Entry<String, HashMap<String, HashMap<String, ArrayList<Item>>>> // blub : bla.getValue().entrySet()) { // System.out.println(" bindstate: " + blub.getKey()); // for (Entry<String, HashMap<String, ArrayList<Item>>> qwertzu : // blub.getValue().entrySet()) { // System.out.println(" type: " + qwertzu.getKey()); // for (Entry<String, ArrayList<Item>> qwer : // qwertzu.getValue().entrySet()) { // System.out.println(" element: " + qwer.getKey()); // } // } // } // } } /** * * @param project * name of project as String * @param bind * create or edit * @param elementName * name of the select1 element * @return ArrayList with all items and its values of given select1 element. */ private ArrayList<Item> getSelect1ByElementName(String project, String bind, String elementName) { ArrayList<Item> listOfItems = new ArrayList<Item>(); int count = config.getMaxIndex("ruleSet.context"); for (int i = 0; i <= count; i++) { String myProject = config.getString("ruleSet.context(" + i + ")[@projectName]"); String myBind = config.getString("ruleSet.context(" + i + ").bind"); if (myProject.equals(project) && myBind.equals(bind)) { int type = config.getMaxIndex("ruleSet.context(" + i + ").select1"); for (int j = 0; j <= type; j++) { String myElementName = config.getString("ruleSet.context(" + i + ").select1(" + j + ")[@tns:ref]"); if (myElementName.equals(elementName)) { int item = config.getMaxIndex("ruleSet.context(" + i + ").select1(" + j + ").item"); for (int k = 0; k <= item; k++) { Item myItem = new Item(config.getString("ruleSet.context(" + i + ").select1(" + j + ").item(" + k + ").label"), // the // displayed // value config.getString("ruleSet.context(" + i + ").select1(" + j + ").item(" + k + ").value"), // the // internal // value, // which // will // be // taken // if // label // is // selected config.getBoolean("ruleSet.context(" + i + ").select1(" + j + ").item(" + k + ")[@tns:selected]")); // indicates // whether // given // item // is // preselected // or // not listOfItems.add(myItem); } } } } } return listOfItems; } /** * * @param project * name of project as String * @param bind * create or edit * @param elementName * name of the select element * @return ArrayList with all items and its values of given select1 element. */ private ArrayList<Item> getSelectByElementName(String project, String bind, String elementName) { ArrayList<Item> listOfItems = new ArrayList<Item>(); int count = config.getMaxIndex("ruleSet.context"); for (int i = 0; i <= count; i++) { String myProject = config.getString("ruleSet.context(" + i + ")[@projectName]"); String myBind = config.getString("ruleSet.context(" + i + ").bind"); if (myProject.equals(project) && myBind.equals(bind)) { int type = config.getMaxIndex("ruleSet.context(" + i + ").select"); for (int j = 0; j <= type; j++) { String myElementName = config.getString("ruleSet.context(" + i + ").select(" + j + ")[@tns:ref]"); if (myElementName.equals(elementName)) { int item = config.getMaxIndex("ruleSet.context(" + i + ").select(" + j + ").item"); for (int k = 0; k <= item; k++) { Item myItem = new Item(config.getString("ruleSet.context(" + i + ").select(" + j + ").item(" + k + ").label"), // the // displayed // value config.getString("ruleSet.context(" + i + ").select(" + j + ").item(" + k + ").value"), // the // internal // value, // which // will // be // taken // if // label // is // selected config.getBoolean("ruleSet.context(" + i + ").select(" + j + ").item(" + k + ")[@tns:selected]")); // indicates // whether // given // item // is // preselected // or // not listOfItems.add(myItem); } } } } } return listOfItems; } /** * * @param project * name of project as String * @param bind * create or edit * @param elementName * name of the input element * @return item of given input element. */ private ArrayList<Item> getInputByElementName(String project, String bind, String elementName) { ArrayList<Item> listOfItems = new ArrayList<Item>(); int count = config.getMaxIndex("ruleSet.context"); for (int i = 0; i <= count; i++) { String myProject = config.getString("ruleSet.context(" + i + ")[@projectName]"); String myBind = config.getString("ruleSet.context(" + i + ").bind"); if (myProject.equals(project) && myBind.equals(bind)) { int type = config.getMaxIndex("ruleSet.context(" + i + ").input"); for (int j = 0; j <= type; j++) { String myElementName = config.getString("ruleSet.context(" + i + ").input(" + j + ")[@tns:ref]"); if (myElementName.equals(elementName)) { Item myItem = new Item(config.getString("ruleSet.context(" + i + ").input(" + j + ").label"), // the // displayed // value config.getString("ruleSet.context(" + i + ").input(" + j + ").label"), false); listOfItems.add(myItem); } } } } return listOfItems; } /** * @param project * name of project as String * @param bind * create or edit * @param elementName * name of the textarea element * @return item of given textarea element. */ private ArrayList<Item> getTextareaByElementName(String project, String bind, String elementName) { ArrayList<Item> listOfItems = new ArrayList<Item>(); int count = config.getMaxIndex("ruleSet.context"); for (int i = 0; i <= count; i++) { String myProject = config.getString("ruleSet.context(" + i + ")[@projectName]"); String myBind = config.getString("ruleSet.context(" + i + ").bind"); if (myProject.equals(project) && myBind.equals(bind)) { int type = config.getMaxIndex("ruleSet.context(" + i + ").textarea"); for (int j = 0; j <= type; j++) { String myElementName = config.getString("ruleSet.context(" + i + ").textarea(" + j + ")[@tns:ref]"); if (myElementName.equals(elementName)) { Item myItem = new Item(config.getString("ruleSet.context(" + i + ").textarea(" + j + ").label"), // the // displayed // value config.getString("ruleSet.context(" + i + ").textarea(" + j + ").label"), false); listOfItems.add(myItem); } } } } return listOfItems; } /** * * @param project * project of element * @param bind * create or edit * @param elementName * name of element * @return returns type of element */ public DisplayType getElementTypeByName(String myproject, String mybind, String myelementName) { synchronized (allValues) { if (allValues.isEmpty() && config != null) { getDisplayItems(); } else if (config == null) { return DisplayType.textarea; } HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>> bind = allValues.get(myproject); if (bind == null) { return DisplayType.textarea; } HashMap<String, HashMap<String, ArrayList<Item>>> itemsByType = bind.get(mybind); if (itemsByType == null) { return DisplayType.textarea; } Set<String> itemTypes = itemsByType.keySet(); for (String type : itemTypes) { HashMap<String, ArrayList<Item>> typeList = itemsByType.get(type); Set<String> names = typeList.keySet(); for (String name : names) { if (name.equals(myelementName)) { return DisplayType.getByTitle(type); } } } } return DisplayType.textarea; } /** * @param project * name of project as String * @param bind * create or edit * @param elementName * name of the element * @param displayType * type of the element * @return ArrayList with all values of given element */ public ArrayList<Item> getItemsByNameAndType(String myproject, String mybind, String myelementName, DisplayType mydisplayType) { ArrayList<Item> values = new ArrayList<Item>(); synchronized (allValues) { if (allValues.isEmpty() && config != null) { getDisplayItems(); } else if (config == null) { values.add(new Item(myelementName, "", false)); return values; } HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>> bind = allValues.get(myproject); if (bind.isEmpty()) { values.add(new Item(myelementName, "", false)); return values; } HashMap<String, HashMap<String, ArrayList<Item>>> itemsByType = bind.get(mybind); if (itemsByType.isEmpty()) { values.add(new Item(myelementName, "", false)); return values; } HashMap<String, ArrayList<Item>> typeList = itemsByType.get(mydisplayType.getTitle()); if (typeList.isEmpty()) { values.add(new Item(myelementName, "", false)); return values; } values = typeList.get(myelementName); if (values.isEmpty()) { values.add(new Item(myelementName, "", false)); return values; } } return values; } /** * refreshes the hierarchical HashMap with values from xml file. If HashMap * is used by another thread, the function will wait until * */ public void refresh() { if (config != null && !allValues.isEmpty()) { synchronized (allValues) { allValues.clear(); getDisplayItems(); } } } }
true
true
private synchronized void getDisplayItems() { if (allValues.isEmpty() && config != null) { int countRuleSet = config.getMaxIndex("ruleSet"); for (int i = 0; i <= countRuleSet; i++) { int projectContext = config.getMaxIndex("ruleSet(" + i + ").context"); for (int j = 0; j <= projectContext; j++) { HashMap<String, HashMap<String, ArrayList<Item>>> itemsByType = new HashMap<String, HashMap<String, ArrayList<Item>>>(); HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>> bindstate = new HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>>(); String projectName = config.getString("ruleSet(" + i + ").context(" + j + ")[@projectName]"); String bind = config.getString("ruleSet(" + i + ").context(" + j + ").bind"); int countSelect1 = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select1"); int countSelect = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select"); int countTextArea = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").textarea"); int countInput = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").input"); HashMap<String, ArrayList<Item>> select1 = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> select = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> input = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> textarea = new HashMap<String, ArrayList<Item>>(); for (int k = 0; k <= countSelect1; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select1(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelect1ByElementName(projectName, bind, elementName); select1.put(elementName, items); } for (int k = 0; k <= countSelect; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelectByElementName(projectName, bind, elementName); select.put(elementName, items); } for (int k = 0; k <= countTextArea; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").textarea(" + k + ")[@tns:ref]"); ArrayList<Item> items = getTextareaByElementName(projectName, bind, elementName); textarea.put(elementName, items); } for (int k = 0; k <= countInput; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").input(" + k + ")[@tns:ref]"); ArrayList<Item> items = getInputByElementName(projectName, bind, elementName); input.put(elementName, items); } itemsByType.put("select1", select1); itemsByType.put("select", select); itemsByType.put("input", input); itemsByType.put("textarea", textarea); bindstate.put(bind, itemsByType); allValues.put(projectName, bindstate); } } } // for (Entry<String, HashMap<String, HashMap<String, HashMap<String, // ArrayList<Item>>>>> bla : allValues.entrySet()) { // System.out.println("proj:" + bla.getKey()); // for (Entry<String, HashMap<String, HashMap<String, ArrayList<Item>>>> // blub : bla.getValue().entrySet()) { // System.out.println(" bindstate: " + blub.getKey()); // for (Entry<String, HashMap<String, ArrayList<Item>>> qwertzu : // blub.getValue().entrySet()) { // System.out.println(" type: " + qwertzu.getKey()); // for (Entry<String, ArrayList<Item>> qwer : // qwertzu.getValue().entrySet()) { // System.out.println(" element: " + qwer.getKey()); // } // } // } // } }
private synchronized void getDisplayItems() { if (allValues.isEmpty() && config != null) { int countRuleSet = config.getMaxIndex("ruleSet"); for (int i = 0; i <= countRuleSet; i++) { int projectContext = config.getMaxIndex("ruleSet(" + i + ").context"); for (int j = 0; j <= projectContext; j++) { HashMap<String, HashMap<String, ArrayList<Item>>> itemsByType = new HashMap<String, HashMap<String, ArrayList<Item>>>(); HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>> bindstate = new HashMap<String, HashMap<String, HashMap<String, ArrayList<Item>>>>(); String projectName = config.getString("ruleSet(" + i + ").context(" + j + ")[@projectName]"); String bind = config.getString("ruleSet(" + i + ").context(" + j + ").bind"); int countSelect1 = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select1"); int countSelect = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").select"); int countTextArea = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").textarea"); int countInput = config.getMaxIndex("ruleSet(" + i + ").context(" + j + ").input"); HashMap<String, ArrayList<Item>> select1 = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> select = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> input = new HashMap<String, ArrayList<Item>>(); HashMap<String, ArrayList<Item>> textarea = new HashMap<String, ArrayList<Item>>(); for (int k = 0; k <= countSelect1; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select1(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelect1ByElementName(projectName, bind, elementName); select1.put(elementName, items); } for (int k = 0; k <= countSelect; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").select(" + k + ")[@tns:ref]"); ArrayList<Item> items = getSelectByElementName(projectName, bind, elementName); select.put(elementName, items); } for (int k = 0; k <= countTextArea; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").textarea(" + k + ")[@tns:ref]"); ArrayList<Item> items = getTextareaByElementName(projectName, bind, elementName); textarea.put(elementName, items); } for (int k = 0; k <= countInput; k++) { String elementName = config.getString("ruleSet(" + i + ").context(" + j + ").input(" + k + ")[@tns:ref]"); ArrayList<Item> items = getInputByElementName(projectName, bind, elementName); input.put(elementName, items); } itemsByType.put("select1", select1); itemsByType.put("select", select); itemsByType.put("input", input); itemsByType.put("textarea", textarea); if (allValues.get(projectName) == null) { bindstate.put(bind, itemsByType); allValues.put(projectName, bindstate); } else { bindstate = allValues.get(projectName); bindstate.put(bind, itemsByType); } } } } // for (Entry<String, HashMap<String, HashMap<String, HashMap<String, // ArrayList<Item>>>>> bla : allValues.entrySet()) { // System.out.println("proj:" + bla.getKey()); // for (Entry<String, HashMap<String, HashMap<String, ArrayList<Item>>>> // blub : bla.getValue().entrySet()) { // System.out.println(" bindstate: " + blub.getKey()); // for (Entry<String, HashMap<String, ArrayList<Item>>> qwertzu : // blub.getValue().entrySet()) { // System.out.println(" type: " + qwertzu.getKey()); // for (Entry<String, ArrayList<Item>> qwer : // qwertzu.getValue().entrySet()) { // System.out.println(" element: " + qwer.getKey()); // } // } // } // } }
diff --git a/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/attributes/SootAttributesJavaColorer.java b/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/attributes/SootAttributesJavaColorer.java index 9602c1d5..bf2ccec9 100644 --- a/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/attributes/SootAttributesJavaColorer.java +++ b/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/attributes/SootAttributesJavaColorer.java @@ -1,254 +1,255 @@ /* Soot - a J*va Optimization Framework * Copyright (C) 2003 Jennifer Lhotak * * 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. */ package ca.mcgill.sable.soot.attributes; import java.util.*; import org.eclipse.jface.text.*; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.*; import org.eclipse.ui.*; import ca.mcgill.sable.soot.editors.*; public class SootAttributesJavaColorer { private ITextViewer viewer; private IEditorPart editorPart; //private ArrayList textPresList; private Color bgColor; int count = 0; public void computeColors(SootAttributesHandler handler, ITextViewer viewer, IEditorPart editorPart){ setViewer(viewer); setEditorPart(editorPart); if ((handler == null) || (handler.getAttrList() == null)) return; Iterator it = handler.getAttrList().iterator(); TextPresentation tp = new TextPresentation(); //if (tp.isEmpty()){ // tp.addStyleRange(tp.getDefaultStyleRange()); // System.out.println("tp has no default"); //} //Color bgColor Display display = getEditorPart().getSite().getShell().getDisplay(); display.asyncExec( new Runnable() { public void run() { Color bgColor = getViewer().getTextWidget().getBackground(); setBgColor(bgColor); }; }); //setBgColor(bgColor); //textPresList = newArrayList(); //System.out.println("computing colors"); while (it.hasNext()) { // sets colors for stmts SootAttribute sa = (SootAttribute)it.next(); if ((sa.getRed() == 0) && (sa.getGreen() == 0) && (sa.getBlue() == 0)){ } else { //System.out.println("java line: "+sa.getJava_ln()+" start: "+sa.getJavaOffsetStart()+1+" end: "+ sa.getJavaOffsetEnd()+1); boolean fg = false; if (sa.getFg() == 1){ fg = true; } setAttributeTextColor(tp, sa.getJavaStartLn(), sa.getJavaEndLn(), sa.getJavaOffsetStart()+1, sa.getJavaOffsetEnd()+1, sa.getRGBColor(), fg);//, tp); } // sets colors for valueboxes if (sa.getValueAttrs() != null){ Iterator valIt = sa.getValueAttrs().iterator(); while (valIt.hasNext()){ PosColAttribute vba = (PosColAttribute)valIt.next(); if ((vba.getRed() == 0) && (vba.getGreen() == 0) && (vba.getBlue() == 0)){ } else { //System.out.println("java line: "+sa.getJava_ln()+" start: "+vba.getSourceStartOffset()+1+" end: "+ vba.getSourceEndOffset()+1); boolean fg = false; if (vba.getFg() == 1) { fg = true; } setAttributeTextColor(tp, sa.getJavaStartLn(), sa.getJavaEndLn(), vba.getSourceStartOffset()+1, vba.getSourceEndOffset()+1, vba.getRGBColor(), fg);//, tp); } } } } //changeTextPres(tp); //return tp; } private void setAttributeTextColor(TextPresentation tp, int sline, int eline, int start, int end, RGB colorKey, boolean fg) {//, TextPresentation tp){ System.out.println("startline: "+sline+" soffset: "+start+" endoffset: "+end); //System.out.println("setting text color"); Display display = getEditorPart().getSite().getShell().getDisplay(); //Color backgroundColor = getEditorPart().getSite().getShell().getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND); //TextPresentation tp = new TextPresentation(); //if (getTextPresList() == null) { //setTextPresList(new ArrayList()); //} //getTextPresList().add(tp); ColorManager colorManager = new ColorManager(); int sLineOffset = 0; int eLineOffset = 0; try { sLineOffset = getViewer().getDocument().getLineOffset((sline-1)); eLineOffset = getViewer().getDocument().getLineOffset((eline-1)); //System.out.println("slineOffset: "+sLineOffset); } catch(Exception e){ + return; } //System.out.println("style range: "); //System.out.println("start: "+start); //System.out.println("end: "+end); //StyleRange sr = new StyleRange((lineOffset + start - 1 ), (end - start), colorManager.getColor(colorKey), getViewer().get.getTextWidget().getBackground()); //tp.addStyleRange(sr); //Color c = tp.getFirstStyleRange().background; //final TextPresentation newPresentation = tp; final boolean foreground = fg; final int s = sLineOffset + start - 1; //System.out.println("start offset: "+s); int e = eLineOffset + end - 1; //System.out.println("end offset: "+e); final int l = e - s; //System.out.println("length: "+l); final Color ck = colorManager.getColor(colorKey); final Color oldBgC = colorManager.getColor(IJimpleColorConstants.JIMPLE_DEFAULT); display.asyncExec( new Runnable() { public void run() { TextPresentation tp = new TextPresentation(); //System.out.println("about to create style range"); StyleRange sr; //System.out.println("line: "+sline+" start: "+s+" length: "+l); if (l != 0){ if (foreground){ sr = new StyleRange(s, l, ck, getBgColor()); } else { sr = new StyleRange(s, l, oldBgC, ck); } //if (count == 0 | count == 1){ tp.addStyleRange(sr); } //} //count++; getViewer().changeTextPresentation(tp, true); //getViewer().setTextColor(ck, s, l, false); }; }); //tp.clear(); } private void changeTextPres(TextPresentation tp) { System.out.println("changing text pres"); Display display = getEditorPart().getSite().getShell().getDisplay(); final TextPresentation pres = tp; display.asyncExec(new Runnable() { public void run(){ getViewer().changeTextPresentation(pres, true); }; }); } /*public void clearTextPresentations(){ if (getTextPresList() == null) return; Iterator it = getTextPresList().iterator(); while (it.hasNext()){ TextPresentation tp = (TextPresentation)it.next(); tp.clear(); //System.out.println("cleared TextPresentation"); } }*/ /** * @return */ public ITextViewer getViewer() { return viewer; } /** * @param viewer */ public void setViewer(ITextViewer viewer) { this.viewer = viewer; } /** * @return */ public IEditorPart getEditorPart() { return editorPart; } /** * @param part */ public void setEditorPart(IEditorPart part) { editorPart = part; } /** * @return */ /*public ArrayList getTextPresList() { return textPresList; }*/ /** * @param list */ /* void setTextPresList(ArrayList list) { textPresList = list; }*/ /** * @return */ public Color getBgColor() { return bgColor; } /** * @param color */ public void setBgColor(Color color) { bgColor = color; } }
true
true
private void setAttributeTextColor(TextPresentation tp, int sline, int eline, int start, int end, RGB colorKey, boolean fg) {//, TextPresentation tp){ System.out.println("startline: "+sline+" soffset: "+start+" endoffset: "+end); //System.out.println("setting text color"); Display display = getEditorPart().getSite().getShell().getDisplay(); //Color backgroundColor = getEditorPart().getSite().getShell().getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND); //TextPresentation tp = new TextPresentation(); //if (getTextPresList() == null) { //setTextPresList(new ArrayList()); //} //getTextPresList().add(tp); ColorManager colorManager = new ColorManager(); int sLineOffset = 0; int eLineOffset = 0; try { sLineOffset = getViewer().getDocument().getLineOffset((sline-1)); eLineOffset = getViewer().getDocument().getLineOffset((eline-1)); //System.out.println("slineOffset: "+sLineOffset); } catch(Exception e){ } //System.out.println("style range: "); //System.out.println("start: "+start); //System.out.println("end: "+end); //StyleRange sr = new StyleRange((lineOffset + start - 1 ), (end - start), colorManager.getColor(colorKey), getViewer().get.getTextWidget().getBackground()); //tp.addStyleRange(sr); //Color c = tp.getFirstStyleRange().background; //final TextPresentation newPresentation = tp; final boolean foreground = fg; final int s = sLineOffset + start - 1; //System.out.println("start offset: "+s); int e = eLineOffset + end - 1; //System.out.println("end offset: "+e); final int l = e - s; //System.out.println("length: "+l); final Color ck = colorManager.getColor(colorKey); final Color oldBgC = colorManager.getColor(IJimpleColorConstants.JIMPLE_DEFAULT); display.asyncExec( new Runnable() { public void run() { TextPresentation tp = new TextPresentation(); //System.out.println("about to create style range"); StyleRange sr; //System.out.println("line: "+sline+" start: "+s+" length: "+l); if (l != 0){ if (foreground){ sr = new StyleRange(s, l, ck, getBgColor()); } else { sr = new StyleRange(s, l, oldBgC, ck); } //if (count == 0 | count == 1){ tp.addStyleRange(sr); } //} //count++; getViewer().changeTextPresentation(tp, true); //getViewer().setTextColor(ck, s, l, false); }; }); //tp.clear(); } private void changeTextPres(TextPresentation tp) { System.out.println("changing text pres"); Display display = getEditorPart().getSite().getShell().getDisplay(); final TextPresentation pres = tp; display.asyncExec(new Runnable() { public void run(){ getViewer().changeTextPresentation(pres, true); }; }); } /*public void clearTextPresentations(){ if (getTextPresList() == null) return; Iterator it = getTextPresList().iterator(); while (it.hasNext()){ TextPresentation tp = (TextPresentation)it.next(); tp.clear(); //System.out.println("cleared TextPresentation"); } }*/
private void setAttributeTextColor(TextPresentation tp, int sline, int eline, int start, int end, RGB colorKey, boolean fg) {//, TextPresentation tp){ System.out.println("startline: "+sline+" soffset: "+start+" endoffset: "+end); //System.out.println("setting text color"); Display display = getEditorPart().getSite().getShell().getDisplay(); //Color backgroundColor = getEditorPart().getSite().getShell().getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND); //TextPresentation tp = new TextPresentation(); //if (getTextPresList() == null) { //setTextPresList(new ArrayList()); //} //getTextPresList().add(tp); ColorManager colorManager = new ColorManager(); int sLineOffset = 0; int eLineOffset = 0; try { sLineOffset = getViewer().getDocument().getLineOffset((sline-1)); eLineOffset = getViewer().getDocument().getLineOffset((eline-1)); //System.out.println("slineOffset: "+sLineOffset); } catch(Exception e){ return; } //System.out.println("style range: "); //System.out.println("start: "+start); //System.out.println("end: "+end); //StyleRange sr = new StyleRange((lineOffset + start - 1 ), (end - start), colorManager.getColor(colorKey), getViewer().get.getTextWidget().getBackground()); //tp.addStyleRange(sr); //Color c = tp.getFirstStyleRange().background; //final TextPresentation newPresentation = tp; final boolean foreground = fg; final int s = sLineOffset + start - 1; //System.out.println("start offset: "+s); int e = eLineOffset + end - 1; //System.out.println("end offset: "+e); final int l = e - s; //System.out.println("length: "+l); final Color ck = colorManager.getColor(colorKey); final Color oldBgC = colorManager.getColor(IJimpleColorConstants.JIMPLE_DEFAULT); display.asyncExec( new Runnable() { public void run() { TextPresentation tp = new TextPresentation(); //System.out.println("about to create style range"); StyleRange sr; //System.out.println("line: "+sline+" start: "+s+" length: "+l); if (l != 0){ if (foreground){ sr = new StyleRange(s, l, ck, getBgColor()); } else { sr = new StyleRange(s, l, oldBgC, ck); } //if (count == 0 | count == 1){ tp.addStyleRange(sr); } //} //count++; getViewer().changeTextPresentation(tp, true); //getViewer().setTextColor(ck, s, l, false); }; }); //tp.clear(); } private void changeTextPres(TextPresentation tp) { System.out.println("changing text pres"); Display display = getEditorPart().getSite().getShell().getDisplay(); final TextPresentation pres = tp; display.asyncExec(new Runnable() { public void run(){ getViewer().changeTextPresentation(pres, true); }; }); } /*public void clearTextPresentations(){ if (getTextPresList() == null) return; Iterator it = getTextPresList().iterator(); while (it.hasNext()){ TextPresentation tp = (TextPresentation)it.next(); tp.clear(); //System.out.println("cleared TextPresentation"); } }*/
diff --git a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java index 86115f29..8723c123 100644 --- a/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java +++ b/pentaho-gwt-widgets/src/org/pentaho/gwt/widgets/client/listbox/CustomListBox.java @@ -1,619 +1,619 @@ package org.pentaho.gwt.widgets.client.listbox; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.*; import com.google.gwt.core.client.GWT; import org.pentaho.gwt.widgets.client.utils.ElementUtils; import org.pentaho.gwt.widgets.client.utils.Rectangle; import java.util.ArrayList; import java.util.List; /** * * ComplexListBox is a List-style widget can contain custom list-items made (images + text, text + checkboxes) * This list is displayed as a drop-down style component by default. If the visibleRowCount property is set higher * than 1 (default), the list is rendered as a multi-line list box. * * <P>Usage: * * <p> * * <pre> * ComplexListBox list = new ComplexListBox(); * * list.addItem("Alberta"); * list.addItem("Atlanta"); * list.addItem("San Francisco"); * list.addItem(new DefaultListItem("Testing", new Image("16x16sample.png"))); * list.addItem(new DefaultListItem("Testing 2", new CheckBox())); * * list.setVisibleRowCount(6); // turns representation from drop-down to list * * list.addChangeListener(new ChangeListener(){ * public void onChange(Widget widget) { * System.out.println(""+list.getSelectedIdex()); * } * }); *</pre> * * User: NBaker * Date: Mar 9, 2009 * Time: 11:01:57 AM * */ public class CustomListBox extends HorizontalPanel implements PopupListener, MouseListener, FocusListener, KeyboardListener{ private List<ListItem> items = new ArrayList<ListItem>(); private int selectedIndex = -1; private DropDownArrow arrow = new DropDownArrow(); private int visible = 1; private int maxDropVisible = 15; private VerticalPanel listPanel = new VerticalPanel(); private ScrollPanel listScrollPanel = new ScrollPanel(); // Members for drop-down style private Grid dropGrid = new Grid(1,2); private boolean popupShowing = false; private DropPopupPanel popup = new DropPopupPanel(); private PopupList popupVbox = new PopupList(); private FocusPanel fPanel = new FocusPanel(); private ScrollPanel popupScrollPanel = new ScrollPanel(); private List<ChangeListener> listeners = new ArrayList<ChangeListener>(); private final int spacing = 2; private int maxHeight, maxWidth, averageHeight; //height and width of largest ListItem private String primaryStyleName; private String height, width; private String popupHeight, popupWidth; public CustomListBox(){ dropGrid.getColumnFormatter().setWidth(0, "100%"); dropGrid.setWidget(0,1, arrow); dropGrid.setCellPadding(0); dropGrid.setCellSpacing(spacing); updateUI(); // Add List Panel to it's scrollPanel listScrollPanel.add(listPanel); listScrollPanel.setHeight("100%"); listScrollPanel.setWidth("100%"); listScrollPanel.getElement().getStyle().setProperty("overflowX","hidden"); //listScrollPanel.getElement().getStyle().setProperty("padding",spacing+"px"); listPanel.setSpacing(spacing); listPanel.setWidth("100%"); //default to drop-down fPanel.add(dropGrid); fPanel.setHeight("100%"); super.add(fPanel); popup.addPopupListener(this); popupScrollPanel.add(popupVbox); popupScrollPanel.getElement().getStyle().setProperty("overflowX","hidden"); popupVbox.setWidth("100%"); popupVbox.setSpacing(spacing); popup.add(popupScrollPanel); fPanel.addMouseListener(this); fPanel.addFocusListener(this); fPanel.addKeyboardListener(this); setStyleName("custom-list"); } /** * Only {@link: DefaultListItem} and Strings (as labels) may be passed into this Widget */ @Override public void add(Widget child) { throw new UnsupportedOperationException( "This panel does not support no-arg add()"); } /** * Convenience method to support the more conventional method of child attachment * @param listItem */ public void add(ListItem listItem){ this.addItem(listItem); } /** * Convenience method to support the more conventional method of child attachment * @param label */ public void add(String label){ this.addItem(label); } /** * Adds the given ListItem to the list control. * * @param item ListItem */ public void addItem(ListItem item){ items.add(item); item.setListBox(this); // If first one added, set selectedIndex to 0 if(items.size() == 1){ setSelectedIndex(0); } updateUI(); } /** * Convenience method creates a {@link: DefaultListItem} with the given text and adds it to the list control * * @param label */ public void addItem(String label){ DefaultListItem item = new DefaultListItem(label); items.add(item); item.setListBox(this); // If first one added, set selectedIndex to 0 if(items.size() == 1){ setSelectedIndex(0); } updateUI(); } /** * Returns a list of current ListItems. * * @return List of ListItems */ public List<ListItem> getItems(){ return items; } /** * Sets the number of items to be displayed at once in the lsit control. If set to 1 (default) the list is rendered * as a drop-down * * @param visibleCount number of rows to be visible. */ public void setVisibleRowCount(int visibleCount){ int prevCount = visible; this.visible = visibleCount; if(visible > 1 && prevCount == 1){ // switched from drop-down to list fPanel.remove(dropGrid); fPanel.add(listScrollPanel); } else if(visible == 1 && prevCount > 1){ // switched from list to drop-down fPanel.remove(listScrollPanel); fPanel.add(dropGrid); } updateUI(); } /** * Returns the number of rows visible in the list * @return number of visible rows. */ public int getVisibleRowCount(){ return visible; } private void updateUI(){ if(visible > 1){ updateList(); } else { updateDropDown(); } } /** * Returns the number of rows to be displayed in the drop-down popup. * * @return number of visible popup items. */ public int getMaxDropVisible() { return maxDropVisible; } /** * Sets the number of items to be visible in the drop-down popup. If set lower than the number of items * a scroll-bar with provide access to hidden items. * * @param maxDropVisible number of items visible in popup. */ public void setMaxDropVisible(int maxDropVisible) { this.maxDropVisible = maxDropVisible; // Update the popup to respect this value if(maxHeight > 0){ //Items already added System.out.println("Max heihgt : "+this.maxDropVisible * maxHeight); this.popupHeight = this.maxDropVisible * maxHeight + "px"; } } private void updateSelectedDropWidget(){ Widget selectedWidget = new Label(""); //Default to show in case of empty sets? if(selectedIndex >= 0){ selectedWidget = items.get(selectedIndex).getWidgetForDropdown(); } else if(items.size() > 0){ selectedWidget = items.get(0).getWidgetForDropdown(); } dropGrid.setWidget(0,0, selectedWidget); } /** * Called by updateUI when the list is not a drop-down (visible row count > 1) */ private void updateList(){ popupVbox.clear(); maxHeight = 0; maxWidth = 0; //actually going to average up the heights for(ListItem li : this.items){ Widget w = li.getWidget(); Rectangle rect = ElementUtils.getSize(w.getElement()); // we only care about this if the user hasn't specified a height. if(height == null){ maxHeight += rect.height; } maxWidth = Math.max(maxWidth,rect.width); // Add it to the dropdown listPanel.add(w); listPanel.setCellWidth(w, "100%"); } if(height == null){ maxHeight = Math.round(maxHeight / this.items.size()); } // we only care about this if the user has specified a visible row count and no heihgt if(height == null){ this.fPanel.setHeight((this.visible * (maxHeight + spacing)) + "px"); } if(width == null){ this.fPanel.setWidth(maxWidth + 20 + "px"); //20 is scrollbar space } } /** * Called by updateUI when the list is a drop-down (visible row count = 1) */ private void updateDropDown(){ // Update Shown selection in grid updateSelectedDropWidget(); // Update popup panel, // Calculate the size of the largest list item. popupVbox.clear(); maxWidth = 0; averageHeight = 0; // Actually used to set the width of the arrow popupHeight = null; for(ListItem li : this.items){ Widget w = li.getWidget(); Rectangle rect = ElementUtils.getSize(w.getElement()); maxWidth = Math.max(maxWidth,rect.width); maxHeight = Math.max(maxHeight,rect.height); averageHeight += rect.height; // Add it to the dropdown popupVbox.add(w); popupVbox.setCellWidth(w, "100%"); } // Average the height of the items if(items.size() > 0){ averageHeight = Math.round(averageHeight / items.size()); } // Set the size of the drop-down based on the largest list item if(width == null){ dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px"); this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px"; } else { dropGrid.setWidth("100%"); } // Store the the size of the popup to respect MaxDropVisible now that we know the item height // This cannot be set here as the popup is not visible :( if(maxDropVisible > 0){ // (Lesser of maxDropVisible or items size) * (Average item height + spacing value) - this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing * this.items.size())) + "px"; + this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing )) + "px"; } } /** * Used internally to hide/show drop-down popup. */ private void togglePopup(){ if(popupShowing == false){ popupScrollPanel.setWidth(this.getElement().getOffsetWidth() - 8 +"px"); popup.setPopupPosition(this.getElement().getAbsoluteLeft(), this.getElement().getAbsoluteTop() + this.getElement().getOffsetHeight()+2); popup.show(); // Set the size of the popup calculated in updateDropDown(). if(this.popupHeight != null){ this.popupScrollPanel.getElement().getStyle().setProperty("height", this.popupHeight); } if(this.popupWidth != null){ this.popupScrollPanel.getElement().getStyle().setProperty("width", this.popupWidth); } scrollSelectedItemIntoView(); popupShowing = true; } else { popup.hide(); fPanel.setFocus(true); } } private void scrollSelectedItemIntoView(){ // Scroll to view currently selected widget //DOM.scrollIntoView(this.getSelectedItem().getWidget().getElement()); // Side effect of the previous call scrolls the scrollpanel to the right. Compensate here //popupScrollPanel.setHorizontalScrollPosition(0); // if the position of the selected item is greater than the height of the scroll area plus it's scroll offset if( ((this.selectedIndex + 1) * this.averageHeight) > popupScrollPanel.getOffsetHeight() + popupScrollPanel.getScrollPosition()){ popupScrollPanel.setScrollPosition( (((this.selectedIndex ) * this.averageHeight) - popupScrollPanel.getOffsetHeight()) + averageHeight ); return; } // if the position of the selected item is Less than the scroll offset if( ((this.selectedIndex) * this.averageHeight) < popupScrollPanel.getScrollPosition()){ popupScrollPanel.setScrollPosition( ((this.selectedIndex ) * this.averageHeight)); } } /** * Selects the given ListItem in the list. * * @param item ListItem to be selected. */ public void setSelectedItem(ListItem item){ if(items.contains(item) == false){ throw new RuntimeException("Item not in collection"); } // Clear previously selected item if(selectedIndex > -1){ items.get(selectedIndex).onDeselect(); } if(visible == 1){ // Drop-down mode if(popupShowing) { togglePopup(); } } setSelectedIndex(items.indexOf(item)); } /** * Selects the ListItem at the given index (zero-based) * * @param idx index of ListItem to select */ public void setSelectedIndex(int idx){ if(idx < 0 || idx > items.size()){ throw new RuntimeException("Index out of bounds: "+ idx); } // De-Select the current if(selectedIndex > -1){ items.get(selectedIndex).onDeselect(); } selectedIndex = idx; items.get(idx).onSelect(); for(ChangeListener l : listeners){ l.onChange(this); } if(visible == 1){ updateSelectedDropWidget(); scrollSelectedItemIntoView(); } } /** * Registers a ChangeListener with the list. * * @param listener ChangeListner */ public void addChangeListener(ChangeListener listener){ listeners.add(listener); } /** * Removes to given ChangeListener from list. * * @param listener ChangeListener */ public void removeChangeListener(ChangeListener listener){ this.listeners.remove(listener); } /** * Returns the selected index of the list (zero-based) * * @return Integer index */ public int getSelectedIdex(){ return selectedIndex; } /** * Returns the currently selected item * * @return currently selected Item */ public ListItem getSelectedItem(){ if(selectedIndex < 0){ return null; } return items.get(selectedIndex); } @Override public void setStylePrimaryName(String s) { super.setStylePrimaryName(s); this.primaryStyleName = s; // This may have came in late. Update ListItems for(ListItem item : items){ item.setStylePrimaryName(s); } } @Override protected void onAttach() { super.onAttach(); updateUI(); } @Override /** * Calling setHeight will implecitly change the list from a drop-down style to a list style. */ public void setHeight(String s) { this.height = s; // user has specified height, focusPanel needs to be 100%; this.fPanel.setHeight(s); if(visible == 1){ this.setVisibleRowCount(15); } super.setHeight(s); } @Override public void setWidth(String s) { fPanel.setWidth(s); this.listScrollPanel.setWidth("100%"); this.width = s; super.setWidth(s); } // ======================================= Listener methods ===================================== // public void onPopupClosed(PopupPanel popupPanel, boolean b) { this.popupShowing = false; } public void onMouseDown(Widget widget, int i, int i1) {} public void onMouseEnter(Widget widget) {} public void onMouseLeave(Widget widget) {} public void onMouseMove(Widget widget, int i, int i1) {} public void onMouseUp(Widget widget, int i, int i1) { if(visible == 1){ //drop-down mode this.togglePopup(); } } public void onFocus(Widget widget) { fPanel.setFocus(true); } public void onLostFocus(Widget widget) {} public void onKeyDown(Widget widget, char c, int i) {} public void onKeyPress(Widget widget, char c, int i) {} public void onKeyUp(Widget widget, char c, int i) { switch(c){ case 38: // UP if(selectedIndex > 0){ setSelectedIndex(selectedIndex - 1); } break; case 40: // Down if(selectedIndex < items.size() -1){ setSelectedIndex(selectedIndex + 1); } break; case 27: // ESC case 13: // Enter if(popupShowing){ togglePopup(); } break; } } // ======================================= Inner Classes ===================================== // /** * Panel used as a drop-down popup. */ private class DropPopupPanel extends PopupPanel { public DropPopupPanel(){ super(true); setStyleName("drop-popup"); } @Override public boolean onEventPreview(Event event) { if(DOM.isOrHasChild(CustomListBox.this.getElement(), DOM.eventGetTarget(event))){ return true; } return super.onEventPreview(event); } } /** * Panel contained in the popup */ private class PopupList extends VerticalPanel{ public PopupList(){ this.sinkEvents(Event.MOUSEEVENTS); } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); } } /** * This is the arrow rendered in the drop-down. */ private class DropDownArrow extends SimplePanel{ public DropDownArrow(){ Image img = new Image(GWT.getModuleBaseURL() + "arrow.png"); this.setStylePrimaryName("combo-arrow"); super.add(img); ElementUtils.preventTextSelection(this.getElement()); } } }
true
true
private void updateDropDown(){ // Update Shown selection in grid updateSelectedDropWidget(); // Update popup panel, // Calculate the size of the largest list item. popupVbox.clear(); maxWidth = 0; averageHeight = 0; // Actually used to set the width of the arrow popupHeight = null; for(ListItem li : this.items){ Widget w = li.getWidget(); Rectangle rect = ElementUtils.getSize(w.getElement()); maxWidth = Math.max(maxWidth,rect.width); maxHeight = Math.max(maxHeight,rect.height); averageHeight += rect.height; // Add it to the dropdown popupVbox.add(w); popupVbox.setCellWidth(w, "100%"); } // Average the height of the items if(items.size() > 0){ averageHeight = Math.round(averageHeight / items.size()); } // Set the size of the drop-down based on the largest list item if(width == null){ dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px"); this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px"; } else { dropGrid.setWidth("100%"); } // Store the the size of the popup to respect MaxDropVisible now that we know the item height // This cannot be set here as the popup is not visible :( if(maxDropVisible > 0){ // (Lesser of maxDropVisible or items size) * (Average item height + spacing value) this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing * this.items.size())) + "px"; } }
private void updateDropDown(){ // Update Shown selection in grid updateSelectedDropWidget(); // Update popup panel, // Calculate the size of the largest list item. popupVbox.clear(); maxWidth = 0; averageHeight = 0; // Actually used to set the width of the arrow popupHeight = null; for(ListItem li : this.items){ Widget w = li.getWidget(); Rectangle rect = ElementUtils.getSize(w.getElement()); maxWidth = Math.max(maxWidth,rect.width); maxHeight = Math.max(maxHeight,rect.height); averageHeight += rect.height; // Add it to the dropdown popupVbox.add(w); popupVbox.setCellWidth(w, "100%"); } // Average the height of the items if(items.size() > 0){ averageHeight = Math.round(averageHeight / items.size()); } // Set the size of the drop-down based on the largest list item if(width == null){ dropGrid.setWidth(maxWidth + (spacing*6) + maxHeight + "px"); this.popupWidth = maxWidth + (spacing*6) + maxHeight + "px"; } else { dropGrid.setWidth("100%"); } // Store the the size of the popup to respect MaxDropVisible now that we know the item height // This cannot be set here as the popup is not visible :( if(maxDropVisible > 0){ // (Lesser of maxDropVisible or items size) * (Average item height + spacing value) this.popupHeight = (Math.min(this.maxDropVisible, this.items.size()) * (averageHeight + this.spacing )) + "px"; } }
diff --git a/PocketSafe/src/com/monster/pocketsafe/main/CMPassHolder.java b/PocketSafe/src/com/monster/pocketsafe/main/CMPassHolder.java index f702ddd..928423b 100644 --- a/PocketSafe/src/com/monster/pocketsafe/main/CMPassHolder.java +++ b/PocketSafe/src/com/monster/pocketsafe/main/CMPassHolder.java @@ -1,119 +1,120 @@ package com.monster.pocketsafe.main; import java.math.BigInteger; import java.util.Date; import android.util.Log; import com.monster.pocketsafe.sec.IMAes; import com.monster.pocketsafe.sec.IMBase64; import com.monster.pocketsafe.utils.IMLocator; import com.monster.pocketsafe.utils.IMTimer; import com.monster.pocketsafe.utils.IMTimerObserver; import com.monster.pocketsafe.utils.MyException; import com.monster.pocketsafe.utils.MyException.TTypMyException; public class CMPassHolder implements IMPassHolder, IMTimerObserver { private IMLocator mLocator; private IMPassHolderObserver mObserver; private String mPass; private String mKey; private IMAes mAes; private IMBase64 mBase64; private long mInterval; private IMTimer mTimer; private Date mTimExpire; public CMPassHolder(IMLocator locator) { mLocator = locator; mAes = mLocator.createAes(); mBase64 = mLocator.createBase64(); mTimer = mLocator.createTimer(); mTimer.SetObserver(this); } private void restartTimer() throws MyException { Date dat = new Date(); mTimExpire = new Date(dat.getTime()+mInterval); mTimer.cancelTimer(); mTimer.startTimer(mInterval); } public void setPass(String pass) throws MyException { if (pass==null || pass.length()==0) throw new MyException(TTypMyException.EPassInvalid); mPass = pass; + mTimExpire = null; //for pass check in getKey(); try { if (mKey!=null) getKey(); } catch (MyException e) { Log.e("!!!", "Invalid pass: "+e.getId()); mPass=null; throw e; } restartTimer(); } public String getPass() throws MyException { return mPass; } public void setKey(String _key) { mKey = _key; } public BigInteger getKey() throws MyException { Date dat = new Date(); if (mTimExpire!=null && dat.after(mTimExpire)) { mPass=null; } if (mPass==null) throw new MyException(TTypMyException.EPassExpired); String key = mAes.decrypt(mPass, mKey); byte[] b = mBase64.decode(key.getBytes()); BigInteger res = new BigInteger(b); return res; } public boolean isPassValid() { return (mPass!=null); } public void setInterval(long _ms) throws MyException { mInterval = _ms; if ( isPassValid() ) { restartTimer(); } } public void timerEvent(IMTimer sender) throws Exception { if (mPass!=null) { mPass = null; mTimExpire=null; if (mObserver!=null) mObserver.passExpired(this); } } public void setObserever(IMPassHolderObserver observer) { mObserver = observer; } public void clearPass() { if (mPass!=null) { mPass=null; mTimExpire=null; mTimer.cancelTimer(); } } }
true
true
public void setPass(String pass) throws MyException { if (pass==null || pass.length()==0) throw new MyException(TTypMyException.EPassInvalid); mPass = pass; try { if (mKey!=null) getKey(); } catch (MyException e) { Log.e("!!!", "Invalid pass: "+e.getId()); mPass=null; throw e; } restartTimer(); }
public void setPass(String pass) throws MyException { if (pass==null || pass.length()==0) throw new MyException(TTypMyException.EPassInvalid); mPass = pass; mTimExpire = null; //for pass check in getKey(); try { if (mKey!=null) getKey(); } catch (MyException e) { Log.e("!!!", "Invalid pass: "+e.getId()); mPass=null; throw e; } restartTimer(); }
diff --git a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java index 13799c3b9..3f424517e 100644 --- a/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java +++ b/core/org.eclipse.ptp.core/src/org/eclipse/ptp/rtsystem/AbstractProxyRuntimeSystem.java @@ -1,960 +1,960 @@ /******************************************************************************* * Copyright (c) 2006 The Regents of the University of California. * This material was produced under U.S. Government contract W-7405-ENG-36 * for Los Alamos National Laboratory, which is operated by the University * of California for the U.S. Department of Energy. The U.S. Government has * rights to use, reproduce, and distribute this software. NEITHER THE * GOVERNMENT NOR THE UNIVERSITY MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, 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 * * LA-CC 04-115 *******************************************************************************/ package org.eclipse.ptp.rtsystem; import java.io.IOException; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.ptp.core.PTPCorePlugin; import org.eclipse.ptp.core.attributes.AttributeDefinitionManager; import org.eclipse.ptp.core.attributes.AttributeManager; import org.eclipse.ptp.core.attributes.IAttribute; import org.eclipse.ptp.core.attributes.IAttributeDefinition; import org.eclipse.ptp.core.attributes.IllegalValueException; import org.eclipse.ptp.core.attributes.IntegerAttribute; import org.eclipse.ptp.core.attributes.StringAttribute; import org.eclipse.ptp.core.elements.IPJob; import org.eclipse.ptp.core.elements.attributes.ElementAttributeManager; import org.eclipse.ptp.core.elements.attributes.ElementAttributes; import org.eclipse.ptp.core.elements.attributes.ErrorAttributes; import org.eclipse.ptp.core.elements.attributes.JobAttributes; import org.eclipse.ptp.core.elements.attributes.MessageAttributes.Level; import org.eclipse.ptp.core.util.RangeSet; import org.eclipse.ptp.rtsystem.events.RuntimeAttributeDefinitionEvent; import org.eclipse.ptp.rtsystem.events.RuntimeConnectedStateEvent; import org.eclipse.ptp.rtsystem.events.RuntimeErrorStateEvent; import org.eclipse.ptp.rtsystem.events.RuntimeJobChangeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeMachineChangeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeMessageEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNewJobEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNewMachineEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNewNodeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNewProcessEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNewQueueEvent; import org.eclipse.ptp.rtsystem.events.RuntimeNodeChangeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeProcessChangeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeQueueChangeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveAllEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveJobEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveMachineEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveNodeEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveProcessEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRemoveQueueEvent; import org.eclipse.ptp.rtsystem.events.RuntimeRunningStateEvent; import org.eclipse.ptp.rtsystem.events.RuntimeShutdownStateEvent; import org.eclipse.ptp.rtsystem.events.RuntimeStartupErrorEvent; import org.eclipse.ptp.rtsystem.events.RuntimeSubmitJobErrorEvent; import org.eclipse.ptp.rtsystem.events.RuntimeTerminateJobErrorEvent; import org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeClient; import org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeAttributeDefEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeConnectedStateEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorStateEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeJobChangeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMachineChangeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMessageEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewJobEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewMachineEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewNodeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewProcessEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewQueueEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNodeChangeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeProcessChangeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeQueueChangeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveAllEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveJobEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveMachineEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveNodeEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveProcessEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveQueueEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRunningStateEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeShutdownStateEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeStartupErrorEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeSubmitJobErrorEvent; import org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeTerminateJobErrorEvent; /* * ProxyAttributeDefEvents are formatted as follows: * * EVENT_HEADER NUM_DEFS ATTR_DEF ... ATTR_DEF * * where: * * EVENT_HEADER is the event message header * NUM_DEFS is the number of attribute definitions to follow * ATTR_DEF is an attribute definition of the form: * * NUM_ARGS ID TYPE NAME DESCRIPTION DISPLAY DEFAULT [ADDITIONAL_PARAMS] * * where: * * NUM_ARGS is the number of arguments in the attribute definition * ID is a unique definition ID * TYPE is the type of the attribute. Legal types are: * 'BOOLEAN', 'DATE', 'DOUBLE', 'ENUMERATED', 'INTEGER', 'STRING', 'ARRAY' * NAME is the short name of the attribute * DESCRIPTION is the long name of the attribute * DISPLAY is true if the attribute should be displayed in a UI * DEFAULT is the default value of the attribute * ADDITIONAL_PARAMS are optional parameters depending on the attribute type: * BOOLEAN - none * DATE - DATE_STYLE TIME_STYLE LOCALE [MIN MAX] * DOUBLE - [MIN MAX] * ENUMERATED - VAL ... VAL * INTEGER - [MIN MAX] * STRING - none * ARRAY - none * MIN is the minimum allowable value for the attribute * MAX is the maximum allowable value for the attribute * DATE_STYLE is the date format: SHORT, MEDIUM, LONG, or FULL * TIME_STYLE is the time format: SHORT, MEDIUM, LONG, or FULL * LOCALE is the country (see java.lang.Local) * NUM_VALS is the number of enumerated values * VAL is the enumerated value * * ProxyNew*Events are formatted as follows: * * EVENT_HEADER PARENT_ID NUM_RANGES ID_RANGE NUM_ATTRS KEY=VALUE ... KEY=VALUE ... * * where: * * EVENT_HEADER is the event message header * PARENT_ID is the model element ID of the parent element * NUM_RANGES is the number of ID_RANGEs to follow * ID_RANGE is a range of model element ID's in RangeSet notation * NUM_ATTRS is the number of attributes to follow * KEY=VALUE are key/value pairs, where KEY is the attribute ID and VALUE is the attribute value * * Proxy*ChangeEvents are formatted as follows: * * EVENT_HEADER NUM_RANGES ID_RANGE NUM_ATTRS KEY=VALUE ... KEY=VALUE * * where: * * EVENT_HEADER is the event message header * NUM_RANGES is the number of ID_RANGEs to follow * ID_RANGE is a range of model element ID's in RangeSet notation * NUM_ATTRS is the number of attributes to follow * KEY=VALUE are key/value pairs, where KEY is the attribute ID and VALUE is the new attribute value * * ProxyRemove*Events (apart from ProxyRemoveAllEvent) are formatted as follows: * * EVENT_HEADER ID_RANGE * * where: * * EVENT_HEADER is the event message header * ID_RANGE is a range of model element ID's in RangeSet notation. * * The ProxyRemoveAllEvent is formatted as follows: * * EVENT_HEADER * * where: * * EVENT_HEADER is the event message header */ public abstract class AbstractProxyRuntimeSystem extends AbstractRuntimeSystem implements IProxyRuntimeEventListener { private final static int ATTR_MIN_LEN = 5; protected IProxyRuntimeClient proxy = null; private AttributeDefinitionManager attrDefManager; private int jobSubIdCount = 0; private Map<String, AttributeManager> jobSubs = Collections.synchronizedMap(new HashMap<String, AttributeManager>()); public AbstractProxyRuntimeSystem(IProxyRuntimeClient proxy, AttributeDefinitionManager manager) { this.proxy = proxy; this.attrDefManager = manager; proxy.addProxyRuntimeEventListener(this); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeAttributeDefEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeAttributeDefEvent) */ public void handleEvent(IProxyRuntimeAttributeDefEvent e) { String[] attrs = e.getAttributes(); if (attrs.length >= ATTR_MIN_LEN + 2) { try { int numDefs = Integer.parseInt(attrs[0]); ArrayList<IAttributeDefinition<?,?,?>> attrDefs = new ArrayList<IAttributeDefinition<?,?,?>>(numDefs); int pos = 1; for (int i = 0; i < numDefs; i++) { int numArgs = Integer.parseInt(attrs[pos]); if (numArgs >= ATTR_MIN_LEN && pos + numArgs < attrs.length) { IAttributeDefinition<?,?,?> attrDef = parseAttributeDefinition(attrs, pos + 1, pos + numArgs); if (attrDef != null) { attrDefs.add(attrDef); } pos += numArgs + 1; } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: bad arg count")); return; } } fireRuntimeAttributeDefinitionEvent(new RuntimeAttributeDefinitionEvent(attrDefs.toArray(new IAttributeDefinition[attrDefs.size()]))); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert arg to integer")); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: not enough arguments")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener#handleProxyRuntimeErrorStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorStateEvent) */ public void handleEvent(IProxyRuntimeErrorStateEvent e) { fireRuntimeErrorStateEvent(new RuntimeErrorStateEvent()); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeErrorEvent) */ public void handleEvent(IProxyRuntimeMessageEvent e) { String[] attrs = e.getAttributes(); if (attrs.length > 0) { AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1); fireRuntimeMessageEvent(new RuntimeMessageEvent(mgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeJobChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeJobChangeEvent) */ public void handleEvent(IProxyRuntimeJobChangeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0); if (eMgr != null) { fireRuntimeJobChangeEvent(new RuntimeJobChangeEvent(eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeMachineChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeMachineChangeEvent) */ public void handleEvent(IProxyRuntimeMachineChangeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0); if (eMgr != null) { fireRuntimeMachineChangeEvent(new RuntimeMachineChangeEvent(eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewJobEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewJobEvent) */ public void handleEvent(IProxyRuntimeNewJobEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 2) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1); if (eMgr != null) { /* * Find any job submission attributes and add to the jobs */ for (Map.Entry<RangeSet, AttributeManager> entry : eMgr.getEntrySet()) { StringAttribute subIdAttr = entry.getValue().getAttribute(JobAttributes.getSubIdAttributeDefinition()); if (subIdAttr != null) { String subId = subIdAttr.getValueAsString(); AttributeManager mgr = jobSubs.get(subId); if (mgr != null) { entry.getValue().addAttributes(mgr.getAttributes()); } jobSubs.remove(subId); } } fireRuntimeNewJobEvent(new RuntimeNewJobEvent(attrs[0], eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewMachineEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewMachineEvent) */ public void handleEvent(IProxyRuntimeNewMachineEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 2) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1); if (eMgr != null) { fireRuntimeNewMachineEvent(new RuntimeNewMachineEvent(attrs[0], eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewNodeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewNodeEvent) */ public void handleEvent(IProxyRuntimeNewNodeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 2) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1); if (eMgr != null) { fireRuntimeNewNodeEvent(new RuntimeNewNodeEvent(attrs[0], eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewProcessEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewProcessEvent) */ public void handleEvent(IProxyRuntimeNewProcessEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 2) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1); if (eMgr != null) { fireRuntimeNewProcessEvent(new RuntimeNewProcessEvent(attrs[0], eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNewQueueEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNewQueueEvent) */ public void handleEvent(IProxyRuntimeNewQueueEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 2) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 1); if (eMgr != null) { fireRuntimeNewQueueEvent(new RuntimeNewQueueEvent(attrs[0], eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeNodeChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeNodeChangeEvent) */ public void handleEvent(IProxyRuntimeNodeChangeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0); if (eMgr != null) { fireRuntimeNodeChangeEvent(new RuntimeNodeChangeEvent(eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeProcessChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeProcessChangeEvent) */ public void handleEvent(IProxyRuntimeProcessChangeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0); if (eMgr != null) { fireRuntimeProcessChangeEvent(new RuntimeProcessChangeEvent(eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeQueueChangeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeQueueChangeEvent) */ public void handleEvent(IProxyRuntimeQueueChangeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } ElementAttributeManager eMgr = getElementAttributeManager(attrs, 0); if (eMgr != null) { fireRuntimeQueueChangeEvent(new RuntimeQueueChangeEvent(eMgr)); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeConnectedStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeConnectedStateEvent) */ public void handleEvent(IProxyRuntimeConnectedStateEvent e) { fireRuntimeConnectedStateEvent(new RuntimeConnectedStateEvent()); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.IProxyRuntimeEventListener#handleProxyRuntimeRemoveAllEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveAllEvent) */ public void handleEvent(IProxyRuntimeRemoveAllEvent e) { fireRuntimeRemoveAllEvent(new RuntimeRemoveAllEvent()); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveJobEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveJobEvent) */ public void handleEvent(IProxyRuntimeRemoveJobEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } fireRuntimeRemoveJobEvent(new RuntimeRemoveJobEvent(new RangeSet(attrs[0]))); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveMachineEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveMachineEvent) */ public void handleEvent(IProxyRuntimeRemoveMachineEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } fireRuntimeRemoveMachineEvent(new RuntimeRemoveMachineEvent(new RangeSet(attrs[0]))); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveNodeEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveNodeEvent) */ public void handleEvent(IProxyRuntimeRemoveNodeEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } fireRuntimeRemoveNodeEvent(new RuntimeRemoveNodeEvent(new RangeSet(attrs[0]))); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveProcessEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveProcessEvent) */ public void handleEvent(IProxyRuntimeRemoveProcessEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } fireRuntimeRemoveProcessEvent(new RuntimeRemoveProcessEvent(new RangeSet(attrs[0]))); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRemoveQueueEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRemoveQueueEvent) */ public void handleEvent(IProxyRuntimeRemoveQueueEvent e) { String[] attrs = e.getAttributes(); if (attrs.length < 1) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "AbstractProxyRuntimeSystem: not enough arguments")); return; } fireRuntimeRemoveQueueEvent(new RuntimeRemoveQueueEvent(new RangeSet(attrs[0]))); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeRunningStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeRunningStateEvent) */ public void handleEvent(IProxyRuntimeRunningStateEvent e) { fireRuntimeRunningStateEvent(new RuntimeRunningStateEvent()); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeShutdownStateEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeShutdownStateEvent) */ public void handleEvent(IProxyRuntimeShutdownStateEvent e) { fireRuntimeShutdownStateEvent(new RuntimeShutdownStateEvent()); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeStartupErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeStartupErrorEvent) */ public void handleEvent( IProxyRuntimeStartupErrorEvent e) { String[] attrs = e.getAttributes(); if (attrs.length > 0) { AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1); IntegerAttribute codeAttr = mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition()); StringAttribute msgAttr = mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition()); if (codeAttr == null || msgAttr == null) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "StartupErrorEvent: missing attibutes")); } else { fireRuntimeStartupErrorEvent(new RuntimeStartupErrorEvent(codeAttr.getValue(), msgAttr.getValue())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "StartupErrorEvent: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeSubmitJobErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeSubmitJobErrorEvent) */ public void handleEvent( IProxyRuntimeSubmitJobErrorEvent e) { String[] attrs = e.getAttributes(); if (attrs.length > 0) { AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1); IntegerAttribute codeAttr = (IntegerAttribute) mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition()); StringAttribute msgAttr = (StringAttribute) mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition()); StringAttribute jobSubIdAttr = (StringAttribute) mgr.getAttribute(JobAttributes.getSubIdAttributeDefinition()); if (codeAttr == null || msgAttr == null || jobSubIdAttr == null) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "SubmitJobErrorEvent: missing attibutes")); } else { fireRuntimeSubmitJobErrorEvent(new RuntimeSubmitJobErrorEvent(codeAttr.getValue(), msgAttr.getValue(), jobSubIdAttr.getValue())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "SubmitJobErrorEvent: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeEventListener#handleProxyRuntimeTerminateJobErrorEvent(org.eclipse.ptp.rtsystem.proxy.event.IProxyRuntimeTerminateJobErrorEvent) */ public void handleEvent( IProxyRuntimeTerminateJobErrorEvent e) { String[] attrs = e.getAttributes(); if (attrs.length > 0) { AttributeManager mgr = getAttributeManager(attrs, 0, attrs.length - 1); IntegerAttribute codeAttr = (IntegerAttribute) mgr.getAttribute(ErrorAttributes.getCodeAttributeDefinition()); StringAttribute msgAttr = (StringAttribute) mgr.getAttribute(ErrorAttributes.getMsgAttributeDefinition()); StringAttribute jobIdAttr = (StringAttribute) mgr.getAttribute(ElementAttributes.getIdAttributeDefinition()); if (codeAttr == null || msgAttr == null || jobIdAttr == null) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "TerminateJobErrorEvent: missing attibutes")); } else { fireRuntimeTerminateJobErrorEvent(new RuntimeTerminateJobErrorEvent(codeAttr.getValue(), msgAttr.getValue(), jobIdAttr.getValue())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "TerminateJobErrorEvent: could not parse message")); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.IRuntimeSystem#shutdown() */ public void shutdown() { proxy.shutdown(); } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.IRuntimeSystem#startup() */ public boolean startup() throws CoreException { return proxy.startup(); } public String submitJob(AttributeManager attrMgr) throws CoreException { try { /* * Add the job submission ID to the attributes. This is done here to force the * use of the ID. */ String id = getJobSubmissionID(); StringAttribute jobSubAttr = JobAttributes.getSubIdAttributeDefinition().create(id); attrMgr.addAttribute(jobSubAttr); proxy.submitJob(attrMgr.toStringArray()); jobSubs.put(id, attrMgr); return id; } catch(IOException e) { throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR, "Control system is shut down, proxy exception. The proxy may have crashed or been killed.", null)); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.IControlSystem#terminateJob(org.eclipse.ptp.core.elements.IPJob) */ public void terminateJob(IPJob job) throws CoreException { if(job == null) { System.err.println("ERROR: Tried to abort a null job."); return; } try { proxy.terminateJob(job.getID()); } catch(IOException e) { throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR, "Control system is shut down, proxy exception. The proxy may have crashed or been killed.", null)); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.IMonitoringSystem#startEvents() */ public void startEvents() throws CoreException { try { proxy.startEvents(); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR, e.getMessage(), e)); } } /* (non-Javadoc) * @see org.eclipse.ptp.rtsystem.IMonitoringSystem#stopEvents() */ public void stopEvents() throws CoreException { try { proxy.stopEvents(); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, PTPCorePlugin.getUniqueIdentifier(), IStatus.ERROR, e.getMessage(), e)); } } /** * @param kvs * @param start * @param end * @return */ private AttributeManager getAttributeManager(String[] kvs, int start, int end) { AttributeManager mgr = new AttributeManager(); for (int i = start; i <= end; i++) { String[] kv = kvs[i].split("="); if (kv.length == 2) { try { IAttributeDefinition<?,?,?> attrDef = attrDefManager.getAttributeDefinition(kv[0]); if(attrDef != null) { IAttribute<?,?,?> attr = attrDef.create(kv[1]); mgr.addAttribute(attr); } else { System.out.println("AbstractProxyRuntimSystem: unknown attribute definition"); } } catch (IllegalValueException e1) { System.out.println("AbstractProxyRuntimSystem: invalid attribute for definition"); } } } return mgr; } /** * @param attrs * @param pos * @return */ private ElementAttributeManager getElementAttributeManager(String[] attrs, int pos) { ElementAttributeManager eMgr = new ElementAttributeManager(); try { int numRanges = Integer.parseInt(attrs[pos++]); for (int i = 0; i < numRanges; i++) { if (pos >= attrs.length) { return null; } RangeSet ids = new RangeSet(attrs[pos++]); int numAttrs = Integer.parseInt(attrs[pos++]); int start = pos; int end = pos + numAttrs - 1; if (end >= attrs.length) { return null; } eMgr.setAttributeManager(ids, getAttributeManager(attrs, start, end)); pos = end + 1; } } catch (NumberFormatException e1) { return null; } return eMgr; } /** * Parse and extract an attribute definition. * * On entry, we know that end < attrs.length and end - start >= ATTR_MIN_LEN * */ private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) { int pos = start; IAttributeDefinition<?,?,?> attrDef = null; String attrId = attrs[pos++]; String attrType = attrs[pos++]; String attrName = attrs[pos++]; String attrDesc = attrs[pos++]; boolean attrDisplay; try { attrDisplay = Boolean.parseBoolean(attrs[pos++]); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attr to boolean")); return null; } String attrDefault = attrs[pos++]; if (attrType.equals("BOOLEAN")) { try { Boolean defVal = Boolean.parseBoolean(attrDefault); attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to boolean")); } } else if (attrType.equals("DATE")) { if (end - pos > 2) { try { int dateStyle = toDateStyle(attrs[pos++]); int timeStyle = toDateStyle(attrs[pos++]); Locale locale = toLocale(attrs[pos++]); DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); Date defVal = fmt.parse(attrDefault); if (end - pos > 1) { Date min = fmt.parse(attrs[pos++]); Date max = fmt.parse(attrs[pos++]); attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt, min, max); } else { attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt); } } catch (ParseException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format")); } } else if (attrType.equals("DOUBLE")) { try { Double defVal = Double.parseDouble(attrDefault); - if (end - pos > 1) { + if (end - pos > 0) { Double min = Double.parseDouble(attrs[pos++]); Double max = Double.parseDouble(attrs[pos++]); attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("ENUMERATED")) { ArrayList<String> values = new ArrayList<String>(); while (pos <= end) { values.add(attrs[pos++]); } try { attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault, values.toArray(new String[values.size()])); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("INTEGER")) { try { Integer defVal = Integer.parseInt(attrDefault); - if (end - pos > 1) { + if (end - pos > 0) { Integer min = Integer.parseInt(attrs[pos++]); Integer max = Integer.parseInt(attrs[pos++]); attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("BIGINTEGER")) { try { BigInteger defVal = new BigInteger(attrDefault); - if (end - pos > 1) { + if (end - pos > 0) { BigInteger min = new BigInteger(attrs[pos++]); BigInteger max = new BigInteger(attrs[pos++]); attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to BigInteger")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("STRING")) { attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type")); } return attrDef; } /** * @param val * @return */ private int toDateStyle(String val) { if (val.equals("SHORT")) { return DateFormat.SHORT; } else if (val.equals("MEDIUM")) { return DateFormat.MEDIUM; } else if (val.equals("LONG")) { return DateFormat.LONG; } else if (val.equals("FULL")) { return DateFormat.FULL; } else { return DateFormat.DEFAULT; } } /** * @param val * @return */ private Locale toLocale(String val) { if (val.equals("CANADA")) { return Locale.CANADA; } else if (val.equals("CHINA")) { return Locale.CHINA; } else if (val.equals("FRANCE")) { return Locale.FRANCE; } else if (val.equals("GERMANY")) { return Locale.GERMANY; } else if (val.equals("ITALY")) { return Locale.ITALY; } else if (val.equals("JAPAN")) { return Locale.JAPAN; } else if (val.equals("TAIWAN")) { return Locale.TAIWAN; } else if (val.equals("UK")) { return Locale.UK; } else if (val.equals("US")) { return Locale.US; } else { return Locale.US; } } private String getJobSubmissionID() { long time = System.currentTimeMillis(); return "JOB_" + Long.toString(time) + Integer.toString(jobSubIdCount++); } }
false
true
private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) { int pos = start; IAttributeDefinition<?,?,?> attrDef = null; String attrId = attrs[pos++]; String attrType = attrs[pos++]; String attrName = attrs[pos++]; String attrDesc = attrs[pos++]; boolean attrDisplay; try { attrDisplay = Boolean.parseBoolean(attrs[pos++]); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attr to boolean")); return null; } String attrDefault = attrs[pos++]; if (attrType.equals("BOOLEAN")) { try { Boolean defVal = Boolean.parseBoolean(attrDefault); attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to boolean")); } } else if (attrType.equals("DATE")) { if (end - pos > 2) { try { int dateStyle = toDateStyle(attrs[pos++]); int timeStyle = toDateStyle(attrs[pos++]); Locale locale = toLocale(attrs[pos++]); DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); Date defVal = fmt.parse(attrDefault); if (end - pos > 1) { Date min = fmt.parse(attrs[pos++]); Date max = fmt.parse(attrs[pos++]); attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt, min, max); } else { attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt); } } catch (ParseException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format")); } } else if (attrType.equals("DOUBLE")) { try { Double defVal = Double.parseDouble(attrDefault); if (end - pos > 1) { Double min = Double.parseDouble(attrs[pos++]); Double max = Double.parseDouble(attrs[pos++]); attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("ENUMERATED")) { ArrayList<String> values = new ArrayList<String>(); while (pos <= end) { values.add(attrs[pos++]); } try { attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault, values.toArray(new String[values.size()])); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("INTEGER")) { try { Integer defVal = Integer.parseInt(attrDefault); if (end - pos > 1) { Integer min = Integer.parseInt(attrs[pos++]); Integer max = Integer.parseInt(attrs[pos++]); attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("BIGINTEGER")) { try { BigInteger defVal = new BigInteger(attrDefault); if (end - pos > 1) { BigInteger min = new BigInteger(attrs[pos++]); BigInteger max = new BigInteger(attrs[pos++]); attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to BigInteger")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("STRING")) { attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type")); } return attrDef; }
private IAttributeDefinition<?,?,?> parseAttributeDefinition(String[] attrs, int start, int end) { int pos = start; IAttributeDefinition<?,?,?> attrDef = null; String attrId = attrs[pos++]; String attrType = attrs[pos++]; String attrName = attrs[pos++]; String attrDesc = attrs[pos++]; boolean attrDisplay; try { attrDisplay = Boolean.parseBoolean(attrs[pos++]); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attr to boolean")); return null; } String attrDefault = attrs[pos++]; if (attrType.equals("BOOLEAN")) { try { Boolean defVal = Boolean.parseBoolean(attrDefault); attrDef = attrDefManager.createBooleanAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert attrs to boolean")); } } else if (attrType.equals("DATE")) { if (end - pos > 2) { try { int dateStyle = toDateStyle(attrs[pos++]); int timeStyle = toDateStyle(attrs[pos++]); Locale locale = toLocale(attrs[pos++]); DateFormat fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); Date defVal = fmt.parse(attrDefault); if (end - pos > 1) { Date min = fmt.parse(attrs[pos++]); Date max = fmt.parse(attrs[pos++]); attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt, min, max); } else { attrDef = attrDefManager.createDateAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, fmt); } } catch (ParseException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not parse date")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: missing date format")); } } else if (attrType.equals("DOUBLE")) { try { Double defVal = Double.parseDouble(attrDefault); if (end - pos > 0) { Double min = Double.parseDouble(attrs[pos++]); Double max = Double.parseDouble(attrs[pos++]); attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createDoubleAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to double")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("ENUMERATED")) { ArrayList<String> values = new ArrayList<String>(); while (pos <= end) { values.add(attrs[pos++]); } try { attrDef = attrDefManager.createStringSetAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault, values.toArray(new String[values.size()])); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("INTEGER")) { try { Integer defVal = Integer.parseInt(attrDefault); if (end - pos > 0) { Integer min = Integer.parseInt(attrs[pos++]); Integer max = Integer.parseInt(attrs[pos++]); attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to integer")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("BIGINTEGER")) { try { BigInteger defVal = new BigInteger(attrDefault); if (end - pos > 0) { BigInteger min = new BigInteger(attrs[pos++]); BigInteger max = new BigInteger(attrs[pos++]); attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal, min, max); } else { attrDef = attrDefManager.createBigIntegerAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, defVal); } } catch (NumberFormatException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not convert args to BigInteger")); } catch (IllegalValueException ex) { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: could not create attribute definition, " + ex.getMessage())); } } else if (attrType.equals("STRING")) { attrDef = attrDefManager.createStringAttributeDefinition(attrId, attrName, attrDesc, attrDisplay, attrDefault); } else { fireRuntimeMessageEvent(new RuntimeMessageEvent(Level.ERROR, "Bad proxy event: unknown attribute type")); } return attrDef; }
diff --git a/src/org/pentaho/platform/dataaccess/datasource/ui/admindialog/DatasourceAdminDialogController.java b/src/org/pentaho/platform/dataaccess/datasource/ui/admindialog/DatasourceAdminDialogController.java index 468c18eb..fc437063 100644 --- a/src/org/pentaho/platform/dataaccess/datasource/ui/admindialog/DatasourceAdminDialogController.java +++ b/src/org/pentaho/platform/dataaccess/datasource/ui/admindialog/DatasourceAdminDialogController.java @@ -1,429 +1,429 @@ package org.pentaho.platform.dataaccess.datasource.ui.admindialog; import java.util.List; import org.pentaho.agilebi.modeler.services.IModelerServiceAsync; import org.pentaho.database.model.IDatabaseConnection; import org.pentaho.metadata.model.Domain; import org.pentaho.platform.dataaccess.datasource.DSWUIDatasourceService; import org.pentaho.platform.dataaccess.datasource.IDatasourceInfo; import org.pentaho.platform.dataaccess.datasource.IUIDatasourceAdminService; import org.pentaho.platform.dataaccess.datasource.JdbcDatasourceService; import org.pentaho.platform.dataaccess.datasource.MetadataUIDatasourceService; import org.pentaho.platform.dataaccess.datasource.MondrianUIDatasourceService; import org.pentaho.platform.dataaccess.datasource.UIDatasourceServiceManager; import org.pentaho.platform.dataaccess.datasource.ui.importing.AnalysisImportDialogModel; import org.pentaho.platform.dataaccess.datasource.ui.importing.MetadataImportDialogModel; import org.pentaho.platform.dataaccess.datasource.wizard.GwtDatasourceEditorEntryPoint; import org.pentaho.platform.dataaccess.datasource.wizard.service.IXulAsyncConnectionService; import org.pentaho.platform.dataaccess.datasource.wizard.service.IXulAsyncDSWDatasourceService; import org.pentaho.platform.dataaccess.datasource.wizard.service.IXulAsyncDatasourceServiceManager; import org.pentaho.ui.database.gwt.GwtDatabaseDialog; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.XulServiceCallback; import org.pentaho.ui.xul.binding.Binding; import org.pentaho.ui.xul.binding.BindingConvertor; import org.pentaho.ui.xul.binding.BindingException; import org.pentaho.ui.xul.binding.BindingExceptionHandler; import org.pentaho.ui.xul.binding.BindingFactory; import org.pentaho.ui.xul.components.XulButton; import org.pentaho.ui.xul.components.XulLabel; import org.pentaho.ui.xul.components.XulMenuitem; import org.pentaho.ui.xul.containers.XulDialog; import org.pentaho.ui.xul.containers.XulMenupopup; import org.pentaho.ui.xul.containers.XulTree; import org.pentaho.ui.xul.containers.XulTreeCols; import org.pentaho.ui.xul.stereotype.Bindable; import org.pentaho.ui.xul.util.AbstractXulDialogController; public class DatasourceAdminDialogController extends AbstractXulDialogController<IDatasourceInfo> implements BindingExceptionHandler{ // ~ Static fields/initializers ====================================================================================== // ~ Instance fields ================================================================================================= private BindingFactory bf; private IXulAsyncDatasourceServiceManager datasourceServiceManager; private IXulAsyncConnectionService connectionService; private IModelerServiceAsync modelerService; private IXulAsyncDSWDatasourceService dswService; private DatasourceAdminDialogModel datasourceAdminDialogModel = new DatasourceAdminDialogModel(); private XulDialog datasourceAdminDialog; private XulDialog datasourceAdminErrorDialog; private XulLabel datasourceAdminErrorLabel = null; //private XulMenuList datasourceTypeMenuList; private XulButton datasourceAddButton; private XulMenupopup datasourceTypeMenuPopup; private XulButton exportDatasourceButton; private XulButton editDatasourceButton; private XulButton removeDatasourceButton; private Binding editDatasourceButtonBinding; private Binding removeDatasourceButtonBinding; private Binding exportDatasourceButtonBinding; private GwtDatabaseDialog databaseDialog; private boolean administrator; XulTree datasourceTable = null; XulTreeCols datasourceTreeCols = null; UIDatasourceServiceManager manager; private GwtDatasourceEditorEntryPoint entryPoint; /** * Sets up bindings. */ @Bindable public void init() { datasourceTable = (XulTree) document.getElementById("datasourcesListTable"); //$NON-NLS-1$ datasourceTreeCols = (XulTreeCols) document.getElementById("datasourcesListCols"); //$NON-NLS-1$ datasourceAdminDialog = (XulDialog) document.getElementById("datasourceAdminDialog"); //$NON-NLS-1$ datasourceAdminErrorDialog = (XulDialog) document.getElementById("datasourceAdminErrorDialog"); //$NON-NLS-1$ datasourceAdminErrorLabel = (XulLabel) document.getElementById("datasourceAdminErrorLabel");//$NON-NLS-1$ //datasourceTypeMenuList = (XulMenuList) document.getElementById("datasourceTypeMenuList");//$NON-NLS-1$ datasourceAddButton = (XulButton) document.getElementById("datasourceAddButton"); //$NON-NLS-1$ datasourceTypeMenuPopup = (XulMenupopup) document.getElementById("datasourceTypeMenuPopup"); //$NON-NLS-1$ exportDatasourceButton = (XulButton) document.getElementById("exportDatasourceButton"); //$NON-NLS-1$ editDatasourceButton = (XulButton) document.getElementById("editDatasourceButton"); //$NON-NLS-1$ removeDatasourceButton = (XulButton) document.getElementById("removeDatasourceButton"); //$NON-NLS-1$ bf.setBindingType(Binding.Type.ONE_WAY); try { //Binding datasourceBinding = bf.createBinding(datasourceAdminDialogModel, "datasourceTypes", datasourceTypeMenuList, "elements"); BindingConvertor<IDatasourceInfo, Boolean> removeDatasourceButtonConvertor = new BindingConvertor<IDatasourceInfo, Boolean>() { @Override public Boolean sourceToTarget(final IDatasourceInfo datasourceInfo) { return datasourceInfo.isRemovable(); } @Override public IDatasourceInfo targetToSource(final Boolean value) { throw new UnsupportedOperationException(); } }; BindingConvertor<IDatasourceInfo, Boolean> editDatasourceButtonConvertor = new BindingConvertor<IDatasourceInfo, Boolean>() { @Override public Boolean sourceToTarget(final IDatasourceInfo datasourceInfo) { return datasourceInfo.isEditable(); } @Override public IDatasourceInfo targetToSource(final Boolean value) { throw new UnsupportedOperationException(); } }; BindingConvertor<IDatasourceInfo, Boolean> exportDatasourceButtonConvertor = new BindingConvertor<IDatasourceInfo, Boolean>() { @Override public Boolean sourceToTarget(final IDatasourceInfo datasourceInfo) { return datasourceInfo.isExportable(); } @Override public IDatasourceInfo targetToSource(final Boolean value) { throw new UnsupportedOperationException(); } }; removeDatasourceButtonBinding = bf.createBinding(datasourceAdminDialogModel, "selectedDatasource", //$NON-NLS-1$ removeDatasourceButton, "!disabled", removeDatasourceButtonConvertor); //$NON-NLS-1$ editDatasourceButtonBinding = bf.createBinding(datasourceAdminDialogModel, "selectedDatasource", //$NON-NLS-1$ editDatasourceButton, "!disabled", editDatasourceButtonConvertor); //$NON-NLS-1$ exportDatasourceButtonBinding = bf.createBinding(datasourceAdminDialogModel, "selectedDatasource", //$NON-NLS-1$ exportDatasourceButton, "!disabled", exportDatasourceButtonConvertor); //$NON-NLS-1$ bf.createBinding(datasourceAdminDialogModel, "datasources", datasourceTable, "elements"); bf.createBinding(datasourceTable, "selectedItems", datasourceAdminDialogModel, "selectedDatasource", //$NON-NLS-1$//$NON-NLS-2$ new BindingConvertor<List, IDatasourceInfo>() { @Override public IDatasourceInfo sourceToTarget( List datasources) { if(datasources != null && datasources.size() > 0) { return (IDatasourceInfo) datasources.get(0); } return null; } @Override public List targetToSource( IDatasourceInfo arg0 ) { throw new UnsupportedOperationException(); } }).fireSourceChanged(); bf.createBinding(datasourceTable, "selectedItem", datasourceAdminDialogModel, "selectedDatasource").fireSourceChanged(); removeDatasourceButtonBinding.fireSourceChanged(); editDatasourceButtonBinding.fireSourceChanged(); exportDatasourceButtonBinding.fireSourceChanged(); setupNativeHooks(this); // Initialize UI Datasource Service Manager manager = new UIDatasourceServiceManager(); // Register Builtin datasources manager.registerService(new JdbcDatasourceService(connectionService)); manager.registerService(new MondrianUIDatasourceService(datasourceServiceManager)); manager.registerService(new MetadataUIDatasourceService(datasourceServiceManager)); manager.registerService(new DSWUIDatasourceService(datasourceServiceManager)); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private native void setupNativeHooks(DatasourceAdminDialogController controller)/*-{ $wnd.pho.showDatasourceAdminErrorDialog = function(title, errorMessage) { controller.@org.pentaho.platform.dataaccess.datasource.ui.admindialog.DatasourceAdminDialogController::openErrorDialog(Ljava/lang/String;Ljava/lang/String;)(title, errorMessage); } $wnd.pho.refreshDatasourceList = function() { controller.@org.pentaho.platform.dataaccess.datasource.ui.admindialog.DatasourceAdminDialogController::refreshDatasourceList()(); } }-*/; /** * ID of this controller. This is how event handlers are referenced in <code>.xul</code> files. */ @Override public String getName() { return "datasourceAdminDialogController"; //$NON-NLS-1$ } public void setBindingFactory(final BindingFactory bf) { this.bf = bf; this.bf.setExceptionHandler(this); } public void setDatasourceServiceManager(final IXulAsyncDatasourceServiceManager datasourceServiceManager) { this.datasourceServiceManager = datasourceServiceManager; } public void setConnectionService(final IXulAsyncConnectionService connectionService) { this.connectionService = connectionService; } public void setModelerService(final IModelerServiceAsync modelerService) { this.modelerService = modelerService; } public void setDSWService(final IXulAsyncDSWDatasourceService dswService) { this.dswService = dswService; } private void refreshDatasourceList() { datasourceAdminDialogModel.setDatasourcesList(null); manager.getIds(new XulServiceCallback<List<IDatasourceInfo>>() { @Override public void success(List<IDatasourceInfo> infoList) { datasourceAdminDialogModel.setDatasourcesList(infoList); } @Override public void error(String message, Throwable error) { openErrorDialog("Error", message + error.getMessage()); } }); } private void getDatasourceTypes() { List<String> datasourceTypes = manager.getTypes(); // Clear out the current component list List<XulComponent> components = datasourceTypeMenuPopup.getChildNodes(); for(XulComponent component:components) { datasourceTypeMenuPopup.removeComponent(component); } for(String datasourceType:datasourceTypes) { XulMenuitem menuItem; try { menuItem = (XulMenuitem) document.createElement("menuitem"); menuItem.setLabel(datasourceType); menuItem.setCommand(getName() + ".launchNewUI(\""+ datasourceType + "\")"); menuItem.setId(datasourceType); datasourceTypeMenuPopup.addChild(menuItem); } catch (XulException e) { throw new RuntimeException(e); } } datasourceAdminDialogModel.setDatasourceTypeList(datasourceTypes); } @Bindable public void launchNewUI(String datasourceType) { IUIDatasourceAdminService service = manager.getService(datasourceType); String newUI = service.getNewUI(); if(newUI != null && newUI.length() > 0) { if(newUI.indexOf("builtin:") >= 0) { if(service.getType().equals(JdbcDatasourceService.TYPE)) { entryPoint.showDatabaseDialog(new DialogListener<IDatabaseConnection>() { @Override public void onDialogAccept(IDatabaseConnection returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(MondrianUIDatasourceService.TYPE)){ - entryPoint.showAnalysisImportDialog(new DialogListener<AnalysisImportDialogModel>() { + entryPoint.showAnalysisImportDialog(new DialogListener() { @Override - public void onDialogAccept(AnalysisImportDialogModel returnValue) { + public void onDialogAccept(Object returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { // TODO Auto-generated method stub } }); } else if (service.getType().equals(MetadataUIDatasourceService.TYPE)){ entryPoint.showMetadataImportDialog(new DialogListener<MetadataImportDialogModel>() { @Override public void onDialogAccept(MetadataImportDialogModel returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(DSWUIDatasourceService.TYPE)){ entryPoint.showWizard(false, new DialogListener<Domain>() { @Override public void onDialogAccept(Domain returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } } else if(newUI.indexOf("javascript:") >= 0) { String script = newUI.substring(newUI.indexOf(":") + 1); executeJavaScript(script); } } } private native void executeJavaScript(String script) /*-{ try{ var callback = "{ onCancel: function(){} ,onOk: function(returnValue){$wnd.pho.refreshDatasourceList();},onError: function(errorMessage){$wnd.pho.showDatasourceAdminErrorDialog('Error', errorMessage);}}"; var updatedScript = script.replace(/\{callback\}/g, callback); eval(updatedScript); } catch (e){ $wnd.pho.showDatasourceAdminErrorDialog("Error", e.message); } }-*/; @Bindable public void launchEditUI() { IDatasourceInfo datasourceInfo = datasourceAdminDialogModel.getSelectedDatasource(); } @Override public void showDialog() { super.showDialog(); refreshDatasourceList(); getDatasourceTypes(); } @Override protected XulDialog getDialog() { return datasourceAdminDialog; } @Override protected IDatasourceInfo getDialogResult() { return datasourceAdminDialogModel.getDatasourcesList().get(datasourceAdminDialogModel.getSelectedIndex()); } @Bindable public void openErrorDialog(String title, String message) { datasourceAdminErrorDialog.setTitle(title); datasourceAdminErrorLabel.setValue(message); datasourceAdminErrorDialog.show(); } @Bindable public void closeErrorDialog() { if (!datasourceAdminErrorDialog.isHidden()) { datasourceAdminErrorDialog.hide(); } } public void setEntryPoint(GwtDatasourceEditorEntryPoint entryPoint) { this.entryPoint = entryPoint; } @Override public void handleException(BindingException t) { t.printStackTrace(); } }
false
true
public void launchNewUI(String datasourceType) { IUIDatasourceAdminService service = manager.getService(datasourceType); String newUI = service.getNewUI(); if(newUI != null && newUI.length() > 0) { if(newUI.indexOf("builtin:") >= 0) { if(service.getType().equals(JdbcDatasourceService.TYPE)) { entryPoint.showDatabaseDialog(new DialogListener<IDatabaseConnection>() { @Override public void onDialogAccept(IDatabaseConnection returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(MondrianUIDatasourceService.TYPE)){ entryPoint.showAnalysisImportDialog(new DialogListener<AnalysisImportDialogModel>() { @Override public void onDialogAccept(AnalysisImportDialogModel returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { // TODO Auto-generated method stub } }); } else if (service.getType().equals(MetadataUIDatasourceService.TYPE)){ entryPoint.showMetadataImportDialog(new DialogListener<MetadataImportDialogModel>() { @Override public void onDialogAccept(MetadataImportDialogModel returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(DSWUIDatasourceService.TYPE)){ entryPoint.showWizard(false, new DialogListener<Domain>() { @Override public void onDialogAccept(Domain returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } } else if(newUI.indexOf("javascript:") >= 0) { String script = newUI.substring(newUI.indexOf(":") + 1); executeJavaScript(script); } } }
public void launchNewUI(String datasourceType) { IUIDatasourceAdminService service = manager.getService(datasourceType); String newUI = service.getNewUI(); if(newUI != null && newUI.length() > 0) { if(newUI.indexOf("builtin:") >= 0) { if(service.getType().equals(JdbcDatasourceService.TYPE)) { entryPoint.showDatabaseDialog(new DialogListener<IDatabaseConnection>() { @Override public void onDialogAccept(IDatabaseConnection returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(MondrianUIDatasourceService.TYPE)){ entryPoint.showAnalysisImportDialog(new DialogListener() { @Override public void onDialogAccept(Object returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { // TODO Auto-generated method stub } }); } else if (service.getType().equals(MetadataUIDatasourceService.TYPE)){ entryPoint.showMetadataImportDialog(new DialogListener<MetadataImportDialogModel>() { @Override public void onDialogAccept(MetadataImportDialogModel returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } else if (service.getType().equals(DSWUIDatasourceService.TYPE)){ entryPoint.showWizard(false, new DialogListener<Domain>() { @Override public void onDialogAccept(Domain returnValue) { refreshDatasourceList(); } @Override public void onDialogCancel() { // TODO Auto-generated method stub } @Override public void onDialogReady() { // TODO Auto-generated method stub } @Override public void onDialogError(String errorMessage) { openErrorDialog("Error", errorMessage); } }); } } else if(newUI.indexOf("javascript:") >= 0) { String script = newUI.substring(newUI.indexOf(":") + 1); executeJavaScript(script); } } }
diff --git a/modules/library/render/src/main/java/org/geotools/map/MapContent.java b/modules/library/render/src/main/java/org/geotools/map/MapContent.java index a933e01f..9b542041 100644 --- a/modules/library/render/src/main/java/org/geotools/map/MapContent.java +++ b/modules/library/render/src/main/java/org/geotools/map/MapContent.java @@ -1,786 +1,789 @@ /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2003-2008, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * 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 org.geotools.map; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.event.MapBoundsEvent; import org.geotools.map.event.MapBoundsListener; import org.geotools.map.event.MapLayerEvent; import org.geotools.map.event.MapLayerListEvent; import org.geotools.map.event.MapLayerListListener; import org.geotools.map.event.MapLayerListener; import org.geotools.referencing.CRS; import org.geotools.util.logging.Logging; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; /** * Store the contents of a map for display primarily as a list of Layers. * <p> * This object is similar to early drafts of the OGC Open Web Service Context specification. * * @author Jody Garnett * * @source $URL: http://svn.osgeo.org/geotools/branches/2.7.x/build/maven/javadoc/../../../modules/library/render/src/main/java/org/geotools/map/MapContent.java $ * http://svn.osgeo.org/geotools/trunk/modules/library/render/src/main/java/org/geotools * /map/MapContext.java $ * @version $Id: Map.java 35310 2010-04-30 10:32:15Z jive $ */ public class MapContent { /** The logger for the map module. */ static protected final Logger LOGGER = Logging.getLogger("org.geotools.map"); /** List of Layers to be rendered */ private CopyOnWriteArrayList<Layer> layerList; /** MapLayerListListeners to be notified in the event of change */ private CopyOnWriteArrayList<MapLayerListListener> mapListeners; /** Map used to hold application specific information */ private HashMap<String, Object> userData; /** Map title */ private String title; /** PropertyListener list used for notifications */ private CopyOnWriteArrayList<PropertyChangeListener> propertyListeners; /** * Viewport for map rendering. * * While the map maintains one viewport internally to better reflect a map context document you * are free to maintain a seperate viewport; or indeed construct many viewports representing * tiles to be renderered. */ protected MapViewport viewport; /** Listener used to watch individual layers and report changes to MapLayerListListeners */ private MapLayerListener layerListener; public MapContent() { } /** * Checks that dispose has been called; producing a warning if needed. */ @Override protected void finalize() throws Throwable { if( this.layerList != null){ if( !this.layerList.isEmpty()){ LOGGER.severe("Call MapContent dispose() to prevent memory leaks"); } } super.finalize(); } /** * Clean up any listeners or cached state associated with this MapContent. * <p> * Please note that open connections (FeatureSources and GridCoverage readers) are * the responsibility of your application and are not cleaned up by this method. */ public void dispose(){ if( this.mapListeners != null ){ this.mapListeners.clear(); this.mapListeners = null; } if( this.layerList != null ){ // remove mapListeners prior to removing layers for( Layer layer : layerList ){ if( layer == null ) continue; if( this.layerListener != null ){ layer.removeMapLayerListener(layerListener); } layer.dispose(); } layerList.clear(); layerList = null; } if( this.layerListener != null ){ this.layerListener = null; } if( this.propertyListeners != null ){ this.propertyListeners.clear(); this.propertyListeners = null; } this.title = null; if( this.userData != null ){ // remove property listeners prior to removing userData this.userData.clear(); this.userData = null; } } public MapContent(MapContext context){ for( MapLayer mapLayer : context.getLayers() ){ layers().add( mapLayer.toLayer() ); } if( context.getTitle() != null ){ setTitle( context.getTitle() ); } if( context.getAbstract() != null ){ getUserData().put("abstract", context.getAbstract() ); } if( context.getContactInformation() != null ){ getUserData().put("contact", context.getContactInformation() ); } if( context.getKeywords() != null ){ getUserData().put("keywords", context.getKeywords() ); } if( context.getAreaOfInterest() != null ){ getViewport().setBounds( context.getAreaOfInterest() ); } } @Deprecated public MapContent(CoordinateReferenceSystem crs) { getViewport().setCoordinateReferenceSystem(crs); } @Deprecated public MapContent(MapLayer[] array) { this(array, null); } @Deprecated public MapContent(MapLayer[] array, CoordinateReferenceSystem crs) { this(array, "Untitled", "", "", null, crs); } @Deprecated public MapContent(MapLayer[] array, String title, String contextAbstract, String contactInformation, String[] keywords) { this(array, title, contextAbstract, contactInformation, keywords, null); } @Deprecated public MapContent(MapLayer[] array, String title, String contextAbstract, String contactInformation, String[] keywords, final CoordinateReferenceSystem crs) { if( array != null ){ for (MapLayer mapLayer : array) { if( mapLayer == null ){ continue; } Layer layer = mapLayer.toLayer(); layers().add( layer ); } } if (title != null) { setTitle(title); } if (contextAbstract != null) { getUserData().put("abstract", contextAbstract); } if (contactInformation != null) { getUserData().put("contact", contactInformation); } if (keywords != null) { getUserData().put("keywords", keywords); } if (crs != null) { getViewport().setCoordinateReferenceSystem(crs); } } /** * Register interest in receiving a {@link LayerListEvent}. A <code>LayerListEvent</code> is * sent if a layer is added or removed, but not if the data within a layer changes. * * @param listener * The object to notify when Layers have changed. */ public void addMapLayerListListener(MapLayerListListener listener) { if (mapListeners == null) { mapListeners = new CopyOnWriteArrayList<MapLayerListListener>(); } boolean added = mapListeners.addIfAbsent(listener); if (added && mapListeners.size() == 1) { listenToMapLayers(true); } } /** * Listen to the map layers; passing any events on to our own mapListListeners. * <p> * This method only has an effect if we have any actuall mapListListeners. * * @param listen * True to connect to all the layers and listen to events */ protected synchronized void listenToMapLayers(boolean listen) { if( mapListeners == null || mapListeners.isEmpty()){ return; // not worth listening nobody is interested } if (layerListener == null) { layerListener = new MapLayerListener() { public void layerShown(MapLayerEvent event) { Layer layer = (Layer) event.getSource(); int index = layers().indexOf(layer); fireLayerEvent(layer, index, event); } public void layerSelected(MapLayerEvent event) { Layer layer = (Layer) event.getSource(); int index = layers().indexOf(layer); fireLayerEvent(layer, index, event); } public void layerHidden(MapLayerEvent event) { Layer layer = (Layer) event.getSource(); int index = layers().indexOf(layer); fireLayerEvent(layer, index, event); } public void layerDeselected(MapLayerEvent event) { Layer layer = (Layer) event.getSource(); int index = layers().indexOf(layer); fireLayerEvent(layer, index, event); } public void layerChanged(MapLayerEvent event) { Layer layer = (Layer) event.getSource(); int index = layers().indexOf(layer); fireLayerEvent(layer, index, event); } }; } if (listen) { for (Layer layer : layers()) { layer.addMapLayerListener(layerListener); } } else { for (Layer layer : layers()) { layer.removeMapLayerListener(layerListener); } } } /** * Remove interest in receiving {@link LayerListEvent}. * * @param listener * The object to stop sending <code>LayerListEvent</code>s. */ public void removeMapLayerListListener(MapLayerListListener listener) { if (mapListeners != null) { mapListeners.remove(listener); } } /** * Add a new layer (if not already present). * <p> * In an interactive setting this will trigger a {@link LayerListEvent} * * @param layer * @return true if the layer was added */ public boolean addLayer(Layer layer) { return layers().addIfAbsent(layer); } /** * Remove a layer, if present, and trigger a {@link LayerListEvent}. * * @param layer * a MapLayer that will be added. * * @return true if the layer has been removed */ public boolean removeLayer(Layer layer) { return layers().remove(layer); } /** * Moves a layer from a position to another. Will fire a MapLayerListEvent * * @param sourcePosition * the layer current position * @param destPosition * the layer new position */ public void moveLayer(int sourcePosition, int destPosition) { List<Layer> layers = layers(); Layer destLayer = layers.get(destPosition); Layer sourceLayer = layers.get(sourcePosition); layers.set(destPosition, sourceLayer); layers.set(sourcePosition, destLayer); } /** * Direct access to the layer list; contents arranged by zorder. * <p> * Please note this list is live and modifications made to the list will trigger * {@link LayerListEvent} * * @return Direct access to layers */ public synchronized CopyOnWriteArrayList<Layer> layers() { if (layerList == null) { layerList = new CopyOnWriteArrayList<Layer>() { private static final long serialVersionUID = 8011733882551971475L; public void add(int index, Layer element) { super.add(index, element); if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, index, index); } @Override public boolean add(Layer element) { boolean added = super.add(element); if (added) { if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, size() - 1, size() - 1); } return added; } public boolean addAll(Collection<? extends Layer> c) { int start = size() - 1; boolean added = super.addAll(c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } public boolean addAll(int index, Collection<? extends Layer> c) { boolean added = super.addAll(index, c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, index, size() - 1); return added; } @Override public int addAllAbsent(Collection<? extends Layer> c) { int start = size() - 1; int added = super.addAllAbsent(c); if( layerListener != null ){ // taking the risk that layer is correctly impelmented and will // not have layerListener not mapped for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } @Override - public boolean addIfAbsent(Layer e) { - boolean added = super.addIfAbsent(e); + public boolean addIfAbsent(Layer element) { + boolean added = super.addIfAbsent(element); if (added) { - fireLayerAdded(e, size() - 1, size() - 1); + if (layerListener != null) { + element.addMapLayerListener(layerListener); + } + fireLayerAdded(element, size() - 1, size() - 1); } return added; } @Override public void clear() { for( Layer element : this ){ if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } super.clear(); fireLayerRemoved(null, -1, -1); } @Override public Layer remove(int index) { Layer removed = super.remove(index); fireLayerRemoved(removed, index, index); if( layerListener != null ){ removed.removeMapLayerListener( layerListener ); } removed.dispose(); return removed; } @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { fireLayerRemoved((Layer) o, -1, -1); if( o instanceof Layer ){ Layer element = (Layer) o; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } return removed; } @Override public boolean removeAll(Collection<?> c) { for( Object obj : c ){ if( !contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.removeAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } @Override public boolean retainAll(Collection<?> c) { for( Object obj : c ){ if( contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.retainAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } }; } return layerList; } protected void fireLayerAdded(Layer element, int fromIndex, int toIndex) { if (mapListeners == null) { return; } MapLayerListEvent event = new MapLayerListEvent(this, element, fromIndex, toIndex); for (MapLayerListListener mapLayerListListener : mapListeners) { try { mapLayerListListener.layerAdded(event); } catch (Throwable t) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(), "layerAdded", t.getLocalizedMessage(), t); } } } } protected void fireLayerRemoved(Layer element, int fromIndex, int toIndex) { if (mapListeners == null) { return; } MapLayerListEvent event = new MapLayerListEvent(this, element, fromIndex, toIndex); for (MapLayerListListener mapLayerListListener : mapListeners) { try { mapLayerListListener.layerRemoved(event); } catch (Throwable t) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(), "layerAdded", t.getLocalizedMessage(), t); } } } } protected void fireLayerEvent(Layer element, int index, MapLayerEvent layerEvent) { if (mapListeners == null) { return; } MapLayerListEvent mapEvent = new MapLayerListEvent(this, element, index, layerEvent); for (MapLayerListListener mapLayerListListener : mapListeners) { try { mapLayerListListener.layerChanged(mapEvent); } catch (Throwable t) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.logp(Level.FINE, mapLayerListListener.getClass().getName(), "layerAdded", t.getLocalizedMessage(), t); } } } } /** * Get the bounding box of all the layers in this Map. If all the layers cannot determine the * bounding box in the speed required for each layer, then null is returned. The bounds will be * expressed in the Map coordinate system. * * @return The bounding box of the features or null if unknown and too expensive for the method * to calculate. * * @throws IOException * if an IOException occurs while accessing the FeatureSource bounds */ public ReferencedEnvelope getMaxBounds() throws IOException { CoordinateReferenceSystem mapCrs = getCoordinateReferenceSystem(); ReferencedEnvelope maxBounds = null; for (Layer layer : layers()) { if (layer == null) { continue; } ReferencedEnvelope layerBounds = layer.getBounds(); if (layerBounds == null || layerBounds.isEmpty() || layerBounds.isNull()) { continue; } if (mapCrs == null) { // crs for the map is not defined; let us start with the first CRS we see then! maxBounds = new ReferencedEnvelope(layerBounds); mapCrs = layerBounds.getCoordinateReferenceSystem(); continue; } ReferencedEnvelope normalized; if (CRS.equalsIgnoreMetadata(mapCrs, layerBounds.getCoordinateReferenceSystem())) { normalized = layerBounds; } else { try { normalized = layerBounds.transform(mapCrs, true); } catch (Exception e) { LOGGER.log(Level.FINE, "Unable to transform: {0}", e); continue; } } if (maxBounds == null) { maxBounds = normalized; } else { maxBounds.expandToInclude(normalized); } } if (maxBounds == null && mapCrs != null) { maxBounds = new ReferencedEnvelope(mapCrs); } return maxBounds; } // // Viewport Information // /** * Viewport describing the area visiable on screen. * <p> * Applications may create multiple viewports (perhaps to render tiles of content); the viewport * recorded here is intended for interactive applications where it is helpful to have a single * viewport representing what the user is seeing on screen. */ public synchronized MapViewport getViewport() { if (viewport == null) { viewport = new MapViewport(); } return viewport; } /** * Register interest in receiving {@link MapBoundsEvent}s. * * @param listener * The object to notify when the area of interest has changed. */ public void addMapBoundsListener(MapBoundsListener listener) { getViewport().addMapBoundsListener(listener); } /** * Remove interest in receiving a {@link BoundingBoxEvent}s. * * @param listener * The object to stop sending change events. */ public void removeMapBoundsListener(MapBoundsListener listener) { getViewport().removeMapBoundsListener(listener); } /** * The extent of the map currently (sometimes called the map "viewport". * <p> * Note Well: The bounds should match your screen aspect ratio (or the map will appear * squashed). Please note this only covers spatial extent; you may wish to use the user data map * to record the current viewport time or elevation. */ ReferencedEnvelope getBounds() { return getViewport().getBounds(); } /** * The coordinate reference system used for rendering the map. * <p> * The coordinate reference system used for rendering is often considered to be the "world" * coordinate reference system; this is distinct from the coordinate reference system used for * each layer (which is often data dependent). * </p> * * @return coordinate reference system used for rendering the map. */ public CoordinateReferenceSystem getCoordinateReferenceSystem() { return getViewport().getCoordianteReferenceSystem(); } /** * Set the <code>CoordinateReferenceSystem</code> for this map's internal viewport. * * @param crs * @throws FactoryException * @throws TransformException */ void setCoordinateReferenceSystem(CoordinateReferenceSystem crs) { getViewport().setCoordinateReferenceSystem(crs); } // // Properties // /** * Registers PropertyChangeListener to receive events. * * @param listener * The listener to register. */ public void addPropertyChangeListener(java.beans.PropertyChangeListener listener) { if (propertyListeners == null) { propertyListeners = new CopyOnWriteArrayList<java.beans.PropertyChangeListener>(); } if (!propertyListeners.contains(listener)) { propertyListeners.add(listener); } } /** * Removes PropertyChangeListener from the list of listeners. * * @param listener * The listener to remove. */ public void removePropertyChangeListener(java.beans.PropertyChangeListener listener) { if (propertyListeners != null) { propertyListeners.remove(listener); } } /** * As an example it can be used to record contact details, map abstract, keywords and so forth * for an OGC "Open Web Service Context" document. * <p> * Modifications to the userData will result in a propertyChange event. * </p> * * @return */ public synchronized java.util.Map<String, Object> getUserData() { if (userData == null) { userData = new HashMap<String, Object>() { private static final long serialVersionUID = 8011733882551971475L; public Object put(String key, Object value) { Object old = super.put(key, value); fireProperty(key, old, value); return old; } public Object remove(Object key) { Object old = super.remove(key); fireProperty((String) key, old, null); return old; } @Override public void putAll(java.util.Map<? extends String, ? extends Object> m) { super.putAll(m); fireProperty("userData", null, null); } @Override public void clear() { super.clear(); fireProperty("userData", null, null); } }; } return this.userData; } /** * Get the title, returns an empty string if it has not been set yet. * * @return the title, or an empty string if it has not been set. */ public String getTitle() { return title; } /** * Set the title of this context. * * @param title * the title. */ public void setTitle(String title) { String old = this.title; this.title = title; fireProperty("title", old, title); } protected void fireProperty(String propertyName, Object old, Object value) { if (propertyListeners == null) { return; } PropertyChangeEvent event = new PropertyChangeEvent(this, "propertyName", old, value); for (PropertyChangeListener propertyChangeListener : propertyListeners) { try { propertyChangeListener.propertyChange(event); } catch (Throwable t) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.logp(Level.FINE, propertyChangeListener.getClass().getName(), "propertyChange", t.getLocalizedMessage(), t); } } } } }
false
true
public synchronized CopyOnWriteArrayList<Layer> layers() { if (layerList == null) { layerList = new CopyOnWriteArrayList<Layer>() { private static final long serialVersionUID = 8011733882551971475L; public void add(int index, Layer element) { super.add(index, element); if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, index, index); } @Override public boolean add(Layer element) { boolean added = super.add(element); if (added) { if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, size() - 1, size() - 1); } return added; } public boolean addAll(Collection<? extends Layer> c) { int start = size() - 1; boolean added = super.addAll(c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } public boolean addAll(int index, Collection<? extends Layer> c) { boolean added = super.addAll(index, c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, index, size() - 1); return added; } @Override public int addAllAbsent(Collection<? extends Layer> c) { int start = size() - 1; int added = super.addAllAbsent(c); if( layerListener != null ){ // taking the risk that layer is correctly impelmented and will // not have layerListener not mapped for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } @Override public boolean addIfAbsent(Layer e) { boolean added = super.addIfAbsent(e); if (added) { fireLayerAdded(e, size() - 1, size() - 1); } return added; } @Override public void clear() { for( Layer element : this ){ if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } super.clear(); fireLayerRemoved(null, -1, -1); } @Override public Layer remove(int index) { Layer removed = super.remove(index); fireLayerRemoved(removed, index, index); if( layerListener != null ){ removed.removeMapLayerListener( layerListener ); } removed.dispose(); return removed; } @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { fireLayerRemoved((Layer) o, -1, -1); if( o instanceof Layer ){ Layer element = (Layer) o; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } return removed; } @Override public boolean removeAll(Collection<?> c) { for( Object obj : c ){ if( !contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.removeAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } @Override public boolean retainAll(Collection<?> c) { for( Object obj : c ){ if( contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.retainAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } }; } return layerList; }
public synchronized CopyOnWriteArrayList<Layer> layers() { if (layerList == null) { layerList = new CopyOnWriteArrayList<Layer>() { private static final long serialVersionUID = 8011733882551971475L; public void add(int index, Layer element) { super.add(index, element); if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, index, index); } @Override public boolean add(Layer element) { boolean added = super.add(element); if (added) { if( layerListener != null ){ element.addMapLayerListener(layerListener); } fireLayerAdded(element, size() - 1, size() - 1); } return added; } public boolean addAll(Collection<? extends Layer> c) { int start = size() - 1; boolean added = super.addAll(c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } public boolean addAll(int index, Collection<? extends Layer> c) { boolean added = super.addAll(index, c); if( layerListener != null ){ for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, index, size() - 1); return added; } @Override public int addAllAbsent(Collection<? extends Layer> c) { int start = size() - 1; int added = super.addAllAbsent(c); if( layerListener != null ){ // taking the risk that layer is correctly impelmented and will // not have layerListener not mapped for( Layer element : c ){ element.addMapLayerListener(layerListener); } } fireLayerAdded(null, start, size() - 1); return added; } @Override public boolean addIfAbsent(Layer element) { boolean added = super.addIfAbsent(element); if (added) { if (layerListener != null) { element.addMapLayerListener(layerListener); } fireLayerAdded(element, size() - 1, size() - 1); } return added; } @Override public void clear() { for( Layer element : this ){ if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } super.clear(); fireLayerRemoved(null, -1, -1); } @Override public Layer remove(int index) { Layer removed = super.remove(index); fireLayerRemoved(removed, index, index); if( layerListener != null ){ removed.removeMapLayerListener( layerListener ); } removed.dispose(); return removed; } @Override public boolean remove(Object o) { boolean removed = super.remove(o); if (removed) { fireLayerRemoved((Layer) o, -1, -1); if( o instanceof Layer ){ Layer element = (Layer) o; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } return removed; } @Override public boolean removeAll(Collection<?> c) { for( Object obj : c ){ if( !contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.removeAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } @Override public boolean retainAll(Collection<?> c) { for( Object obj : c ){ if( contains(obj) ){ continue; } if( obj instanceof Layer ){ Layer element = (Layer) obj; if( layerListener != null ){ element.removeMapLayerListener( layerListener ); } element.dispose(); } } boolean removed = super.retainAll(c); fireLayerRemoved(null, 0, size() - 1); return removed; } }; } return layerList; }
diff --git a/lttng/org.eclipse.linuxtools.lttng.headless/src/JniTraceTest.java b/lttng/org.eclipse.linuxtools.lttng.headless/src/JniTraceTest.java index 575f7b2b6..8cd2a2fb2 100644 --- a/lttng/org.eclipse.linuxtools.lttng.headless/src/JniTraceTest.java +++ b/lttng/org.eclipse.linuxtools.lttng.headless/src/JniTraceTest.java @@ -1,85 +1,85 @@ /******************************************************************************* * Copyright (c) 2009 Ericsson * * 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: * William Bourque (wbourque@gmail.com) - Initial API and implementation *******************************************************************************/ import java.util.ArrayList; import org.eclipse.linuxtools.lttng.jni.JniEvent; import org.eclipse.linuxtools.lttng.jni.JniMarkerField; import org.eclipse.linuxtools.lttng.jni.JniTrace; import org.eclipse.linuxtools.lttng.jni.common.JniTime; import org.eclipse.linuxtools.lttng.jni.factory.JniTraceFactory; public class JniTraceTest { public static void main(String[] args) { // Path of the trace final String TRACE_PATH = "/home/william/trace-614601events-nolost-newformat"; // *** Change this to run several time over the same trace final int NB_OF_PASS = 1; // *** Change this to true to parse all the events in the trace // Otherwise, events are just read final boolean PARSE_EVENTS = true; // Work variables JniTrace tmptrace = null; JniEvent tmpevent = null; Long nbEvent = 0L; try { // Get the trace from the Factory... // This assume the path is correct and that the correct version of the lib is installed tmptrace = JniTraceFactory.getJniTrace(TRACE_PATH, false); // Seek beginning tmptrace.seekToTime(new JniTime(0L)); // Run up to "NB_OF_PASS" on the same trace for (int x=0; x<NB_OF_PASS; x++ ){ tmpevent = tmptrace.readNextEvent(); nbEvent++; while ( tmpevent != null ) { // Parse event if asked if ( PARSE_EVENTS ) { ArrayList<JniMarkerField> tmpFields = tmpevent.getMarkersMap().get(tmpevent.getEventMarkerId()).getMarkerFieldsArrayList(); for ( int pos=0; pos<tmpFields.size(); pos++ ) { @SuppressWarnings("unused") Object newValue = tmpevent.parseFieldById(pos); // *** Uncomment the following to print the parsed content // Warning : this is VERY intensive //if ( pos == (tmpFields.size() -1) ) { - // tracetest.printC(tmpFields.get(pos).getField() + ":" + newValue + " "); + // tmptrace.printC(tmpevent.getEventPtr().getLibraryId(), tmpFields.get(pos).getField() + ":" + newValue + " "); //} else { - // tracetest.printlnC(tmpFields.get(pos).getField() + ":" + newValue + " "); + // tmptrace.printlnC(tmpevent.getEventPtr().getLibraryId(), tmpFields.get(pos).getField() + ":" + newValue + " "); //} } } tmpevent = tmptrace.readNextEvent(); nbEvent++; } } System.out.println("NB Events read : " + nbEvent); } catch (Exception e) { e.printStackTrace(); } } }
false
true
public static void main(String[] args) { // Path of the trace final String TRACE_PATH = "/home/william/trace-614601events-nolost-newformat"; // *** Change this to run several time over the same trace final int NB_OF_PASS = 1; // *** Change this to true to parse all the events in the trace // Otherwise, events are just read final boolean PARSE_EVENTS = true; // Work variables JniTrace tmptrace = null; JniEvent tmpevent = null; Long nbEvent = 0L; try { // Get the trace from the Factory... // This assume the path is correct and that the correct version of the lib is installed tmptrace = JniTraceFactory.getJniTrace(TRACE_PATH, false); // Seek beginning tmptrace.seekToTime(new JniTime(0L)); // Run up to "NB_OF_PASS" on the same trace for (int x=0; x<NB_OF_PASS; x++ ){ tmpevent = tmptrace.readNextEvent(); nbEvent++; while ( tmpevent != null ) { // Parse event if asked if ( PARSE_EVENTS ) { ArrayList<JniMarkerField> tmpFields = tmpevent.getMarkersMap().get(tmpevent.getEventMarkerId()).getMarkerFieldsArrayList(); for ( int pos=0; pos<tmpFields.size(); pos++ ) { @SuppressWarnings("unused") Object newValue = tmpevent.parseFieldById(pos); // *** Uncomment the following to print the parsed content // Warning : this is VERY intensive //if ( pos == (tmpFields.size() -1) ) { // tracetest.printC(tmpFields.get(pos).getField() + ":" + newValue + " "); //} else { // tracetest.printlnC(tmpFields.get(pos).getField() + ":" + newValue + " "); //} } } tmpevent = tmptrace.readNextEvent(); nbEvent++; } } System.out.println("NB Events read : " + nbEvent); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { // Path of the trace final String TRACE_PATH = "/home/william/trace-614601events-nolost-newformat"; // *** Change this to run several time over the same trace final int NB_OF_PASS = 1; // *** Change this to true to parse all the events in the trace // Otherwise, events are just read final boolean PARSE_EVENTS = true; // Work variables JniTrace tmptrace = null; JniEvent tmpevent = null; Long nbEvent = 0L; try { // Get the trace from the Factory... // This assume the path is correct and that the correct version of the lib is installed tmptrace = JniTraceFactory.getJniTrace(TRACE_PATH, false); // Seek beginning tmptrace.seekToTime(new JniTime(0L)); // Run up to "NB_OF_PASS" on the same trace for (int x=0; x<NB_OF_PASS; x++ ){ tmpevent = tmptrace.readNextEvent(); nbEvent++; while ( tmpevent != null ) { // Parse event if asked if ( PARSE_EVENTS ) { ArrayList<JniMarkerField> tmpFields = tmpevent.getMarkersMap().get(tmpevent.getEventMarkerId()).getMarkerFieldsArrayList(); for ( int pos=0; pos<tmpFields.size(); pos++ ) { @SuppressWarnings("unused") Object newValue = tmpevent.parseFieldById(pos); // *** Uncomment the following to print the parsed content // Warning : this is VERY intensive //if ( pos == (tmpFields.size() -1) ) { // tmptrace.printC(tmpevent.getEventPtr().getLibraryId(), tmpFields.get(pos).getField() + ":" + newValue + " "); //} else { // tmptrace.printlnC(tmpevent.getEventPtr().getLibraryId(), tmpFields.get(pos).getField() + ":" + newValue + " "); //} } } tmpevent = tmptrace.readNextEvent(); nbEvent++; } } System.out.println("NB Events read : " + nbEvent); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/ForumActivity.java b/UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/ForumActivity.java index a3b1217..a2ab09e 100644 --- a/UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/ForumActivity.java +++ b/UserVoiceSDK/src/com/uservoice/uservoicesdk/activity/ForumActivity.java @@ -1,274 +1,279 @@ package com.uservoice.uservoicesdk.activity; import java.util.ArrayList; import java.util.List; import java.util.Locale; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.SearchView; import android.widget.TextView; import com.uservoice.uservoicesdk.R; import com.uservoice.uservoicesdk.Session; import com.uservoice.uservoicesdk.babayaga.Babayaga; import com.uservoice.uservoicesdk.dialog.SuggestionDialogFragment; import com.uservoice.uservoicesdk.flow.InitManager; import com.uservoice.uservoicesdk.model.Forum; import com.uservoice.uservoicesdk.model.Suggestion; import com.uservoice.uservoicesdk.rest.Callback; import com.uservoice.uservoicesdk.rest.RestResult; import com.uservoice.uservoicesdk.rest.RestTask; import com.uservoice.uservoicesdk.ui.DefaultCallback; import com.uservoice.uservoicesdk.ui.PaginatedAdapter; import com.uservoice.uservoicesdk.ui.PaginationScrollListener; import com.uservoice.uservoicesdk.ui.SearchAdapter; import com.uservoice.uservoicesdk.ui.SearchExpandListener; import com.uservoice.uservoicesdk.ui.SearchQueryListener; public class ForumActivity extends BaseListActivity implements SearchActivity { private List<Suggestion> suggestions; private Forum forum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.uv_feedback_forum); suggestions = new ArrayList<Suggestion>(); getListView().setDivider(null); setListAdapter(new PaginatedAdapter<Suggestion>(this, R.layout.uv_suggestion_item, suggestions) { boolean initializing = true; @Override public void loadMore() { + // Need to notify data set change as initializing flag + // will impact count below + if (initializing) { + notifyDataSetChanged(); + } initializing = false; super.loadMore(); } @Override public int getViewTypeCount() { return super.getViewTypeCount() + 2; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == 2 || super.isEnabled(position); } @Override public int getCount() { return super.getCount() + 2 + (initializing ? 1 : 0); } @Override public int getItemViewType(int position) { if (position == 0) return 2; if (position == 1) return 3; if (position == 2 && initializing) return LOADING; return super.getItemViewType(position - 2); } @Override public Object getItem(int position) { return super.getItem(position - 2); } @Override public View getView(int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); if (type == 2 || type == 3) { View view = convertView; if (view == null) { if (type == 2) { view = getLayoutInflater().inflate(R.layout.uv_text_item, null); TextView text = (TextView) view.findViewById(R.id.uv_text); text.setText(R.string.uv_post_an_idea); view.findViewById(R.id.uv_divider).setVisibility(View.GONE); view.findViewById(R.id.uv_text2).setVisibility(View.GONE); } else if (type == 3) { view = getLayoutInflater().inflate(R.layout.uv_header_item_light, null); TextView text = (TextView) view.findViewById(R.id.uv_header_text); text.setText(R.string.uv_idea_text_heading); } } return view; } else { return super.getView(position, convertView, parent); } } @Override protected void customizeLayout(View view, Suggestion model) { TextView textView = (TextView) view.findViewById(R.id.uv_suggestion_title); textView.setText(model.getTitle()); textView = (TextView) view.findViewById(R.id.uv_subscriber_count); textView.setText(String.valueOf(model.getNumberOfSubscribers())); textView = (TextView) view.findViewById(R.id.uv_suggestion_status); View colorView = view.findViewById(R.id.uv_suggestion_status_color); if (model.getStatus() == null) { textView.setVisibility(View.GONE); colorView.setVisibility(View.GONE); } else { int color = Color.parseColor(model.getStatusColor()); textView.setVisibility(View.VISIBLE); textView.setTextColor(color); textView.setText(model.getStatus().toUpperCase(Locale.getDefault())); colorView.setVisibility(View.VISIBLE); colorView.setBackgroundColor(color); } } @Override public void loadPage(int page, Callback<List<Suggestion>> callback) { Suggestion.loadSuggestions(forum, page, callback); } @Override public RestTask search(final String query, final Callback<List<Suggestion>> callback) { return Suggestion.searchSuggestions(forum, query, new Callback<List<Suggestion>>() { @Override public void onModel(List<Suggestion> model) { Babayaga.track(Babayaga.Event.SEARCH_IDEAS, query, model); callback.onModel(model); } @Override public void onError(RestResult error) { callback.onError(error); } }); } @Override public int getTotalNumberOfObjects() { return forum.getNumberOfOpenSuggestions(); } }); getListView().setOnScrollListener(new PaginationScrollListener(getModelAdapter()) { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (forum != null) super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { startActivity(new Intent(ForumActivity.this, PostIdeaActivity.class)); } else if (position != 1) { Suggestion suggestion = (Suggestion) getModelAdapter().getItem(position); Session.getInstance().setSuggestion(suggestion); SuggestionDialogFragment dialog = new SuggestionDialogFragment(suggestion); dialog.show(getSupportFragmentManager(), "SuggestionDialogFragment"); } } }); new InitManager(this, new Runnable() { @Override public void run() { loadForum(); Session.getInstance().setSignInListener(new Runnable() { @Override public void run() { if (forum != null) { getModelAdapter().reload(); } } }); } }).init(); } @SuppressLint("NewApi") @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.uv_forum, menu); if (hasActionBar()) { menu.findItem(R.id.uv_menu_search).setOnActionExpandListener(new SearchExpandListener(this)); SearchView search = (SearchView) menu.findItem(R.id.uv_menu_search).getActionView(); search.setOnQueryTextListener(new SearchQueryListener(this)); } else { menu.findItem(R.id.uv_menu_search).setVisible(false); } menu.findItem(R.id.uv_new_idea).setVisible(Session.getInstance().getConfig().shouldShowPostIdea()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.uv_new_idea) { startActivity(new Intent(this, PostIdeaActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override protected void onStop() { Session.getInstance().setSignInListener(null); super.onStop(); } private void loadForum() { if (Session.getInstance().getForum() != null) { forum = Session.getInstance().getForum(); Babayaga.track(Babayaga.Event.VIEW_FORUM, forum.getId()); setTitle(forum.getName()); getModelAdapter().loadMore(); return; } Forum.loadForum(Session.getInstance().getConfig().getForumId(), new DefaultCallback<Forum>(this) { @Override public void onModel(Forum model) { Session.getInstance().setForum(model); forum = model; setTitle(forum.getName()); getModelAdapter().loadMore(); } }); } @Override public SearchAdapter<?> getSearchAdapter() { return getModelAdapter(); } @SuppressWarnings("unchecked") public PaginatedAdapter<Suggestion> getModelAdapter() { return (PaginatedAdapter<Suggestion>) getListAdapter(); } @Override public void showSearch() { } @Override public void hideSearch() { } public void suggestionUpdated(Suggestion model) { getModelAdapter().notifyDataSetChanged(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.uv_feedback_forum); suggestions = new ArrayList<Suggestion>(); getListView().setDivider(null); setListAdapter(new PaginatedAdapter<Suggestion>(this, R.layout.uv_suggestion_item, suggestions) { boolean initializing = true; @Override public void loadMore() { initializing = false; super.loadMore(); } @Override public int getViewTypeCount() { return super.getViewTypeCount() + 2; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == 2 || super.isEnabled(position); } @Override public int getCount() { return super.getCount() + 2 + (initializing ? 1 : 0); } @Override public int getItemViewType(int position) { if (position == 0) return 2; if (position == 1) return 3; if (position == 2 && initializing) return LOADING; return super.getItemViewType(position - 2); } @Override public Object getItem(int position) { return super.getItem(position - 2); } @Override public View getView(int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); if (type == 2 || type == 3) { View view = convertView; if (view == null) { if (type == 2) { view = getLayoutInflater().inflate(R.layout.uv_text_item, null); TextView text = (TextView) view.findViewById(R.id.uv_text); text.setText(R.string.uv_post_an_idea); view.findViewById(R.id.uv_divider).setVisibility(View.GONE); view.findViewById(R.id.uv_text2).setVisibility(View.GONE); } else if (type == 3) { view = getLayoutInflater().inflate(R.layout.uv_header_item_light, null); TextView text = (TextView) view.findViewById(R.id.uv_header_text); text.setText(R.string.uv_idea_text_heading); } } return view; } else { return super.getView(position, convertView, parent); } } @Override protected void customizeLayout(View view, Suggestion model) { TextView textView = (TextView) view.findViewById(R.id.uv_suggestion_title); textView.setText(model.getTitle()); textView = (TextView) view.findViewById(R.id.uv_subscriber_count); textView.setText(String.valueOf(model.getNumberOfSubscribers())); textView = (TextView) view.findViewById(R.id.uv_suggestion_status); View colorView = view.findViewById(R.id.uv_suggestion_status_color); if (model.getStatus() == null) { textView.setVisibility(View.GONE); colorView.setVisibility(View.GONE); } else { int color = Color.parseColor(model.getStatusColor()); textView.setVisibility(View.VISIBLE); textView.setTextColor(color); textView.setText(model.getStatus().toUpperCase(Locale.getDefault())); colorView.setVisibility(View.VISIBLE); colorView.setBackgroundColor(color); } } @Override public void loadPage(int page, Callback<List<Suggestion>> callback) { Suggestion.loadSuggestions(forum, page, callback); } @Override public RestTask search(final String query, final Callback<List<Suggestion>> callback) { return Suggestion.searchSuggestions(forum, query, new Callback<List<Suggestion>>() { @Override public void onModel(List<Suggestion> model) { Babayaga.track(Babayaga.Event.SEARCH_IDEAS, query, model); callback.onModel(model); } @Override public void onError(RestResult error) { callback.onError(error); } }); } @Override public int getTotalNumberOfObjects() { return forum.getNumberOfOpenSuggestions(); } }); getListView().setOnScrollListener(new PaginationScrollListener(getModelAdapter()) { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (forum != null) super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { startActivity(new Intent(ForumActivity.this, PostIdeaActivity.class)); } else if (position != 1) { Suggestion suggestion = (Suggestion) getModelAdapter().getItem(position); Session.getInstance().setSuggestion(suggestion); SuggestionDialogFragment dialog = new SuggestionDialogFragment(suggestion); dialog.show(getSupportFragmentManager(), "SuggestionDialogFragment"); } } }); new InitManager(this, new Runnable() { @Override public void run() { loadForum(); Session.getInstance().setSignInListener(new Runnable() { @Override public void run() { if (forum != null) { getModelAdapter().reload(); } } }); } }).init(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.uv_feedback_forum); suggestions = new ArrayList<Suggestion>(); getListView().setDivider(null); setListAdapter(new PaginatedAdapter<Suggestion>(this, R.layout.uv_suggestion_item, suggestions) { boolean initializing = true; @Override public void loadMore() { // Need to notify data set change as initializing flag // will impact count below if (initializing) { notifyDataSetChanged(); } initializing = false; super.loadMore(); } @Override public int getViewTypeCount() { return super.getViewTypeCount() + 2; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == 2 || super.isEnabled(position); } @Override public int getCount() { return super.getCount() + 2 + (initializing ? 1 : 0); } @Override public int getItemViewType(int position) { if (position == 0) return 2; if (position == 1) return 3; if (position == 2 && initializing) return LOADING; return super.getItemViewType(position - 2); } @Override public Object getItem(int position) { return super.getItem(position - 2); } @Override public View getView(int position, View convertView, ViewGroup parent) { int type = getItemViewType(position); if (type == 2 || type == 3) { View view = convertView; if (view == null) { if (type == 2) { view = getLayoutInflater().inflate(R.layout.uv_text_item, null); TextView text = (TextView) view.findViewById(R.id.uv_text); text.setText(R.string.uv_post_an_idea); view.findViewById(R.id.uv_divider).setVisibility(View.GONE); view.findViewById(R.id.uv_text2).setVisibility(View.GONE); } else if (type == 3) { view = getLayoutInflater().inflate(R.layout.uv_header_item_light, null); TextView text = (TextView) view.findViewById(R.id.uv_header_text); text.setText(R.string.uv_idea_text_heading); } } return view; } else { return super.getView(position, convertView, parent); } } @Override protected void customizeLayout(View view, Suggestion model) { TextView textView = (TextView) view.findViewById(R.id.uv_suggestion_title); textView.setText(model.getTitle()); textView = (TextView) view.findViewById(R.id.uv_subscriber_count); textView.setText(String.valueOf(model.getNumberOfSubscribers())); textView = (TextView) view.findViewById(R.id.uv_suggestion_status); View colorView = view.findViewById(R.id.uv_suggestion_status_color); if (model.getStatus() == null) { textView.setVisibility(View.GONE); colorView.setVisibility(View.GONE); } else { int color = Color.parseColor(model.getStatusColor()); textView.setVisibility(View.VISIBLE); textView.setTextColor(color); textView.setText(model.getStatus().toUpperCase(Locale.getDefault())); colorView.setVisibility(View.VISIBLE); colorView.setBackgroundColor(color); } } @Override public void loadPage(int page, Callback<List<Suggestion>> callback) { Suggestion.loadSuggestions(forum, page, callback); } @Override public RestTask search(final String query, final Callback<List<Suggestion>> callback) { return Suggestion.searchSuggestions(forum, query, new Callback<List<Suggestion>>() { @Override public void onModel(List<Suggestion> model) { Babayaga.track(Babayaga.Event.SEARCH_IDEAS, query, model); callback.onModel(model); } @Override public void onError(RestResult error) { callback.onError(error); } }); } @Override public int getTotalNumberOfObjects() { return forum.getNumberOfOpenSuggestions(); } }); getListView().setOnScrollListener(new PaginationScrollListener(getModelAdapter()) { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (forum != null) super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } }); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { startActivity(new Intent(ForumActivity.this, PostIdeaActivity.class)); } else if (position != 1) { Suggestion suggestion = (Suggestion) getModelAdapter().getItem(position); Session.getInstance().setSuggestion(suggestion); SuggestionDialogFragment dialog = new SuggestionDialogFragment(suggestion); dialog.show(getSupportFragmentManager(), "SuggestionDialogFragment"); } } }); new InitManager(this, new Runnable() { @Override public void run() { loadForum(); Session.getInstance().setSignInListener(new Runnable() { @Override public void run() { if (forum != null) { getModelAdapter().reload(); } } }); } }).init(); }
diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsOutboundGatewayParser.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsOutboundGatewayParser.java index 5f455084e2..0be030de0b 100644 --- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsOutboundGatewayParser.java +++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsOutboundGatewayParser.java @@ -1,101 +1,102 @@ /* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.integration.jms.config; import org.w3c.dom.Element; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.ExpressionFactoryBean; import org.springframework.integration.config.xml.AbstractConsumerEndpointParser; import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.springframework.util.StringUtils; /** * Parser for the &lt;outbound-gateway&gt; element of the integration 'jms' namespace. * * @author Mark Fisher * @author Oleg Zhurakousky */ public class JmsOutboundGatewayParser extends AbstractConsumerEndpointParser { @Override protected String getInputChannelAttributeName() { return "request-channel"; } @Override protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( "org.springframework.integration.jms.JmsOutboundGateway"); builder.addPropertyReference("connectionFactory", element.getAttribute("connection-factory")); String requestDestination = element.getAttribute("request-destination"); String requestDestinationName = element.getAttribute("request-destination-name"); String requestDestinationExpression = element.getAttribute("request-destination-expression"); boolean hasRequestDestination = StringUtils.hasText(requestDestination); boolean hasRequestDestinationName = StringUtils.hasText(requestDestinationName); boolean hasRequestDestinationExpression = StringUtils.hasText(requestDestinationExpression); if (!(hasRequestDestination ^ hasRequestDestinationName ^ hasRequestDestinationExpression)) { parserContext.getReaderContext().error("Exactly one of the 'request-destination', " + "'request-destination-name', or 'request-destination-expression' attributes is required.", element); } if (hasRequestDestination) { builder.addPropertyReference("requestDestination", requestDestination); } else if (hasRequestDestinationName) { builder.addPropertyValue("requestDestinationName", requestDestinationName); } else if (hasRequestDestinationExpression) { BeanDefinitionBuilder expressionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class); expressionBuilder.addConstructorArgValue(requestDestinationExpression); builder.addPropertyValue("requestDestinationExpression", expressionBuilder.getBeanDefinition()); } IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-destination"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-destination-name"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "correlation-key"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "message-converter"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "header-mapper"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "destination-resolver"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-request-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-reply-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "receive-timeout"); + IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "send-timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "request-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "time-to-live"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "priority"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-qos-enabled"); String deliveryMode = element.getAttribute("delivery-mode"); String deliveryPersistent = element.getAttribute("delivery-persistent"); if (StringUtils.hasText(deliveryMode) && StringUtils.hasText(deliveryPersistent)) { parserContext.getReaderContext().error( "The 'delivery-mode' and 'delivery-persistent' attributes are mutually exclusive.", element); return null; } if (StringUtils.hasText(deliveryMode)) { parserContext.getReaderContext().warning( "The 'delivery-mode' attribute is deprecated. Use 'delivery-persistent' instead.", element); builder.addPropertyValue("deliveryMode", deliveryMode); } else if (StringUtils.hasText(deliveryPersistent)) { builder.addPropertyValue("deliveryPersistent", deliveryPersistent); } return builder; } }
true
true
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( "org.springframework.integration.jms.JmsOutboundGateway"); builder.addPropertyReference("connectionFactory", element.getAttribute("connection-factory")); String requestDestination = element.getAttribute("request-destination"); String requestDestinationName = element.getAttribute("request-destination-name"); String requestDestinationExpression = element.getAttribute("request-destination-expression"); boolean hasRequestDestination = StringUtils.hasText(requestDestination); boolean hasRequestDestinationName = StringUtils.hasText(requestDestinationName); boolean hasRequestDestinationExpression = StringUtils.hasText(requestDestinationExpression); if (!(hasRequestDestination ^ hasRequestDestinationName ^ hasRequestDestinationExpression)) { parserContext.getReaderContext().error("Exactly one of the 'request-destination', " + "'request-destination-name', or 'request-destination-expression' attributes is required.", element); } if (hasRequestDestination) { builder.addPropertyReference("requestDestination", requestDestination); } else if (hasRequestDestinationName) { builder.addPropertyValue("requestDestinationName", requestDestinationName); } else if (hasRequestDestinationExpression) { BeanDefinitionBuilder expressionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class); expressionBuilder.addConstructorArgValue(requestDestinationExpression); builder.addPropertyValue("requestDestinationExpression", expressionBuilder.getBeanDefinition()); } IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-destination"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-destination-name"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "correlation-key"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "message-converter"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "header-mapper"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "destination-resolver"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-request-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-reply-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "receive-timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "request-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "time-to-live"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "priority"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-qos-enabled"); String deliveryMode = element.getAttribute("delivery-mode"); String deliveryPersistent = element.getAttribute("delivery-persistent"); if (StringUtils.hasText(deliveryMode) && StringUtils.hasText(deliveryPersistent)) { parserContext.getReaderContext().error( "The 'delivery-mode' and 'delivery-persistent' attributes are mutually exclusive.", element); return null; } if (StringUtils.hasText(deliveryMode)) { parserContext.getReaderContext().warning( "The 'delivery-mode' attribute is deprecated. Use 'delivery-persistent' instead.", element); builder.addPropertyValue("deliveryMode", deliveryMode); } else if (StringUtils.hasText(deliveryPersistent)) { builder.addPropertyValue("deliveryPersistent", deliveryPersistent); } return builder; }
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition( "org.springframework.integration.jms.JmsOutboundGateway"); builder.addPropertyReference("connectionFactory", element.getAttribute("connection-factory")); String requestDestination = element.getAttribute("request-destination"); String requestDestinationName = element.getAttribute("request-destination-name"); String requestDestinationExpression = element.getAttribute("request-destination-expression"); boolean hasRequestDestination = StringUtils.hasText(requestDestination); boolean hasRequestDestinationName = StringUtils.hasText(requestDestinationName); boolean hasRequestDestinationExpression = StringUtils.hasText(requestDestinationExpression); if (!(hasRequestDestination ^ hasRequestDestinationName ^ hasRequestDestinationExpression)) { parserContext.getReaderContext().error("Exactly one of the 'request-destination', " + "'request-destination-name', or 'request-destination-expression' attributes is required.", element); } if (hasRequestDestination) { builder.addPropertyReference("requestDestination", requestDestination); } else if (hasRequestDestinationName) { builder.addPropertyValue("requestDestinationName", requestDestinationName); } else if (hasRequestDestinationExpression) { BeanDefinitionBuilder expressionBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionFactoryBean.class); expressionBuilder.addConstructorArgValue(requestDestinationExpression); builder.addPropertyValue("requestDestinationExpression", expressionBuilder.getBeanDefinition()); } IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-destination"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-destination-name"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "correlation-key"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "message-converter"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "header-mapper"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "destination-resolver"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-request-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-reply-payload"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "receive-timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "send-timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "request-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-pub-sub-domain"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "time-to-live"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "priority"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-qos-enabled"); String deliveryMode = element.getAttribute("delivery-mode"); String deliveryPersistent = element.getAttribute("delivery-persistent"); if (StringUtils.hasText(deliveryMode) && StringUtils.hasText(deliveryPersistent)) { parserContext.getReaderContext().error( "The 'delivery-mode' and 'delivery-persistent' attributes are mutually exclusive.", element); return null; } if (StringUtils.hasText(deliveryMode)) { parserContext.getReaderContext().warning( "The 'delivery-mode' attribute is deprecated. Use 'delivery-persistent' instead.", element); builder.addPropertyValue("deliveryMode", deliveryMode); } else if (StringUtils.hasText(deliveryPersistent)) { builder.addPropertyValue("deliveryPersistent", deliveryPersistent); } return builder; }
diff --git a/src/bitronix/tm/Configuration.java b/src/bitronix/tm/Configuration.java index fe3e2fd..f5b674f 100644 --- a/src/bitronix/tm/Configuration.java +++ b/src/bitronix/tm/Configuration.java @@ -1,543 +1,543 @@ package bitronix.tm; import bitronix.tm.utils.PropertyException; import bitronix.tm.utils.PropertyUtils; import bitronix.tm.utils.Service; import bitronix.tm.utils.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.util.Properties; /** * Configuration repository of the transaction manager. You can set configurable values either via the properties file * or by setting properties of the {@link Configuration} object. * Once the transaction manager has started it is not possible to change the configuration: all calls to setters will * throw a {@link IllegalStateException}. * <p>The configuration filename must be specified with the <code>bitronix.tm.configuration</code> system property.</p> * <p>The default settings are good enough for running in a test environment but certainly not for production usage. * Also, all properties are reset to their default value after the transaction manager has shut down.</p> * <p>All those properties can refer to other defined ones or to system properties using the Ant notation: * <code>${some.property.name}</code>.</p> * <p>&copy; Bitronix 2005, 2006, 2007</p> * * @author lorban */ public class Configuration implements Service { private final static Logger log = LoggerFactory.getLogger(Configuration.class); private final static int MAX_SERVER_ID_LENGTH = 51; private String serverId; private byte[] serverIdArray; private String logPart1Filename; private String logPart2Filename; private boolean forcedWriteEnabled; private boolean forceBatchingEnabled; private int maxLogSizeInMb; private boolean filterLogStatus; private boolean skipCorruptedLogs; private boolean asynchronous2Pc; private boolean warnAboutZeroResourceTransaction; private int defaultTransactionTimeout; private int gracefulShutdownInterval; private int backgroundRecoveryInterval; private int retryUnrecoverableResourcesRegistrationInterval; private boolean disableJmx; private String jndiUserTransactionName; private String resourceConfigurationFilename; protected Configuration() { try { InputStream in = null; Properties properties; try { String configurationFilename = System.getProperty("bitronix.tm.configuration"); if (configurationFilename != null) { if (log.isDebugEnabled()) log.debug("loading configuration file " + configurationFilename); in = new FileInputStream(configurationFilename); } else { if (log.isDebugEnabled()) log.debug("loading default configuration"); in = Thread.currentThread().getContextClassLoader().getResourceAsStream("bitronix-default-config.properties"); } properties = new Properties(); if (in != null) properties.load(in); else if (log.isDebugEnabled()) log.debug("no configuration file found, using default settings"); } finally { if (in != null) in.close(); } serverId = getString(properties, "bitronix.tm.serverId", null); logPart1Filename = getString(properties, "bitronix.tm.journal.disk.logPart1Filename", "btm1.tlog"); logPart2Filename = getString(properties, "bitronix.tm.journal.disk.logPart2Filename", "btm2.tlog"); forcedWriteEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forcedWriteEnabled", true); forceBatchingEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forceBatchingEnabled", true); maxLogSizeInMb = getInt(properties, "bitronix.tm.journal.disk.maxLogSize", 2); filterLogStatus = getBoolean(properties, "bitronix.tm.journal.disk.filterLogStatus", false); skipCorruptedLogs = getBoolean(properties, "bitronix.tm.journal.disk.skipCorruptedLogs", false); asynchronous2Pc = getBoolean(properties, "bitronix.tm.2pc.async", false); warnAboutZeroResourceTransaction = getBoolean(properties, "bitronix.tm.2pc.warnAboutZeroResourceTransactions", true); defaultTransactionTimeout = getInt(properties, "bitronix.tm.timer.defaultTransactionTimeout", 60); gracefulShutdownInterval = getInt(properties, "bitronix.tm.timer.gracefulShutdownInterval", 60); backgroundRecoveryInterval = getInt(properties, "bitronix.tm.timer.backgroundRecoveryInterval", 0); retryUnrecoverableResourcesRegistrationInterval = getInt(properties, "bitronix.tm.timer.retryUnrecoverableResourcesRegistrationInterval", 0); disableJmx = getBoolean(properties, "bitronix.tm.disableJmx", false); - jndiUserTransactionName = getString(properties, "bitronix.tm.jndi.jndiUserTransactionName", null); + jndiUserTransactionName = getString(properties, "bitronix.tm.jndi.userTransactionName", null); resourceConfigurationFilename = getString(properties, "bitronix.tm.resource.configuration", null); } catch (IOException ex) { throw new InitializationException("error loading configuration", ex); } } /** * ASCII ID that must uniquely identify this TM instance. It must not exceed 51 characters or it will be truncated. * <p>Property name:<br/><b>bitronix.tm.serverId -</b> <i>(defaults to server's IP address but that's unsafe for * production use)</i></p> * @return the unique ID of this TM instance. */ public String getServerId() { return serverId; } /** * Set the ASCII ID that must uniquely identify this TM instance. It must not exceed 51 characters or it will be * truncated. * @see #getServerId() * @param serverId the unique ID of this TM instance. */ public void setServerId(String serverId) { checkNotStarted(); this.serverId = serverId; } /** * Get the journal fragment file 1 name. * <p>Property name:<br/><b>bitronix.tm.journal.disk.logPart1Filename -</b> <i>(defaults to btm1.tlog)</i></p> * @return the journal fragment file 1 name. */ public String getLogPart1Filename() { return logPart1Filename; } /** * Set the journal fragment file 1 name. * @see #getLogPart1Filename() * @param logPart1Filename the journal fragment file 1 name. */ public void setLogPart1Filename(String logPart1Filename) { checkNotStarted(); this.logPart1Filename = logPart1Filename; } /** * Get the journal fragment file 2 name. * <p>Property name:<br/><b>bitronix.tm.journal.disk.logPart2Filename -</b> <i>(defaults to btm2.tlog)</i></p> * @return the journal fragment file 2 name. */ public String getLogPart2Filename() { return logPart2Filename; } /** * Set the journal fragment file 2 name. * @see #getLogPart2Filename() * @param logPart2Filename the journal fragment file 2 name. */ public void setLogPart2Filename(String logPart2Filename) { checkNotStarted(); this.logPart2Filename = logPart2Filename; } /** * Are logs forced to disk ? Do not set to false in production since without disk force, integrity is not * guaranteed. * <p>Property name:<br/><b>bitronix.tm.journal.disk.forcedWriteEnabled -</b> <i>(defaults to true)</i></p> * @return true if logs are forced to disk, false otherwise. */ public boolean isForcedWriteEnabled() { return forcedWriteEnabled; } /** * Set if logs are forced to disk. Do not set to false in production since without disk force, integrity is not * guaranteed. * @see #isForcedWriteEnabled() * @param forcedWriteEnabled true if logs should be forced to disk, false otherwise. */ public void setForcedWriteEnabled(boolean forcedWriteEnabled) { checkNotStarted(); this.forcedWriteEnabled = forcedWriteEnabled; } /** * Are disk forces batched ? Disabling batching can seriously lower the transaction manager's throughput. * <p>Property name:<br/><b>bitronix.tm.journal.disk.forceBatchingEnabled -</b> <i>(defaults to true)</i></p> * @return true if disk forces are batched, false otherwise. */ public boolean isForceBatchingEnabled() { return forceBatchingEnabled; } /** * Set if disk forces are batched. Disabling batching can seriously lower the transaction manager's throughput. * @see #isForceBatchingEnabled() * @param forceBatchingEnabled true if disk forces are batched, false otherwise. */ public void setForceBatchingEnabled(boolean forceBatchingEnabled) { checkNotStarted(); this.forceBatchingEnabled = forceBatchingEnabled; } /** * Maximum size in megabytes of the journal fragments. Larger logs allow transactions to stay longer in-doubt but * the TM pauses longer when a fragment is full. * <p>Property name:<br/><b>bitronix.tm.journal.disk.maxLogSize -</b> <i>(defaults to 2)</i></p> * @return the maximum size in megabytes of the journal fragments. */ public int getMaxLogSizeInMb() { return maxLogSizeInMb; } /** * Set the Maximum size in megabytes of the journal fragments. Larger logs allow transactions to stay longer * in-doubt but the TM pauses longer when a fragment is full. * @see #getMaxLogSizeInMb() * @param maxLogSizeInMb the maximum size in megabytes of the journal fragments. */ public void setMaxLogSizeInMb(int maxLogSizeInMb) { checkNotStarted(); this.maxLogSizeInMb = maxLogSizeInMb; } /** * Should only mandatory logs be written ? Enabling this parameter lowers space usage of the fragments but makes * debugging more complex. * <p>Property name:<br/><b>bitronix.tm.journal.disk.filterLogStatus -</b> <i>(defaults to false)</i></p> * @return true if only mandatory logs should be written. */ public boolean isFilterLogStatus() { return filterLogStatus; } /** * Set if only mandatory logs should be written. Enabling this parameter lowers space usage of the fragments but * makes debugging more complex. * @see #isFilterLogStatus() * @param filterLogStatus true if only mandatory logs should be written. */ public void setFilterLogStatus(boolean filterLogStatus) { checkNotStarted(); this.filterLogStatus = filterLogStatus; } /** * Should corrupted logs be skipped ? * <p>Property name:<br/><b>bitronix.tm.journal.disk.skipCorruptedLogs -</b> <i>(defaults to false)</i></p> * @return true if corrupted logs should be skipped. */ public boolean isSkipCorruptedLogs() { return skipCorruptedLogs; } /** * Set if corrupted logs should be skipped. * @see #isSkipCorruptedLogs() * @param skipCorruptedLogs true if corrupted logs should be skipped. */ public void setSkipCorruptedLogs(boolean skipCorruptedLogs) { this.skipCorruptedLogs = skipCorruptedLogs; } /** * Should two phase commit be executed asynchronously ? Asynchronous two phase commit can improve performance when * there are many resources enlisted in transactions but is more CPU intensive due to the dynamic thread spawning * requirements. It also makes debugging more complex. * <p>Property name:<br/><b>bitronix.tm.2pc.async -</b> <i>(defaults to false)</i></p> * @return true if two phase commit should be executed asynchronously. */ public boolean isAsynchronous2Pc() { return asynchronous2Pc; } /** * Set if two phase commit should be executed asynchronously. Asynchronous two phase commit can improve performance * when there are many resources enlisted in transactions but is more CPU intensive due to the dynamic thread * spawning requirements. It also makes debugging more complex. * @see #isAsynchronous2Pc() * @param asynchronous2Pc true if two phase commit should be executed asynchronously. */ public void setAsynchronous2Pc(boolean asynchronous2Pc) { checkNotStarted(); this.asynchronous2Pc = asynchronous2Pc; } /** * Should transactions executed without a single enlisted resource result in a warning or not ? Most of the time * transactions executed with no enlisted resource reflect a bug or a mis-configuration somewhere. * <p>Property name:<br/><b>bitronix.tm.2pc.warnAboutZeroResourceTransactions -</b> <i>(defaults to true)</i></p> * @return true if transactions executed without a single enlisted resource should result in a warning. */ public boolean isWarnAboutZeroResourceTransaction() { return warnAboutZeroResourceTransaction; } /** * Set if transactions executed without a single enlisted resource should result in a warning or not. Most of the * time transactions executed with no enlisted resource reflect a bug or a mis-configuration somewhere. * @see #isWarnAboutZeroResourceTransaction() * @param warnAboutZeroResourceTransaction true if transactions executed without a single enlisted resource should * result in a warning. */ public void setWarnAboutZeroResourceTransaction(boolean warnAboutZeroResourceTransaction) { checkNotStarted(); this.warnAboutZeroResourceTransaction = warnAboutZeroResourceTransaction; } /** * Default transaction timeout in seconds. * <p>Property name:<br/><b>bitronix.tm.timer.defaultTransactionTimeout -</b> <i>(defaults to 60)</i></p> * @return the default transaction timeout in seconds. */ public int getDefaultTransactionTimeout() { return defaultTransactionTimeout; } /** * Set the default transaction timeout in seconds. * @see #getDefaultTransactionTimeout() * @param defaultTransactionTimeout the default transaction timeout in seconds. */ public void setDefaultTransactionTimeout(int defaultTransactionTimeout) { checkNotStarted(); this.defaultTransactionTimeout = defaultTransactionTimeout; } /** * Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time. * <p>Property name:<br/><b>bitronix.tm.timer.gracefulShutdownInterval -</b> <i>(defaults to 60)</i></p> * @return the maximum amount of time in seconds. */ public int getGracefulShutdownInterval() { return gracefulShutdownInterval; } /** * Set the maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown * time. * @see #getGracefulShutdownInterval() * @param gracefulShutdownInterval the maximum amount of time in seconds. */ public void setGracefulShutdownInterval(int gracefulShutdownInterval) { checkNotStarted(); this.gracefulShutdownInterval = gracefulShutdownInterval; } /** * Interval in minutes at which to run the recovery process in the background. Disabled when set to 0. * <p>Property name:<br/><b>bitronix.tm.timer.backgroundRecoveryInterval -</b> <i>(defaults to 0)</i></p> * @return the interval in minutes. */ public int getBackgroundRecoveryInterval() { return backgroundRecoveryInterval; } /** * Set the interval in minutes at which to run the recovery process in the background. Disabled when set to 0. * @see #getBackgroundRecoveryInterval() * @param backgroundRecoveryInterval the interval in minutes. */ public void setBackgroundRecoveryInterval(int backgroundRecoveryInterval) { checkNotStarted(); this.backgroundRecoveryInterval = backgroundRecoveryInterval; } /** * Interval in minutes at which to retry unrecoverable resources registration in the background. Disabled when set * to 0. * <p>Property name:<br/><b>bitronix.tm.timer.retryUnrecoverableResourcesRegistrationInterval -</b> * <i>(defaults to 0)</i></p> * @return the interval in minutes. */ public int getRetryUnrecoverableResourcesRegistrationInterval() { return retryUnrecoverableResourcesRegistrationInterval; } /** * Set the interval in minutes at which to retry unrecoverable resources registration in the background. Disabled * when set to 0. * @see #getResourceConfigurationFilename() * @param retryUnrecoverableResourcesRegistrationInterval the interval in minutes. */ public void setRetryUnrecoverableResourcesRegistrationInterval(int retryUnrecoverableResourcesRegistrationInterval) { checkNotStarted(); this.retryUnrecoverableResourcesRegistrationInterval = retryUnrecoverableResourcesRegistrationInterval; } /** * Should JMX Mbeans not be registered even if a JMX MBean server is detected ? * <p>Property name:<br/><b>bitronix.tm.disableJmx -</b> <i>(defaults to false)</i></p> * @return true if JMX MBeans should never be registered. */ public boolean isDisableJmx() { return disableJmx; } /** * Set if JMX Mbeans should not be registered even if a JMX MBean server is detected. * @see #isDisableJmx() * @param disableJmx true if JMX MBeans should never be registered. */ public void setDisableJmx(boolean disableJmx) { this.disableJmx = disableJmx; } /** * Get the name the {@link javax.transaction.UserTransaction} should be bound under in the * {@link bitronix.tm.jndi.BitronixContext}. * @return the name the {@link javax.transaction.UserTransaction} should * be bound under in the {@link bitronix.tm.jndi.BitronixContext}. */ public String getJndiUserTransactionName() { return jndiUserTransactionName; } /** * Set the name the {@link javax.transaction.UserTransaction} should be bound under in the * {@link bitronix.tm.jndi.BitronixContext}. * @see #getJndiUserTransactionName() * @param jndiUserTransactionName the name the {@link javax.transaction.UserTransaction} should * be bound under in the {@link bitronix.tm.jndi.BitronixContext}. */ public void setJndiUserTransactionName(String jndiUserTransactionName) { checkNotStarted(); this.jndiUserTransactionName = jndiUserTransactionName; } /** * {@link bitronix.tm.resource.ResourceLoader} configuration file name. {@link bitronix.tm.resource.ResourceLoader} * will be disabled if this value is null. * <p>Property name:<br/><b>bitronix.tm.resource.configuration -</b> <i>(defaults to null)</i></p> * @return the filename of the resources configuration file or null if not configured. */ public String getResourceConfigurationFilename() { return resourceConfigurationFilename; } /** * Set the {@link bitronix.tm.resource.ResourceLoader} configuration file name. * @see #getResourceConfigurationFilename() * @param resourceConfigurationFilename the filename of the resources configuration file or null you do not want to * use the {@link bitronix.tm.resource.ResourceLoader}. */ public void setResourceConfigurationFilename(String resourceConfigurationFilename) { checkNotStarted(); this.resourceConfigurationFilename = resourceConfigurationFilename; } /** * Build the server ID byte array that will be prepended in generated UIDs. Once built, the value is cached for * the duration of the JVM lifespan. * @return the server ID. */ public byte[] buildServerIdArray() { if (serverIdArray == null) { try { serverIdArray = serverId.substring(0, Math.min(serverId.length(), MAX_SERVER_ID_LENGTH)).getBytes("US-ASCII"); } catch (Exception ex) { log.warn("cannot get this JVM unique ID. Make sure it is configured and you only use ASCII characters. Will use IP address instead (unsafe for production usage!)."); try { serverIdArray = InetAddress.getLocalHost().getHostAddress().getBytes("US-ASCII"); } catch (Exception ex2) { final String unknownServerId = "unknown-server-id"; log.warn("cannot get the local IP address. Will replace it with '" + unknownServerId + "' constant (highly unsafe!)."); serverIdArray = unknownServerId.getBytes(); } } if (serverIdArray.length > MAX_SERVER_ID_LENGTH) { byte[] truncatedServerId = new byte[MAX_SERVER_ID_LENGTH]; System.arraycopy(serverIdArray, 0, truncatedServerId, 0, MAX_SERVER_ID_LENGTH); serverIdArray = truncatedServerId; } log.info("JVM unique ID: <" + new String(serverIdArray) + ">"); } return serverIdArray; } public void shutdown() { } public String toString() { StringBuffer sb = new StringBuffer(512); sb.append("a Configuration with ["); try { sb.append(PropertyUtils.propertiesToString(this)); } catch (PropertyException ex) { sb.append("???"); if (log.isDebugEnabled()) log.debug("error accessing properties of Configuration object", ex); } sb.append("]"); return sb.toString(); } /* * Internal implementation */ private void checkNotStarted() { if (TransactionManagerServices.isTransactionManagerRunning()) throw new IllegalStateException("cannot change the configuration while the transaction manager is running"); } static String getString(Properties properties, String key, String defaultValue) { String value = System.getProperty(key); if (value == null) { value = properties.getProperty(key); if (value == null) return defaultValue; } return evaluate(properties, value); } static boolean getBoolean(Properties properties, String key, boolean defaultValue) { return Boolean.valueOf(getString(properties, key, "" + defaultValue)).booleanValue(); } static int getInt(Properties properties, String key, int defaultValue) { return Integer.parseInt(getString(properties, key, "" + defaultValue)); } private static String evaluate(Properties properties, String value) { String result = value; int startIndex = value.indexOf('$'); if (startIndex > -1 && value.charAt(startIndex +1) == '{') { int endIndex = value.indexOf('}'); if (startIndex +2 == endIndex) throw new IllegalArgumentException("property ref cannot refer to an empty name: ${}"); if (endIndex == -1) throw new IllegalArgumentException("unclosed property ref: ${" + value.substring(startIndex +2)); String subPropertyKey = value.substring(startIndex +2, endIndex); String subPropertyValue = getString(properties, subPropertyKey, null); result = result.substring(0, startIndex) + subPropertyValue + result.substring(endIndex +1); return evaluate(properties, result); } return result; } }
true
true
protected Configuration() { try { InputStream in = null; Properties properties; try { String configurationFilename = System.getProperty("bitronix.tm.configuration"); if (configurationFilename != null) { if (log.isDebugEnabled()) log.debug("loading configuration file " + configurationFilename); in = new FileInputStream(configurationFilename); } else { if (log.isDebugEnabled()) log.debug("loading default configuration"); in = Thread.currentThread().getContextClassLoader().getResourceAsStream("bitronix-default-config.properties"); } properties = new Properties(); if (in != null) properties.load(in); else if (log.isDebugEnabled()) log.debug("no configuration file found, using default settings"); } finally { if (in != null) in.close(); } serverId = getString(properties, "bitronix.tm.serverId", null); logPart1Filename = getString(properties, "bitronix.tm.journal.disk.logPart1Filename", "btm1.tlog"); logPart2Filename = getString(properties, "bitronix.tm.journal.disk.logPart2Filename", "btm2.tlog"); forcedWriteEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forcedWriteEnabled", true); forceBatchingEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forceBatchingEnabled", true); maxLogSizeInMb = getInt(properties, "bitronix.tm.journal.disk.maxLogSize", 2); filterLogStatus = getBoolean(properties, "bitronix.tm.journal.disk.filterLogStatus", false); skipCorruptedLogs = getBoolean(properties, "bitronix.tm.journal.disk.skipCorruptedLogs", false); asynchronous2Pc = getBoolean(properties, "bitronix.tm.2pc.async", false); warnAboutZeroResourceTransaction = getBoolean(properties, "bitronix.tm.2pc.warnAboutZeroResourceTransactions", true); defaultTransactionTimeout = getInt(properties, "bitronix.tm.timer.defaultTransactionTimeout", 60); gracefulShutdownInterval = getInt(properties, "bitronix.tm.timer.gracefulShutdownInterval", 60); backgroundRecoveryInterval = getInt(properties, "bitronix.tm.timer.backgroundRecoveryInterval", 0); retryUnrecoverableResourcesRegistrationInterval = getInt(properties, "bitronix.tm.timer.retryUnrecoverableResourcesRegistrationInterval", 0); disableJmx = getBoolean(properties, "bitronix.tm.disableJmx", false); jndiUserTransactionName = getString(properties, "bitronix.tm.jndi.jndiUserTransactionName", null); resourceConfigurationFilename = getString(properties, "bitronix.tm.resource.configuration", null); } catch (IOException ex) { throw new InitializationException("error loading configuration", ex); } }
protected Configuration() { try { InputStream in = null; Properties properties; try { String configurationFilename = System.getProperty("bitronix.tm.configuration"); if (configurationFilename != null) { if (log.isDebugEnabled()) log.debug("loading configuration file " + configurationFilename); in = new FileInputStream(configurationFilename); } else { if (log.isDebugEnabled()) log.debug("loading default configuration"); in = Thread.currentThread().getContextClassLoader().getResourceAsStream("bitronix-default-config.properties"); } properties = new Properties(); if (in != null) properties.load(in); else if (log.isDebugEnabled()) log.debug("no configuration file found, using default settings"); } finally { if (in != null) in.close(); } serverId = getString(properties, "bitronix.tm.serverId", null); logPart1Filename = getString(properties, "bitronix.tm.journal.disk.logPart1Filename", "btm1.tlog"); logPart2Filename = getString(properties, "bitronix.tm.journal.disk.logPart2Filename", "btm2.tlog"); forcedWriteEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forcedWriteEnabled", true); forceBatchingEnabled = getBoolean(properties, "bitronix.tm.journal.disk.forceBatchingEnabled", true); maxLogSizeInMb = getInt(properties, "bitronix.tm.journal.disk.maxLogSize", 2); filterLogStatus = getBoolean(properties, "bitronix.tm.journal.disk.filterLogStatus", false); skipCorruptedLogs = getBoolean(properties, "bitronix.tm.journal.disk.skipCorruptedLogs", false); asynchronous2Pc = getBoolean(properties, "bitronix.tm.2pc.async", false); warnAboutZeroResourceTransaction = getBoolean(properties, "bitronix.tm.2pc.warnAboutZeroResourceTransactions", true); defaultTransactionTimeout = getInt(properties, "bitronix.tm.timer.defaultTransactionTimeout", 60); gracefulShutdownInterval = getInt(properties, "bitronix.tm.timer.gracefulShutdownInterval", 60); backgroundRecoveryInterval = getInt(properties, "bitronix.tm.timer.backgroundRecoveryInterval", 0); retryUnrecoverableResourcesRegistrationInterval = getInt(properties, "bitronix.tm.timer.retryUnrecoverableResourcesRegistrationInterval", 0); disableJmx = getBoolean(properties, "bitronix.tm.disableJmx", false); jndiUserTransactionName = getString(properties, "bitronix.tm.jndi.userTransactionName", null); resourceConfigurationFilename = getString(properties, "bitronix.tm.resource.configuration", null); } catch (IOException ex) { throw new InitializationException("error loading configuration", ex); } }
diff --git a/src/main/java/net/sf/jooreports/opendocument/OpenDocumentIO.java b/src/main/java/net/sf/jooreports/opendocument/OpenDocumentIO.java index 2152bd4..0752bae 100644 --- a/src/main/java/net/sf/jooreports/opendocument/OpenDocumentIO.java +++ b/src/main/java/net/sf/jooreports/opendocument/OpenDocumentIO.java @@ -1,111 +1,112 @@ package net.sf.jooreports.opendocument; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Set; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; public class OpenDocumentIO { public static final Charset UTF_8 = Charset.forName("UTF-8"); public static InputStreamReader toUtf8Reader(InputStream inputStream) { return new InputStreamReader(inputStream, UTF_8); } public static OutputStreamWriter toUtf8Writer(OutputStream outputStream) { return new OutputStreamWriter(outputStream, UTF_8); } public static OpenDocumentArchive readZip(InputStream inputStream) throws IOException { OpenDocumentArchive archive = new OpenDocumentArchive(); ZipInputStream zipInputStream = new ZipInputStream(inputStream); while (true) { ZipEntry zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { break; } OutputStream entryOutputStream = archive.getEntryOutputStream(zipEntry.getName()); IOUtils.copy(zipInputStream, entryOutputStream); entryOutputStream.close(); zipInputStream.closeEntry(); } zipInputStream.close(); return archive; } public static OpenDocumentArchive readDirectory(File directory) throws IOException { if (!(directory.isDirectory() && directory.canRead())) { throw new IllegalArgumentException("not a readable directory: " + directory); } OpenDocumentArchive archive = new OpenDocumentArchive(); readSubDirectory(directory, "", archive); return archive; } private static void readSubDirectory(File subDirectory, String parentName, OpenDocumentArchive archive) throws IOException { String[] fileNames = subDirectory.list(); for (int i = 0; i < fileNames.length; i++) { File file = new File(subDirectory, fileNames[i]); String relativeName = parentName + fileNames[i]; if (file.isDirectory()) { readSubDirectory(file, relativeName + "/", archive); } else { InputStream fileInputStream = new FileInputStream(file); OutputStream entryOutputStream = archive.getEntryOutputStream(relativeName); IOUtils.copy(fileInputStream, entryOutputStream); entryOutputStream.close(); fileInputStream.close(); } } } public static void writeZip(OpenDocumentArchive archive, OutputStream outputStream) throws IOException { ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream); Set entryNames = archive.getEntryNames(); // OpenDocument spec requires 'mimetype' to be the first entry writeZipEntry(zipOutputStream, archive, "mimetype", ZipEntry.STORED); for (Iterator it = entryNames.iterator(); it.hasNext();) { String entryName = (String) it.next(); if (!"mimetype".equals(entryName)) { writeZipEntry(zipOutputStream, archive, entryName, ZipEntry.DEFLATED); } } zipOutputStream.close(); } private static void writeZipEntry(ZipOutputStream zipOutputStream, OpenDocumentArchive archive, String entryName, int method) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); - zipOutputStream.putNextEntry(zipEntry); InputStream entryInputStream = archive.getEntryInputStream(entryName); zipEntry.setMethod(method); if (method == ZipEntry.STORED) { byte[] inputBytes = IOUtils.toByteArray(entryInputStream); CRC32 crc = new CRC32(); crc.update(inputBytes); zipEntry.setCrc(crc.getValue()); zipEntry.setSize(inputBytes.length); zipEntry.setCompressedSize(inputBytes.length); + zipOutputStream.putNextEntry(zipEntry); IOUtils.write(inputBytes, zipOutputStream); } else { + zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(entryInputStream, zipOutputStream); } IOUtils.closeQuietly(entryInputStream); zipOutputStream.closeEntry(); } }
false
true
private static void writeZipEntry(ZipOutputStream zipOutputStream, OpenDocumentArchive archive, String entryName, int method) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); zipOutputStream.putNextEntry(zipEntry); InputStream entryInputStream = archive.getEntryInputStream(entryName); zipEntry.setMethod(method); if (method == ZipEntry.STORED) { byte[] inputBytes = IOUtils.toByteArray(entryInputStream); CRC32 crc = new CRC32(); crc.update(inputBytes); zipEntry.setCrc(crc.getValue()); zipEntry.setSize(inputBytes.length); zipEntry.setCompressedSize(inputBytes.length); IOUtils.write(inputBytes, zipOutputStream); } else { IOUtils.copy(entryInputStream, zipOutputStream); } IOUtils.closeQuietly(entryInputStream); zipOutputStream.closeEntry(); }
private static void writeZipEntry(ZipOutputStream zipOutputStream, OpenDocumentArchive archive, String entryName, int method) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); InputStream entryInputStream = archive.getEntryInputStream(entryName); zipEntry.setMethod(method); if (method == ZipEntry.STORED) { byte[] inputBytes = IOUtils.toByteArray(entryInputStream); CRC32 crc = new CRC32(); crc.update(inputBytes); zipEntry.setCrc(crc.getValue()); zipEntry.setSize(inputBytes.length); zipEntry.setCompressedSize(inputBytes.length); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(inputBytes, zipOutputStream); } else { zipOutputStream.putNextEntry(zipEntry); IOUtils.copy(entryInputStream, zipOutputStream); } IOUtils.closeQuietly(entryInputStream); zipOutputStream.closeEntry(); }
diff --git a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java index da0b244f..c27832e3 100644 --- a/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java +++ b/CubicRecorder/src/main/java/org/cubictest/recorder/ui/RecordEditorAction.java @@ -1,182 +1,182 @@ /* * This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE * Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html */ package org.cubictest.recorder.ui; import org.cubictest.common.utils.ErrorHandler; import org.cubictest.common.utils.UserInfo; import org.cubictest.export.exceptions.ExporterException; import org.cubictest.export.utils.exported.ExportUtils; import org.cubictest.exporters.selenium.ui.RunSeleniumRunnerAction; import org.cubictest.model.ExtensionPoint; import org.cubictest.model.ExtensionStartPoint; import org.cubictest.model.ExtensionTransition; import org.cubictest.model.Page; import org.cubictest.model.SubTest; import org.cubictest.model.SubTestStartPoint; import org.cubictest.model.Test; import org.cubictest.model.Transition; import org.cubictest.model.UrlStartPoint; import org.cubictest.recorder.CubicRecorder; import org.cubictest.recorder.GUIAwareRecorder; import org.cubictest.recorder.IRecorder; import org.cubictest.recorder.selenium.SeleniumRecorder; import org.cubictest.ui.gef.interfaces.exported.IDisposeListener; import org.cubictest.ui.gef.interfaces.exported.ITestEditor; import org.cubictest.ui.gef.layout.AutoLayout; import org.eclipse.core.resources.IResource; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; /** * Action for starting / stopping the CubicRecorder. * */ public class RecordEditorAction implements IEditorActionDelegate { IResource currentFile; private boolean running; private SeleniumRecorder seleniumRecorder; private ITestEditor testEditor; public RecordEditorAction() { super(); } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { AutoLayout autoLayout = new AutoLayout(testEditor); Test test = testEditor.getTest(); if (test.getStartPoint() instanceof SubTestStartPoint) { ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. "); return; } test.resetStatus(); if(!running) { setRunning(true); if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) { ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" + "Tip: Create a new test and record from there."); return; //ModelUtil should show error message. } IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout); IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder); seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt()); testEditor.addDisposeListener(new IDisposeListener() { public void disposed() { stopSelenium(null); } }); try { new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder); if (test.getStartPoint() instanceof ExtensionStartPoint) { ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" + "Press OK to continue."); //play forward to extension start point long now = System.currentTimeMillis(); while (!seleniumRecorder.isSeleniumStarted()) { if (System.currentTimeMillis() > now + (35 * 1000)) { throw new ExporterException("Timeout waiting for Selenium to start"); } //wait for selenium (server & test system) to start Thread.yield(); Thread.sleep(100); } RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction(); runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open)."); runner.setShowCompletedMessageInStatusLine(true); runner.setStopSeleniumWhenFinished(false); runner.setSelenium(seleniumRecorder.getSelenium()); - runner.setTest(((SubTest) test.getStartPoint()).getTest(true)); + runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true)); if (test.getStartPoint().getOutTransitions().size() == 0) { ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point."); } ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint(); runner.setTargetExtensionPoint(targetExPoint); runner.run(action); } cubicRecorder.setEnabled(true); guiAwareRecorder.setEnabled(true); } catch (Exception e) { ErrorHandler.logAndShowErrorDialog(e); stopSelenium(autoLayout); UserInfo.setStatusLine(null); return; } } else { UserInfo.setStatusLine(null); stopSelenium(autoLayout); } } private void stopSelenium(AutoLayout autoLayout) { try { setRunning(false); if (seleniumRecorder != null) { seleniumRecorder.stop(); } if (autoLayout != null) { autoLayout.setPageSelected(null); } } catch(Exception e) { ErrorHandler.logAndRethrow(e); } } /** * @see IActionDelegate#selectionChanged(IAction, ISelection) */ public void selectionChanged(IAction action, ISelection selection) {} public void setActiveEditor(IAction action, IEditorPart targetEditor) { this.testEditor = (ITestEditor) targetEditor; } private void setRunning(boolean run) { running = run; } /** * Get the initial URL start point of the test (expands subtests). */ private UrlStartPoint getInitialUrlStartPoint(Test test) { if (test.getStartPoint() instanceof UrlStartPoint) { return (UrlStartPoint) test.getStartPoint(); } else { //ExtensionStartPoint, get url start point recursively: return getInitialUrlStartPoint(((ExtensionStartPoint) test.getStartPoint()).getTest(true)); } } public boolean firstPageIsEmpty(Test test) { for(Transition t : test.getStartPoint().getOutTransitions()) { if(t.getEnd() instanceof Page && ((Page)t.getEnd()).getElements().size() == 0) { return true; } } return false; } }
true
true
public void run(IAction action) { AutoLayout autoLayout = new AutoLayout(testEditor); Test test = testEditor.getTest(); if (test.getStartPoint() instanceof SubTestStartPoint) { ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. "); return; } test.resetStatus(); if(!running) { setRunning(true); if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) { ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" + "Tip: Create a new test and record from there."); return; //ModelUtil should show error message. } IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout); IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder); seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt()); testEditor.addDisposeListener(new IDisposeListener() { public void disposed() { stopSelenium(null); } }); try { new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder); if (test.getStartPoint() instanceof ExtensionStartPoint) { ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" + "Press OK to continue."); //play forward to extension start point long now = System.currentTimeMillis(); while (!seleniumRecorder.isSeleniumStarted()) { if (System.currentTimeMillis() > now + (35 * 1000)) { throw new ExporterException("Timeout waiting for Selenium to start"); } //wait for selenium (server & test system) to start Thread.yield(); Thread.sleep(100); } RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction(); runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open)."); runner.setShowCompletedMessageInStatusLine(true); runner.setStopSeleniumWhenFinished(false); runner.setSelenium(seleniumRecorder.getSelenium()); runner.setTest(((SubTest) test.getStartPoint()).getTest(true)); if (test.getStartPoint().getOutTransitions().size() == 0) { ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point."); } ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint(); runner.setTargetExtensionPoint(targetExPoint); runner.run(action); } cubicRecorder.setEnabled(true); guiAwareRecorder.setEnabled(true); } catch (Exception e) { ErrorHandler.logAndShowErrorDialog(e); stopSelenium(autoLayout); UserInfo.setStatusLine(null); return; } } else { UserInfo.setStatusLine(null); stopSelenium(autoLayout); } }
public void run(IAction action) { AutoLayout autoLayout = new AutoLayout(testEditor); Test test = testEditor.getTest(); if (test.getStartPoint() instanceof SubTestStartPoint) { ErrorHandler.logAndShowErrorDialog("It is not possible to record from tests that start with a SubTest start point. "); return; } test.resetStatus(); if(!running) { setRunning(true); if (test.getStartPoint() instanceof ExtensionStartPoint && test.getStartPoint().getOutTransitions().size() >= 1 && !firstPageIsEmpty(test)) { ErrorHandler.showWarnDialog("Could not record from extension start point, as test is not empty.\n\n" + "Tip: Create a new test and record from there."); return; //ModelUtil should show error message. } IRecorder cubicRecorder = new CubicRecorder(test, testEditor.getCommandStack(), autoLayout); IRecorder guiAwareRecorder = new GUIAwareRecorder(cubicRecorder); seleniumRecorder = new SeleniumRecorder(guiAwareRecorder, getInitialUrlStartPoint(test).getBeginAt()); testEditor.addDisposeListener(new IDisposeListener() { public void disposed() { stopSelenium(null); } }); try { new ProgressMonitorDialog(new Shell()).run(false, false, seleniumRecorder); if (test.getStartPoint() instanceof ExtensionStartPoint) { ErrorHandler.showInfoDialog("Test browser will be forwarded to start point for test." + "\n" + "Press OK to continue."); //play forward to extension start point long now = System.currentTimeMillis(); while (!seleniumRecorder.isSeleniumStarted()) { if (System.currentTimeMillis() > now + (35 * 1000)) { throw new ExporterException("Timeout waiting for Selenium to start"); } //wait for selenium (server & test system) to start Thread.yield(); Thread.sleep(100); } RunSeleniumRunnerAction runner = new RunSeleniumRunnerAction(); runner.setCustomCompletedMessage("Test browser forwarded. Result: $result. Recording can begin (test browser is open)."); runner.setShowCompletedMessageInStatusLine(true); runner.setStopSeleniumWhenFinished(false); runner.setSelenium(seleniumRecorder.getSelenium()); runner.setPreSelectedTest(((SubTest) test.getStartPoint()).getTest(true)); if (test.getStartPoint().getOutTransitions().size() == 0) { ErrorHandler.logAndShowErrorDialogAndThrow("To start recording, the test must have at least one page connected to the start point."); } ExtensionPoint targetExPoint = ((ExtensionTransition) test.getStartPoint().getOutTransitions().get(0)).getExtensionPoint(); runner.setTargetExtensionPoint(targetExPoint); runner.run(action); } cubicRecorder.setEnabled(true); guiAwareRecorder.setEnabled(true); } catch (Exception e) { ErrorHandler.logAndShowErrorDialog(e); stopSelenium(autoLayout); UserInfo.setStatusLine(null); return; } } else { UserInfo.setStatusLine(null); stopSelenium(autoLayout); } }
diff --git a/server-vertx/src/main/java/org/jboss/aerogear/simplepush/vertx/UserAgentReaper.java b/server-vertx/src/main/java/org/jboss/aerogear/simplepush/vertx/UserAgentReaper.java index 8b3d197..f26af71 100644 --- a/server-vertx/src/main/java/org/jboss/aerogear/simplepush/vertx/UserAgentReaper.java +++ b/server-vertx/src/main/java/org/jboss/aerogear/simplepush/vertx/UserAgentReaper.java @@ -1,45 +1,45 @@ package org.jboss.aerogear.simplepush.vertx; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentMap; import org.vertx.java.core.Handler; import org.vertx.java.core.logging.Logger; import org.vertx.java.platform.Verticle; public class UserAgentReaper extends Verticle { @Override public void start() { final Logger logger = container.logger(); final Long reaperTimeout = container.config().getLong("reaperTimeout", 300000); logger.info("Started UserAgent Reaper with timeout of [" + reaperTimeout + "]"); final ConcurrentMap<String, Long> lastAccessedMap = vertx.sharedData().getMap(VertxSimplePushServer.LAST_ACCESSED_MAP); - final ConcurrentMap<String, Long> writeHandlerMap = vertx.sharedData().getMap(VertxSimplePushServer.WRITE_HANDLER_MAP); + final ConcurrentMap<String, String> writeHandlerMap = vertx.sharedData().getMap(VertxSimplePushServer.WRITE_HANDLER_MAP); vertx.setPeriodic(reaperTimeout, new Handler<Long>() { @Override public void handle(final Long timerId) { logger.info("UserAgentReaper reaping...."); final Set<String> markedForRemoval = new HashSet<String>(); final Set<Entry<String, Long>> entrySet = lastAccessedMap.entrySet(); for (Entry<String, Long> entry : entrySet) { final String uaid = entry.getKey(); final Long timestamp = entry.getValue(); final long now = System.currentTimeMillis(); if (timestamp + reaperTimeout < now) { markedForRemoval.add(uaid); vertx.eventBus().send(VertxSimplePushServer.USER_AGENT_REMOVER, uaid); } } for (String uaid : markedForRemoval) { lastAccessedMap.remove(uaid); writeHandlerMap.remove(uaid); } } }); } }
true
true
public void start() { final Logger logger = container.logger(); final Long reaperTimeout = container.config().getLong("reaperTimeout", 300000); logger.info("Started UserAgent Reaper with timeout of [" + reaperTimeout + "]"); final ConcurrentMap<String, Long> lastAccessedMap = vertx.sharedData().getMap(VertxSimplePushServer.LAST_ACCESSED_MAP); final ConcurrentMap<String, Long> writeHandlerMap = vertx.sharedData().getMap(VertxSimplePushServer.WRITE_HANDLER_MAP); vertx.setPeriodic(reaperTimeout, new Handler<Long>() { @Override public void handle(final Long timerId) { logger.info("UserAgentReaper reaping...."); final Set<String> markedForRemoval = new HashSet<String>(); final Set<Entry<String, Long>> entrySet = lastAccessedMap.entrySet(); for (Entry<String, Long> entry : entrySet) { final String uaid = entry.getKey(); final Long timestamp = entry.getValue(); final long now = System.currentTimeMillis(); if (timestamp + reaperTimeout < now) { markedForRemoval.add(uaid); vertx.eventBus().send(VertxSimplePushServer.USER_AGENT_REMOVER, uaid); } } for (String uaid : markedForRemoval) { lastAccessedMap.remove(uaid); writeHandlerMap.remove(uaid); } } }); }
public void start() { final Logger logger = container.logger(); final Long reaperTimeout = container.config().getLong("reaperTimeout", 300000); logger.info("Started UserAgent Reaper with timeout of [" + reaperTimeout + "]"); final ConcurrentMap<String, Long> lastAccessedMap = vertx.sharedData().getMap(VertxSimplePushServer.LAST_ACCESSED_MAP); final ConcurrentMap<String, String> writeHandlerMap = vertx.sharedData().getMap(VertxSimplePushServer.WRITE_HANDLER_MAP); vertx.setPeriodic(reaperTimeout, new Handler<Long>() { @Override public void handle(final Long timerId) { logger.info("UserAgentReaper reaping...."); final Set<String> markedForRemoval = new HashSet<String>(); final Set<Entry<String, Long>> entrySet = lastAccessedMap.entrySet(); for (Entry<String, Long> entry : entrySet) { final String uaid = entry.getKey(); final Long timestamp = entry.getValue(); final long now = System.currentTimeMillis(); if (timestamp + reaperTimeout < now) { markedForRemoval.add(uaid); vertx.eventBus().send(VertxSimplePushServer.USER_AGENT_REMOVER, uaid); } } for (String uaid : markedForRemoval) { lastAccessedMap.remove(uaid); writeHandlerMap.remove(uaid); } } }); }
diff --git a/GUI/sec01/ex04/PropertyDialog.java b/GUI/sec01/ex04/PropertyDialog.java index e938725..fad6406 100644 --- a/GUI/sec01/ex04/PropertyDialog.java +++ b/GUI/sec01/ex04/PropertyDialog.java @@ -1,253 +1,254 @@ package sec01.ex04; import java.awt.*; import java.awt.event.*; public class PropertyDialog extends Frame implements ActionListener{ private static final long serialVersionUID = 1L; private static final int NORMAL_LABEL_FONT_SIZE = 15; private GridBagLayout gbl = new GridBagLayout(); public static String buFont = PropertyData.font; // �o�b�t�@�p public static int buFontSize = PropertyData.fontSize; // �o�b�t�@�p public static String buColor = PropertyData.color; // �o�b�t�@�p public static String buBackgroundColor = PropertyData.backgroundColor; // �o�b�t�@�p private Choice fontChoice; private Choice sizeChoice; private Choice colorChoice; private Choice backgroundColorChoice; private static Label preview; public PropertyDialog() { setTitle("Property dialog"); setSize(560, 200); setLocationRelativeTo(null); setResizable(false); setLayout(gbl); PropertyData.load(); // ���x���̔z�u Label fontLabel = new Label("Font"); Label sizeLabel = new Label("Font size"); Label colorLabel = new Label("Color"); Label backgroundColorLabel = new Label("Background color"); fontLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); sizeLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); colorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); backgroundColorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); addLabel(fontLabel, 0, 0, 1, 1); addLabel(sizeLabel, 0, 1, 1, 1); addLabel(colorLabel, 0, 2, 1, 1); addLabel(backgroundColorLabel, 0, 3, 1, 1); // ���j���[�{�b�N�X�̔z�u fontChoice = new Choice(); sizeChoice = new Choice(); colorChoice = new Choice(); backgroundColorChoice = new Choice(); setFontChoice(fontChoice); setSizeChoice(sizeChoice); setColorChoice(colorChoice); setColorChoice(backgroundColorChoice); addChoice(fontChoice, 1, 0, 3, 1); addChoice(sizeChoice, 1, 1, 1, 1); addChoice(colorChoice, 1, 2, 1, 1); addChoice(backgroundColorChoice, 1, 3, 1, 1); // �{�^���̔z�u Button okButton = new Button("OK"); Button cancelButton = new Button("Cancel"); okButton.addActionListener(this); cancelButton.addActionListener(this); addButton(okButton, 3, 4, 1, 1); addButton(cancelButton, 4, 4, 1, 1); // ���X�i�[�̒lj� fontChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFont = PropertyData.fonts[cho.getSelectedIndex()]; Font f = new Font(buFont, Font.PLAIN, 35); PropertyDialog.preview.setFont(f); + PropertyDialog.preview.setText("Preview"); } }); sizeChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFontSize = PropertyData.sizes[cho.getSelectedIndex()]; } }); colorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); backgroundColorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buBackgroundColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); preview = new Label("Preview", Label.CENTER); Font f = new Font(buFont, Font.PLAIN, 35); preview.setFont(f); preview.setBackground(Color.LIGHT_GRAY); preview.setForeground(Color.DARK_GRAY); addPreviewLabel(preview, 2, 2, 2, 2); Label memo = new Label("��For font", Label.CENTER); - Font memoFont = new Font("Casual", Font.BOLD, 20); + Font memoFont = new Font("Arial Black", Font.BOLD, 20); memo.setFont(memoFont); addLabel(memo, 2, 1, 1, 1); //�~�������ꂽ�Ƃ��̏��� addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); } }); } public void load() { reloadPropertyData(); this.setVisible(true); } private void setFontChoice(Choice ch) { String[] fonts = PropertyData.fonts; for(int i = 0; i < fonts.length; i++){ ch.addItem(fonts[i]); } } private void setSizeChoice(Choice ch) { int[] sizes = PropertyData.sizes; for(int i = 0; i < sizes.length; i++){ ch.addItem(Integer.toString(sizes[i])); } } private void setColorChoice(Choice ch) { ch.addItem("Black"); ch.addItem("Red"); ch.addItem("Blue"); ch.addItem("Cyan"); ch.addItem("DarkGray"); ch.addItem("Gray"); ch.addItem("Green"); ch.addItem("LightGray"); ch.addItem("Magenta"); ch.addItem("Orange"); ch.addItem("Pink"); ch.addItem("White"); ch.addItem("Yellow"); } private void addLabel(Label label, int x, int y, int w, int h) { GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; gbc.anchor = GridBagConstraints.EAST; gbc.insets = new Insets(5, 5, 5, 5); gbl.setConstraints(label, gbc); add(label); } private void addPreviewLabel(Label label, int x, int y, int w, int h) { GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = h; gbc.anchor = GridBagConstraints.EAST; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(5, 5, 5, 5); gbl.setConstraints(label, gbc); add(label); } private void addChoice(Choice choice, int x, int y, int w, int h) { GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(5, 5, 5, 5); gbl.setConstraints(choice, gbc); add(choice); } private void addButton(Button button, int x, int y, int w, int h) { GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.weightx = 100.0; gbc.weighty = 100.0; gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; gbc.anchor = GridBagConstraints.SOUTHWEST; gbc.insets = new Insets(5, 5, 5, 5); gbl.setConstraints(button, gbc); add(button); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == "OK") { setPropertyData(); repaint(); setVisible(false); } else if (e.getActionCommand() == "Cancel") { setVisible(false); } } private void setPropertyData() { PropertyData.setData(buFont, buFontSize, buColor, buBackgroundColor); } private void reloadPropertyData() { buFont = PropertyData.font; buFontSize = PropertyData.fontSize; buColor = PropertyData.color; buBackgroundColor = PropertyData.backgroundColor; resetComboBoxSelectedItem(); } private void resetComboBoxSelectedItem() { fontChoice.select(PropertyData.font); Integer size = PropertyData.fontSize; sizeChoice.select(size.toString()); colorChoice.select(PropertyData.color); backgroundColorChoice.select(PropertyData.backgroundColor); } }
false
true
public PropertyDialog() { setTitle("Property dialog"); setSize(560, 200); setLocationRelativeTo(null); setResizable(false); setLayout(gbl); PropertyData.load(); // ���x���̔z�u Label fontLabel = new Label("Font"); Label sizeLabel = new Label("Font size"); Label colorLabel = new Label("Color"); Label backgroundColorLabel = new Label("Background color"); fontLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); sizeLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); colorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); backgroundColorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); addLabel(fontLabel, 0, 0, 1, 1); addLabel(sizeLabel, 0, 1, 1, 1); addLabel(colorLabel, 0, 2, 1, 1); addLabel(backgroundColorLabel, 0, 3, 1, 1); // ���j���[�{�b�N�X�̔z�u fontChoice = new Choice(); sizeChoice = new Choice(); colorChoice = new Choice(); backgroundColorChoice = new Choice(); setFontChoice(fontChoice); setSizeChoice(sizeChoice); setColorChoice(colorChoice); setColorChoice(backgroundColorChoice); addChoice(fontChoice, 1, 0, 3, 1); addChoice(sizeChoice, 1, 1, 1, 1); addChoice(colorChoice, 1, 2, 1, 1); addChoice(backgroundColorChoice, 1, 3, 1, 1); // �{�^���̔z�u Button okButton = new Button("OK"); Button cancelButton = new Button("Cancel"); okButton.addActionListener(this); cancelButton.addActionListener(this); addButton(okButton, 3, 4, 1, 1); addButton(cancelButton, 4, 4, 1, 1); // ���X�i�[�̒lj� fontChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFont = PropertyData.fonts[cho.getSelectedIndex()]; Font f = new Font(buFont, Font.PLAIN, 35); PropertyDialog.preview.setFont(f); } }); sizeChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFontSize = PropertyData.sizes[cho.getSelectedIndex()]; } }); colorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); backgroundColorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buBackgroundColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); preview = new Label("Preview", Label.CENTER); Font f = new Font(buFont, Font.PLAIN, 35); preview.setFont(f); preview.setBackground(Color.LIGHT_GRAY); preview.setForeground(Color.DARK_GRAY); addPreviewLabel(preview, 2, 2, 2, 2); Label memo = new Label("��For font", Label.CENTER); Font memoFont = new Font("Casual", Font.BOLD, 20); memo.setFont(memoFont); addLabel(memo, 2, 1, 1, 1); //�~�������ꂽ�Ƃ��̏��� addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); } }); }
public PropertyDialog() { setTitle("Property dialog"); setSize(560, 200); setLocationRelativeTo(null); setResizable(false); setLayout(gbl); PropertyData.load(); // ���x���̔z�u Label fontLabel = new Label("Font"); Label sizeLabel = new Label("Font size"); Label colorLabel = new Label("Color"); Label backgroundColorLabel = new Label("Background color"); fontLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); sizeLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); colorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); backgroundColorLabel.setFont(new Font("Arial", Font.PLAIN, NORMAL_LABEL_FONT_SIZE)); addLabel(fontLabel, 0, 0, 1, 1); addLabel(sizeLabel, 0, 1, 1, 1); addLabel(colorLabel, 0, 2, 1, 1); addLabel(backgroundColorLabel, 0, 3, 1, 1); // ���j���[�{�b�N�X�̔z�u fontChoice = new Choice(); sizeChoice = new Choice(); colorChoice = new Choice(); backgroundColorChoice = new Choice(); setFontChoice(fontChoice); setSizeChoice(sizeChoice); setColorChoice(colorChoice); setColorChoice(backgroundColorChoice); addChoice(fontChoice, 1, 0, 3, 1); addChoice(sizeChoice, 1, 1, 1, 1); addChoice(colorChoice, 1, 2, 1, 1); addChoice(backgroundColorChoice, 1, 3, 1, 1); // �{�^���̔z�u Button okButton = new Button("OK"); Button cancelButton = new Button("Cancel"); okButton.addActionListener(this); cancelButton.addActionListener(this); addButton(okButton, 3, 4, 1, 1); addButton(cancelButton, 4, 4, 1, 1); // ���X�i�[�̒lj� fontChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFont = PropertyData.fonts[cho.getSelectedIndex()]; Font f = new Font(buFont, Font.PLAIN, 35); PropertyDialog.preview.setFont(f); PropertyDialog.preview.setText("Preview"); } }); sizeChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buFontSize = PropertyData.sizes[cho.getSelectedIndex()]; } }); colorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); backgroundColorChoice.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { Choice cho = (Choice)e.getItemSelectable(); PropertyDialog.buBackgroundColor = PropertyData.strColors[cho.getSelectedIndex()]; } }); preview = new Label("Preview", Label.CENTER); Font f = new Font(buFont, Font.PLAIN, 35); preview.setFont(f); preview.setBackground(Color.LIGHT_GRAY); preview.setForeground(Color.DARK_GRAY); addPreviewLabel(preview, 2, 2, 2, 2); Label memo = new Label("��For font", Label.CENTER); Font memoFont = new Font("Arial Black", Font.BOLD, 20); memo.setFont(memoFont); addLabel(memo, 2, 1, 1, 1); //�~�������ꂽ�Ƃ��̏��� addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); } }); }
diff --git a/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java b/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java index 95d1cef7..d5590f48 100644 --- a/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java +++ b/src/main/java/org/codehaus/gmavenplus/mojo/ExecuteMojo.java @@ -1,127 +1,128 @@ /* * Copyright (C) 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.gmavenplus.mojo; import com.google.common.io.Closer; import org.codehaus.gmavenplus.util.ReflectionUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; /** * Executes Groovy scripts (in the pom or external). * * @author Keegan Witt * * @goal execute */ public class ExecuteMojo extends AbstractGroovyMojo { /** * Groovy scripts to run (in order). Can be an actual Groovy script or a * {@link java.net.URL URL} to a Groovy script (local or remote). * * @parameter * @required */ protected String[] scripts; /** * Whether to continue executing remaining scripts when a script fails. * * @parameter default-value="false" */ protected boolean continueExecuting; /** * The encoding of script files. * * @parameter default-value="${project.build.sourceEncoding}" */ protected String sourceEncoding; /** * Executes this mojo. * * @throws MojoExecutionException If an unexpected problem occurs. Throwing this exception causes a "BUILD ERROR" message to be displayed * @throws MojoFailureException If an expected problem (such as a compilation failure) occurs. Throwing this exception causes a "BUILD FAILURE" message to be displayed */ public void execute() throws MojoExecutionException, MojoFailureException { logGroovyVersion("execute"); try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); + ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "project", project); // TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { logGroovyVersion("execute"); try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); // TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } }
public void execute() throws MojoExecutionException, MojoFailureException { logGroovyVersion("execute"); try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); // create a GroovyShell to run scripts in Object shell = ReflectionUtils.invokeConstructor(ReflectionUtils.findConstructor(groovyShellClass)); ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "setProperty", String.class, Object.class), shell, "project", project); // TODO: load runtime project dependencies onto classpath before executing so they can be used in scripts? // run the scripts int scriptNum = 1; for (String script : scripts) { Closer closer = Closer.create(); try { try { URL url = new URL(script); // it's a URL to a script getLog().info("Fetching Groovy script from " + url.toString() + "."); BufferedReader reader = closer.register(new BufferedReader(new InputStreamReader(url.openStream(), sourceEncoding))); StringBuilder scriptSource = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { scriptSource.append(line).append("\n"); } if (!scriptSource.toString().isEmpty()) { ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, scriptSource.toString()); } } catch (MalformedURLException e) { // it's not a URL to a script, treat as a script body ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(groovyShellClass, "evaluate", String.class), shell, script); } catch (Throwable throwable) { throw closer.rethrow(throwable); } finally { closer.close(); } } catch (IOException ioe) { if (continueExecuting) { getLog().error("An Exception occurred while executing script " + scriptNum + ". Continuing to execute remaining scripts.", ioe); } else { throw new MojoExecutionException("An Exception occurred while executing script " + scriptNum + ".", ioe); } } scriptNum++; } } catch (ClassNotFoundException e) { throw new MojoExecutionException("Unable to get a Groovy class from classpath. Do you have Groovy as a compile dependency in your project?", e); } catch (InvocationTargetException e) { throw new MojoExecutionException("Error occurred while calling a method on a Groovy class from classpath.", e); } catch (InstantiationException e) { throw new MojoExecutionException("Error occurred while instantiating a Groovy class from classpath.", e); } catch (IllegalAccessException e) { throw new MojoExecutionException("Unable to access a method on a Groovy class from classpath.", e); } }
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecReducer.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecReducer.java index 8b526baa..28fc9658 100644 --- a/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecReducer.java +++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecReducer.java @@ -1,270 +1,270 @@ /** * 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.hive.ql.exec; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryUsage; import java.net.URLClassLoader; import java.util.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.util.ReflectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.plan.mapredWork; import org.apache.hadoop.hive.ql.plan.tableDesc; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.exec.ExecMapper.reportStats; import org.apache.hadoop.hive.serde2.Deserializer; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.io.ByteWritable; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Writable; public class ExecReducer extends MapReduceBase implements Reducer { private JobConf jc; private OutputCollector<?,?> oc; private Operator<?> reducer; private Reporter rp; private boolean abort = false; private boolean isTagged = false; private long cntr = 0; private long nextCntr = 1; private static String [] fieldNames; public static final Log l4j = LogFactory.getLog("ExecReducer"); // used to log memory usage periodically private MemoryMXBean memoryMXBean; // TODO: move to DynamicSerDe when it's ready private Deserializer inputKeyDeserializer; // Input value serde needs to be an array to support different SerDe // for different tags private SerDe[] inputValueDeserializer = new SerDe[Byte.MAX_VALUE]; static { ArrayList<String> fieldNameArray = new ArrayList<String> (); for(Utilities.ReduceField r: Utilities.ReduceField.values()) { fieldNameArray.add(r.toString()); } fieldNames = fieldNameArray.toArray(new String [0]); } tableDesc keyTableDesc; tableDesc[] valueTableDesc; public void configure(JobConf job) { ObjectInspector[] rowObjectInspector = new ObjectInspector[Byte.MAX_VALUE]; ObjectInspector[] valueObjectInspector = new ObjectInspector[Byte.MAX_VALUE]; ObjectInspector keyObjectInspector; // Allocate the bean at the beginning - memoryMXBean = ManagementFactory.getMemoryMXBean(); l4j.info("maximum memory = " + memoryMXBean.getHeapMemoryUsage().getMax()); try { l4j.info("conf classpath = " + Arrays.asList(((URLClassLoader)job.getClassLoader()).getURLs())); l4j.info("thread classpath = " + Arrays.asList(((URLClassLoader)Thread.currentThread().getContextClassLoader()).getURLs())); } catch (Exception e) { l4j.info("cannot get classpath: " + e.getMessage()); } jc = job; mapredWork gWork = Utilities.getMapRedWork(job); reducer = gWork.getReducer(); reducer.setParentOperators(null); // clear out any parents as reducer is the root isTagged = gWork.getNeedsTagging(); try { keyTableDesc = gWork.getKeyDesc(); inputKeyDeserializer = (SerDe)ReflectionUtils.newInstance(keyTableDesc.getDeserializerClass(), null); inputKeyDeserializer.initialize(null, keyTableDesc.getProperties()); keyObjectInspector = inputKeyDeserializer.getObjectInspector(); valueTableDesc = new tableDesc[gWork.getTagToValueDesc().size()]; for(int tag=0; tag<gWork.getTagToValueDesc().size(); tag++) { // We should initialize the SerDe with the TypeInfo when available. valueTableDesc[tag] = gWork.getTagToValueDesc().get(tag); inputValueDeserializer[tag] = (SerDe)ReflectionUtils.newInstance(valueTableDesc[tag].getDeserializerClass(), null); inputValueDeserializer[tag].initialize(null, valueTableDesc[tag].getProperties()); valueObjectInspector[tag] = inputValueDeserializer[tag].getObjectInspector(); ArrayList<ObjectInspector> ois = new ArrayList<ObjectInspector>(); ois.add(keyObjectInspector); ois.add(valueObjectInspector[tag]); ois.add(PrimitiveObjectInspectorFactory.writableByteObjectInspector); rowObjectInspector[tag] = ObjectInspectorFactory.getStandardStructObjectInspector( Arrays.asList(fieldNames), ois); } } catch (Exception e) { throw new RuntimeException(e); } //initialize reduce operator tree try { l4j.info(reducer.dump(0)); reducer.initialize(jc, rowObjectInspector); } catch (Throwable e) { abort = true; if (e instanceof OutOfMemoryError) { // Don't create a new object if we are already out of memory throw (OutOfMemoryError) e; } else { throw new RuntimeException ("Reduce operator initialization failed", e); } } } private Object keyObject; private Object[] valueObject = new Object[Byte.MAX_VALUE]; private BytesWritable groupKey; ArrayList<Object> row = new ArrayList<Object>(3); ByteWritable tag = new ByteWritable(); public void reduce(Object key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { if(oc == null) { // propagete reporter and output collector to all operators oc = output; rp = reporter; reducer.setOutputCollector(oc); reducer.setReporter(rp); } try { BytesWritable keyWritable = (BytesWritable)key; tag.set((byte)0); if (isTagged) { // remove the tag int size = keyWritable.getSize() - 1; tag.set(keyWritable.get()[size]); keyWritable.setSize(size); } if (!keyWritable.equals(groupKey)) { // If a operator wants to do some work at the beginning of a group if (groupKey == null) { groupKey = new BytesWritable(); } else { // If a operator wants to do some work at the end of a group l4j.trace("End Group"); reducer.endGroup(); } groupKey.set(keyWritable.get(), 0, keyWritable.getSize()); l4j.trace("Start Group"); reducer.startGroup(); } try { keyObject = inputKeyDeserializer.deserialize(keyWritable); } catch (Exception e) { throw new HiveException("Unable to deserialize reduce input key from " + Utilities.formatBinaryString(keyWritable.get(), 0, keyWritable.getSize()) + " with properties " + keyTableDesc.getProperties(), e); } // System.err.print(keyObject.toString()); while (values.hasNext()) { BytesWritable valueWritable = (BytesWritable) values.next(); //System.err.print(who.getHo().toString()); try { valueObject[tag.get()] = inputValueDeserializer[tag.get()].deserialize(valueWritable); } catch (SerDeException e) { throw new HiveException("Unable to deserialize reduce input value (tag=" + tag.get() + ") from " + - Utilities.formatBinaryString(valueWritable.getBytes(), 0, valueWritable.getLength()) + Utilities.formatBinaryString(valueWritable.get(), 0, valueWritable.getSize()) + " with properties " + valueTableDesc[tag.get()].getProperties(), e); } row.clear(); row.add(keyObject); row.add(valueObject[tag.get()]); // The tag is not used any more, we should remove it. row.add(tag); if (l4j.isInfoEnabled()) { cntr++; if (cntr == nextCntr) { long used_memory = memoryMXBean.getHeapMemoryUsage().getUsed(); l4j.info("ExecReducer: processing " + cntr + " rows: used memory = " + used_memory); nextCntr = getNextCntr(cntr); } } reducer.process(row, tag.get()); } } catch (Throwable e) { abort = true; if (e instanceof OutOfMemoryError) { // Don't create a new object if we are already out of memory throw (OutOfMemoryError) e; } else { throw new IOException (e); } } } private long getNextCntr(long cntr) { // A very simple counter to keep track of number of rows processed by the reducer. It dumps // every 1 million times, and quickly before that if (cntr >= 1000000) return cntr + 1000000; return 10 * cntr; } public void close() { // No row was processed if(oc == null) { l4j.trace("Close called no row"); } try { if (groupKey != null) { // If a operator wants to do some work at the end of a group l4j.trace("End Group"); reducer.endGroup(); } if (l4j.isInfoEnabled()) { l4j.info("ExecReducer: processed " + cntr + " rows: used memory = " + memoryMXBean.getHeapMemoryUsage().getUsed()); } reducer.close(abort); reportStats rps = new reportStats (rp); reducer.preorderMap(rps); return; } catch (Exception e) { if(!abort) { // signal new failure to map-reduce l4j.error("Hit error while closing operators - failing tree"); throw new RuntimeException ("Error while closing operators: " + e.getMessage(), e); } } } }
true
true
public void reduce(Object key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { if(oc == null) { // propagete reporter and output collector to all operators oc = output; rp = reporter; reducer.setOutputCollector(oc); reducer.setReporter(rp); } try { BytesWritable keyWritable = (BytesWritable)key; tag.set((byte)0); if (isTagged) { // remove the tag int size = keyWritable.getSize() - 1; tag.set(keyWritable.get()[size]); keyWritable.setSize(size); } if (!keyWritable.equals(groupKey)) { // If a operator wants to do some work at the beginning of a group if (groupKey == null) { groupKey = new BytesWritable(); } else { // If a operator wants to do some work at the end of a group l4j.trace("End Group"); reducer.endGroup(); } groupKey.set(keyWritable.get(), 0, keyWritable.getSize()); l4j.trace("Start Group"); reducer.startGroup(); } try { keyObject = inputKeyDeserializer.deserialize(keyWritable); } catch (Exception e) { throw new HiveException("Unable to deserialize reduce input key from " + Utilities.formatBinaryString(keyWritable.get(), 0, keyWritable.getSize()) + " with properties " + keyTableDesc.getProperties(), e); } // System.err.print(keyObject.toString()); while (values.hasNext()) { BytesWritable valueWritable = (BytesWritable) values.next(); //System.err.print(who.getHo().toString()); try { valueObject[tag.get()] = inputValueDeserializer[tag.get()].deserialize(valueWritable); } catch (SerDeException e) { throw new HiveException("Unable to deserialize reduce input value (tag=" + tag.get() + ") from " + Utilities.formatBinaryString(valueWritable.getBytes(), 0, valueWritable.getLength()) + " with properties " + valueTableDesc[tag.get()].getProperties(), e); } row.clear(); row.add(keyObject); row.add(valueObject[tag.get()]); // The tag is not used any more, we should remove it. row.add(tag); if (l4j.isInfoEnabled()) { cntr++; if (cntr == nextCntr) { long used_memory = memoryMXBean.getHeapMemoryUsage().getUsed(); l4j.info("ExecReducer: processing " + cntr + " rows: used memory = " + used_memory); nextCntr = getNextCntr(cntr); } } reducer.process(row, tag.get()); } } catch (Throwable e) { abort = true; if (e instanceof OutOfMemoryError) { // Don't create a new object if we are already out of memory throw (OutOfMemoryError) e; } else { throw new IOException (e); } } }
public void reduce(Object key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { if(oc == null) { // propagete reporter and output collector to all operators oc = output; rp = reporter; reducer.setOutputCollector(oc); reducer.setReporter(rp); } try { BytesWritable keyWritable = (BytesWritable)key; tag.set((byte)0); if (isTagged) { // remove the tag int size = keyWritable.getSize() - 1; tag.set(keyWritable.get()[size]); keyWritable.setSize(size); } if (!keyWritable.equals(groupKey)) { // If a operator wants to do some work at the beginning of a group if (groupKey == null) { groupKey = new BytesWritable(); } else { // If a operator wants to do some work at the end of a group l4j.trace("End Group"); reducer.endGroup(); } groupKey.set(keyWritable.get(), 0, keyWritable.getSize()); l4j.trace("Start Group"); reducer.startGroup(); } try { keyObject = inputKeyDeserializer.deserialize(keyWritable); } catch (Exception e) { throw new HiveException("Unable to deserialize reduce input key from " + Utilities.formatBinaryString(keyWritable.get(), 0, keyWritable.getSize()) + " with properties " + keyTableDesc.getProperties(), e); } // System.err.print(keyObject.toString()); while (values.hasNext()) { BytesWritable valueWritable = (BytesWritable) values.next(); //System.err.print(who.getHo().toString()); try { valueObject[tag.get()] = inputValueDeserializer[tag.get()].deserialize(valueWritable); } catch (SerDeException e) { throw new HiveException("Unable to deserialize reduce input value (tag=" + tag.get() + ") from " + Utilities.formatBinaryString(valueWritable.get(), 0, valueWritable.getSize()) + " with properties " + valueTableDesc[tag.get()].getProperties(), e); } row.clear(); row.add(keyObject); row.add(valueObject[tag.get()]); // The tag is not used any more, we should remove it. row.add(tag); if (l4j.isInfoEnabled()) { cntr++; if (cntr == nextCntr) { long used_memory = memoryMXBean.getHeapMemoryUsage().getUsed(); l4j.info("ExecReducer: processing " + cntr + " rows: used memory = " + used_memory); nextCntr = getNextCntr(cntr); } } reducer.process(row, tag.get()); } } catch (Throwable e) { abort = true; if (e instanceof OutOfMemoryError) { // Don't create a new object if we are already out of memory throw (OutOfMemoryError) e; } else { throw new IOException (e); } } }
diff --git a/Test.java b/Test.java index 1d7ccc8..f2866a8 100644 --- a/Test.java +++ b/Test.java @@ -1,71 +1,73 @@ /** Test.java * * Base class for deriving test classes. A derived test class commonly * contains concrete <code>name()</code>, <code>plan()</code> and * <code>test()</code> methods producing, respectively, the name of the test * class, the planned number of tests, and the results of running the tests * themselves. * * The method <code>ok(boolean, String)</code> defined in this class is used * every time a test is performed by the derived class. That is, a derived * class that plans five tests (say) will also call the <code>ok</code> * method five times. * * Copyright 2005-2006 Jonathan Alvarsson, Carl Masak */ public abstract class Test { protected int testsRun = 0; protected int successfulTests = 0; protected String name; protected int testsPlanned; public Test( String name, int testsPlanned ) { this.name = name; this.testsPlanned = testsPlanned; } private void nextTest() { System.out.printf( "%03d - ", ++this.testsRun ); } public void ok( boolean success, String description ) { nextTest(); if (success) { ++this.successfulTests; System.out.println("[ ok ] " + description.toLowerCase()); } else { System.out.println("[NOT OK] " + description.toLowerCase()); } } public void ok( boolean success ) { ok( success, "" ); } public void test() { runTests(); if (testsRun != testsPlanned) System.out.printf( "Warning: %d tests planned but %d run.\n", testsPlanned, testsRun ); System.out.printf( "%d tests successful (%d%%)", - successfulTests, 100*successfulTests/testsPlanned ); + successfulTests, + (int)(100.0*successfulTests/testsPlanned + .5) ); if (successfulTests < testsRun) System.out.printf( ", %d failed (%d%%)", testsRun-successfulTests, - 100*(testsRun-successfulTests)/testsPlanned ); + (int)(100.0*(testsRun-successfulTests) + / testsPlanned + .5) ); System.out.println( "." ); } protected abstract void runTests(); }
false
true
public void test() { runTests(); if (testsRun != testsPlanned) System.out.printf( "Warning: %d tests planned but %d run.\n", testsPlanned, testsRun ); System.out.printf( "%d tests successful (%d%%)", successfulTests, 100*successfulTests/testsPlanned ); if (successfulTests < testsRun) System.out.printf( ", %d failed (%d%%)", testsRun-successfulTests, 100*(testsRun-successfulTests)/testsPlanned ); System.out.println( "." ); }
public void test() { runTests(); if (testsRun != testsPlanned) System.out.printf( "Warning: %d tests planned but %d run.\n", testsPlanned, testsRun ); System.out.printf( "%d tests successful (%d%%)", successfulTests, (int)(100.0*successfulTests/testsPlanned + .5) ); if (successfulTests < testsRun) System.out.printf( ", %d failed (%d%%)", testsRun-successfulTests, (int)(100.0*(testsRun-successfulTests) / testsPlanned + .5) ); System.out.println( "." ); }
diff --git a/okapi/connectors/microsoft/src/main/java/net/sf/okapi/connectors/microsoft/ApacheHttpClientForMT.java b/okapi/connectors/microsoft/src/main/java/net/sf/okapi/connectors/microsoft/ApacheHttpClientForMT.java index 35b7ef6a1..262d83b36 100644 --- a/okapi/connectors/microsoft/src/main/java/net/sf/okapi/connectors/microsoft/ApacheHttpClientForMT.java +++ b/okapi/connectors/microsoft/src/main/java/net/sf/okapi/connectors/microsoft/ApacheHttpClientForMT.java @@ -1,148 +1,148 @@ /*=========================================================================== Copyright (C) 2012 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.connectors.microsoft; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class ApacheHttpClientForMT { private static final boolean USEHTTPCLIENT = true; public static String getAzureAccessToken(String sUral, String sClientID, String sEcret) { if (USEHTTPCLIENT) { return getExpensiveAzureAccessToken(sUral, sClientID, sEcret); } else { return getCheapAzureAccessToken(sUral, sClientID, sEcret); } } public static String getExpensiveAzureAccessToken(String sUral, String sClientID, String sEcret) { String sResult=null; HttpClient client=null; UrlEncodedFormEntity uefe; try { client = new DefaultHttpClient(); HttpPost post = new HttpPost(sUral); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials")); nameValuePairs.add(new BasicNameValuePair("client_id", sClientID)); nameValuePairs.add(new BasicNameValuePair("client_secret", sEcret)); nameValuePairs.add(new BasicNameValuePair("scope", "http://api.microsofttranslator.com")); uefe = new UrlEncodedFormEntity(nameValuePairs); sResult = fromInputStreamToString(uefe.getContent(),"UTF-8"); sResult = ""; post.setEntity(uefe); HttpResponse response = client.execute(post); if ( response != null ) { BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { sResult += line; } } } catch ( Exception e ) { int i = 1; i = i + 1; } return sResult; } public static String getCheapAzureAccessToken (String sUral, String sClientID, String sEcret) { String sResult=null; // String sStuff=null; // String sAddress; String sContent; HttpURLConnection conn; // sAddress = String.format(sUral); URL url; try { sContent = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s", - sClientID,URLEncoder.encode(sEcret),"http://api.microsofttranslator.com"); + sClientID,URLEncoder.encode(sEcret,"UTF-8"),"http://api.microsofttranslator.com"); url = new URL(sUral); conn = (HttpURLConnection)url.openConnection(); conn.addRequestProperty("Content-Type", "text/xml"); // conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1"); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter osw = null; // osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(sContent); int code = conn.getResponseCode(); if (code==200) sResult = fromInputStreamToString(conn.getInputStream(), "UTF-8"); } catch ( MalformedURLException e ) { return sResult; } catch ( UnsupportedEncodingException e ) { return sResult; } catch ( IOException e ) { return sResult; } return sResult; } static private String fromInputStreamToString (InputStream stream, String encoding) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(stream, encoding)); StringBuilder sb = new StringBuilder(); String line = null; while ( (line = br.readLine()) != null ) { sb.append(line + "\n"); } br.close(); return sb.toString(); } }
true
true
public static String getCheapAzureAccessToken (String sUral, String sClientID, String sEcret) { String sResult=null; // String sStuff=null; // String sAddress; String sContent; HttpURLConnection conn; // sAddress = String.format(sUral); URL url; try { sContent = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s", sClientID,URLEncoder.encode(sEcret),"http://api.microsofttranslator.com"); url = new URL(sUral); conn = (HttpURLConnection)url.openConnection(); conn.addRequestProperty("Content-Type", "text/xml"); // conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1"); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter osw = null; // osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(sContent); int code = conn.getResponseCode(); if (code==200) sResult = fromInputStreamToString(conn.getInputStream(), "UTF-8"); } catch ( MalformedURLException e ) { return sResult; } catch ( UnsupportedEncodingException e ) { return sResult; } catch ( IOException e ) { return sResult; } return sResult; }
public static String getCheapAzureAccessToken (String sUral, String sClientID, String sEcret) { String sResult=null; // String sStuff=null; // String sAddress; String sContent; HttpURLConnection conn; // sAddress = String.format(sUral); URL url; try { sContent = String.format("grant_type=client_credentials&client_id=%s&client_secret=%s&scope=%s", sClientID,URLEncoder.encode(sEcret,"UTF-8"),"http://api.microsofttranslator.com"); url = new URL(sUral); conn = (HttpURLConnection)url.openConnection(); conn.addRequestProperty("Content-Type", "text/xml"); // conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1"); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); OutputStreamWriter osw = null; // osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(sContent); int code = conn.getResponseCode(); if (code==200) sResult = fromInputStreamToString(conn.getInputStream(), "UTF-8"); } catch ( MalformedURLException e ) { return sResult; } catch ( UnsupportedEncodingException e ) { return sResult; } catch ( IOException e ) { return sResult; } return sResult; }
diff --git a/src/GUI/NewOperations.java b/src/GUI/NewOperations.java index dd06882..eb658b7 100644 --- a/src/GUI/NewOperations.java +++ b/src/GUI/NewOperations.java @@ -1,1009 +1,1009 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GUI; import static GUI.MainWindow.Black; import static GUI.MainWindow.Gray; import controller.Controller; import deliver.Deliver; import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * * @author NasK */ public class NewOperations extends javax.swing.JDialog { private Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons2/cog.png")); //<editor-fold defaultstate="collapsed" desc=" Nombres del los jTextFields "> private String SINTAX_ORDER = "SINTAX_ORDER"; private String EXEC_COMMAND = "EXEC_COMMAND"; private String SINTAX_COMMAND = "SINTAX_COMMAND"; private String SINTAX_OPERATION_1 = "SINTAX_OPERATION"; private String SINTAX_OPERATION_2 = "SINTAX_OPERATION"; private String BASIC_PROCESS = "BASIC_PROCESS"; private String NEW_PROCESS = "NEW_PROCESS"; private String SINTAX_ASSOC = "SINTAX_ASSOC"; //</editor-fold> private JOptionPane Err = new JOptionPane(); private JOptionPane Info = new JOptionPane(); /** * Creates new form NewOperations */ public NewOperations(javax.swing.JFrame frame) { initComponents(); MyinitComponents(frame); } /** * 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 Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); orderFormat = new javax.swing.JTextField(); orderFormatInsert = new javax.swing.JButton(); orderFormatInfo = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); commandFormatExe = new javax.swing.JTextField(); commandFormatExeInsert = new javax.swing.JButton(); commandFormatExeInfo = new javax.swing.JButton(); commandFormatSintax = new javax.swing.JTextField(); commandFormatSintaxInsert = new javax.swing.JButton(); commandFormatSintaxInfo = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); concatOperationSintax = new javax.swing.JTextField(); concatOperationSintaxInsert = new javax.swing.JButton(); concatOperationSintaxInfo = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); compAsigOperationSintax = new javax.swing.JTextField(); compAsigOperationSintaxInsert = new javax.swing.JButton(); compAsigOperationSintaxInfo = new javax.swing.JButton(); jSeparator4 = new javax.swing.JSeparator(); basicProcessingFormat = new javax.swing.JTextField(); basicProcessingFormatInsert = new javax.swing.JButton(); basicProcessingFormatInfo = new javax.swing.JButton(); newProcessingFormat = new javax.swing.JTextField(); newProcessingFormatInsert = new javax.swing.JButton(); newProcessingFormatInfo = new javax.swing.JButton(); jSeparator5 = new javax.swing.JSeparator(); associationFormat = new javax.swing.JTextField(); associationFormatInsert = new javax.swing.JButton(); associationFormatInfo = new javax.swing.JButton(); jSeparator6 = new javax.swing.JSeparator(); closeButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setLocationByPlatform(true); setMaximumSize(new java.awt.Dimension(1000, 1000)); setPreferredSize(new java.awt.Dimension(606, 260)); setResizable(false); jSplitPane1.setDividerLocation(295); jSplitPane1.setEnabled(false); jPanel1.setPreferredSize(new java.awt.Dimension(270, 45)); orderFormat.setText("X_ORDEN_SINTAX"); orderFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatActionPerformed(evt); } }); orderFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { orderFormatFocusLost(evt); } public void focusGained(java.awt.event.FocusEvent evt) { orderFormatFocusGained(evt); } }); orderFormatInsert.setText("Insert"); orderFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInsertActionPerformed(evt); } }); orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N orderFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInfoActionPerformed(evt); } }); commandFormatExe.setText("C_EJECUTA_COMANDO"); commandFormatExe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeActionPerformed(evt); } }); commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatExeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatExeFocusLost(evt); } }); commandFormatExeInsert.setText("Insert"); commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInsertActionPerformed(evt); } }); commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInfoActionPerformed(evt); } }); commandFormatSintax.setText("C_SINTAXIS_COMANDO"); commandFormatSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxActionPerformed(evt); } }); commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusLost(evt); } }); commandFormatSintaxInsert.setText("Insert"); commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInsertActionPerformed(evt); } }); commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInfoActionPerformed(evt); } }); concatOperationSintax.setText("X_OPERACION_SINTAX"); concatOperationSintax.setToolTipText("ADDITION-CONCATENATION"); concatOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxActionPerformed(evt); } }); concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusLost(evt); } }); concatOperationSintaxInsert.setText("Insert"); concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInsertActionPerformed(evt); } }); concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInfoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator3) .addComponent(jSeparator2) .addComponent(jSeparator1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 2, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(orderFormatInsert)) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatExeInsert)) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatSintaxInsert)) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(concatOperationSintaxInsert) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) - .addContainerGap(62, Short.MAX_VALUE)) + .addContainerGap(40, Short.MAX_VALUE)) ); jSplitPane1.setLeftComponent(jPanel1); jPanel2.setPreferredSize(new java.awt.Dimension(270, 45)); compAsigOperationSintax.setText("X_OPERACION_SINTAX"); compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT"); compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxActionPerformed(evt); } }); compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusLost(evt); } }); compAsigOperationSintaxInsert.setText("Insert"); compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInsertActionPerformed(evt); } }); compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInfoActionPerformed(evt); } }); basicProcessingFormat.setText("_TRATAR_BASICO"); basicProcessingFormat.setToolTipText("LOGIC AND"); basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatActionPerformed(evt); } }); basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusLost(evt); } }); basicProcessingFormatInsert.setText("Insert"); basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInsertActionPerformed(evt); } }); basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInfoActionPerformed(evt); } }); newProcessingFormat.setText("_TRATAR_NUEVO"); newProcessingFormat.setToolTipText("LOGIC OPERATION"); newProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatActionPerformed(evt); } }); newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { newProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { newProcessingFormatFocusLost(evt); } }); newProcessingFormatInsert.setText("Insert"); newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInsertActionPerformed(evt); } }); newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInfoActionPerformed(evt); } }); associationFormat.setText("X_ASOCIAR_SINTAX"); associationFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatActionPerformed(evt); } }); associationFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { associationFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { associationFormatFocusLost(evt); } }); associationFormatInsert.setText("Insert"); associationFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInsertActionPerformed(evt); } }); associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N associationFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInfoActionPerformed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator4) .addComponent(jSeparator5) .addComponent(jSeparator6) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(closeButton) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(compAsigOperationSintaxInsert)) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(basicProcessingFormatInsert)) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(newProcessingFormatInsert)) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(associationFormatInsert)) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) - .addContainerGap(33, Short.MAX_VALUE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jSplitPane1.setRightComponent(jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 590, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) - .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents //<editor-fold defaultstate="collapsed" desc=" MyinitComponents "> private void MyinitComponents(javax.swing.JFrame frame) { setIconImage(icon); this.setTitle("New Operations"); this.setModal(true); this.setLocationRelativeTo(frame); Deliver.setOrigin(this); Deliver.setDestination(frame); orderFormat.setForeground(Gray); commandFormatExe.setForeground(Gray); commandFormatSintax.setForeground(Gray); concatOperationSintax.setForeground(Gray); compAsigOperationSintax.setForeground(Gray); basicProcessingFormat.setForeground(Gray); newProcessingFormat.setForeground(Gray); associationFormat.setForeground(Gray); orderFormat.setText(SINTAX_ORDER); commandFormatExe.setText(EXEC_COMMAND); commandFormatSintax.setText(SINTAX_COMMAND); concatOperationSintax.setText(SINTAX_OPERATION_1); compAsigOperationSintax.setText(SINTAX_OPERATION_2); basicProcessingFormat.setText(BASIC_PROCESS); newProcessingFormat.setText(NEW_PROCESS); associationFormat.setText(SINTAX_ASSOC); orderFormatInsert.requestFocus(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" Acciones Comunes "> private void opActions(int Index, JTextField jtf, JButton jb, String preText) { if (!jtf.getText().equalsIgnoreCase(preText)) { Object[] what = new Object[1]; what[0] = jtf.getText(); Controller.controller(Index, what); if (preText.equalsIgnoreCase("")) { jtf.setForeground(Black); } else { jtf.setForeground(Gray); } jtf.setText(preText); jb.requestFocus(); } } private void opFocus(JTextField jtf, String preText, Color c, String postText) { if (jtf.getText().equalsIgnoreCase(preText)) { jtf.setForeground(c); jtf.setText(postText); } } //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" TextField & Buttons "> //<editor-fold defaultstate="collapsed" desc=" 1.orderFormat "> private void orderFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatActionPerformed int Index = Controller.orderFormat; JTextField jtf = orderFormat; JButton jb = orderFormatInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_orderFormatActionPerformed private void orderFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_orderFormatFocusGained JTextField jtf = orderFormat; String preText = SINTAX_ORDER; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_orderFormatFocusGained private void orderFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_orderFormatFocusLost JTextField jtf = orderFormat; String preText = ""; Color c = Gray; String postText = SINTAX_ORDER; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_orderFormatFocusLost private void orderFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatInsertActionPerformed int Index = Controller.orderFormat; JTextField jtf = orderFormat; JButton jb = orderFormatInsert; String preText = SINTAX_ORDER; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_orderFormatInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 2.commandFormatExe "> private void commandFormatExeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeActionPerformed int Index = Controller.commandFormatExe; JTextField jtf = commandFormatExe; JButton jb = commandFormatExeInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_commandFormatExeActionPerformed private void commandFormatExeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatExeFocusGained JTextField jtf = commandFormatExe; String preText = EXEC_COMMAND; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_commandFormatExeFocusGained private void commandFormatExeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatExeFocusLost JTextField jtf = commandFormatExe; String preText = ""; Color c = Gray; String postText = EXEC_COMMAND; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_commandFormatExeFocusLost private void commandFormatExeInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeInsertActionPerformed int Index = Controller.commandFormatExe; JTextField jtf = commandFormatExe; JButton jb = commandFormatExeInsert; String preText = EXEC_COMMAND; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_commandFormatExeInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 3.commandFormatSintax "> private void commandFormatSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxActionPerformed int Index = Controller.commandFormatSintax; JTextField jtf = commandFormatSintax; JButton jb = commandFormatSintaxInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_commandFormatSintaxActionPerformed private void commandFormatSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatSintaxFocusGained JTextField jtf = commandFormatSintax; String preText = SINTAX_COMMAND; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_commandFormatSintaxFocusGained private void commandFormatSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatSintaxFocusLost JTextField jtf = commandFormatSintax; String preText = ""; Color c = Gray; String postText = SINTAX_COMMAND; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_commandFormatSintaxFocusLost private void commandFormatSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxInsertActionPerformed int Index = Controller.commandFormatSintax; JTextField jtf = commandFormatSintax; JButton jb = commandFormatSintaxInsert; String preText = SINTAX_COMMAND; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_commandFormatSintaxInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 4.concatOperationSintax "> private void concatOperationSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxActionPerformed int Index = Controller.concatOperationSintax; JTextField jtf = concatOperationSintax; JButton jb = concatOperationSintaxInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_concatOperationSintaxActionPerformed private void concatOperationSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_concatOperationSintaxFocusGained JTextField jtf = concatOperationSintax; String preText = SINTAX_OPERATION_1; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_concatOperationSintaxFocusGained private void concatOperationSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_concatOperationSintaxFocusLost JTextField jtf = concatOperationSintax; String preText = ""; Color c = Gray; String postText = SINTAX_OPERATION_1; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_concatOperationSintaxFocusLost private void concatOperationSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxInsertActionPerformed int Index = Controller.concatOperationSintax; JTextField jtf = concatOperationSintax; JButton jb = concatOperationSintaxInsert; String preText = SINTAX_OPERATION_1; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_concatOperationSintaxInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 5.compAsigOperationSintax "> private void compAsigOperationSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxActionPerformed int Index = Controller.compAsigOperationSintax; JTextField jtf = compAsigOperationSintax; JButton jb = compAsigOperationSintaxInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_compAsigOperationSintaxActionPerformed private void compAsigOperationSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxFocusGained JTextField jtf = compAsigOperationSintax; String preText = SINTAX_OPERATION_2; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_compAsigOperationSintaxFocusGained private void compAsigOperationSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxFocusLost JTextField jtf = compAsigOperationSintax; String preText = ""; Color c = Gray; String postText = SINTAX_OPERATION_2; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_compAsigOperationSintaxFocusLost private void compAsigOperationSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxInsertActionPerformed int Index = Controller.compAsigOperationSintax; JTextField jtf = compAsigOperationSintax; JButton jb = compAsigOperationSintaxInsert; String preText = SINTAX_OPERATION_2; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_compAsigOperationSintaxInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 6.basicProcessingFormat "> private void basicProcessingFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatActionPerformed int Index = Controller.basicProcessingFormat; JTextField jtf = basicProcessingFormat; JButton jb = basicProcessingFormatInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_basicProcessingFormatActionPerformed private void basicProcessingFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_basicProcessingFormatFocusGained JTextField jtf = basicProcessingFormat; String preText = BASIC_PROCESS; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_basicProcessingFormatFocusGained private void basicProcessingFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_basicProcessingFormatFocusLost JTextField jtf = basicProcessingFormat; String preText = ""; Color c = Gray; String postText = BASIC_PROCESS; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_basicProcessingFormatFocusLost private void basicProcessingFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatInsertActionPerformed int Index = Controller.basicProcessingFormat; JTextField jtf = basicProcessingFormat; JButton jb = basicProcessingFormatInsert; String preText = BASIC_PROCESS; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_basicProcessingFormatInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 7.newProcessingFormat "> private void newProcessingFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatActionPerformed int Index = Controller.newProcessingFormat; JTextField jtf = newProcessingFormat; JButton jb = newProcessingFormatInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_newProcessingFormatActionPerformed private void newProcessingFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_newProcessingFormatFocusGained JTextField jtf = newProcessingFormat; String preText = NEW_PROCESS; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_newProcessingFormatFocusGained private void newProcessingFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_newProcessingFormatFocusLost JTextField jtf = newProcessingFormat; String preText = ""; Color c = Gray; String postText = NEW_PROCESS; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_newProcessingFormatFocusLost private void newProcessingFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatInsertActionPerformed int Index = Controller.newProcessingFormat; JTextField jtf = newProcessingFormat; JButton jb = newProcessingFormatInsert; String preText = NEW_PROCESS; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_newProcessingFormatInsertActionPerformed //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" 8.associationFormat "> private void associationFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatActionPerformed int Index = Controller.associationFormat; JTextField jtf = associationFormat; JButton jb = associationFormatInsert; String preText = ""; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_associationFormatActionPerformed private void associationFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_associationFormatFocusGained JTextField jtf = associationFormat; String preText = SINTAX_ASSOC; Color c = Black; String postText = ""; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_associationFormatFocusGained private void associationFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_associationFormatFocusLost JTextField jtf = associationFormat; String preText = ""; Color c = Gray; String postText = SINTAX_ASSOC; opFocus(jtf, preText, c, postText); }//GEN-LAST:event_associationFormatFocusLost private void associationFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatInsertActionPerformed int Index = Controller.associationFormat; JTextField jtf = associationFormat; JButton jb = associationFormatInsert; String preText = SINTAX_ASSOC; opActions(Index, jtf, jb, preText); }//GEN-LAST:event_associationFormatInsertActionPerformed //</editor-fold> //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" FailureManager "> public void showError(String error) { String[] es = error.split("@"); String Text = "<html><b>Input example:</b><br>" + "<i>" + es[0] + "</i><br><br>" + "<b>Output example:</b><br>" + "<i>" + es[1] + "</i></html>"; Err.showMessageDialog(this, Text, "Invalid Input format", JOptionPane.ERROR_MESSAGE); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" Info Buttons "> public void showInfo(String info) { Info.showMessageDialog(this, info, "Format info", JOptionPane.INFORMATION_MESSAGE); } private void orderFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> [C],[S],[I],[D],[U],[Q] </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^X_ORDEN_SINTAX.”[C],[S],[I],[D],[U],[Q]” </i></html>"; showInfo(Text); }//GEN-LAST:event_orderFormatInfoActionPerformed private void commandFormatExeInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> [-c CENTRAL] -u USUARIO_EOC [–x SERVICIO] –e COMANDO " + "[-t TEMPORIZACION] [-s TAMANO] [-p PATRONES] [-m MAQUINA] " + "[-r RESPALDO] </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^C_EJECUTA_COMANDO.”[-c CENTRAL] -u USUARIO_EOC [–x SERVICIO]" + " –e COMANDO [-t TEMPORIZACION] [-s TAMANO] [-p PATRONES] " + "[-m MAQUINA] [-r RESPALDO]” </i></html>"; showInfo(Text); }//GEN-LAST:event_commandFormatExeInfoActionPerformed private void commandFormatSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> -u OMEGAAXE –t X: MY_TIEMPO –e SASTP –r NO </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^C_EJECUTA_COMANDO.”-u OMEGAAXE –t X: MY_TIEMPO –e SASTP " + "–r NO” </i></html>"; showInfo(Text); }//GEN-LAST:event_commandFormatSintaxInfoActionPerformed private void concatOperationSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> XH:VAR_DATE SH:FECHA XH:CASI_FECHA </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^X_OPERACION_SINTAX.”XH:VAR_DATE + SH:FECHA = " + "XH:CASI_FECHA” </i></html>"; showInfo(Text); }//GEN-LAST:event_concatOperationSintaxInfoActionPerformed private void compAsigOperationSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> XH:VAR_UNO != EH:ORIGEN XH:VAR_TRES XH:VAR_DOS XH:ESLOGAN </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^X_OPERACION_SINTAX.”XH:VAR_UNO != EH:ORIGEN # XH:VAR_TRES" + " = XH:ESLOGAN # XH:VAR_DOS = XH:ESLOGAN” </i></html>"; showInfo(Text); }//GEN-LAST:event_compAsigOperationSintaxInfoActionPerformed private void basicProcessingFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> insert XH:VAR_VACIA , EH:ORIGEN XH:CONDI , FALSE </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^I_TRATAR_INSERT.”XH:VAR_VACIA , EH:ORIGEN # XH:CONDI , " + "FALSE” </i></html>"; showInfo(Text); }//GEN-LAST:event_basicProcessingFormatInfoActionPerformed private void newProcessingFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> insert EH:ORIGEN == ‘MI_CENTRAL’ A XN:NUMERO >= EN:SECUENCIA B " + "XN:NUM > 100 C ; !(C | B) & A </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^I_TRATAR_INSERT.”EH:ORIGEN == ‘MI_CENTRAL’ = A ; " + "XN:NUMERO >= EN:SECUENCIA = B ; XN:NUM > 100 = C # !(C | B) " + "& A” </i></html>"; showInfo(Text); }//GEN-LAST:event_newProcessingFormatInfoActionPerformed private void associationFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatInfoActionPerformed String Text = "<html><b>Input example:</b><br>" + "<i> REGIS_A ; CAUSA_A </i><br><br>" + "<b>Output example:</b><br>" + "<i> %^X_ASOCIAR_SINTAX.\"REGIS_A # CAUSA_A\" </i></html>"; showInfo(Text); }//GEN-LAST:event_associationFormatInfoActionPerformed //</editor-fold> private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed this.dispose(); }//GEN-LAST:event_closeButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField associationFormat; private javax.swing.JButton associationFormatInfo; private javax.swing.JButton associationFormatInsert; private javax.swing.JTextField basicProcessingFormat; private javax.swing.JButton basicProcessingFormatInfo; private javax.swing.JButton basicProcessingFormatInsert; private javax.swing.JButton closeButton; private javax.swing.JTextField commandFormatExe; private javax.swing.JButton commandFormatExeInfo; private javax.swing.JButton commandFormatExeInsert; private javax.swing.JTextField commandFormatSintax; private javax.swing.JButton commandFormatSintaxInfo; private javax.swing.JButton commandFormatSintaxInsert; private javax.swing.JTextField compAsigOperationSintax; private javax.swing.JButton compAsigOperationSintaxInfo; private javax.swing.JButton compAsigOperationSintaxInsert; private javax.swing.JTextField concatOperationSintax; private javax.swing.JButton concatOperationSintaxInfo; private javax.swing.JButton concatOperationSintaxInsert; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JSeparator jSeparator6; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTextField newProcessingFormat; private javax.swing.JButton newProcessingFormatInfo; private javax.swing.JButton newProcessingFormatInsert; private javax.swing.JTextField orderFormat; private javax.swing.JButton orderFormatInfo; private javax.swing.JButton orderFormatInsert; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); orderFormat = new javax.swing.JTextField(); orderFormatInsert = new javax.swing.JButton(); orderFormatInfo = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); commandFormatExe = new javax.swing.JTextField(); commandFormatExeInsert = new javax.swing.JButton(); commandFormatExeInfo = new javax.swing.JButton(); commandFormatSintax = new javax.swing.JTextField(); commandFormatSintaxInsert = new javax.swing.JButton(); commandFormatSintaxInfo = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); concatOperationSintax = new javax.swing.JTextField(); concatOperationSintaxInsert = new javax.swing.JButton(); concatOperationSintaxInfo = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); compAsigOperationSintax = new javax.swing.JTextField(); compAsigOperationSintaxInsert = new javax.swing.JButton(); compAsigOperationSintaxInfo = new javax.swing.JButton(); jSeparator4 = new javax.swing.JSeparator(); basicProcessingFormat = new javax.swing.JTextField(); basicProcessingFormatInsert = new javax.swing.JButton(); basicProcessingFormatInfo = new javax.swing.JButton(); newProcessingFormat = new javax.swing.JTextField(); newProcessingFormatInsert = new javax.swing.JButton(); newProcessingFormatInfo = new javax.swing.JButton(); jSeparator5 = new javax.swing.JSeparator(); associationFormat = new javax.swing.JTextField(); associationFormatInsert = new javax.swing.JButton(); associationFormatInfo = new javax.swing.JButton(); jSeparator6 = new javax.swing.JSeparator(); closeButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setLocationByPlatform(true); setMaximumSize(new java.awt.Dimension(1000, 1000)); setPreferredSize(new java.awt.Dimension(606, 260)); setResizable(false); jSplitPane1.setDividerLocation(295); jSplitPane1.setEnabled(false); jPanel1.setPreferredSize(new java.awt.Dimension(270, 45)); orderFormat.setText("X_ORDEN_SINTAX"); orderFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatActionPerformed(evt); } }); orderFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { orderFormatFocusLost(evt); } public void focusGained(java.awt.event.FocusEvent evt) { orderFormatFocusGained(evt); } }); orderFormatInsert.setText("Insert"); orderFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInsertActionPerformed(evt); } }); orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N orderFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInfoActionPerformed(evt); } }); commandFormatExe.setText("C_EJECUTA_COMANDO"); commandFormatExe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeActionPerformed(evt); } }); commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatExeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatExeFocusLost(evt); } }); commandFormatExeInsert.setText("Insert"); commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInsertActionPerformed(evt); } }); commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInfoActionPerformed(evt); } }); commandFormatSintax.setText("C_SINTAXIS_COMANDO"); commandFormatSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxActionPerformed(evt); } }); commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusLost(evt); } }); commandFormatSintaxInsert.setText("Insert"); commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInsertActionPerformed(evt); } }); commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInfoActionPerformed(evt); } }); concatOperationSintax.setText("X_OPERACION_SINTAX"); concatOperationSintax.setToolTipText("ADDITION-CONCATENATION"); concatOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxActionPerformed(evt); } }); concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusLost(evt); } }); concatOperationSintaxInsert.setText("Insert"); concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInsertActionPerformed(evt); } }); concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInfoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator3) .addComponent(jSeparator2) .addComponent(jSeparator1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 2, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(orderFormatInsert)) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatExeInsert)) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatSintaxInsert)) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(concatOperationSintaxInsert) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(62, Short.MAX_VALUE)) ); jSplitPane1.setLeftComponent(jPanel1); jPanel2.setPreferredSize(new java.awt.Dimension(270, 45)); compAsigOperationSintax.setText("X_OPERACION_SINTAX"); compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT"); compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxActionPerformed(evt); } }); compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusLost(evt); } }); compAsigOperationSintaxInsert.setText("Insert"); compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInsertActionPerformed(evt); } }); compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInfoActionPerformed(evt); } }); basicProcessingFormat.setText("_TRATAR_BASICO"); basicProcessingFormat.setToolTipText("LOGIC AND"); basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatActionPerformed(evt); } }); basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusLost(evt); } }); basicProcessingFormatInsert.setText("Insert"); basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInsertActionPerformed(evt); } }); basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInfoActionPerformed(evt); } }); newProcessingFormat.setText("_TRATAR_NUEVO"); newProcessingFormat.setToolTipText("LOGIC OPERATION"); newProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatActionPerformed(evt); } }); newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { newProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { newProcessingFormatFocusLost(evt); } }); newProcessingFormatInsert.setText("Insert"); newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInsertActionPerformed(evt); } }); newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInfoActionPerformed(evt); } }); associationFormat.setText("X_ASOCIAR_SINTAX"); associationFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatActionPerformed(evt); } }); associationFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { associationFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { associationFormatFocusLost(evt); } }); associationFormatInsert.setText("Insert"); associationFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInsertActionPerformed(evt); } }); associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N associationFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInfoActionPerformed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator4) .addComponent(jSeparator5) .addComponent(jSeparator6) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(closeButton) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(compAsigOperationSintaxInsert)) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(basicProcessingFormatInsert)) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(newProcessingFormatInsert)) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(associationFormatInsert)) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) .addContainerGap(33, Short.MAX_VALUE)) ); jSplitPane1.setRightComponent(jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 590, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); orderFormat = new javax.swing.JTextField(); orderFormatInsert = new javax.swing.JButton(); orderFormatInfo = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); commandFormatExe = new javax.swing.JTextField(); commandFormatExeInsert = new javax.swing.JButton(); commandFormatExeInfo = new javax.swing.JButton(); commandFormatSintax = new javax.swing.JTextField(); commandFormatSintaxInsert = new javax.swing.JButton(); commandFormatSintaxInfo = new javax.swing.JButton(); jSeparator2 = new javax.swing.JSeparator(); concatOperationSintax = new javax.swing.JTextField(); concatOperationSintaxInsert = new javax.swing.JButton(); concatOperationSintaxInfo = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); jPanel2 = new javax.swing.JPanel(); compAsigOperationSintax = new javax.swing.JTextField(); compAsigOperationSintaxInsert = new javax.swing.JButton(); compAsigOperationSintaxInfo = new javax.swing.JButton(); jSeparator4 = new javax.swing.JSeparator(); basicProcessingFormat = new javax.swing.JTextField(); basicProcessingFormatInsert = new javax.swing.JButton(); basicProcessingFormatInfo = new javax.swing.JButton(); newProcessingFormat = new javax.swing.JTextField(); newProcessingFormatInsert = new javax.swing.JButton(); newProcessingFormatInfo = new javax.swing.JButton(); jSeparator5 = new javax.swing.JSeparator(); associationFormat = new javax.swing.JTextField(); associationFormatInsert = new javax.swing.JButton(); associationFormatInfo = new javax.swing.JButton(); jSeparator6 = new javax.swing.JSeparator(); closeButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setLocationByPlatform(true); setMaximumSize(new java.awt.Dimension(1000, 1000)); setPreferredSize(new java.awt.Dimension(606, 260)); setResizable(false); jSplitPane1.setDividerLocation(295); jSplitPane1.setEnabled(false); jPanel1.setPreferredSize(new java.awt.Dimension(270, 45)); orderFormat.setText("X_ORDEN_SINTAX"); orderFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatActionPerformed(evt); } }); orderFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { orderFormatFocusLost(evt); } public void focusGained(java.awt.event.FocusEvent evt) { orderFormatFocusGained(evt); } }); orderFormatInsert.setText("Insert"); orderFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInsertActionPerformed(evt); } }); orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N orderFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { orderFormatInfoActionPerformed(evt); } }); commandFormatExe.setText("C_EJECUTA_COMANDO"); commandFormatExe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeActionPerformed(evt); } }); commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatExeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatExeFocusLost(evt); } }); commandFormatExeInsert.setText("Insert"); commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInsertActionPerformed(evt); } }); commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatExeInfoActionPerformed(evt); } }); commandFormatSintax.setText("C_SINTAXIS_COMANDO"); commandFormatSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxActionPerformed(evt); } }); commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { commandFormatSintaxFocusLost(evt); } }); commandFormatSintaxInsert.setText("Insert"); commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInsertActionPerformed(evt); } }); commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { commandFormatSintaxInfoActionPerformed(evt); } }); concatOperationSintax.setText("X_OPERACION_SINTAX"); concatOperationSintax.setToolTipText("ADDITION-CONCATENATION"); concatOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxActionPerformed(evt); } }); concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { concatOperationSintaxFocusLost(evt); } }); concatOperationSintaxInsert.setText("Insert"); concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInsertActionPerformed(evt); } }); concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { concatOperationSintaxInfoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator3) .addComponent(jSeparator2) .addComponent(jSeparator1) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 2, Short.MAX_VALUE))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(orderFormatInsert)) .addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatExeInsert)) .addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(commandFormatSintaxInsert)) .addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(concatOperationSintaxInsert) .addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(40, Short.MAX_VALUE)) ); jSplitPane1.setLeftComponent(jPanel1); jPanel2.setPreferredSize(new java.awt.Dimension(270, 45)); compAsigOperationSintax.setText("X_OPERACION_SINTAX"); compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT"); compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxActionPerformed(evt); } }); compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { compAsigOperationSintaxFocusLost(evt); } }); compAsigOperationSintaxInsert.setText("Insert"); compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInsertActionPerformed(evt); } }); compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { compAsigOperationSintaxInfoActionPerformed(evt); } }); basicProcessingFormat.setText("_TRATAR_BASICO"); basicProcessingFormat.setToolTipText("LOGIC AND"); basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatActionPerformed(evt); } }); basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { basicProcessingFormatFocusLost(evt); } }); basicProcessingFormatInsert.setText("Insert"); basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInsertActionPerformed(evt); } }); basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { basicProcessingFormatInfoActionPerformed(evt); } }); newProcessingFormat.setText("_TRATAR_NUEVO"); newProcessingFormat.setToolTipText("LOGIC OPERATION"); newProcessingFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatActionPerformed(evt); } }); newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { newProcessingFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { newProcessingFormatFocusLost(evt); } }); newProcessingFormatInsert.setText("Insert"); newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInsertActionPerformed(evt); } }); newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newProcessingFormatInfoActionPerformed(evt); } }); associationFormat.setText("X_ASOCIAR_SINTAX"); associationFormat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatActionPerformed(evt); } }); associationFormat.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { associationFormatFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { associationFormatFocusLost(evt); } }); associationFormatInsert.setText("Insert"); associationFormatInsert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInsertActionPerformed(evt); } }); associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N associationFormatInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationFormatInfoActionPerformed(evt); } }); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator4) .addComponent(jSeparator5) .addComponent(jSeparator6) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(closeButton) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(associationFormatInsert) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(compAsigOperationSintaxInsert)) .addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(basicProcessingFormatInsert)) .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(newProcessingFormatInsert)) .addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(associationFormatInsert)) .addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jSplitPane1.setRightComponent(jPanel2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 590, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java b/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java index b0b2a81..b44c6ed 100644 --- a/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java +++ b/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java @@ -1,96 +1,99 @@ package plugins.WebOfTrust.fcp; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.index.lucene.QueryContext; import plugins.WebOfTrust.WebOfTrust; import plugins.WebOfTrust.datamodel.IContext; import plugins.WebOfTrust.datamodel.IVertex; import plugins.WebOfTrust.datamodel.Rel; import freenet.node.FSParseException; import freenet.support.SimpleFieldSet; public class GetIdentitiesByPartialNickname extends GetIdentity { public GetIdentitiesByPartialNickname(GraphDatabaseService db) { super(db); } @Override public SimpleFieldSet handle(SimpleFieldSet input) { final String trusterID = input.get("Truster"); final String partialNickname = input.get("PartialNickname").trim(); final String partialID = input.get("PartialID").trim(); final String context = input.get("Context"); int maxIdentities = 0; try { maxIdentities = input.getInt("MaxIdentities"); } catch (FSParseException e) { throw new IllegalArgumentException("MaxIdentities has an incorrect value"); } //find all identities for given context reply.putSingle("Message", "Identities"); int i = 0; //find trusterID final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle(); final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID); final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle(); //get all identities with a specific context if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph { for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname))) { //check if identity has the context boolean has_context = false; for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) { if (contextRel.getEndNode().equals(contextNode)) { has_context = true; break; } } if (has_context) { //check whether keypart matches as well if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID)) { //find the score relation if present Relationship directScore = null; for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) { if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID)) { directScore = rel; break; } } //check whether the trust is >= 0 before including - if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0) + if (identity.hasProperty(treeOwnerTrustProperty)) { - addIdentityReplyFields(directScore, identity, Integer.toString(i), true, trusterID); - i += 1; + if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0) + { + addIdentityReplyFields(directScore, identity, Integer.toString(i), true, trusterID); + i += 1; + } } } } if (i > maxIdentities) throw new IllegalStateException("Number of matched identies exceeds maxIdentities"); } } if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + i + " identities for the context: " + context); return reply; } }
false
true
public SimpleFieldSet handle(SimpleFieldSet input) { final String trusterID = input.get("Truster"); final String partialNickname = input.get("PartialNickname").trim(); final String partialID = input.get("PartialID").trim(); final String context = input.get("Context"); int maxIdentities = 0; try { maxIdentities = input.getInt("MaxIdentities"); } catch (FSParseException e) { throw new IllegalArgumentException("MaxIdentities has an incorrect value"); } //find all identities for given context reply.putSingle("Message", "Identities"); int i = 0; //find trusterID final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle(); final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID); final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle(); //get all identities with a specific context if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph { for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname))) { //check if identity has the context boolean has_context = false; for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) { if (contextRel.getEndNode().equals(contextNode)) { has_context = true; break; } } if (has_context) { //check whether keypart matches as well if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID)) { //find the score relation if present Relationship directScore = null; for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) { if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID)) { directScore = rel; break; } } //check whether the trust is >= 0 before including if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0) { addIdentityReplyFields(directScore, identity, Integer.toString(i), true, trusterID); i += 1; } } } if (i > maxIdentities) throw new IllegalStateException("Number of matched identies exceeds maxIdentities"); } } if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + i + " identities for the context: " + context); return reply; }
public SimpleFieldSet handle(SimpleFieldSet input) { final String trusterID = input.get("Truster"); final String partialNickname = input.get("PartialNickname").trim(); final String partialID = input.get("PartialID").trim(); final String context = input.get("Context"); int maxIdentities = 0; try { maxIdentities = input.getInt("MaxIdentities"); } catch (FSParseException e) { throw new IllegalArgumentException("MaxIdentities has an incorrect value"); } //find all identities for given context reply.putSingle("Message", "Identities"); int i = 0; //find trusterID final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle(); final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID); final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle(); //get all identities with a specific context if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph { for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname))) { //check if identity has the context boolean has_context = false; for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT)) { if (contextRel.getEndNode().equals(contextNode)) { has_context = true; break; } } if (has_context) { //check whether keypart matches as well if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID)) { //find the score relation if present Relationship directScore = null; for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS)) { if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID)) { directScore = rel; break; } } //check whether the trust is >= 0 before including if (identity.hasProperty(treeOwnerTrustProperty)) { if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0) { addIdentityReplyFields(directScore, identity, Integer.toString(i), true, trusterID); i += 1; } } } } if (i > maxIdentities) throw new IllegalStateException("Number of matched identies exceeds maxIdentities"); } } if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + i + " identities for the context: " + context); return reply; }
diff --git a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java index b1fe4569d..4da5b7cd5 100644 --- a/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java +++ b/activemq-core/src/main/java/org/apache/activemq/transport/nio/NIOOutputStream.java @@ -1,229 +1,229 @@ /** * 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.transport.nio; import java.io.EOFException; import java.io.IOException; import java.io.InterruptedIOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import javax.net.ssl.SSLEngine; import org.apache.activemq.transport.tcp.TimeStampStream; /** * An optimized buffered outputstream for Tcp */ public class NIOOutputStream extends OutputStream implements TimeStampStream { private static final int BUFFER_SIZE = 8192; private final WritableByteChannel out; private final byte[] buffer; private final ByteBuffer byteBuffer; private int count; private boolean closed; private volatile long writeTimestamp = -1;//concurrent reads of this value private SSLEngine engine; /** * Constructor * * @param out */ public NIOOutputStream(WritableByteChannel out) { this(out, BUFFER_SIZE); } /** * Creates a new buffered output stream to write data to the specified * underlying output stream with the specified buffer size. * * @param out the underlying output stream. * @param size the buffer size. * @throws IllegalArgumentException if size <= 0. */ public NIOOutputStream(WritableByteChannel out, int size) { this.out = out; if (size <= 0) { throw new IllegalArgumentException("Buffer size <= 0"); } buffer = new byte[size]; byteBuffer = ByteBuffer.wrap(buffer); } /** * write a byte on to the stream * * @param b - byte to write * @throws IOException */ public void write(int b) throws IOException { checkClosed(); if (availableBufferToWrite() < 1) { flush(); } buffer[count++] = (byte)b; } /** * write a byte array to the stream * * @param b the byte buffer * @param off the offset into the buffer * @param len the length of data to write * @throws IOException */ public void write(byte b[], int off, int len) throws IOException { checkClosed(); if (availableBufferToWrite() < len) { flush(); } if (buffer.length >= len) { System.arraycopy(b, off, buffer, count, len); count += len; } else { write(ByteBuffer.wrap(b, off, len)); } } /** * flush the data to the output stream This doesn't call flush on the * underlying outputstream, because Tcp is particularly efficent at doing * this itself .... * * @throws IOException */ public void flush() throws IOException { if (count > 0 && out != null) { byteBuffer.position(0); byteBuffer.limit(count); write(byteBuffer); count = 0; } } /** * close this stream * * @throws IOException */ public void close() throws IOException { super.close(); if (engine != null) { engine.closeOutbound(); } closed = true; } /** * Checks that the stream has not been closed * * @throws IOException */ protected void checkClosed() throws IOException { if (closed) { throw new EOFException("Cannot write to the stream any more it has already been closed"); } } /** * @return the amount free space in the buffer */ private int availableBufferToWrite() { return buffer.length - count; } protected void write(ByteBuffer data) throws IOException { ByteBuffer plain; if (engine != null) { plain = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); plain.clear(); engine.wrap(data, plain); plain.flip(); } else { plain = data; } int remaining = plain.remaining(); int lastRemaining = remaining - 1; long delay = 1; try { writeTimestamp = System.currentTimeMillis(); while (remaining > 0) { // We may need to do a little bit of sleeping to avoid a busy loop. // Slow down if no data was written out.. if (remaining == lastRemaining) { try { // Use exponential rollback to increase sleep time. Thread.sleep(delay); delay *= 2; if (delay > 1000) { delay = 1000; } } catch (InterruptedException e) { throw new InterruptedIOException(); } } else { delay = 1; } lastRemaining = remaining; // Since the write is non-blocking, all the data may not have been // written. out.write(plain); remaining = data.remaining(); // if the data buffer was larger than the packet buffer we might need to // wrap more packets until we reach the end of data, but only when plain // has no more space since we are non-blocking and a write might not have // written anything. - if (data.hasRemaining() && !plain.hasRemaining()) { + if (engine != null && data.hasRemaining() && !plain.hasRemaining()) { plain.clear(); engine.wrap(data, plain); plain.flip(); } } } finally { writeTimestamp = -1; } } /* (non-Javadoc) * @see org.apache.activemq.transport.tcp.TimeStampStream#isWriting() */ public boolean isWriting() { return writeTimestamp > 0; } /* (non-Javadoc) * @see org.apache.activemq.transport.tcp.TimeStampStream#getWriteTimestamp() */ public long getWriteTimestamp() { return writeTimestamp; } public void setEngine(SSLEngine engine) { this.engine = engine; } }
true
true
protected void write(ByteBuffer data) throws IOException { ByteBuffer plain; if (engine != null) { plain = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); plain.clear(); engine.wrap(data, plain); plain.flip(); } else { plain = data; } int remaining = plain.remaining(); int lastRemaining = remaining - 1; long delay = 1; try { writeTimestamp = System.currentTimeMillis(); while (remaining > 0) { // We may need to do a little bit of sleeping to avoid a busy loop. // Slow down if no data was written out.. if (remaining == lastRemaining) { try { // Use exponential rollback to increase sleep time. Thread.sleep(delay); delay *= 2; if (delay > 1000) { delay = 1000; } } catch (InterruptedException e) { throw new InterruptedIOException(); } } else { delay = 1; } lastRemaining = remaining; // Since the write is non-blocking, all the data may not have been // written. out.write(plain); remaining = data.remaining(); // if the data buffer was larger than the packet buffer we might need to // wrap more packets until we reach the end of data, but only when plain // has no more space since we are non-blocking and a write might not have // written anything. if (data.hasRemaining() && !plain.hasRemaining()) { plain.clear(); engine.wrap(data, plain); plain.flip(); } } } finally { writeTimestamp = -1; } }
protected void write(ByteBuffer data) throws IOException { ByteBuffer plain; if (engine != null) { plain = ByteBuffer.allocate(engine.getSession().getPacketBufferSize()); plain.clear(); engine.wrap(data, plain); plain.flip(); } else { plain = data; } int remaining = plain.remaining(); int lastRemaining = remaining - 1; long delay = 1; try { writeTimestamp = System.currentTimeMillis(); while (remaining > 0) { // We may need to do a little bit of sleeping to avoid a busy loop. // Slow down if no data was written out.. if (remaining == lastRemaining) { try { // Use exponential rollback to increase sleep time. Thread.sleep(delay); delay *= 2; if (delay > 1000) { delay = 1000; } } catch (InterruptedException e) { throw new InterruptedIOException(); } } else { delay = 1; } lastRemaining = remaining; // Since the write is non-blocking, all the data may not have been // written. out.write(plain); remaining = data.remaining(); // if the data buffer was larger than the packet buffer we might need to // wrap more packets until we reach the end of data, but only when plain // has no more space since we are non-blocking and a write might not have // written anything. if (engine != null && data.hasRemaining() && !plain.hasRemaining()) { plain.clear(); engine.wrap(data, plain); plain.flip(); } } } finally { writeTimestamp = -1; } }
diff --git a/ini/trakem2/persistence/Loader.java b/ini/trakem2/persistence/Loader.java index 66936976..80707590 100644 --- a/ini/trakem2/persistence/Loader.java +++ b/ini/trakem2/persistence/Loader.java @@ -1,4697 +1,4697 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005, 2006 Albert Cardona and Rodney Douglas. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.persistence; import ini.trakem2.utils.IJError; /** * Database cleanup copy-paste: drop table ab_attributes, ab_ball_points, ab_displayables, ab_displays, ab_labels, ab_layer_sets, ab_layers, ab_links, ab_patches, ab_pipe_points, ab_profiles, ab_projects, ab_things, ab_zdisplayables; drop sequence ab_ids; * */ import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.WindowManager; import ij.gui.GenericDialog; import ij.gui.Roi; import ij.gui.YesNoCancelDialog; import ij.io.DirectoryChooser; import ij.io.FileInfo; import ij.io.FileSaver; import ij.io.Opener; import ij.io.OpenDialog; import ij.io.TiffEncoder; import ij.plugin.filter.PlugInFilter; import ij.process.ByteProcessor; import ij.process.ImageProcessor; import ij.process.FloatProcessor; import ij.process.StackProcessor; import ij.process.StackStatistics; import ij.process.ImageStatistics; import ij.measure.Calibration; import ini.trakem2.Project; import ini.trakem2.display.Ball; import ini.trakem2.display.DLabel; import ini.trakem2.display.Display; import ini.trakem2.display.Displayable; import ini.trakem2.display.Layer; import ini.trakem2.display.LayerSet; import ini.trakem2.display.Patch; import ini.trakem2.display.Pipe; import ini.trakem2.display.Profile; import ini.trakem2.display.YesNoDialog; import ini.trakem2.display.ZDisplayable; import ini.trakem2.tree.*; import ini.trakem2.utils.*; import ini.trakem2.io.*; import ini.trakem2.imaging.*; import ini.trakem2.ControlWindow; import javax.swing.tree.*; import javax.swing.JPopupMenu; import javax.swing.JMenuItem; import java.awt.Color; import java.awt.Component; import java.awt.Checkbox; import java.awt.Cursor; //import java.awt.FileDialog; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; import java.awt.geom.Area; import java.awt.geom.AffineTransform; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.Map; import java.util.HashSet; import java.util.Set; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.IdentityHashMap; import java.util.HashMap; import java.util.Vector; import java.util.LinkedHashSet; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import java.util.zip.Inflater; import java.util.zip.Deflater; import javax.swing.JMenu; import mpi.fruitfly.math.datastructures.FloatArray2D; import mpi.fruitfly.registration.ImageFilter; import mpi.fruitfly.registration.PhaseCorrelation2D; import mpi.fruitfly.registration.Feature; import mpi.fruitfly.general.MultiThreading; import java.util.concurrent.atomic.AtomicInteger; /** Handle all data-related issues with a virtualization engine, including load/unload and saving, saving as and overwriting. */ abstract public class Loader { // Only one thread at a time is to use the connection and cache protected final Object db_lock = new Object(); private boolean db_busy = false; protected Opener opener = new Opener(); /** The cache is shared, and can be flagged to do massive flushing. */ private boolean massive_mode = false; /** Keep track of whether there are any unsaved changes.*/ protected boolean changes = false; static public final int ERROR_PATH_NOT_FOUND = Integer.MAX_VALUE; /** Whether incremental garbage collection is enabled. */ /* static protected final boolean Xincgc = isXincgcSet(); static protected final boolean isXincgcSet() { String[] args = IJ.getInstance().getArgs(); for (int i=0; i<args.length; i++) { if ("-Xingc".equals(args[i])) return true; } return false; } */ static public final BufferedImage NOT_FOUND = new BufferedImage(10, 10, BufferedImage.TYPE_BYTE_BINARY); static { Graphics2D g = NOT_FOUND.createGraphics(); g.setColor(Color.white); g.drawRect(1, 1, 8, 8); g.drawLine(3, 3, 7, 7); g.drawLine(7, 3, 3, 7); } // the cache: shared, for there is only one JVM! (we could open a second one, and store images there, and transfer them through sockets) // What I need is not provided: a LinkedHashMap with a method to do 'removeFirst' or remove(0) !!! To call my_map.entrySet().iterator() to delete the the first element of a LinkedHashMap is just too much calling for an operation that has to be blazing fast. So I create a double list setup with arrays. The variables are not static because each loader could be connected to a different database, and each database has its own set of unique ids. Memory from other loaders is free by the releaseOthers(double) method. transient protected FIFOImagePlusMap imps = new FIFOImagePlusMap(50); transient protected FIFOImageMipMaps mawts = new FIFOImageMipMaps(50); //transient protected CacheMipMaps mawts = new CacheMipMaps(50); static transient protected Vector<Loader> v_loaders = null; // Vector: synchronized protected Loader() { // register if (null == v_loaders) v_loaders = new Vector<Loader>(); v_loaders.add(this); if (!ControlWindow.isGUIEnabled()) { opener.setSilentMode(true); } // debug: report cache status every ten seconds /* final Loader lo = this; new Thread() { public void run() { setPriority(Thread.NORM_PRIORITY); while (true) { try { Thread.sleep(1000); } catch (InterruptedException ie) {} synchronized(db_lock) { lock(); //if (!v_loaders.contains(lo)) { // unlock(); // break; //} // TODO BROKEN: not registered! Utils.log2("CACHE: \n\timps: " + imps.size() + "\n\tmawts: " + mawts.size()); mawts.debug(); unlock(); } } } }.start(); */ Utils.log2("MAX_MEMORY: " + max_memory); } /** When the loader has completed its initialization, it should return true on this method. */ abstract public boolean isReady(); /** To be called within a synchronized(db_lock) */ protected final void lock() { //Utils.printCaller(this, 7); while (db_busy) { try { db_lock.wait(); } catch (InterruptedException ie) {} } db_busy = true; } /** To be called within a synchronized(db_lock) */ protected final void unlock() { //Utils.printCaller(this, 7); if (db_busy) { db_busy = false; db_lock.notifyAll(); } } /** Release all memory and unregister itself. Child Loader classes should call this method in their destroy() methods. */ synchronized public void destroy() { if (null != IJ.getInstance() && IJ.getInstance().quitting()) { return; // no need to do anything else } Utils.showStatus("Releasing all memory ..."); destroyCache(); if (null != v_loaders) { v_loaders.remove(this); // sync issues when deleting two loaders consecutively if (0 == v_loaders.size()) v_loaders = null; } } /**Retrieve next id from a sequence for a new DBObject to be added.*/ abstract public long getNextId(); /** Ask for the user to provide a template XML file to extract a root TemplateThing. */ public TemplateThing askForXMLTemplate(Project project) { // ask for an .xml file or a .dtd file //fd.setFilenameFilter(new XMLFileFilter(XMLFileFilter.BOTH)); String user = System.getProperty("user.name"); OpenDialog od = new OpenDialog("Select XML Template", (user.equals("albertca") || user.equals("cardona")) ? "/home/" + user + "/temp" : OpenDialog.getDefaultDirectory(), null); String file = od.getFileName(); if (null == file || file.toLowerCase().startsWith("null")) return null; // if there is a path, read it out if possible String path = od.getDirectory() + "/" + file; TemplateThing[] roots = DTDParser.extractTemplate(path); if (null == roots || roots.length < 1) return null; if (roots.length > 1) { Utils.showMessage("Found more than one root.\nUsing first root only."); } return roots[0]; } private boolean temp_snapshots_enabled = true; public void startLargeUpdate() { LayerSet ls = Project.findProject(this).getRootLayerSet(); temp_snapshots_enabled = ls.areSnapshotsEnabled(); if (temp_snapshots_enabled) ls.setSnapshotsEnabled(false); } public void commitLargeUpdate() { Project.findProject(this).getRootLayerSet().setSnapshotsEnabled(temp_snapshots_enabled); } public void rollback() { Project.findProject(this).getRootLayerSet().setSnapshotsEnabled(temp_snapshots_enabled); } abstract public double[][][] fetchBezierArrays(long id); abstract public ArrayList fetchPipePoints(long id); abstract public ArrayList fetchBallPoints(long id); abstract public Area fetchArea(long area_list_id, long layer_id); /* GENERIC, from DBObject calls */ abstract public boolean addToDatabase(DBObject ob); abstract public boolean updateInDatabase(DBObject ob, String key); abstract public boolean removeFromDatabase(DBObject ob); /* Reflection would be the best way to do all above; when it's about and 'id', one only would have to check whether the field in question is a BIGINT and the object given a DBObject, and call getId(). Such an approach demands, though, perfect matching of column names with class field names. */ // for cache flushing public boolean getMassiveMode() { return massive_mode; } // for cache flushing public final void setMassiveMode(boolean m) { massive_mode = m; //Utils.log2("massive mode is " + m + " for loader " + this); } /** Retrieves a zipped ImagePlus from the given InputStream. The stream is not closed and must be closed elsewhere. No error checking is done as to whether the stream actually contains a zipped tiff file. */ protected ImagePlus unzipTiff(InputStream i_stream, String title) { ImagePlus imp; try { // Reading a zipped tiff file in the database /* // works but not faster byte[] bytes = null; // new style: RAM only ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int len; int length = 0; while (true) { len = i_stream.read(buf); if (len<0) break; length += len; out.write(buf, 0, len); } Inflater infl = new Inflater(); infl.setInput(out.toByteArray(), 0, length); int buflen = length + length; buf = new byte[buflen]; //short almost for sure int offset = 0; ArrayList al = new ArrayList(); while (true) { len = infl.inflate(buf, offset, buf.length); al.add(buf); if (0 == infl.getRemaining()) break; buf = new byte[length*2]; offset += len; } infl.end(); byte[][] b = new byte[al.size()][]; al.toArray(b); int blength = buflen * (b.length -1) + len; // the last may be shorter bytes = new byte[blength]; for (int i=0; i<b.length -1; i++) { System.arraycopy(b[i], 0, bytes, i*buflen, buflen); } System.arraycopy(b[b.length-1], 0, bytes, buflen * (b.length-1), len); */ //OLD, creates tmp file (archive style) ZipInputStream zis = new ZipInputStream(i_stream); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; //copying savagely from ImageJ's Opener.openZip() ZipEntry entry = zis.getNextEntry(); // I suspect this is needed as an iterator int len; while (true) { len = zis.read(buf); if (len<0) break; out.write(buf, 0, len); } zis.close(); byte[] bytes = out.toByteArray(); ij.IJ.redirectErrorMessages(); imp = opener.openTiff(new ByteArrayInputStream(bytes), title); // NO! Database images may get preprocessed everytime one opends them. The preprocessor is only intended to be applied to files opened from the file system. //preProcess(imp); //old //ij.IJ.redirectErrorMessages(); //imp = new Opener().openTiff(i_stream, title); } catch (Exception e) { IJError.print(e); return null; } return imp; } public void addCrossLink(long project_id, long id1, long id2) {} /** Remove a link between two objects. Returns true always in this empty method. */ public boolean removeCrossLink(long id1, long id2) { return true; } synchronized public void cache(Displayable d) { cache(d, null); notify(); } /** Add to the cache, or if already there, make it be the last (to be flushed the last). */ public void cache(final Displayable d, final ImagePlus imp) { synchronized (db_lock) { lock(); final long id = d.getId(); // each Displayable has a unique id for each database, not for different databases, that's why the cache is NOT shared. if (d instanceof Patch) { Patch p = (Patch)d; if (null == imps.get(id)) { // the 'get' call already puts it at the end if there. imps.put(id, imp); } } else { Utils.log("Loader.cache: don't know how to cache: " + d); } unlock(); } } synchronized public void updateCache(Patch patch) { updateCache(patch, imps.get(patch.getId())); } /** Update the awt, replace the imp with the new imp, and remake the snapshot from the awt*/ public void updateCache(Patch patch, ImagePlus imp) { synchronized (db_lock) { lock(); imps.put(patch.getId(), imp); // replace with the new imp unlock(); } patch.createImage(imp); // create from the cached new imp, and cache the new awt } /** Cache any ImagePlus, as long as a unique id is assigned to it there won't be problems; you can obtain a unique id from method getNextId() .*/ public void cacheImagePlus(long id, ImagePlus imp) { synchronized (db_lock) { lock(); imps.put(id, imp); // TODO this looks totally unnecessary unlock(); } } public void decacheImagePlus(long id) { synchronized (db_lock) { lock(); ImagePlus imp = imps.remove(id); flush(imp); unlock(); } } public void decacheImagePlus(long[] id) { synchronized (db_lock) { lock(); for (int i=0; i<id.length; i++) { ImagePlus imp = imps.remove(id[i]); flush(imp); } unlock(); } } public void updateCache(final Displayable d, final String key) { /* CRUFT FROM THE PAST, for LayerStack I think if (key.startsWith("points=")) { long lid = Long.parseLong(key.substring(7)); // for AreaList decacheImagePlus(lid); } else if (d instanceof ZDisplayable) { // remove all layers in which the ZDisplayable paints to ZDisplayable zd = (ZDisplayable)d; for (Iterator it = zd.getLayerSet().getLayers().iterator(); it.hasNext(); ) { Layer layer = (Layer)it.next(); if (zd.paintsAt(layer)) decacheImagePlus(layer.getId()); } } else { // remove the layer where the Displayable paints to if (null == d.getLayer()) { // Top Level LayerSet has no layer return; } decacheImagePlus(d.getLayer().getId()); } */ } /////////////////// static protected final Runtime RUNTIME = Runtime.getRuntime(); static public final long getCurrentMemory() { // totalMemory() is the amount of current JVM heap allocation, whether it's being used or not. It may grow over time if -Xms < -Xmx return RUNTIME.totalMemory() - RUNTIME.freeMemory(); } static public final long getFreeMemory() { // max_memory changes as some is reserved by image opening calls return max_memory - getCurrentMemory(); } /** Really available maximum memory, in bytes. */ static protected long max_memory = RUNTIME.maxMemory() - 128000000; // 128 M always free //static protected long max_memory = (long)(IJ.maxMemory() - 128000000); // 128 M always free /** Measure whether there are at least 'n_bytes' free. */ static final protected boolean enoughFreeMemory(final long n_bytes) { long free = getFreeMemory(); if (free < n_bytes) { return false; } //if (Runtime.getRuntime().freeMemory() < n_bytes + MIN_FREE_BYTES) return false; return n_bytes < max_memory - getCurrentMemory(); } public final boolean releaseToFit(final int width, final int height, final int type, float factor) { long bytes = width * height; switch (type) { case ImagePlus.GRAY32: bytes *= 5; // 4 for the FloatProcessor, and 1 for the generated pixels8 to make an image if (factor < 4) factor = 4; // for Open_MRC_Leginon ... TODO this is unnecessary in all other cases break; case ImagePlus.COLOR_RGB: bytes *= 4; break; case ImagePlus.GRAY16: bytes *= 3; // 2 for the ShortProcessor, and 1 for the pixels8 break; default: // times 1 break; } return releaseToFit((long)(bytes*factor)); } /** Release enough memory so that as many bytes as passed as argument can be loaded. */ public final boolean releaseToFit(final long bytes) { if (bytes > max_memory) { Utils.log("Can't fit " + bytes + " bytes in memory."); // Try anyway releaseAll(); return false; } final boolean previous = massive_mode; if (bytes > max_memory / 4) setMassiveMode(true); if (enoughFreeMemory(bytes)) return true; boolean result = true; synchronized (db_lock) { lock(); result = releaseToFit2(bytes); unlock(); } setMassiveMode(previous); return result; } // non-locking version protected final boolean releaseToFit2(long n_bytes) { //if (enoughFreeMemory(n_bytes)) return true; if (releaseMemory(0.5D, true, n_bytes) >= n_bytes) return true; // Java will free on its own if it has to // else, wait for GC int iterations = 30; while (iterations > 0) { if (0 == imps.size() && 0 == mawts.size()) { // wait for GC ... System.gc(); try { Thread.sleep(300); } catch (InterruptedException ie) {} } if (enoughFreeMemory(n_bytes)) return true; iterations--; } return true; } /** This method tries to cope with the lack of real time garbage collection in java (that is, lack of predictable time for memory release). */ public final int runGC() { //Utils.printCaller("runGC", 4); final long initial = IJ.currentMemory(); long now = initial; final int max = 7; long sleep = 50; // initial value int iterations = 0; do { //Runtime.getRuntime().runFinalization(); // enforce it System.gc(); Thread.yield(); try { Thread.sleep(sleep); } catch (InterruptedException ie) {} sleep += sleep; // incremental now = IJ.currentMemory(); Utils.log("\titer " + iterations + " initial: " + initial + " now: " + now); Utils.log2("\t mawts: " + mawts.size() + " imps: " + imps.size()); iterations++; } while (now >= initial && iterations < max); Utils.log2("finished runGC"); if (iterations >= 7) { //Utils.printCaller(this, 10); } return iterations + 1; } static public final void runGCAll() { Loader[] lo = new Loader[v_loaders.size()]; v_loaders.toArray(lo); for (int i=0; i<lo.length; i++) { lo[i].runGC(); } } static public void printCacheStatus() { Loader[] lo = new Loader[v_loaders.size()]; v_loaders.toArray(lo); for (int i=0; i<lo.length; i++) { Utils.log2("Loader " + i + " : mawts: " + lo[i].mawts.size() + " imps: " + lo[i].imps.size()); } } /** The minimal number of memory bytes that should always be free. */ public static final long MIN_FREE_BYTES = max_memory > 1000000000 /*1 Gb*/ ? 150000000 /*150 Mb*/ : 50000000 /*50 Mb*/; // (long)(max_memory * 0.2f); /** Remove up to half the ImagePlus cache of others (but their mawts first if needed) and then one single ImagePlus of this Loader's cache. */ protected final long releaseMemory() { return releaseMemory(0.5D, true, MIN_FREE_BYTES); } private final long measureSize(final ImagePlus imp) { if (null == imp) return 0; final long size = imp.getWidth() * imp.getHeight(); switch (imp.getType()) { case ImagePlus.GRAY16: return size * 2 + 100; case ImagePlus.GRAY32: case ImagePlus.COLOR_RGB: return size * 4 + 100; // some overhead, it's 16 but allowing for a lot more case ImagePlus.GRAY8: return size + 100; case ImagePlus.COLOR_256: return size + 868; // 100 + 3 * 256 (the LUT) } return 0; } /** Returns a lower-bound estimate: as if it was grayscale; plus some overhead. */ private final long measureSize(final Image img) { if (null == img) return 0; return img.getWidth(null) * img.getHeight(null) + 100; } public long releaseMemory(double percent, boolean from_all_projects) { if (!from_all_projects) return releaseMemory(percent); long mem = 0; for (Loader loader : v_loaders) mem += loader.releaseMemory(percent); return mem; } /** From 0 to 1. */ public long releaseMemory(double percent) { if (percent <= 0) return 0; if (percent > 1) percent = 1; synchronized (db_lock) { try { lock(); return releaseMemory(percent, false, MIN_FREE_BYTES); } catch (Throwable e) { IJError.print(e); } finally { // gets called by the 'return' above and by any other sort of try{}catch interruption unlock(); } } return 0; } /** Release as much of the cache as necessary to make at least min_free_bytes free.<br /> * The very last thing to remove is the stored awt.Image objects.<br /> * Removes one ImagePlus at a time if a == 0, else up to 0 &lt; a &lt;= 1.0 .<br /> * NOT locked, however calls must take care of that.<br /> */ protected final long releaseMemory(final double a, final boolean release_others, final long min_free_bytes) { long released = 0; try { //while (!enoughFreeMemory(min_free_bytes)) { while (released < min_free_bytes) { if (enoughFreeMemory(min_free_bytes)) return released; // release the cache of other loaders (up to 'a' of the ImagePlus cache of them if necessary) if (massive_mode) { // release others regardless of the 'release_others' boolean released += releaseOthers(0.5D); // reset if (released >= min_free_bytes) return released; // remove half of the imps if (0 != imps.size()) { for (int i=imps.size()/2; i>-1; i--) { ImagePlus imp = imps.removeFirst(); released += measureSize(imp); flush(imp); } Thread.yield(); if (released >= min_free_bytes) return released; } // finally, release snapshots if (0 != mawts.size()) { // release almost all snapshots (they're cheap to reload/recreate) for (int i=(int)(mawts.size() * 0.25); i>-1; i--) { Image mawt = mawts.removeFirst(); released += measureSize(mawt); if (null != mawt) mawt.flush(); } if (released >= min_free_bytes) return released; } } else { if (release_others) { released += releaseOthers(a); if (released >= min_free_bytes) return released; } if (0 == imps.size()) { // release half the cached awt images if (0 != mawts.size()) { for (int i=mawts.size()/3; i>-1; i--) { Image im = mawts.removeFirst(); released += measureSize(im); if (null != im) im.flush(); } if (released >= min_free_bytes) return released; } } // finally: if (a > 0.0D && a <= 1.0D) { // up to 'a' of the ImagePlus cache: for (int i=(int)(imps.size() * a); i>-1; i--) { ImagePlus imp = imps.removeFirst(); released += measureSize(imp); flush(imp); } } else { // just one: ImagePlus imp = imps.removeFirst(); flush(imp); } } // sanity check: if (0 == imps.size() && 0 == mawts.size()) { Utils.log2("Loader.releaseMemory: empty cache."); // in any case, can't release more: mawts.gc(); return released; } } } catch (Exception e) { IJError.print(e); } return released; } /** Release memory from other loaders. */ private long releaseOthers(double a) { if (null == v_loaders || 1 == v_loaders.size()) return 0; if (a <= 0.0D || a > 1.0D) return 0; final Iterator it = v_loaders.iterator(); long released = 0; while (it.hasNext()) { Loader loader = (Loader)it.next(); if (loader == this) continue; else { loader.setMassiveMode(false); // otherwise would loop back! released += loader.releaseMemory(a, false, MIN_FREE_BYTES); } } return released; } /** Empties the caches. */ public void releaseAll() { synchronized (db_lock) { lock(); try { for (ImagePlus imp : imps.removeAll()) { flush(imp); } mawts.removeAndFlushAll(); } catch (Exception e) { IJError.print(e); } unlock(); } } private void destroyCache() { synchronized (db_lock) { try { lock(); if (null != IJ.getInstance() && IJ.getInstance().quitting()) { return; } if (null != imps) { for (ImagePlus imp : imps.removeAll()) { flush(imp); } imps = null; } if (null != mawts) { mawts.removeAndFlushAll(); } } catch (Exception e) { unlock(); IJError.print(e); } finally { unlock(); } } } /** Removes from the cache all awt images bond to the given id. */ public void decacheAWT(final long id) { synchronized (db_lock) { lock(); mawts.removeAndFlush(id); // where are my lisp macros! Wrapping any function in a synch/lock/unlock could be done crudely with reflection, but what a pain unlock(); } } public void cacheOffscreen(final Layer layer, final Image awt) { synchronized (db_lock) { lock(); mawts.put(layer.getId(), awt, 0); unlock(); } } /** Transform mag to nearest scale level that delivers an equally sized or larger image.<br /> * Requires 0 &lt; mag &lt;= 1.0<br /> * Returns -1 if the magnification is NaN or negative or zero.<br /> * As explanation:<br /> * mag = 1 / Math.pow(2, level) <br /> * so that 100% is 0, 50% is 1, 25% is 2, and so on, but represented in values between 0 and 1. */ static public final int getMipMapLevel(final double mag, final double size) { // check parameters if (mag > 1) return 0; // there is no level for mag > 1, so use mag = 1 if (mag <= 0 || Double.isNaN(mag)) return -1; //error signal // int level = (int)(0.0001 + Math.log(1/mag) / Math.log(2)); // compensating numerical instability: 1/0.25 should be 2 eaxctly int max_level = (int)(0.5 + (Math.log(size) - Math.log(32)) / Math.log(2)); // no +1, this is not the length of the images[] array but the actual highest level if (max_level > 6) { Utils.log2("ERROR max_level > 6: " + max_level + ", size: " + size); } return Math.min(level, max_level); /* int level = 0; double scale; while (true) { scale = 1 / Math.pow(2, level); //Utils.log2("scale, mag, level: " + scale + ", " + mag + ", " + level); if (Math.abs(scale - mag) < 0.00000001) { //if (scale == mag) { // floating-point typical behaviour break; } else if (scale < mag) { // provide the previous one level--; break; } // else, continue search level++; } return level; */ } public static final double maxDim(final Displayable d) { return Math.max(d.getWidth(), d.getHeight()); } /** Returns true if there is a cached awt image for the given mag and Patch id. */ public boolean isCached(final Patch p, final double mag) { synchronized (db_lock) { lock(); boolean b = mawts.contains(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); return b; } } public Image getCached(final long id, final int level) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(id, level); unlock(); } return awt; } /** Above or equal in size. */ public Image getCachedClosestAboveImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestAbove(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } /** Below, not equal. */ public Image getCachedClosestBelowImage(final Patch p, final double mag) { Image awt = null; synchronized (db_lock) { lock(); awt = mawts.getClosestBelow(p.getId(), Loader.getMipMapLevel(mag, maxDim(p))); unlock(); } return awt; } protected class PatchLoadingLock extends Lock { String key; PatchLoadingLock(String key) { this.key = key; } } /** Table of dynamic locks, a single one per Patch if any. */ private Hashtable<String,PatchLoadingLock> ht_plocks = new Hashtable<String,PatchLoadingLock>(); protected final PatchLoadingLock getOrMakePatchLoadingLock(final Patch p, final int level) { final String key = p.getId() + "." + level; PatchLoadingLock plock = ht_plocks.get(key); if (null != plock) return plock; plock = new PatchLoadingLock(key); ht_plocks.put(key, plock); return plock; } protected final void removePatchLoadingLock(final PatchLoadingLock pl) { ht_plocks.remove(pl.key); } public Image fetchImage(Patch p) { return fetchImage(p, 1.0); } /** Fetch a suitable awt.Image for the given mag(nification). * If the mag is bigger than 1.0, it will return as if was 1.0. * Will return Loader.NOT_FOUND if, err, not found (probably an Exception will print along). */ public Image fetchImage(final Patch p, double mag) { // Below, the complexity of the synchronized blocks is to provide sufficient granularity. Keep in mind that only one thread at at a time can access a synchronized block for the same object (in this case, the db_lock), and thus calling lock() and unlock() is not enough. One needs to break the statement in as many synch blocks as possible for maximizing the number of threads concurrently accessing different parts of this function. if (mag > 1.0) mag = 1.0; // Don't want to create gigantic images! final int level = Loader.getMipMapLevel(mag, maxDim(p)); // testing: // if (level > 0) level--; // passing an image double the size, so it's like interpolating when doing nearest neighbor since the images are blurred with sigma 0.5 // SLOW, very slow ... // find an equal or larger existing pyramid awt Image mawt = null; final long id = p.getId(); long n_bytes = 0; PatchLoadingLock plock = null; synchronized (db_lock) { lock(); try { if (null == mawts) { return NOT_FOUND; // when lazy repainting after closing a project, the awts is null } if (level > 0 && isMipMapsEnabled()) { // 1 - check if the exact level is cached mawt = mawts.get(id, level); if (null != mawt) { //Utils.log2("returning cached exact mawt for level " + level); return mawt; } // releaseMemory(); plock = getOrMakePatchLoadingLock(p, level); } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } // 2 - check if the exact file is present for the desired level if (level > 0 && isMipMapsEnabled()) { synchronized (plock) { plock.lock(); synchronized (db_lock) { lock(); mawt = mawts.get(id, level); unlock(); } if (null != mawt) { plock.unlock(); return mawt; // was loaded by a different thread } // going to load: synchronized (db_lock) { lock(); n_bytes = estimateImageFileSize(p, level); max_memory -= n_bytes; unlock(); } releaseToFit(n_bytes * 3); // triple, for the jpeg decoder alloc/dealloc at least 2 copies mawt = fetchMipMapAWT(p, level); synchronized (db_lock) { try { lock(); max_memory += n_bytes; if (null != mawt) { mawts.put(id, mawt, level); //Utils.log2("returning exact mawt from file for level " + level); Display.repaintSnapshot(p); return mawt; } // 3 - else, load closest level to it but still giving a larger image int lev = getClosestMipMapLevel(p, level); // finds the file for the returned level, otherwise returns zero //Utils.log2("closest mipmap level is " + lev); if (lev > 0) { mawt = mawts.getClosestAbove(id, lev); boolean newly_cached = false; if (null == mawt) { // reload existing scaled file releaseToFit(n_bytes); // overshooting mawt = fetchMipMapAWT2(p, lev); if (null != mawt) { mawts.put(id, mawt, lev); newly_cached = true; // means: cached was false, now it is } // else if null, the file did not exist or could not be regenerated or regeneration is off } //Utils.log2("from getClosestMipMapLevel: mawt is " + mawt); if (null != mawt) { if (newly_cached) Display.repaintSnapshot(p); //Utils.log2("returning from getClosestMipMapAWT with level " + lev); return mawt; } } else if (ERROR_PATH_NOT_FOUND == lev) { mawt = NOT_FOUND; } } catch (Exception e) { IJError.print(e); } finally { removePatchLoadingLock(plock); unlock(); plock.unlock(); } } } } synchronized (db_lock) { try { lock(); // 4 - check if any suitable level is cached (whithout mipmaps, it may be the large image) mawt = mawts.getClosestAbove(id, level); if (null != mawt) { //Utils.log2("returning from getClosest with level " + level); return mawt; } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } // 5 - else, fetch the ImageProcessor and make an image from it of the proper size and quality ImageProcessor ip = fetchImageProcessor(p); synchronized (db_lock) { try { lock(); if (null != ip && null != ip.getPixels()) { // if NOT mag == 1.0 // but 0.75 also needs the 1.0 ... problem is, I can't cache level 1.5 or so ImagePlus imp; if (level < 0) { imp = new ImagePlus("", Loader.scaleImage(new ImagePlus("", ip), level, p.getLayer().getParent().snapshotsQuality())); //Utils.log2("mag: " + mag + " w,h: " + imp.getWidth() + ", " + imp.getHeight()); p.putMinAndMax(imp); } else { imp = new ImagePlus("", ip); } mawt = p.createImage(imp); // could lock by calling fetchImagePlus if the imp was null, so CAREFUL mawts.put(id, mawt, level); Display.repaintSnapshot(p); //Utils.log2("Returning from imp with level " + level); return mawt; } } catch (Exception e) { IJError.print(e); } finally { unlock(); } return NOT_FOUND; } } /** Must be called within synchronized db_lock. */ private final Image fetchMipMapAWT2(final Patch p, final int level) { final long size = estimateImageFileSize(p, level); max_memory -= size; unlock(); Image mawt = fetchMipMapAWT(p, level); lock(); max_memory += size; return mawt; } /** Simply reads from the cache, does no reloading at all. If the ImagePlus is not found in the cache, it returns null and the burden is on the calling method to do reconstruct it if necessary. This is intended for the LayerStack. */ public ImagePlus getCachedImagePlus(long id) { synchronized(db_lock) { ImagePlus imp = null; lock(); imp = imps.get(id); unlock(); return imp; } } abstract public ImagePlus fetchImagePlus(Patch p); /** Returns null unless overriden. */ public ImageProcessor fetchImageProcessor(Patch p) { return null; } abstract public Object[] fetchLabel(DLabel label); /**Returns the ImagePlus as a zipped InputStream of bytes; the InputStream has to be closed by whoever is calling this method. */ protected InputStream createZippedStream(ImagePlus imp) throws Exception { FileInfo fi = imp.getFileInfo(); Object info = imp.getProperty("Info"); if (info != null && (info instanceof String)) { fi.info = (String)info; } if (null == fi.description) { fi.description = new ij.io.FileSaver(imp).getDescriptionString(); } //see whether this is a stack or not /* //never the case in my program if (fi.nImages > 1) { IJ.log("saving a stack!"); //virtual stacks would be supported? I don't think so because the FileSaver.saveAsTiffStack(String path) doesn't. if (fi.pixels == null && imp.getStack().isVirtual()) { //don't save it! IJ.showMessage("Virtual stacks not supported."); return false; } //setup stack things as in FileSaver.saveAsTiffStack(String path) fi.sliceLabels = imp.getStack().getSliceLabels(); } */ TiffEncoder te = new TiffEncoder(fi); ByteArrayInputStream i_stream = null; ByteArrayOutputStream o_bytes = new ByteArrayOutputStream(); DataOutputStream o_stream = null; try { /* // works, but not significantly faster and breaks older databases (can't read zipped images properly) byte[] bytes = null; // compress in RAM o_stream = new DataOutputStream(new BufferedOutputStream(o_bytes)); te.write(o_stream); o_stream.flush(); o_stream.close(); Deflater defl = new Deflater(); byte[] unzipped_bytes = o_bytes.toByteArray(); defl.setInput(unzipped_bytes); defl.finish(); bytes = new byte[unzipped_bytes.length]; // this length *should* be enough int length = defl.deflate(bytes); if (length < unzipped_bytes.length) { byte[] bytes2 = new byte[length]; System.arraycopy(bytes, 0, bytes2, 0, length); bytes = bytes2; } */ // old, creates temp file o_bytes = new ByteArrayOutputStream(); // clearing ZipOutputStream zos = new ZipOutputStream(o_bytes); o_stream = new DataOutputStream(new BufferedOutputStream(zos)); zos.putNextEntry(new ZipEntry(imp.getTitle())); te.write(o_stream); o_stream.flush(); //this was missing and was 1) truncating the Path images and 2) preventing the snapshots (which are very small) to be saved at all!! o_stream.close(); // this should ensure the flush above anyway. This can work because closing a ByteArrayOutputStream has no effect. byte[] bytes = o_bytes.toByteArray(); //Utils.showStatus("Zipping " + bytes.length + " bytes...", false); //Utils.debug("Zipped ImagePlus byte array size = " + bytes.length); i_stream = new ByteArrayInputStream(bytes); } catch (Exception e) { Utils.log("Loader: ImagePlus NOT zipped! Problems at writing the ImagePlus using the TiffEncoder.write(dos) :\n " + e); //attempt to cleanup: try { if (null != o_stream) o_stream.close(); if (null != i_stream) i_stream.close(); } catch (IOException ioe) { Utils.log("Loader: Attempt to clean up streams failed."); IJError.print(ioe); } return null; } return i_stream; } /** A dialog to open a stack, making sure there is enough memory for it. */ synchronized public ImagePlus openStack() { final OpenDialog od = new OpenDialog("Select stack", OpenDialog.getDefaultDirectory(), null); String file_name = od.getFileName(); if (null == file_name || file_name.toLowerCase().startsWith("null")) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; File f = new File(dir + file_name); if (!f.exists()) { Utils.showMessage("File " + dir + file_name + " does not exist."); return null; } // avoid opening trakem2 projects if (file_name.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + file_name + " as a stack."); return null; } // estimate file size: assumes an uncompressed tif, or a zipped tif with an average compression ratio of 2.5 long size = f.length() / 1024; // in megabytes if (file_name.length() -4 == file_name.toLowerCase().lastIndexOf(".zip")) { size = (long)(size * 2.5); // 2.5 is a reasonable compression ratio estimate based on my experience } int max_iterations = 15; while (enoughFreeMemory(size)) { if (0 == max_iterations) { // leave it to the Opener class to throw an OutOfMemoryExceptionm if so. break; } max_iterations--; releaseMemory(); } ImagePlus imp_stack = null; try { IJ.redirectErrorMessages(); imp_stack = opener.openImage(f.getCanonicalPath()); } catch (Exception e) { IJError.print(e); return null; } if (null == imp_stack) { Utils.showMessage("Can't open the stack."); return null; } else if (1 == imp_stack.getStackSize()) { Utils.showMessage("Not a stack!"); return null; } return imp_stack; // the open... command } public Bureaucrat importSequenceAsGrid(Layer layer) { return importSequenceAsGrid(layer, null); } public Bureaucrat importSequenceAsGrid(final Layer layer, String dir) { return importSequenceAsGrid(layer, dir, null); } /** Open one of the images to find out the dimensions, and get a good guess at what is the desirable scale for doing phase- and cross-correlations with about 512x512 images. */ private int getCCScaleGuess(final File images_dir, final String[] all_images) { try { if (null != all_images && all_images.length > 0) { Utils.showStatus("Opening one image ... "); String sdir = images_dir.getAbsolutePath().replace('\\', '/'); if (!sdir.endsWith("/")) sdir += "/"; IJ.redirectErrorMessages(); ImagePlus imp = opener.openImage(sdir + all_images[0]); if (null != imp) { int w = imp.getWidth(); int h = imp.getHeight(); flush(imp); imp = null; int cc_scale = (int)((512.0 / (w > h ? w : h)) * 100); if (cc_scale > 100) return 100; return cc_scale; } } } catch (Exception e) { Utils.log2("Could not get an estimate for the optimal scale."); } return 25; } /** Import a sequence of images as a grid, and put them in the layer. If the directory (@param dir) is null, it'll be asked for. The image_file_names can be null, and in any case it's only the names, not the paths. */ public Bureaucrat importSequenceAsGrid(final Layer layer, String dir, final String[] image_file_names) { try { String[] all_images = null; String file = null; // first file File images_dir = null; if (null != dir && null != image_file_names) { all_images = image_file_names; images_dir = new File(dir); } else if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; images_dir = new File(dir); } else { images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } } if (null == image_file_names) all_images = images_dir.list(new ini.trakem2.io.ImageFileFilter("", null)); if (null == file && all_images.length > 0) { file = all_images[0]; } int n_max = all_images.length; String preprocessor = ""; int n_rows = 0; int n_cols = 0; double bx = 0; double by = 0; double bt_overlap = 0; double lr_overlap = 0; boolean link_images = true; boolean stitch_tiles = true; boolean homogenize_contrast = true; /** Need some sort of user properties system. */ /* String username = System.getProperty("user.name"); if (null != username && (username.equals("albert") || username.equals("cardona"))) { preprocessor = ""; //"Adjust_EMMENU_Images"; link_images = false; //true; bt_overlap = 204.8; //102.4; lr_overlap = 204.8; //102.4; // testing cross-correlation stitch_tiles = true; homogenize_contrast = true; } */ // reasonable estimate n_rows = n_cols = (int)Math.floor(Math.sqrt(n_max)); GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_matches: ", ""); gd.addNumericField("first_image: ", 1, 0); gd.addNumericField("last_image: ", n_max, 0); gd.addNumericField("number_of_rows: ", n_rows, 0); gd.addNumericField("number_of_columns: ", n_cols, 0); gd.addMessage("The top left coordinate for the imported grid:"); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Amount of image overlap, in pixels"); gd.addNumericField("bottom-top overlap: ", bt_overlap, 2); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", lr_overlap, 2); gd.addCheckbox("link images", link_images); gd.addStringField("preprocess with: ", preprocessor); // the name of a plugin to use for preprocessing the images before importing, which implements PlugInFilter gd.addCheckbox("use_cross-correlation", stitch_tiles); StitchingTEM.addStitchingRuleChoice(gd); gd.addSlider("tile_overlap (%): ", 1, 100, 10); gd.addSlider("cc_scale (%):", 1, 100, getCCScaleGuess(images_dir, all_images)); gd.addCheckbox("homogenize_contrast", homogenize_contrast); final Component[] c = { (Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), (Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-2), c, null); gd.showDialog(); if (gd.wasCanceled()) return null; final String regex = gd.getNextString(); Utils.log2(new StringBuffer("using regex: ").append(regex).toString()); // avoid destroying backslashes int first = (int)gd.getNextNumber(); if (first < 1) first = 1; int last = (int)gd.getNextNumber(); if (last < 1) last = 1; if (last < first) { Utils.showMessage("Last is smaller that first!"); return null; } n_rows = (int)gd.getNextNumber(); n_cols = (int)gd.getNextNumber(); bx = gd.getNextNumber(); by = gd.getNextNumber(); bt_overlap = gd.getNextNumber(); lr_overlap = gd.getNextNumber(); link_images = gd.getNextBoolean(); preprocessor = gd.getNextString().replace(' ', '_'); // just in case stitch_tiles = gd.getNextBoolean(); float cc_percent_overlap = (float)gd.getNextNumber() / 100f; float cc_scale = (float)gd.getNextNumber() / 100f; homogenize_contrast = gd.getNextBoolean(); int stitching_rule = gd.getNextChoiceIndex(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } String[] file_names = null; if (null == image_file_names) { file_names = images_dir.list(new ini.trakem2.io.ImageFileFilter(regex, null)); Arrays.sort(file_names); //assumes 001, 002, 003 ... that style, since it does binary sorting of strings } else { file_names = all_images; } if (0 == file_names.length) { Utils.showMessage("No images found."); return null; } // check if the selected image is in the list. Otherwise, shift selected image to the first of the included ones. boolean found_first = false; for (int i=0; i<file_names.length; i++) { if (file.equals(file_names[i])) { found_first = true; break; } } if (!found_first) { file = file_names[0]; Utils.log("Using " + file + " as the reference image for size."); } // crop list if (last > file_names.length) last = file_names.length -1; if (first < 1) first = 1; if (1 != first || last != file_names.length) { Utils.log("Cropping list."); String[] file_names2 = new String[last - first + 1]; System.arraycopy(file_names, first -1, file_names2, 0, file_names2.length); file_names = file_names2; } // should be multiple of rows and cols if (file_names.length != n_rows * n_cols) { Utils.log2("n_images:" + file_names.length + " rows,cols : " + n_rows + "," + n_cols + " total=" + n_rows*n_cols); Utils.showMessage("rows * cols does not match with the number of selected images."); return null; } // put in columns ArrayList cols = new ArrayList(); for (int i=0; i<n_cols; i++) { String[] col = new String[n_rows]; for (int j=0; j<n_rows; j++) { col[j] = file_names[j*n_cols + i]; } cols.add(col); } return insertGrid(layer, dir, file, file_names.length, cols, bx, by, bt_overlap, lr_overlap, link_images, preprocessor, stitch_tiles, cc_percent_overlap, cc_scale, homogenize_contrast, stitching_rule); } catch (Exception e) { IJError.print(e); } return null; } private ImagePlus preprocess(String preprocessor, ImagePlus imp, String path) { if (null == imp) return null; try { startSetTempCurrentImage(imp); IJ.redirectErrorMessages(); Object ob = IJ.runPlugIn(preprocessor, "[path=" + path + "]"); ImagePlus pp_imp = WindowManager.getCurrentImage(); if (null != pp_imp) { finishSetTempCurrentImage(); return pp_imp; } else { // discard this image Utils.log("Ignoring " + imp.getTitle() + " from " + path + " since the preprocessor " + preprocessor + " returned null on it."); flush(imp); finishSetTempCurrentImage(); return null; } } catch (Exception e) { IJError.print(e); finishSetTempCurrentImage(); Utils.log("Ignoring " + imp.getTitle() + " from " + path + " since the preprocessor " + preprocessor + " throwed an Exception on it."); flush(imp); } return null; } public Bureaucrat importGrid(Layer layer) { return importGrid(layer, null); } /** Import a grid of images and put them in the layer. If the directory (@param dir) is null, it'll be asked for. */ public Bureaucrat importGrid(Layer layer, String dir) { try { String file = null; if (null == dir) { String[] dn = Utils.selectFile("Select first image"); if (null == dn) return null; dir = dn[0]; file = dn[1]; } String convention = "cdd"; // char digit digit boolean chars_are_columns = true; // examine file name /* if (file.matches("\\A[a-zA-Z]\\d\\d.*")) { // one letter, 2 numbers //means: // \A - beggining of input // [a-zA-Z] - any letter upper or lower case // \d\d - two consecutive digits // .* - any row of chars ini_grid_convention = true; } */ // ask for chars->rows, numbers->columns or viceversa GenericDialog gd = new GenericDialog("Conventions"); gd.addStringField("file_name_contains:", ""); gd.addNumericField("base_x: ", 0, 3); gd.addNumericField("base_y: ", 0, 3); gd.addMessage("Use: x(any), c(haracter), d(igit)"); gd.addStringField("convention: ", convention); final String[] cr = new String[]{"columns", "rows"}; gd.addChoice("characters are: ", cr, cr[0]); gd.addMessage("[File extension ignored]"); gd.addNumericField("bottom-top overlap: ", 0, 3); //as asked by Joachim Walter gd.addNumericField("left-right overlap: ", 0, 3); gd.addCheckbox("link_images", false); gd.addStringField("Preprocess with: ", ""); // the name of a plugin to use for preprocessing the images before importing, which implements Preprocess gd.addCheckbox("use_cross-correlation", false); StitchingTEM.addStitchingRuleChoice(gd); gd.addSlider("tile_overlap (%): ", 1, 100, 10); gd.addSlider("cc_scale (%):", 1, 100, 25); gd.addCheckbox("homogenize_contrast", true); final Component[] c = { (Component)gd.getSliders().get(gd.getSliders().size()-2), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-2), (Component)gd.getSliders().get(gd.getSliders().size()-1), (Component)gd.getNumericFields().get(gd.getNumericFields().size()-1), (Component)gd.getChoices().get(gd.getChoices().size()-1) }; // enable the checkbox to control the slider and its associated numeric field: Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(gd.getCheckboxes().size()-1), c, null); gd.showDialog(); if (gd.wasCanceled()) { return null; } //collect data String regex = gd.getNextString(); // filter away files not containing this tag // the base x,y of the whole grid double bx = gd.getNextNumber(); double by = gd.getNextNumber(); //if (!ini_grid_convention) { convention = gd.getNextString().toLowerCase(); //} if (/*!ini_grid_convention && */ (null == convention || convention.equals("") || -1 == convention.indexOf('c') || -1 == convention.indexOf('d'))) { // TODO check that the convention has only 'cdx' chars and also that there is an island of 'c's and of 'd's only. Utils.showMessage("Convention '" + convention + "' needs both c(haracters) and d(igits), optionally 'x', and nothing else!"); return null; } chars_are_columns = (0 == gd.getNextChoiceIndex()); double bt_overlap = gd.getNextNumber(); double lr_overlap = gd.getNextNumber(); boolean link_images = gd.getNextBoolean(); String preprocessor = gd.getNextString(); boolean stitch_tiles = gd.getNextBoolean(); float cc_percent_overlap = (float)gd.getNextNumber() / 100f; float cc_scale = (float)gd.getNextNumber() / 100f; boolean homogenize_contrast = gd.getNextBoolean(); int stitching_rule = gd.getNextChoiceIndex(); // Ensure tiles overlap if using SIFT if (StitchingTEM.FREE_RULE == stitching_rule) { if (bt_overlap <= 0) bt_overlap = 1; if (lr_overlap <= 0) lr_overlap = 1; } //start magic //get ImageJ-openable files that comply with the convention File images_dir = new File(dir); if (!(images_dir.exists() && images_dir.isDirectory())) { Utils.showMessage("Something went wrong:\n\tCan't find directory " + dir); return null; } String[] file_names = images_dir.list(new ImageFileFilter(regex, convention)); if (null == file && file_names.length > 0) { // the 'selected' file file = file_names[0]; } Utils.showStatus("Adding " + file_names.length + " patches."); if (0 == file_names.length) { Utils.log("Zero files match the convention '" + convention + "'"); return null; } // How to: select all files, and order their names in a double array as they should be placed in the Display. Then place them, displacing by offset, and resizing if necessary. // gather image files: Montage montage = new Montage(convention, chars_are_columns); montage.addAll(file_names); ArrayList cols = montage.getCols(); // an array of Object[] arrays, of unequal length maybe, each containing a column of image file names return insertGrid(layer, dir, file, file_names.length, cols, bx, by, bt_overlap, lr_overlap, link_images, preprocessor, stitch_tiles, cc_percent_overlap, cc_scale, homogenize_contrast, stitching_rule); } catch (Exception e) { IJError.print(e); } return null; } /** * @param layer The Layer to inser the grid into * @param dir The base dir of the images to open * @param cols The list of columns, containing each an array of String file names in each column. * @param bx The top-left X coordinate of the grid to insert * @param by The top-left Y coordinate of the grid to insert * @param bt_overlap bottom-top overlap of the images * @param lr_overlap left-right overlap of the images * @param link_images Link images to their neighbors. * @param preproprecessor The name of a PluginFilter in ImageJ's plugin directory, to be called on every image prior to insertion. */ private Bureaucrat insertGrid(final Layer layer, final String dir_, final String first_image_name, final int n_images, final ArrayList cols, final double bx, final double by, final double bt_overlap, final double lr_overlap, final boolean link_images, final String preprocessor, final boolean stitch_tiles, final float cc_percent_overlap, final float cc_scale, final boolean homogenize_contrast, final int stitching_rule) { // create a Worker, then give it to the Bureaucrat Worker worker = new Worker("Inserting grid") { public void run() { startedWorking(); try { String dir = dir_; ArrayList al = new ArrayList(); setMassiveMode(true);//massive_mode = true; Utils.showProgress(0.0D); opener.setSilentMode(true); // less repaints on IJ status bar Utils.log2("Preprocessor plugin: " + preprocessor); boolean preprocess = null != preprocessor && preprocessor.length() > 0; if (preprocess) { // check the given plugin IJ.redirectErrorMessages(); startSetTempCurrentImage(null); try { Object ob = IJ.runPlugIn(preprocessor, ""); if (!(ob instanceof PlugInFilter)) { Utils.showMessageT("Plug in " + preprocessor + " is invalid: does not implement interface PlugInFilter"); finishSetTempCurrentImage(); return; } finishSetTempCurrentImage(); } catch (Exception e) { IJError.print(e); finishSetTempCurrentImage(); Utils.showMessageT("Plug in " + preprocessor + " is invalid: ImageJ has trhown an exception when testing it with a null image."); return; } } int x = 0; int y = 0; int largest_y = 0; ImagePlus img = null; // open the selected image, to use as reference for width and height if (!enoughFreeMemory(MIN_FREE_BYTES)) releaseMemory(); dir = dir.replace('\\', '/'); // w1nd0wz safe if (!dir.endsWith("/")) dir += "/"; String path = dir + first_image_name; IJ.redirectErrorMessages(); ImagePlus first_img = opener.openImage(path); if (null == first_img) { Utils.log("Selected image to open first is null."); return; } if (preprocess) first_img = preprocess(preprocessor, first_img, path); else preProcess(first_img); // the system wide, if any if (null == first_img) return; final int first_image_width = first_img.getWidth(); final int first_image_height = first_img.getHeight(); final int first_image_type = first_img.getType(); // start final Patch[][] pall = new Patch[cols.size()][((String[])cols.get(0)).length]; int width, height; int k = 0; //counter boolean auto_fix_all = false; boolean ignore_all = false; boolean resize = false; if (!ControlWindow.isGUIEnabled()) { // headless mode: autofix all auto_fix_all = true; resize = true; } startLargeUpdate(); for (int i=0; i<cols.size(); i++) { String[] rows = (String[])cols.get(i); if (i > 0) { x -= lr_overlap; } for (int j=0; j<rows.length; j++) { if (this.quit) { Display.repaint(layer); rollback(); return; } if (j > 0) { y -= bt_overlap; } // get file name String file_name = (String)rows[j]; path = dir + file_name; if (null != first_img && file_name.equals(first_image_name)) { img = first_img; first_img = null; // release pointer } else { // open image //if (!enoughFreeMemory(MIN_FREE_BYTES)) releaseMemory(); // UNSAFE, doesn't wait for GC releaseToFit(first_image_width, first_image_height, first_image_type, 1.5f); try { IJ.redirectErrorMessages(); img = opener.openImage(path); } catch (OutOfMemoryError oome) { printMemState(); throw oome; } // Preprocess ImagePlus if (preprocess) { img = preprocess(preprocessor, img, path); if (null == img) continue; } else { // use standard project wide , if any preProcess(img); } } if (null == img) { Utils.log("null image! skipping."); pall[i][j] = null; continue; } width = img.getWidth(); height = img.getHeight(); int rw = width; int rh = height; if (width != first_image_width || height != first_image_height) { int new_width = first_image_width; int new_height = first_image_height; if (!auto_fix_all && !ignore_all) { GenericDialog gdr = new GenericDialog("Size mismatch!"); gdr.addMessage("The size of " + file_name + " is " + width + " x " + height); gdr.addMessage("but the selected image was " + first_image_width + " x " + first_image_height); gdr.addMessage("Adjust to selected image dimensions?"); gdr.addNumericField("width: ", (double)first_image_width, 0); gdr.addNumericField("height: ", (double)first_image_height, 0); // should not be editable ... or at least, explain in some way that the dimensions can be edited just for this image --> done below gdr.addMessage("[If dimensions are changed they will apply only to this image]"); gdr.addMessage(""); String[] au = new String[]{"fix all", "ignore all"}; gdr.addChoice("Automate:", au, au[1]); gdr.addMessage("Cancel == NO OK = YES"); gdr.showDialog(); if (gdr.wasCanceled()) { resize = false; // do nothing: don't fix/resize } resize = true; //catch values new_width = (int)gdr.getNextNumber(); new_height = (int)gdr.getNextNumber(); int iau = gdr.getNextChoiceIndex(); if (new_width != first_image_width || new_height != first_image_height) { auto_fix_all = false; } else { auto_fix_all = (0 == iau); } ignore_all = (1 == iau); if (ignore_all) resize = false; } if (resize) { //resize Patch dimensions rw = first_image_width; rh = first_image_height; } } //add new Patch at base bx,by plus the x,y of the grid Patch patch = new Patch(layer.getProject(), img.getTitle(), bx + x, by + y, img); // will call back and cache the image if (width != rw || height != rh) patch.setDimensions(rw, rh, false); addedPatchFrom(path, patch); if (homogenize_contrast) setMipMapsRegeneration(false); // prevent it else generateMipMaps(patch); // layer.add(patch, true); // after the above two lines! Otherwise it will paint fine, but throw exceptions on the way patch.updateInDatabase("tiff_snapshot"); // otherwise when reopening it has to fetch all ImagePlus and scale and zip them all! This method though creates the awt and the snap, thus filling up memory and slowing down, but it's worth it. pall[i][j] = patch; al.add(patch); if (ControlWindow.isGUIEnabled()) { layer.getParent().enlargeToFit(patch, LayerSet.NORTHWEST); // northwest to prevent screwing up Patch coordinates. } y += img.getHeight(); Utils.showProgress((double)k / n_images); k++; } x += img.getWidth(); if (largest_y < y) { largest_y = y; } y = 0; //resetting! } // build list final Patch[] pa = new Patch[al.size()]; int f = 0; // list in row-first order for (int j=0; j<pall[0].length; j++) { // 'j' is row for (int i=0; i<pall.length; i++) { // 'i' is column pa[f++] = pall[i][j]; } } // optimize repaints: all to background image Display.clearSelection(layer); // make the first one be top, and the rest under it in left-right and top-bottom order for (int j=0; j<pa.length; j++) { layer.moveBottom(pa[j]); } // make picture //getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show(); // optimize repaints: all to background image Display.clearSelection(layer); if (homogenize_contrast) { setTaskName("homogenizing contrast"); // 0 - check that all images are of the same type int tmp_type = pa[0].getType(); for (int e=1; e<pa.length; e++) { if (pa[e].getType() != tmp_type) { // can't continue tmp_type = Integer.MAX_VALUE; Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + al.get(e)); break; } } if (Integer.MAX_VALUE != tmp_type) { // checking on error flag // Set min and max for all images // 1 - fetch statistics for each image final ArrayList al_st = new ArrayList(); final ArrayList al_p = new ArrayList(); // list of Patch ordered by stdDev ASC int type = -1; releaseMemory(); // need some to operate for (int i=0; i<pa.length; i++) { if (this.quit) { Display.repaint(layer); rollback(); return; } ImagePlus imp = fetchImagePlus(pa[i]); // speed-up trick: extract data from smaller image if (imp.getWidth() > 1024) { releaseToFit(1024, (int)((imp.getHeight() * 1024) / imp.getWidth()), imp.getType(), 1.1f); // cheap and fast nearest-point resizing imp = new ImagePlus(imp.getTitle(), imp.getProcessor().resize(1024)); } if (-1 == type) type = imp.getType(); ImageStatistics i_st = imp.getStatistics(); // order by stdDev, from small to big int q = 0; for (Iterator it = al_st.iterator(); it.hasNext(); ) { ImageStatistics st = (ImageStatistics)it.next(); q++; if (st.stdDev > i_st.stdDev) break; } if (q == al.size()) { al_st.add(i_st); // append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below al_p.add(pa[i]); } else { al_st.add(q, i_st); al_p.add(q, pa[i]); } } final ArrayList al_p2 = (ArrayList)al_p.clone(); // shallow copy of the ordered list // 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here) if (pa.length > 3) { // under 4 images, use them all int i=0; while (i <= pa.length * 0.25) { al_p.remove(i); i++; } int count = i; i = pa.length -1 -count; while (i > (pa.length* 0.75) - count) { al_p.remove(i); i--; } } // 3 - compute common histogram for the middle 50% images final Patch[] p50 = new Patch[al_p.size()]; al_p.toArray(p50); StackStatistics stats = new StackStatistics(new PatchStack(p50, 1)); int n = 1; switch (type) { case ImagePlus.GRAY16: case ImagePlus.GRAY32: n = 2; break; } // 4 - compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; double min = 0; double max = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } // 5 - compute common mean within min,max range double target_mean = getMeanOfRange(stats, min, max); Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean); // 6 - apply to all for (i=al_p2.size()-1; i>-1; i--) { Patch p = (Patch)al_p2.get(i); // the order is different, thus getting it from the proper list double dm = target_mean - getMeanOfRange((ImageStatistics)al_st.get(i), min, max); p.setMinAndMax(min - dm, max - dm); // displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean p.putMinAndMax(fetchImagePlus(p)); } if (isMipMapsEnabled()) { setTaskName("Regenerating snapshots."); // recreate files Utils.log2("Generating mipmaps for " + al.size() + " patches."); Thread t = generateMipMaps(al, false); if (null != t) try { t.join(); } catch (InterruptedException ie) {} } // 7 - flush away any existing awt images, so that they'll be recreated with the new min and max synchronized (db_lock) { lock(); for (i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + "removing mawt for " + pa[i].getId()); } unlock(); } setMipMapsRegeneration(true); Display.repaint(layer, new Rectangle(0, 0, (int)layer.getParent().getLayerWidth(), (int)layer.getParent().getLayerHeight()), 0); // make picture //getFlatImage(layer, layer.getMinimalBoundingBox(Patch.class), 0.25, 1, ImagePlus.GRAY8, Patch.class, null, false).show(); } } if (stitch_tiles) { setTaskName("stitching tiles"); // create undo layer.getParent().createUndoStep(layer); // wait until repainting operations have finished (otherwise, calling crop on an ImageProcessor fails with out of bounds exception sometimes) if (null != Display.getFront()) Display.getFront().getCanvas().waitForRepaint(); Bureaucrat task = StitchingTEM.stitch(pa, cols.size(), cc_percent_overlap, cc_scale, bt_overlap, lr_overlap, true, stitching_rule); if (null != task) try { task.join(); } catch (Exception e) {} } // link with images on top, bottom, left and right. if (link_images) { for (int i=0; i<pall.length; i++) { // 'i' is column for (int j=0; j<pall[0].length; j++) { // 'j' is row Patch p = pall[i][j]; if (null == p) continue; // can happen if a slot is empty if (i>0 && null != pall[i-1][j]) p.link(pall[i-1][j]); if (i<pall.length -1 && null != pall[i+1][j]) p.link(pall[i+1][j]); if (j>0 && null != pall[i][j-1]) p.link(pall[i][j-1]); if (j<pall[0].length -1 && null != pall[i][j+1]) p.link(pall[i][j+1]); } } } commitLargeUpdate(); // resize LayerSet int new_width = x; int new_height = largest_y; layer.getParent().setMinimumDimensions(); //Math.abs(bx) + new_width, Math.abs(by) + new_height); // update indexes layer.updateInDatabase("stack_index"); // so its done once only // create panels in all Displays showing this layer /* // not needed anymore Iterator it = al.iterator(); while (it.hasNext()) { Display.add(layer, (Displayable)it.next(), false); // don't set it active, don't want to reload the ImagePlus! } */ // update Displays Display.update(layer); //reset Loader mode setMassiveMode(false);//massive_mode = false; //debug: } catch (Throwable t) { IJError.print(t); rollback(); setMassiveMode(false); //massive_mode = false; setMipMapsRegeneration(true); } finishedWorking(); }// end of run method }; // watcher thread Bureaucrat burro = new Bureaucrat(worker, layer.getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat importImages(final Layer ref_layer) { return importImages(ref_layer, null, null, 0, 0); } /** Import images from the given text file, which is expected to contain 4 columns:<br /> * - column 1: image file path (if base_dir is not null, it will be prepended)<br /> * - column 2: x coord<br /> * - column 3: y coord<br /> * - column 4: z coord (layer_thickness will be multiplied to it if not zero)<br /> * * Layers will be automatically created as needed inside the LayerSet to which the given ref_layer belongs.. <br /> * The text file can contain comments that start with the # sign.<br /> * Images will be imported in parallel, using as many cores as your machine has.<br /> * The @param calibration transforms the read coordinates into pixel coordinates, including x,y,z, and layer thickness. */ public Bureaucrat importImages(Layer ref_layer, String abs_text_file_path_, String column_separator_, double layer_thickness_, double calibration_) { // check parameters: ask for good ones if necessary if (null == abs_text_file_path_) { String[] file = Utils.selectFile("Select text file"); if (null == file) return null; // user canceled dialog abs_text_file_path_ = file[0] + file[1]; } if (null == ref_layer || null == column_separator_ || 0 == column_separator_.length() || Double.isNaN(layer_thickness_) || layer_thickness_ <= 0 || Double.isNaN(calibration_) || calibration_ <= 0) { GenericDialog gdd = new GenericDialog("Options"); String[] separators = new String[]{"tab", "space", "coma (,)"}; gdd.addMessage("Choose a layer to act as the zero for the Z coordinates:"); Utils.addLayerChoice("Base layer", ref_layer, gdd); gdd.addChoice("Column separator: ", separators, separators[0]); gdd.addNumericField("Layer thickness: ", 60, 2); // default: 60 nm gdd.addNumericField("Calibration (data to pixels): ", 1, 2); gdd.showDialog(); if (gdd.wasCanceled()) return null; layer_thickness_ = gdd.getNextNumber(); if (layer_thickness_ < 0 || Double.isNaN(layer_thickness_)) { Utils.log("Improper layer thickness value."); return null; } calibration_ = gdd.getNextNumber(); if (0 == calibration_ || Double.isNaN(calibration_)) { Utils.log("Improper calibration value."); return null; } ref_layer = ref_layer.getParent().getLayer(gdd.getNextChoiceIndex()); column_separator_ = "\t"; switch (gdd.getNextChoiceIndex()) { case 1: column_separator_ = " "; break; case 2: column_separator_ = ","; break; default: break; } } // make vars accessible from inner threads: final Layer base_layer = ref_layer; final String abs_text_file_path = abs_text_file_path_; final String column_separator = column_separator_; final double layer_thickness = layer_thickness_; final double calibration = calibration_; GenericDialog gd = new GenericDialog("Options"); gd.addMessage("For all touched layers:"); gd.addCheckbox("Homogenize histograms", false); gd.addCheckbox("Register tiles and layers", true); gd.addCheckbox("With overlapping tiles only", true); // TODO could also use near tiles, defining near as "within a radius of one image width from the center of the tile" final Component[] c_enable = { (Component)gd.getCheckboxes().get(2) }; Utils.addEnablerListener((Checkbox)gd.getCheckboxes().get(1), c_enable, null); gd.showDialog(); if (gd.wasCanceled()) return null; final boolean homogenize_contrast = gd.getNextBoolean(); final boolean register_tiles = gd.getNextBoolean(); final boolean overlapping_only = gd.getNextBoolean(); final int layer_subset = gd.getNextChoiceIndex(); final Set touched_layers = Collections.synchronizedSet(new HashSet()); gd = null; final Worker worker = new Worker("Importing images") { public void run() { startedWorking(); final Worker wo = this; try { // 1 - read text file final String[] lines = Utils.openTextFileLines(abs_text_file_path); if (null == lines || 0 == lines.length) { Utils.log2("No images to import from " + abs_text_file_path); finishedWorking(); return; } final String sep2 = column_separator + column_separator; // 2 - set a base dir path if necessary final String[] base_dir = new String[]{null, null}; // second item will work as flag if the dialog to ask for a directory is canceled in any of the threads. ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = MultiThreading.newThreads(); final Lock lock = new Lock(); final LayerSet layer_set = base_layer.getParent(); final double z_zero = base_layer.getZ(); final AtomicInteger n_imported = new AtomicInteger(0); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread(new Runnable() { public void run() { /////////////////////////////// // 3 - parse each line for (int i = ai.getAndIncrement(); i < lines.length; i = ai.getAndIncrement()) { if (wo.hasQuitted()) return; // process line String line = lines[i].replace('\\','/').trim(); // first thing is the backslash removal, before they get processed at all int ic = line.indexOf('#'); if (-1 != ic) line = line.substring(0, ic); // remove comment at end of line if any if (0 == line.length() || '#' == line.charAt(0)) continue; // reduce line, so that separators are really unique while (-1 != line.indexOf(sep2)) { line = line.replaceAll(sep2, column_separator); } String[] column = line.split(column_separator); if (column.length < 4) { Utils.log("Less than 4 columns: can't import from line " + i + " : " + line); continue; } // obtain coordinates double x=0, y=0, z=0; try { x = Double.parseDouble(column[1].trim()); y = Double.parseDouble(column[2].trim()); z = Double.parseDouble(column[3].trim()); } catch (NumberFormatException nfe) { Utils.log("Non-numeric value in a numeric column at line " + i + " : " + line); continue; } x *= calibration; y *= calibration; z = z * calibration + z_zero; // obtain path String path = column[0].trim(); if (0 == path.length()) continue; // check if path is relative if ((!IJ.isWindows() && '/' != path.charAt(0)) || (IJ.isWindows() && 1 != path.indexOf(":/"))) { synchronized (lock) { lock.lock(); if ("QUIT".equals(base_dir[1])) { // dialog to ask for directory was quitted lock.unlock(); finishedWorking(); return; } // path is relative. if (null == base_dir[0]) { // may not be null if another thread that got the lock first set it to non-null // Ask for source directory DirectoryChooser dc = new DirectoryChooser("Choose source directory"); String dir = dc.getDirectory(); if (null == dir) { // quit all threads base_dir[1] = "QUIT"; lock.unlock(); finishedWorking(); return; } // else, set the base dir base_dir[0] = dir.replace('\\', '/'); if (!base_dir[0].endsWith("/")) base_dir[0] += "/"; } lock.unlock(); } } if (null != base_dir[0]) path = base_dir[0] + path; File f = new File(path); if (!f.exists()) { Utils.log("No file found for path " + path); continue; } synchronized (db_lock) { lock(); releaseMemory(); //ensures a usable minimum is free unlock(); } /* */ IJ.redirectErrorMessages(); ImagePlus imp = opener.openImage(path); if (null == imp) { Utils.log("Ignoring unopenable image from " + path); continue; } // add Patch and generate its mipmaps Patch patch = null; Layer layer = null; synchronized (lock) { try { lock.lock(); layer = layer_set.getLayer(z, layer_thickness, true); // will create a new Layer if necessary touched_layers.add(layer); patch = new Patch(layer.getProject(), imp.getTitle(), x, y, imp); addedPatchFrom(path, patch); } catch (Exception e) { IJError.print(e); } finally { lock.unlock(); } } if (null != patch) { if (!generateMipMaps(patch)) { Utils.log("Failed to generate mipmaps for " + patch); } synchronized (lock) { try { lock.lock(); layer.add(patch, true); } catch (Exception e) { IJError.print(e); } finally { lock.unlock(); } } decacheImagePlus(patch.getId()); // no point in keeping it around } wo.setTaskName("Imported " + (n_imported.getAndIncrement() + 1) + "/" + lines.length); } ///////////////////////// } }); } MultiThreading.startAndJoin(threads); ///////////////////////// if (0 == n_imported.get()) { Utils.log("No images imported."); finishedWorking(); return; } base_layer.getParent().setMinimumDimensions(); Display.repaint(base_layer.getParent()); final Layer[] la = new Layer[touched_layers.size()]; touched_layers.toArray(la); if (homogenize_contrast) { setTaskName(""); // layer-wise (layer order is irrelevant): Thread t = homogenizeContrast(la); // multithreaded if (null != t) t.join(); } if (register_tiles) { wo.setTaskName("Registering tiles."); // sequential, from first to last layer Layer first = la[0]; Layer last = la[0]; // order touched layers by Z coord for (int i=1; i<la.length; i++) { if (la[i].getZ() < first.getZ()) first = la[i]; if (la[i].getZ() > last.getZ()) last = la[i]; } LayerSet ls = base_layer.getParent(); List<Layer> las = ls.getLayers().subList(ls.indexOf(first), ls.indexOf(last)+1); // decide if processing all or just the touched ones or what range if (ls.size() != las.size()) { GenericDialog gd = new GenericDialog("Layer Range"); gd.addMessage("Apply registration to layers:"); Utils.addLayerRangeChoices(first, last, gd); gd.showDialog(); if (gd.wasCanceled()) { finishedWorking(); return; } las = ls.getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex()+1); } Layer[] zla = new Layer[las.size()]; zla = las.toArray(zla); Thread t = Registration.registerTilesSIFT(zla, overlapping_only); if (null != t) t.join(); } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, base_layer.getProject()); burro.goHaveBreakfast(); return burro; } private double getMeanOfRange(ImageStatistics st, double min, double max) { if (min == max) return min; double mean = 0; int nn = 0; int first_bin = 0; int last_bin = st.nBins -1; for (int b=0; b<st.nBins; b++) { if (st.min + st.binSize * b > min) { first_bin = b; break; } } for (int b=last_bin; b>first_bin; b--) { if (st.max - st.binSize * b <= max) { last_bin = b; break; } } for (int h=first_bin; h<=last_bin; h++) { nn += st.histogram[h]; mean += h * st.histogram[h]; } return mean /= nn; } /** Used for the revert command. */ abstract public ImagePlus fetchOriginal(Patch patch); /** Set massive mode if not much is cached of the new layer given for loading. */ public void prepare(Layer layer) { /* // this piece of ancient code is doing more harm than good ArrayList al = layer.getDisplayables(); long[] ids = new long[al.size()]; int next = 0; Iterator it = al.iterator(); while (it.hasNext()) { Object ob = it.next(); if (ob instanceof Patch) ids[next++] = ((DBObject)ob).getId(); } int n_cached = 0; double area = 0; if (0 == next) return; // no need else if (n_cached > 0) { // make no assumptions on image compression, assume 8-bit though long estimate = (long)(((area / n_cached) * next * 8) / 1024.0D); // 'next' is total if (!enoughFreeMemory(estimate)) { setMassiveMode(true);//massive_mode = true; } } else setMassiveMode(false); //massive_mode = true; // nothing loaded, so no clue, set it to load fast by flushing fast. */ } /** If the srcRect is null, makes a flat 8-bit or RGB image of the entire layer. Otherwise just of the srcRect. Checks first for enough memory and frees some if feasible. */ public Bureaucrat makeFlatImage(final Layer[] layer, final Rectangle srcRect, final double scale, final int c_alphas, final int type, final boolean force_to_file, final boolean quality) { if (null == layer || 0 == layer.length) { Utils.log2("makeFlatImage: null or empty list of layers to process."); return null; } final Worker worker = new Worker("making flat images") { public void run() { try { // startedWorking(); Rectangle srcRect_ = srcRect; if (null == srcRect_) srcRect_ = layer[0].getParent().get2DBounds(); ImagePlus imp = null; String target_dir = null; boolean choose_dir = force_to_file; // if not saving to a file: if (!force_to_file) { final long size = (long)Math.ceil((srcRect_.width * scale) * (srcRect_.height * scale) * ( ImagePlus.GRAY8 == type ? 1 : 4 ) * layer.length); if (size > IJ.maxMemory() * 0.9) { YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "WARNING", "The resulting stack of flat images is too large to fit in memory.\nChoose a directory to save the slices as an image sequence?"); if (yn.yesPressed()) { choose_dir = true; } else if (yn.cancelPressed()) { finishedWorking(); return; } else { choose_dir = false; // your own risk } } } if (choose_dir) { final DirectoryChooser dc = new DirectoryChooser("Target directory"); target_dir = dc.getDirectory(); if (null == target_dir || target_dir.toLowerCase().startsWith("null")) { finishedWorking(); return; } } if (layer.length > 1) { // 1 - determine stack voxel depth (by choosing one, if there are layers with different thickness) double voxel_depth = 1; if (null != target_dir) { // otherwise, saving separately ArrayList al_thickness = new ArrayList(); for (int i=0; i<layer.length; i++) { Double t = new Double(layer[i].getThickness()); if (!al_thickness.contains(t)) al_thickness.add(t); } if (1 == al_thickness.size()) { // trivial case voxel_depth = ((Double)al_thickness.get(0)).doubleValue(); } else { String[] st = new String[al_thickness.size()]; for (int i=0; i<st.length; i++) { st[i] = al_thickness.get(i).toString(); } GenericDialog gdd = new GenericDialog("Choose voxel depth"); gdd.addChoice("voxel depth: ", st, st[0]); gdd.showDialog(); if (gdd.wasCanceled()) { finishedWorking(); return; } voxel_depth = ((Double)al_thickness.get(gdd.getNextChoiceIndex())).doubleValue(); } } // 2 - get all slices ImageStack stack = null; for (int i=0; i<layer.length; i++) { final ImagePlus slice = getFlatImage(layer[i], srcRect_, scale, c_alphas, type, Displayable.class, quality); if (null == slice) { Utils.log("Could not retrieve flat image for " + layer[i].toString()); continue; } if (null != target_dir) { saveToPath(slice, target_dir, layer[i].getPrintableTitle(), ".tif"); } else { if (null == stack) stack = new ImageStack(slice.getWidth(), slice.getHeight()); stack.addSlice(layer[i].getProject().findLayerThing(layer[i]).toString(), slice.getProcessor()); } } if (null != stack) { imp = new ImagePlus("z=" + layer[0].getZ() + " to z=" + layer[layer.length-1].getZ(), stack); imp.getCalibration().pixelDepth = voxel_depth; } } else { imp = getFlatImage(layer[0], srcRect_, scale, c_alphas, type, Displayable.class, quality); if (null != target_dir) { saveToPath(imp, target_dir, layer[0].getPrintableTitle(), ".tif"); imp = null; // to prevent showing it } } if (null != imp) imp.show(); } catch (Throwable e) { IJError.print(e); } finishedWorking(); }}; // I miss my lisp macros, you have no idea Bureaucrat burro = new Bureaucrat(worker, layer[0].getProject()); burro.goHaveBreakfast(); return burro; } /** Will never overwrite, rather, add an underscore and ordinal to the file name. */ private void saveToPath(final ImagePlus imp, final String dir, final String file_name, final String extension) { if (null == imp) { Utils.log2("Loader.saveToPath: can't save a null image."); return; } // create a unique file name String path = dir + "/" + file_name; File file = new File(path + extension); int k = 1; while (file.exists()) { file = new File(path + "_" + k + ".tif"); k++; } try { new FileSaver(imp).saveAsTiff(file.getAbsolutePath()); } catch (OutOfMemoryError oome) { Utils.log2("Not enough memory. Could not save image for " + file_name); IJError.print(oome); } catch (Exception e) { Utils.log2("Could not save image for " + file_name); IJError.print(e); } } public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, final boolean quality) { return getFlatImage(layer, srcRect_, scale, c_alphas, type, clazz, null, quality); } public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, ArrayList al_displ) { return getFlatImage(layer, srcRect_, scale, c_alphas, type, clazz, al_displ, false); } /** Returns a screenshot of the given layer for the given magnification and srcRect. Returns null if the was not enough memory to create it. * @param al_displ The Displayable objects to paint. If null, all those matching Class clazz are included. * * If the 'quality' flag is given, then the flat image is created at a scale of 1.0, and later scaled down using the Image.getScaledInstance method with the SCALE_AREA_AVERAGING flag. * */ public ImagePlus getFlatImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, ArrayList al_displ, boolean quality) { final Image bi = getFlatAWTImage(layer, srcRect_, scale, c_alphas, type, clazz, al_displ, quality); final ImagePlus imp = new ImagePlus(layer.getPrintableTitle(), bi); bi.flush(); return imp; } public Image getFlatAWTImage(final Layer layer, final Rectangle srcRect_, final double scale, final int c_alphas, final int type, final Class clazz, ArrayList al_displ, boolean quality) { try { // if quality is specified, then a larger image is generated: // - full size if no mipmaps // - double the size if mipmaps is enabled double scaleP = scale; if (quality) { if (isMipMapsEnabled()) { // just double the size scaleP = scale + scale; if (scaleP > 1.0) scaleP = 1.0; } else { // full scaleP = 1.0; } } // dimensions int x = 0; int y = 0; int w = 0; int h = 0; Rectangle srcRect = (null == srcRect_) ? null : (Rectangle)srcRect_.clone(); if (null != srcRect) { x = srcRect.x; y = srcRect.y; w = srcRect.width; h = srcRect.height; } else { w = (int)Math.ceil(layer.getLayerWidth()); h = (int)Math.ceil(layer.getLayerHeight()); srcRect = new Rectangle(0, 0, w, h); } Utils.log2("Loader.getFlatImage: using rectangle " + srcRect); // estimate image size final long n_bytes = (long)((w * h * scaleP * scaleP * (ImagePlus.GRAY8 == type ? 1.0 /*byte*/ : 4.0 /*int*/))); Utils.log2("Flat image estimated size in bytes: " + Long.toString(n_bytes) + " w,h : " + (int)Math.ceil(w * scaleP) + "," + (int)Math.ceil(h * scaleP) + (quality ? " (using 'quality' flag: scaling to " + scale + " is done later with proper area averaging)" : "")); if (!releaseToFit(n_bytes)) { // locks on it's own Utils.showMessage("Not enough free RAM for a flat image."); return null; } // go synchronized (db_lock) { lock(); releaseMemory(); // savage ... unlock(); } BufferedImage bi = null; IndexColorModel icm = null; switch (type) { case ImagePlus.GRAY8: final byte[] r = new byte[256]; final byte[] g = new byte[256]; final byte[] b = new byte[256]; for (int i=0; i<256; i++) { r[i]=(byte)i; g[i]=(byte)i; b[i]=(byte)i; } icm = new IndexColorModel(8, 256, r, g, b); bi = new BufferedImage((int)Math.ceil(w * scaleP), (int)Math.ceil(h * scaleP), BufferedImage.TYPE_BYTE_INDEXED, icm); break; case ImagePlus.COLOR_RGB: bi = new BufferedImage((int)Math.ceil(w * scaleP), (int)Math.ceil(h * scaleP), BufferedImage.TYPE_INT_ARGB); break; default: Utils.log2("Left bi,icm as null"); break; } final Graphics2D g2d = bi.createGraphics(); // fill background with black, since RGB images default to white background if (type == ImagePlus.COLOR_RGB) { g2d.setColor(Color.black); g2d.fillRect(0, 0, bi.getWidth(), bi.getHeight()); } g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // to smooth edges of the images g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); synchronized (db_lock) { lock(); releaseMemory(); // savage ... unlock(); } ArrayList al_zdispl = null; if (null == al_displ) { al_displ = layer.getDisplayables(clazz); al_zdispl = layer.getParent().getZDisplayables(clazz); } else { // separate ZDisplayables into their own array al_displ = (ArrayList)al_displ.clone(); //Utils.log2("al_displ size: " + al_displ.size()); al_zdispl = new ArrayList(); for (Iterator it = al_displ.iterator(); it.hasNext(); ) { Object ob = it.next(); if (ob instanceof ZDisplayable) { it.remove(); al_zdispl.add(ob); } } // order ZDisplayables by their stack order ArrayList al_zdispl2 = layer.getParent().getZDisplayables(); for (Iterator it = al_zdispl2.iterator(); it.hasNext(); ) { Object ob = it.next(); if (!al_zdispl.contains(ob)) it.remove(); } al_zdispl = al_zdispl2; } // prepare the canvas for the srcRect and magnification final AffineTransform at_original = g2d.getTransform(); final AffineTransform atc = new AffineTransform(); atc.scale(scaleP, scaleP); atc.translate(-srcRect.x, -srcRect.y); at_original.preConcatenate(atc); g2d.setTransform(at_original); //Utils.log2("will paint: " + al_displ.size() + " displ and " + al_zdispl.size() + " zdispl"); int total = al_displ.size() + al_zdispl.size(); int count = 0; boolean zd_done = false; for(Iterator it = al_displ.iterator(); it.hasNext(); ) { Displayable d = (Displayable)it.next(); //Utils.log2("d is: " + d); // paint the ZDisplayables before the first label, if any if (!zd_done && d instanceof DLabel) { zd_done = true; for (Iterator itz = al_zdispl.iterator(); itz.hasNext(); ) { ZDisplayable zd = (ZDisplayable)itz.next(); if (!zd.isOutOfRepaintingClip(scaleP, srcRect, null)) { zd.paint(g2d, scaleP, false, c_alphas, layer); } count++; //Utils.log2("Painted " + count + " of " + total); } } if (!d.isOutOfRepaintingClip(scaleP, srcRect, null)) { d.paint(g2d, scaleP, false, c_alphas, layer); //Utils.log("painted: " + d + "\n with: " + scaleP + ", " + c_alphas + ", " + layer); } else { //Utils.log2("out: " + d); } count++; //Utils.log2("Painted " + count + " of " + total); } if (!zd_done) { zd_done = true; for (Iterator itz = al_zdispl.iterator(); itz.hasNext(); ) { ZDisplayable zd = (ZDisplayable)itz.next(); if (!zd.isOutOfRepaintingClip(scaleP, srcRect, null)) { zd.paint(g2d, scaleP, false, c_alphas, layer); } count++; //Utils.log2("Painted " + count + " of " + total); } } // ensure enough memory is available for the processor and a new awt from it releaseToFit((long)(n_bytes*2.3)); // locks on its own try { if (quality) { Image scaled = null; if (!isMipMapsEnabled() || scale >= 0.499) { // there are no proper mipmaps above 50%, so there's need for SCALE_AREA_AVERAGING. scaled = bi.getScaledInstance((int)(w * scale), (int)(h * scale), Image.SCALE_AREA_AVERAGING); // very slow, but best by far if (ImagePlus.GRAY8 == type) { // getScaledInstance generates RGB images for some reason. BufferedImage bi8 = new BufferedImage((int)(w * scale), (int)(h * scale), BufferedImage.TYPE_BYTE_INDEXED, icm); bi8.createGraphics().drawImage(scaled, 0, 0, null); scaled.flush(); scaled = bi8; } } else { // faster, but requires gaussian blurred images (such as the mipmaps) scaled = new BufferedImage((int)(w * scale), (int)(h * scale), bi.getType(), icm); // without a proper grayscale color model, vertical lines appear (is there an underlying problem in the painting?) Graphics2D gs = (Graphics2D)scaled.getGraphics(); //gs.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); gs.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); gs.drawImage(bi, 0, 0, (int)(w * scale), (int)(h * scale), null); } bi.flush(); return scaled; } else { // else the image was made scaled down already, and of the proper type return bi; } } catch (OutOfMemoryError oome) { Utils.log("Not enough memory to create the ImagePlus. Try scaling it down or not using the 'quality' flag."); } } catch (Exception e) { IJError.print(e); } return null; } public Bureaucrat makePrescaledTiles(final Layer[] layer, final Class clazz, final Rectangle srcRect, double max_scale_, final int c_alphas, final int type) { return makePrescaledTiles(layer, clazz, srcRect, max_scale_, c_alphas, type, null); } /** Generate 256x256 tiles, as many as necessary, to cover the given srcRect, starting at max_scale. Designed to be slow but memory-capable. * * filename = z + "/" + row + "_" + column + "_" + s + ".jpg"; * * row and column run from 0 to n stepsize 1 * that is, row = y / ( 256 * 2^s ) and column = x / ( 256 * 2^s ) * * z : z-level (slice) * x,y: the row and column * s: scale, which is 1 / (2^s), in integers: 0, 1, 2 ... * *  var MAX_S = Math.floor( Math.log( MAX_Y + 1 ) / Math.LN2 ) - Math.floor( Math.log( Y_TILE_SIZE ) / Math.LN2 ) - 1; * * The module should not be more than 5 * At al levels, there should be an even number of rows and columns, except for the coarsest level. * The coarsest level should be at least 5x5 tiles. * * Best results obtained when the srcRect approaches or is a square. Black space will pad the right and bottom edges when the srcRect is not exactly a square. * Only the area within the srcRect is ever included, even if actual data exists beyond. * * Returns the watcher thread, for joining purposes, or null if the dialog is canceled or preconditions ar enot passed. */ public Bureaucrat makePrescaledTiles(final Layer[] layer, final Class clazz, final Rectangle srcRect, double max_scale_, final int c_alphas, final int type, String target_dir) { if (null == layer || 0 == layer.length) return null; // choose target directory if (null == target_dir) { DirectoryChooser dc = new DirectoryChooser("Choose target directory"); target_dir = dc.getDirectory(); if (null == target_dir) return null; } target_dir = target_dir.replace('\\', '/'); // Windows fixing if (!target_dir.endsWith("/")) target_dir += "/"; if (max_scale_ > 1) { Utils.log("Prescaled Tiles: using max scale of 1.0"); max_scale_ = 1; // no point } final String dir = target_dir; final double max_scale = max_scale_; final float jpeg_quality = ij.plugin.JpegWriter.getQuality() / 100.0f; Utils.log("Using jpeg quality: " + jpeg_quality); Worker worker = new Worker("Creating prescaled tiles") { private void cleanup() { finishedWorking(); } public void run() { startedWorking(); try { // project name String pname = layer[0].getProject().getTitle(); // create 'z' directories if they don't exist: check and ask! // start with the highest scale level final int[] best = determineClosestPowerOfTwo(srcRect.width > srcRect.height ? srcRect.width : srcRect.height); final int edge_length = best[0]; final int n_edge_tiles = edge_length / 256; Utils.log2("srcRect: " + srcRect); Utils.log2("edge_length, n_edge_tiles, best[1] " + best[0] + ", " + n_edge_tiles + ", " + best[1]); // thumbnail dimensions LayerSet ls = layer[0].getParent(); double ratio = srcRect.width / (double)srcRect.height; double thumb_scale = 1.0; if (ratio >= 1) { // width is larger or equal than height thumb_scale = 192.0 / srcRect.width; } else { thumb_scale = 192.0 / srcRect.height; } for (int iz=0; iz<layer.length; iz++) { if (this.quit) { cleanup(); return; } // 1 - create a directory 'z' named as the layer's Z coordinate String tile_dir = dir + layer[iz].getParent().indexOf(layer[iz]); File fdir = new File(tile_dir); int tag = 1; // Ensure there is a usable directory: while (fdir.exists() && !fdir.isDirectory()) { fdir = new File(tile_dir + "_" + tag); } if (!fdir.exists()) { fdir.mkdir(); Utils.log("Created directory " + fdir); } // if the directory exists already just reuse it, overwritting its files if so. final String tmp = fdir.getAbsolutePath().replace('\\','/'); if (!tile_dir.equals(tmp)) Utils.log("\tWARNING: directory will not be in the standard location."); // debug: Utils.log2("tile_dir: " + tile_dir + "\ntmp: " + tmp); tile_dir = tmp; if (!tile_dir.endsWith("/")) tile_dir += "/"; // 2 - create layer thumbnail, max 192x192 ImagePlus thumb = getFlatImage(layer[iz], srcRect, thumb_scale, c_alphas, type, clazz, true); ImageSaver.saveAsJpeg(thumb.getProcessor(), tile_dir + "small.jpg", jpeg_quality, ImagePlus.COLOR_RGB != type); flush(thumb); thumb = null; // 3 - fill directory with tiles if (edge_length < 256) { // edge_length is the largest length of the 256x256 tile map that covers an area equal or larger than the desired srcRect (because all tiles have to be 256x256 in size) // create single tile per layer makeTile(layer[iz], srcRect, max_scale, c_alphas, type, clazz, jpeg_quality, tile_dir + "0_0_0.jpg"); } else { // create piramid of tiles double scale = 1; //max_scale; // WARNING if scale is different than 1, it will FAIL to set the next scale properly. int scale_pow = 0; int n_et = n_edge_tiles; // cached for local modifications in the loop, works as loop controler while (n_et >= best[1]) { // best[1] is the minimal root found, i.e. 1,2,3,4,5 from hich then powers of two were taken to make up for the edge_length int tile_side = (int)(256/scale); // 0 < scale <= 1, so no precision lost for (int row=0; row<n_et; row++) { for (int col=0; col<n_et; col++) { if (this.quit) { cleanup(); return; } Rectangle tile_src = new Rectangle(srcRect.x + tile_side*row, srcRect.y + tile_side*col, tile_side, tile_side); // in absolute coords, magnification later. // crop bounds if (tile_src.x + tile_src.width > srcRect.x + srcRect.width) tile_src.width = srcRect.x + srcRect.width - tile_src.x; if (tile_src.y + tile_src.height > srcRect.y + srcRect.height) tile_src.height = srcRect.y + srcRect.height - tile_src.y; // negative tile sizes will be made into black tiles // (negative dimensions occur for tiles beyond the edges of srcRect, since the grid of tiles has to be of equal number of rows and cols) makeTile(layer[iz], tile_src, scale, c_alphas, type, clazz, jpeg_quality, new StringBuffer(tile_dir).append(col).append('_').append(row).append('_').append(scale_pow).append(".jpg").toString()); // should be row_col_scale, but results in transposed tiles in googlebrains, so I inversed it. } } scale_pow++; scale = 1 / Math.pow(2, scale_pow); // works as magnification n_et /= 2; } } } } catch (Exception e) { IJError.print(e); } cleanup(); finishedWorking(); }// end of run method }; // watcher thread Bureaucrat burro = new Bureaucrat(worker, layer[0].getProject()); burro.goHaveBreakfast(); return burro; } /** Will overwrite if the file path exists. */ private void makeTile(Layer layer, Rectangle srcRect, double mag, int c_alphas, int type, Class clazz, final float jpeg_quality, String file_path) throws Exception { ImagePlus imp = null; if (srcRect.width > 0 && srcRect.height > 0) { imp = getFlatImage(layer, srcRect, mag, c_alphas, type, clazz, null, true); // with quality } else { imp = new ImagePlus("", new ByteProcessor(256, 256)); // black tile } // correct cropped tiles if (imp.getWidth() < 256 || imp.getHeight() < 256) { ImagePlus imp2 = new ImagePlus(imp.getTitle(), imp.getProcessor().createProcessor(256, 256)); // ensure black background for color images if (imp2.getType() == ImagePlus.COLOR_RGB) { Roi roi = new Roi(0, 0, 256, 256); imp2.setRoi(roi); imp2.getProcessor().setValue(0); // black imp2.getProcessor().fill(); } imp2.getProcessor().insert(imp.getProcessor(), 0, 0); imp = imp2; } // debug //Utils.log("would save: " + srcRect + " at " + file_path); ImageSaver.saveAsJpeg(imp.getProcessor(), file_path, jpeg_quality, ImagePlus.COLOR_RGB != type); } /** Find the closest, but larger, power of 2 number for the given edge size; the base root may be any of {1,2,3,5}. */ private int[] determineClosestPowerOfTwo(final int edge) { int[] starter = new int[]{1, 2, 3, 5}; // I love primer numbers int[] larger = new int[starter.length]; System.arraycopy(starter, 0, larger, 0, starter.length); // I hate java's obscene verbosity for (int i=0; i<larger.length; i++) { while (larger[i] < edge) { larger[i] *= 2; } } int min_larger = larger[0]; int min_i = 0; for (int i=1; i<larger.length; i++) { if (larger[i] < min_larger) { min_i = i; min_larger = larger[i]; } } // 'larger' is now larger or equal to 'edge', and will reduce to starter[min_i] tiles squared. return new int[]{min_larger, starter[min_i]}; } private String last_opened_path = null; /** Subclasses can override this method to register the URL of the imported image. */ public void addedPatchFrom(String path, Patch patch) {} /** Import an image into the given layer, in a separate task thread. */ public Bureaucrat importImage(final Layer layer, final double x, final double y, final String path) { Worker worker = new Worker("Importing image") { public void run() { startedWorking(); try { //// if (null == layer) { Utils.log("Can't import. No layer found."); finishedWorking(); return; } Patch p = importImage(layer.getProject(), x, y, path); if (null != p) layer.add(p); //// } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, layer.getProject()); burro.goHaveBreakfast(); return burro; } public Patch importImage(Project project, double x, double y) { return importImage(project, x, y, null); } /** Import a new image at the given coordinates; does not puts it into any layer, unless it's a stack -in which case importStack is called with the current front layer of the given project as target. If a path is not provided it will be asked for.*/ public Patch importImage(Project project, double x, double y, String path) { if (null == path) { OpenDialog od = new OpenDialog("Import image", ""); String name = od.getFileName(); if (null == name || 0 == name.length()) return null; String dir = od.getDirectory().replace('\\', '/'); if (!dir.endsWith("/")) dir += "/"; path = dir + name; } else { path = path.replace('\\', '/'); } // avoid opening trakem2 projects if (path.toLowerCase().endsWith(".xml")) { Utils.showMessage("Cannot import " + path + " as a stack."); return null; } releaseMemory(); // some: TODO this should read the header only, and figure out the dimensions to do a releaseToFit(n_bytes) call IJ.redirectErrorMessages(); final ImagePlus imp = opener.openImage(path); if (null == imp) return null; preProcess(imp); if (imp.getNSlices() > 1) { // a stack! Layer layer = Display.getFrontLayer(project); if (null == layer) return null; importStack(layer, imp, true, path); // TODO: the x,y location is not set return null; } if (0 == imp.getWidth() || 0 == imp.getHeight()) { Utils.showMessage("Can't import image of zero width or height."); flush(imp); return null; } last_opened_path = path; Patch p = new Patch(project, imp.getTitle(), x, y, imp); addedPatchFrom(last_opened_path, p); if (isMipMapsEnabled()) generateMipMaps(p); return p; } public Patch importNextImage(Project project, double x, double y) { if (null == last_opened_path) { return importImage(project, x, y); } int i_slash = last_opened_path.lastIndexOf("/"); String dir_name = last_opened_path.substring(0, i_slash); File dir = new File(dir_name); String last_file = last_opened_path.substring(i_slash + 1); String[] file_names = dir.list(); String next_file = null; final String exts = "tiftiffjpgjpegpnggifzipdicombmppgm"; for (int i=0; i<file_names.length; i++) { if (last_file.equals(file_names[i]) && i < file_names.length -1) { // loop until finding a suitable next for (int j=i+1; j<file_names.length; j++) { String ext = file_names[j].substring(file_names[j].lastIndexOf('.') + 1).toLowerCase(); if (-1 != exts.indexOf(ext)) { next_file = file_names[j]; break; } } break; } } if (null == next_file) { Utils.showMessage("No more files after " + last_file); return null; } releaseMemory(); // some: TODO this should read the header only, and figure out the dimensions to do a releaseToFit(n_bytes) call IJ.redirectErrorMessages(); ImagePlus imp = opener.openImage(dir_name, next_file); preProcess(imp); if (null == imp) return null; if (0 == imp.getWidth() || 0 == imp.getHeight()) { Utils.showMessage("Can't import image of zero width or height."); flush(imp); return null; } last_opened_path = dir + "/" + next_file; Patch p = new Patch(project, imp.getTitle(), x, y, imp); addedPatchFrom(last_opened_path, p); if (isMipMapsEnabled()) generateMipMaps(p); return p; } public Bureaucrat importStack(Layer first_layer, ImagePlus imp_stack_, boolean ask_for_data) { return importStack(first_layer, imp_stack_, ask_for_data, null); } /** Imports an image stack from a multitiff file and places each slice in the proper layer, creating new layers as it goes. If the given stack is null, popup a file dialog to choose one*/ public Bureaucrat importStack(final Layer first_layer, final ImagePlus imp_stack_, final boolean ask_for_data, final String filepath_) { Utils.log2("Loader.importStack filepath: " + filepath_); if (null == first_layer) return null; Worker worker = new Worker("import stack") { public void run() { startedWorking(); try { String filepath = filepath_; /* On drag and drop the stack is not null! */ //Utils.log2("imp_stack_ is " + imp_stack_); ImagePlus[] imp_stacks = null; if (null == imp_stack_) { imp_stacks = Utils.findOpenStacks(); } else { imp_stacks = new ImagePlus[]{imp_stack_}; } ImagePlus imp_stack = null; // ask to open a stack if it's null if (null == imp_stacks) { imp_stack = openStack(); } else { // choose one from the list GenericDialog gd = new GenericDialog("Choose one"); gd.addMessage("Choose a stack from the list or 'open...' to bring up a file chooser dialog:"); String[] list = new String[imp_stacks.length +1]; for (int i=0; i<list.length -1; i++) { list[i] = imp_stacks[i].getTitle(); } list[list.length-1] = "[ Open stack... ]"; gd.addChoice("choose stack: ", list, list[0]); gd.showDialog(); if (gd.wasCanceled()) { finishedWorking(); return; } int i_choice = gd.getNextChoiceIndex(); if (list.length-1 == i_choice) { // the open... command imp_stack = first_layer.getProject().getLoader().openStack(); } else { imp_stack = imp_stacks[i_choice]; } } // check: if (null == imp_stack) { finishedWorking(); return; } final String props = (String)imp_stack.getProperty("Info"); // check if it's amira labels stack to prevent missimports if (null != props && -1 != props.indexOf("Materials {")) { YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Warning", "You are importing a stack of Amira labels as a regular image stack. Continue anyway?"); if (!yn.yesPressed()) { finishedWorking(); return; } } String dir = imp_stack.getFileInfo().directory; double layer_width = first_layer.getLayerWidth(); double layer_height= first_layer.getLayerHeight(); double current_thickness = first_layer.getThickness(); double thickness = current_thickness; boolean expand_layer_set = false; boolean lock_stack = false; int anchor = LayerSet.NORTHWEST; //default if (ask_for_data) { // ask for slice separation in pixels GenericDialog gd = new GenericDialog("Slice separation?"); gd.addMessage("Please enter the slice thickness, in pixels"); gd.addNumericField("slice_thickness: ", Math.abs(imp_stack.getCalibration().pixelDepth / imp_stack.getCalibration().pixelHeight), 3); // assuming pixelWidth == pixelHeight if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) { gd.addCheckbox("Resize canvas to fit stack", true); gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]); } gd.addCheckbox("Lock stack", false); gd.showDialog(); if (gd.wasCanceled()) { if (null == imp_stacks) { // flush only if it was not open before flush(imp_stack); } finishedWorking(); return; } if (layer_width != imp_stack.getWidth() || layer_height != imp_stack.getHeight()) { expand_layer_set = gd.getNextBoolean(); anchor = gd.getNextChoiceIndex(); } lock_stack = gd.getNextBoolean(); thickness = gd.getNextNumber(); // check provided thickness with that of the first layer: if (thickness != current_thickness) { if (!(1 == first_layer.getParent().size() && first_layer.isEmpty())) { YesNoCancelDialog yn = new YesNoCancelDialog(IJ.getInstance(), "Mismatch!", "The current layer's thickness is " + current_thickness + "\nwhich is " + (thickness < current_thickness ? "larger":"smaller") + " than\nthe desired " + thickness + " for each stack slice.\nAdjust current layer's thickness to " + thickness + " ?"); if (!yn.yesPressed()) { if (null != imp_stack_) flush(imp_stack); // was opened new finishedWorking(); return; } } // else adjust silently first_layer.setThickness(thickness); } } if (null == imp_stack.getStack()) { Utils.showMessage("Not a stack."); finishedWorking(); return; } // WARNING: there are fundamental issues with calibration, because the Layer thickness is disconnected from the Calibration pixelDepth // set LayerSet calibration if there is no calibration boolean calibrate = true; if (ask_for_data && first_layer.getParent().isCalibrated()) { if (!ControlWindow.isGUIEnabled()) { Utils.log2("Loader.importStack: overriding LayerSet calibration with that of the imported stack."); } else { YesNoDialog yn = new YesNoDialog("Calibration", "The layer set is already calibrated. Override with the stack calibration values?"); if (!yn.yesPressed()) { calibrate = false; } } } if (calibrate) { first_layer.getParent().setCalibration(imp_stack.getCalibration()); } if (layer_width < imp_stack.getWidth() || layer_height < imp_stack.getHeight()) { expand_layer_set = true; } if (null == filepath) { // try to get it from the original FileInfo final FileInfo fi = imp_stack.getOriginalFileInfo(); if (null != fi && null != fi.directory && null != fi.fileName) { filepath = fi.directory.replace('\\', '/'); if (!filepath.endsWith("/")) filepath += '/'; filepath += fi.fileName; } Utils.log2("Getting filepath from FileInfo: " + filepath); // check that file exists, otherwise save a copy in the storage folder if (null == filepath || (!filepath.startsWith("http://") && !new File(filepath).exists())) { filepath = handlePathlessImage(imp_stack); } } else { filepath = filepath.replace('\\', '/'); } // Place the first slice in the current layer, and then query the parent LayerSet for subsequent layers, and create them if not present. Patch last_patch = Loader.this.importStackAsPatches(first_layer.getProject(), first_layer, imp_stack, null != imp_stack_ && null != imp_stack_.getCanvas(), filepath); if (null != last_patch) last_patch.setLocked(lock_stack); if (expand_layer_set) { last_patch.getLayer().getParent().setMinimumDimensions(); } Utils.log2("props: " + props); // check if it's an amira stack, then ask to import labels if (null != props && -1 == props.indexOf("Materials {") && -1 != props.indexOf("CoordType")) { YesNoDialog yn = new YesNoDialog(IJ.getInstance(), "Amira Importer", "Import labels as well?"); if (yn.yesPressed()) { // select labels ArrayList al = AmiraImporter.importAmiraLabels(first_layer, last_patch.getX(), last_patch.getY(), imp_stack.getOriginalFileInfo().directory); if (null != al) { // import all created AreaList as nodes in the ProjectTree under a new imported_segmentations node first_layer.getProject().getProjectTree().insertSegmentations(first_layer.getProject(), al); // link them to the images // TODO } } } // it is safe not to flush the imp_stack, because all its resources are being used anyway (all the ImageProcessor), and it has no awt.Image. Unless it's being shown in ImageJ, and then it will be flushed on its own when the user closes its window. } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, first_layer.getProject()); burro.goHaveBreakfast(); return burro; } public String handlePathlessImage(ImagePlus imp) { return null; } abstract protected Patch importStackAsPatches(final Project project, final Layer first_layer, final ImagePlus stack, final boolean as_copy, String filepath); protected String export(Project project, File fxml) { return export(project, fxml, true); } /** Exports the project and its images (optional); if export_images is true, it will be asked for confirmation anyway -beware: for FSLoader, images are not exported since it doesn't own them; only their path.*/ protected String export(final Project project, final File fxml, boolean export_images) { releaseToFit(MIN_FREE_BYTES); String path = null; if (null == project || null == fxml) return null; try { if (export_images && !(this instanceof FSLoader)) { final YesNoCancelDialog yn = ini.trakem2.ControlWindow.makeYesNoCancelDialog("Export images?", "Export images as well?"); if (yn.cancelPressed()) return null; if (yn.yesPressed()) export_images = true; else export_images = false; // 'no' option } // 1 - get headers in DTD format StringBuffer sb_header = new StringBuffer("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<!DOCTYPE ").append(project.getDocType()).append(" [\n"); final HashSet hs = new HashSet(); project.exportDTD(sb_header, hs, "\t"); sb_header.append("] >\n\n"); // 2 - fill in the data String patches_dir = null; if (export_images) { patches_dir = makePatchesDir(fxml); } java.io.Writer writer = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(fxml)), "8859_1"); try { writer.write(sb_header.toString()); sb_header = null; project.exportXML(writer, "", patches_dir); writer.flush(); // make sure all buffered chars are written this.changes = false; path = fxml.getAbsolutePath().replace('\\', '/'); } catch (Exception e) { Utils.log("FAILED to save the file at " + fxml); path = null; } finally { writer.close(); writer = null; } // Remove the patches_dir if empty (can happen when doing a "save" on a FSLoader project if no new Patch have been created that have no path. if (export_images) { File fpd = new File(patches_dir); if (fpd.exists() && fpd.isDirectory()) { // check if it contains any files File[] ff = fpd.listFiles(); boolean rm = true; for (int k=0; k<ff.length; k++) { if (!ff[k].isHidden()) { // one non-hidden file found. rm = false; break; } } if (rm) { try { fpd.delete(); } catch (Exception e) { Utils.log2("Could not delete empty directory " + patches_dir); IJError.print(e); } } } } } catch (Exception e) { IJError.print(e); } ControlWindow.updateTitle(project); return path; } static public long countObjects(final LayerSet ls) { // estimate total number of bytes: large estimate is 500 bytes of xml text for each object int count = 1; // the given LayerSet itself for (Layer la : (ArrayList<Layer>)ls.getLayers()) { count += la.getNDisplayables(); for (Object ls2 : la.getDisplayables(LayerSet.class)) { // can't cast ArrayList<Displayable> to ArrayList<LayerSet> ???? count += countObjects((LayerSet)ls2); } } return count; } /** Calls saveAs() unless overriden. Returns full path to the xml file. */ public String save(Project project) { // yes the project is the same project pointer, which for some reason I never committed myself to place it in the Loader class as a field. String path = saveAs(project); if (null != path) this.changes = false; return path; } /** Exports to an XML file chosen by the user. Images exist already in the file system, so none are exported. Returns the full path to the xml file. */ public String saveAs(Project project) { long size = countObjects(project.getRootLayerSet()) * 500; releaseToFit(size > MIN_FREE_BYTES ? size : MIN_FREE_BYTES); String default_dir = null; default_dir = getStorageFolder(); // Select a file to export to File fxml = Utils.chooseFile(default_dir, null, ".xml"); if (null == fxml) return null; String path = export(project, fxml); if (null != path) this.changes = false; return path; } /** Parses the xml_path and returns the folder in the same directory that has the same name plus "_images". */ public String extractRelativeFolderPath(final File fxml) { try { String patches_dir = fxml.getParent() + "/" + fxml.getName(); if (patches_dir.toLowerCase().lastIndexOf(".xml") == patches_dir.length() - 4) { patches_dir = patches_dir.substring(0, patches_dir.lastIndexOf('.')); } return patches_dir + "_images"; } catch (Exception e) { IJError.print(e); return null; } } protected String makePatchesDir(final File fxml) { // Create a directory to store the images String patches_dir = extractRelativeFolderPath(fxml); if (null == patches_dir) return null; File dir = new File(patches_dir); String patches_dir2 = null; int i = 1; while (dir.exists()) { patches_dir2 = patches_dir + "_" + Integer.toString(i); dir = new File(patches_dir2); i++; } if (null != patches_dir2) patches_dir = patches_dir2; if (null == patches_dir) return null; try { dir.mkdir(); } catch (Exception e) { IJError.print(e); Utils.showMessage("Could not create a directory for the images."); return null; } if (File.separatorChar != patches_dir.charAt(patches_dir.length() -1)) { patches_dir += "/"; } return patches_dir; } /** Returns the path to the saved image. */ public String exportImage(Patch patch, String path, boolean overwrite) { // save only if not there already if (null == path || (!overwrite && new File(path).exists())) return null; synchronized(db_lock) { try { ImagePlus imp = fetchImagePlus(patch); // locks on its own lock(); if (null == imp) { // something went wrong Utils.log("Loader.exportImage: Could not fetch a valid ImagePlus for " + patch.getId()); unlock(); return null; } else { new FileSaver(imp).saveAsZip(path); } } catch (Exception e) { Utils.log("Could not save an image for Patch #" + patch.getId() + " at: " + path); IJError.print(e); unlock(); return null; } unlock(); } return path; } /** Whether any changes need to be saved. */ public boolean hasChanges() { return this.changes; } public void setChanged(final boolean changed) { this.changes = changed; //Utils.printCaller(this, 7); } /** Returns null unless overriden. This is intended for FSLoader projects. */ public String getPath(final Patch patch) { return null; } /** Returns null unless overriden. This is intended for FSLoader projects. */ public String getAbsolutePath(final Patch patch) { return null; } /** Does nothing unless overriden. */ public void setupMenuItems(final JMenu menu, final Project project) {} /** Test whether this Loader needs recurrent calls to a "save" of some sort, such as for the FSLoader. */ public boolean isAsynchronous() { // in the future, DBLoader may also be asynchronous return this.getClass() == FSLoader.class; } /** Throw away all awts and snaps that depend on this image, so that they will be recreated next time they are needed. */ public void decache(final ImagePlus imp) { synchronized(db_lock) { lock(); try { long[] ids = imps.getAll(imp); Utils.log2("decaching " + ids.length); if (null == ids) return; for (int i=0; i<ids.length; i++) { mawts.removeAndFlush(ids[i]); } } catch (Exception e) { IJError.print(e); } finally { unlock(); } } } static private Object temp_current_image_lock = new Object(); static private boolean temp_in_use = false; static private ImagePlus previous_current_image = null; static public void startSetTempCurrentImage(final ImagePlus imp) { synchronized (temp_current_image_lock) { //Utils.log2("temp in use: " + temp_in_use); while (temp_in_use) { try { temp_current_image_lock.wait(); } catch (InterruptedException ie) {} } temp_in_use = true; previous_current_image = WindowManager.getCurrentImage(); WindowManager.setTempCurrentImage(imp); } } /** This method MUST always be called after startSetTempCurrentImage(ImagePlus imp) has been called and the action on the image has finished. */ static public void finishSetTempCurrentImage() { synchronized (temp_current_image_lock) { WindowManager.setTempCurrentImage(previous_current_image); // be nice temp_in_use = false; temp_current_image_lock.notifyAll(); } } static public void setTempCurrentImage(final ImagePlus imp) { synchronized (temp_current_image_lock) { while (temp_in_use) { try { temp_current_image_lock.wait(); } catch (InterruptedException ie) {} } temp_in_use = true; WindowManager.setTempCurrentImage(imp); temp_in_use = false; temp_current_image_lock.notifyAll(); } } protected String preprocessor = null; public boolean setPreprocessor(String plugin_class_name) { if (null == plugin_class_name || 0 == plugin_class_name.length()) { this.preprocessor = null; return true; } // just for the sake of it: plugin_class_name = plugin_class_name.replace(' ', '_'); // check that it can be instantiated try { startSetTempCurrentImage(null); IJ.redirectErrorMessages(); Object ob = IJ.runPlugIn(plugin_class_name, ""); if (null == ob) { Utils.showMessageT("The preprocessor plugin " + plugin_class_name + " was not found."); } else if (!(ob instanceof PlugInFilter)) { Utils.showMessageT("Plug in '" + plugin_class_name + "' is invalid: does not implement PlugInFilter"); } else { // all is good: this.preprocessor = plugin_class_name; } } catch (Exception e) { e.printStackTrace(); Utils.showMessageT("Plug in " + plugin_class_name + " is invalid: ImageJ has thrown an exception when testing it with a null image."); return false; } finally { finishSetTempCurrentImage(); } return true; } public String getPreprocessor() { return preprocessor; } /** Preprocess an image before TrakEM2 ever has a look at it with a system-wide defined preprocessor plugin, specified in the XML file and/or from within the Display properties dialog. Does not lock, and should always run within locking/unlocking statements. */ protected final void preProcess(final ImagePlus imp) { if (null == preprocessor || null == imp) return; // access to WindowManager.setTempCurrentImage(...) is locked within the Loader try { startSetTempCurrentImage(imp); IJ.redirectErrorMessages(); IJ.runPlugIn(preprocessor, ""); } catch (Exception e) { IJError.print(e); } finally { finishSetTempCurrentImage(); } // reset flag imp.changes = false; } /////////////////////// /** List of jobs running on this Loader. */ private ArrayList al_jobs = new ArrayList(); private JPopupMenu popup_jobs = null; private final Object popup_lock = new Object(); private boolean popup_locked = false; /** Adds a new job to monitor.*/ public void addJob(Bureaucrat burro) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; al_jobs.add(burro); popup_locked = false; popup_lock.notifyAll(); } } public void removeJob(Bureaucrat burro) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; if (null != popup_jobs && popup_jobs.isVisible()) { popup_jobs.setVisible(false); } al_jobs.remove(burro); popup_locked = false; popup_lock.notifyAll(); } } public JPopupMenu getJobsPopup(Display display) { synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; this.popup_jobs = new JPopupMenu("Cancel jobs:"); int i = 1; for (Iterator it = al_jobs.iterator(); it.hasNext(); ) { Bureaucrat burro = (Bureaucrat)it.next(); JMenuItem item = new JMenuItem("Job " + i + ": " + burro.getTaskName()); item.addActionListener(display); popup_jobs.add(item); i++; } popup_locked = false; popup_lock.notifyAll(); } return popup_jobs; } /** Names as generated for popup menu items in the getJobsPopup method. If the name is null, it will cancel the last one. Runs in a separate thread so that it can immediately return. */ public void quitJob(final String name) { new Thread () { public void run() { setPriority(Thread.NORM_PRIORITY); Object ob = null; synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; if (null == name && al_jobs.size() > 0) { ob = al_jobs.get(al_jobs.size()-1); } else { int i = Integer.parseInt(name.substring(4, name.indexOf(':'))); if (i >= 1 && i <= al_jobs.size()) ob = al_jobs.get(i-1); // starts at 1 } popup_locked = false; popup_lock.notifyAll(); } if (null != ob) { // will wait until worker returns ((Bureaucrat)ob).quit(); // will require the lock } synchronized (popup_lock) { while (popup_locked) try { popup_lock.wait(); } catch (InterruptedException ie) {} popup_locked = true; popup_jobs = null; popup_locked = false; popup_lock.notifyAll(); } Utils.showStatus("Job canceled."); }}.start(); } public final void printMemState() { Utils.log2(new StringBuffer("mem in use: ").append((IJ.currentMemory() * 100.0f) / max_memory).append('%') .append("\n\timps: ").append(imps.size()) .append("\n\tmawts: ").append(mawts.size()) .toString()); } /** Fixes paths before presenting them to the file system, in an OS-dependent manner. */ protected final ImagePlus openImage(String path) { if (null == path) return null; // supporting samba networks if (path.startsWith("//")) { path = path.replace('/', '\\'); } // debug: Utils.log2("opening image " + path); //Utils.printCaller(this, 25); IJ.redirectErrorMessages(); return opener.openImage(path); } /** Equivalent to File.getName(), does not subtract the slice info from it.*/ protected final String getInternalFileName(Patch p) { final String path = getAbsolutePath(p); if (null == path) return null; int i = path.length() -1; while (i > -1) { if ('/' == path.charAt(i)) { break; } i--; } return path.substring(i+1); } /** Equivalent to File.getName(), but subtracts the slice info from it if any.*/ public final String getFileName(final Patch p) { String name = getInternalFileName(p); int i = name.lastIndexOf("-----#slice="); if (-1 == i) return name; return name.substring(0, i); } /** Check if an awt exists to paint as a snap. */ public boolean isSnapPaintable(final long id) { synchronized (db_lock) { lock(); if (mawts.contains(id)) { unlock(); return true; } unlock(); } return false; } /** If mipmaps regeneration is enabled or not. */ protected boolean mipmaps_regen = true; // used to prevent generating them when, for example, importing a montage public void setMipMapsRegeneration(boolean b) { mipmaps_regen = b; } /** Does nothing unless overriden. */ public void flushMipMaps(boolean forget_dir_mipmaps) {} /** Does nothing unless overriden. */ public void flushMipMaps(final long id) {} /** Does nothing and returns false unless overriden. */ public boolean generateMipMaps(final Patch patch) { return false; } /** Does nothing unless overriden. */ public void removeMipMaps(final Patch patch) {} /** Returns generateMipMaps(al, false). */ public Bureaucrat generateMipMaps(final ArrayList al) { return generateMipMaps(al, false); } /** Does nothing and returns null unless overriden. */ public Bureaucrat generateMipMaps(final ArrayList al, boolean overwrite) { return null; } /** Does nothing and returns false unless overriden. */ public boolean isMipMapsEnabled() { return false; } /** Does nothing and returns zero unless overriden. */ public int getClosestMipMapLevel(final Patch patch, int level) {return 0;} /** Does nothing and returns null unless overriden. */ protected Image fetchMipMapAWT(final Patch patch, final int level) { return null; } /** Does nothing and returns false unless overriden. */ public boolean checkMipMapFileExists(Patch p, double magnification) { return false; } public void adjustChannels(final Patch p, final int old_channels) { /* if (0xffffffff == old_channels) { // reuse any loaded mipmaps Hashtable<Integer,Image> ht = null; synchronized (db_lock) { lock(); ht = mawts.getAll(p.getId()); unlock(); } for (Map.Entry<Integer,Image> entry : ht.entrySet()) { // key is level, value is awt final int level = entry.getKey(); PatchLoadingLock plock = null; synchronized (db_lock) { lock(); plock = getOrMakePatchLoadingLock(p, level); unlock(); } synchronized (plock) { plock.lock(); // block loading of this file Image awt = null; try { awt = p.adjustChannels(entry.getValue()); } catch (Exception e) { IJError.print(e); if (null == awt) continue; } synchronized (db_lock) { lock(); mawts.replace(p.getId(), awt, level); removePatchLoadingLock(plock); unlock(); } plock.unlock(); } } } else { */ // flush away any loaded mipmap for the id synchronized (db_lock) { lock(); mawts.removeAndFlush(p.getId()); unlock(); } // when reloaded, the channels will be adjusted //} } static public ImageProcessor scaleImage(final ImagePlus imp, double mag, final boolean quality) { if (mag > 1) mag = 1; ImageProcessor ip = imp.getProcessor(); if (Math.abs(mag - 1) < 0.000001) return ip; // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise final int w = ip.getWidth(); final int h = ip.getHeight(); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, getMipMapLevel(mag, Math.max(imp.getWidth(), imp.getHeight()))) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } static public ImageProcessor scaleImage(final ImagePlus imp, final int level, final boolean quality) { if (level <= 0) return imp.getProcessor(); // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise ImageProcessor ip = imp.getProcessor(); final int w = ip.getWidth(); final int h = ip.getHeight(); final double mag = 1 / Math.pow(2, level); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, level) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } /* =========================== */ /** Serializes the given object into the path. Returns false on failure. */ public boolean serialize(final Object ob, final String path) { try { final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { IJError.print(e); } return false; } /** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */ public Object deserialize(final String path) { try { if (!new File(path).exists()) return null; final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); final Object ob = in.readObject(); in.close(); return ob; } catch (Exception e) { //IJError.print(e); // too much output if a whole set is wrong e.printStackTrace(); } return null; } public void insertXMLOptions(StringBuffer sb_body, String indent) {} public Bureaucrat optimizeContrast(final ArrayList al_patches) { final Patch[] pa = new Patch[al_patches.size()]; al_patches.toArray(pa); Worker worker = new Worker("Optimize contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = MultiThreading.newThreads(); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { ///////////////////////// for (int g = ai.getAndIncrement(); g < pa.length; g = ai.getAndIncrement()) { if (wo.hasQuitted()) break; ImagePlus imp = fetchImagePlus(pa[g]); ImageStatistics stats = imp.getStatistics(); int type = imp.getType(); imp = null; // Compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; double min=0, max=0; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } pa[g].setMinAndMax(min, max); } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); } else { // recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); } // flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (int i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } for (int i=0; i<pa.length; i++) { Display.repaint(pa[i].getLayer(), pa[i], 0); } } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final Layer[] la) { return homogenizeContrast(la, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(la, min, max, drift_hist_peak, null); } /** Homogenize contrast layer-wise, for all given layers, in a multithreaded manner. */ public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == la || 0 == la.length) return null; Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = new Thread[1]; // MultiThreading.newThreads(); // USING one single thread, for the locking is so bad, to access // the imps and to releaseToFit, that it's not worth it: same images // are being reloaded many times just because they all don't fit in // at the same time. for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { /////////////////////////////// // when quited, rollback() and Display.repaint(layer) for (int i = ai.getAndIncrement(); i < la.length; i = ai.getAndIncrement()) { if (wo.hasQuitted()) { break; } setTaskName("Homogenizing contrast for layer " + (i+1) + " of " + la.length); ArrayList al = la[i].getDisplayables(Patch.class); Patch[] pa = new Patch[al.size()]; al.toArray(pa); if (!homogenizeContrast(la[i], pa, min, max, drift_hist_peak, null == parent ? wo : parent)) { Utils.log("Could not homogenize contrast for images in layer " + la[i]); } } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); for (int i=0; i<la.length; i++) Display.repaint(la[i]); } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, la[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al) { return homogenizeContrast(al, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(al, min, max, drift_hist_peak, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == al || al.size() < 2) return null; final Patch[] pa = new Patch[al.size()]; al.toArray(pa); Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); try { homogenizeContrast(pa[0].getLayer(), pa, min, max, drift_hist_peak, null == parent ? this : parent); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } /* public boolean homogenizeContrast(final Layer layer, final Patch[] pa) { return homogenizeContrast(layer, pa, -1, -1, true, null); } */ /** Homogenize contrast for all given Patch objects, which must be all of the same size and type. Returns false on failure. Needs a layer to repaint when done. */ public boolean homogenizeContrast(final Layer layer, final Patch[] pa, final double min_, final double max_, final boolean drift_hist_peak, final Worker worker) { try { if (null == pa) return false; // error if (0 == pa.length) return true; // done // 0 - check that all images are of the same size and type int ptype = pa[0].getType(); double pw = pa[0].getWidth(); double ph = pa[0].getHeight(); for (int e=1; e<pa.length; e++) { if (pa[e].getType() != ptype) { // can't continue Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + pa[e]); return false; } if (pa[e].getWidth() != pw || pa[e].getHeight() != ph) { Utils.log("Can't homogenize histograms: images are not all of the same size.\nFirst offending image is: " + pa[e]); return false; } } // Set min and max for all images double min = 0; double max = 0; // 1 - fetch statistics for each image final ArrayList al_st = new ArrayList(); final ArrayList al_p = new ArrayList(); // list of Patch ordered by stdDev ASC int type = -1; for (int i=0; i<pa.length; i++) { if (null != worker && worker.hasQuitted()) { return false; } ImagePlus imp = fetchImagePlus(pa[i]); if (-1 == type) type = imp.getType(); releaseToFit(measureSize(imp)); ImageStatistics i_st = imp.getStatistics(); // insert ordered by stdDev, from small to big int q = 0; for (Iterator it = al_st.iterator(); it.hasNext(); ) { ImageStatistics st = (ImageStatistics)it.next(); q++; if (st.stdDev > i_st.stdDev) break; } if (q == pa.length) { al_st.add(i_st); // append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below al_p.add(pa[i]); } else { al_st.add(q, i_st); al_p.add(q, pa[i]); } } final ArrayList al_p2 = (ArrayList)al_p.clone(); // shallow copy of the ordered list // 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here) if (pa.length > 3) { // under 4 images, use them all int i=0; final int quarter = pa.length / 4; while (i < quarter) { al_p.remove(i); i++; } i = 0; int last = al_p.size() -1; while (i < quarter) { // I know that it can be done better, but this is CLEAR al_p.remove(last); // why doesn't ArrayList have a removeLast() method ?? And why is removeRange() 'protected' ?? last--; i++; } } if (null != worker && worker.hasQuitted()) { return false; } // 3 - compute common histogram for the middle 50% images final Patch[] p50 = new Patch[al_p.size()]; al_p.toArray(p50); final ImageStatistics stats = 1 == p50.length ? p50[0].getImagePlus().getStatistics() : new StackStatistics(new PatchStack(p50, 1)); int n = 1; switch (type) { case ImagePlus.GRAY16: case ImagePlus.GRAY32: n = 2; break; } // 4 - compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } // 5 - compute common mean within min,max range final double target_mean = getMeanOfRange(stats, min, max); //Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean + "\nApplying to " + al_p2.size() + " images."); // override values with given defaults if appropriate if (-1 != min_ && -1 != max_) { min = min_; max = max_; } // 6 - apply to all Utils.log2("Lo HC Using: " + min + ", " + max + ", " + drift_hist_peak); for (i=al_p2.size()-1; i>-1; i--) { if (null != worker && worker.hasQuitted()) { return false; } Patch p = (Patch)al_p2.get(i); // the order is different, thus getting it from the proper list if (drift_hist_peak) { double dm = target_mean - getMeanOfRange((ImageStatistics)al_st.get(i), min, max); p.setMinAndMax(min - dm, max - dm); // displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean } else { p.setMinAndMax(min, max); } synchronized (db_lock) { lock(); try { ImagePlus imp = imps.get(p.getId()); if (null != imp) p.putMinAndMax(imp); // else, it will be put when reloading the file } catch (Exception e) { IJError.print(e); } unlock(); } } // 7 - recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); // not threaded: //for (int k=0; k<pa.length; k++) generateMipMaps(pa[k], true); } // 8 - flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } // problem: if the user starts navigating the display, it will maybe end up recreating mipmaps more than once for a few tiles if (null != layer) Display.repaint(layer, new Rectangle(0, 0, (int)layer.getParent().getLayerWidth(), (int)layer.getParent().getLayerHeight()), 0); } catch (Exception e) { IJError.print(e); return false; } return true; } public long estimateImageFileSize(final Patch p, final int level) { if (0 == level) { return (long)(p.getWidth() * p.getHeight() * 5 + 1024); // conservative } // else, compute scale final double scale = 1 / Math.pow(2, level); return (long)(p.getWidth() * scale * p.getHeight() * scale * 5 + 1024); // conservative } // Dummy class to provide access the notifyListeners from Image static private final class ImagePlusAccess extends ImagePlus { final int CLOSE = CLOSED; // from super class ImagePlus final int OPEN = OPENED; final int UPDATE = UPDATED; private Vector<ij.ImageListener> my_listeners; public ImagePlusAccess() { super(); try { java.lang.reflect.Field f = ImagePlus.class.getDeclaredField("listeners"); f.setAccessible(true); this.my_listeners = (Vector<ij.ImageListener>)f.get(this); } catch (Exception e) { IJError.print(e); } } public final void notifyListeners(final ImagePlus imp, final int action) { try { for (ij.ImageListener listener : my_listeners) { switch (action) { case CLOSED: listener.imageClosed(imp); break; case OPENED: listener.imageOpened(imp); break; case UPDATED: listener.imageUpdated(imp); break; } } } catch (Exception e) {} } } static private final ImagePlusAccess ipa = new ImagePlusAccess(); /** Workaround for ImageJ's ImagePlus.flush() method which calls the System.gc() unnecessarily.<br /> * A null pointer as argument is accepted. */ static public final void flush(final ImagePlus imp) { if (null == imp) return; final Roi roi = imp.getRoi(); if (null != roi) roi.setImage(null); //final ImageProcessor ip = imp.getProcessor(); // the nullifying makes no difference, and in low memory situations some bona fide imagepluses may end up failing on the calling method because of lack of time to grab the processor etc. //if (null != ip) ip.setPixels(null); ipa.notifyListeners(imp, ipa.CLOSE); } /** Returns the user's home folder unless overriden. */ public String getStorageFolder() { return System.getProperty("user.home").replace('\\', '/'); } /** Returns null unless overriden. */ public String getMipMapsFolder() { return null; } public Patch addNewImage(ImagePlus imp) { String filename = imp.getTitle(); if (!filename.toLowerCase().endsWith(".tif")) filename += ".tif"; String path = getStorageFolder() + "/" + filename; new FileSaver(imp).saveAsTiff(path); Patch pa = new Patch(Project.findProject(this), imp.getTitle(), 0, 0, imp); addedPatchFrom(path, pa); if (isMipMapsEnabled()) generateMipMaps(pa); return pa; } public String makeProjectName() { return "Untitled " + ControlWindow.getTabIndex(Project.findProject(this)); } /** Will preload in the background as many as possible of the given images for the given magnification, if and only if (1) there is more than one CPU core available [and only the extra ones will be used], and (2) there is more than 1 image to preload. */ static private ImageLoaderThread[] imageloader = null; static private Preloader preloader = null; static public final void setupPreloader(final ControlWindow master) { if (null == imageloader) { int n = Runtime.getRuntime().availableProcessors()-1; if (0 == n) n = 1; // !@#$%^ imageloader = new ImageLoaderThread[n]; for (int i=0; i<imageloader.length; i++) { imageloader[i] = new ImageLoaderThread(); } } if (null == preloader) preloader = new Preloader(); } static public final void destroyPreloader(final ControlWindow master) { if (null != preloader) { preloader.quit(); preloader = null; } if (null != imageloader) { for (int i=0; i<imageloader.length; i++) { if (null != imageloader[i]) { imageloader[i].quit(); } } imageloader = null; } } // Java is pathetically low level. static private final class Tuple { final Patch patch; double mag; boolean repaint; private boolean valid = true; Tuple(final Patch patch, final double mag, final boolean repaint) { this.patch = patch; this.mag = mag; this.repaint = repaint; } public final boolean equals(final Object ob) { // DISABLED: private class Tuple will never be used in lists that contain objects that are not Tuple as well. //if (ob.getClass() != Tuple.class) return false; final Tuple tu = (Tuple)ob; return patch == tu.patch && mag == tu.mag && repaint == tu.repaint; } final void invalidate() { //Utils.log2("@@@@ called invalidate for mag " + mag); valid = false; } } /** Manages available CPU cores for loading images in the background. */ static private class Preloader extends Thread { private final LinkedList<Tuple> queue = new LinkedList<Tuple>(); /** IdentityHashMap uses ==, not .equals() ! */ private final IdentityHashMap<Patch,HashMap<Integer,Tuple>> map = new IdentityHashMap<Patch,HashMap<Integer,Tuple>>(); private boolean go = true; /** Controls access to the queue. */ private final Lock lock = new Lock(); private final Lock lock2 = new Lock(); Preloader() { super("T2-Preloader"); setPriority(Thread.NORM_PRIORITY); start(); } /** WARNING this method effectively limits zoom out to 0.00000001. */ private final int makeKey(final double mag) { // get the nearest equal or higher power of 2 return (int)(0.000005 + Math.abs(Math.log(mag) / Math.log(2))); } public final void quit() { this.go = false; synchronized (lock) { lock.lock(); queue.clear(); lock.unlock(); } synchronized (lock2) { lock2.unlock(); } } private final void addEntry(final Patch patch, final double mag, final boolean repaint) { synchronized (lock) { lock.lock(); final Tuple tu = new Tuple(patch, mag, repaint); HashMap<Integer,Tuple> m = map.get(patch); final int key = makeKey(mag); if (null == m) { m = new HashMap<Integer,Tuple>(); m.put(key, tu); map.put(patch, m); } else { // invalidate previous entry if any Tuple old = m.get(key); if (null != old) old.invalidate(); // in any case: m.put(key, tu); } queue.add(tu); lock.unlock(); } } private final void addPatch(final Patch patch, final double mag, final boolean repaint) { if (patch.getProject().getLoader().isCached(patch, mag)) return; if (repaint && !Display.willPaint(patch, mag)) return; // else, queue: addEntry(patch, mag, repaint); } public final void add(final Patch patch, final double mag, final boolean repaint) { addPatch(patch, mag, repaint); synchronized (lock2) { lock2.unlock(); } } public final void add(final ArrayList<Patch> patches, final double mag, final boolean repaint) { //Utils.log2("@@@@ Adding " + patches.size() + " for mag " + mag); for (Patch p : patches) { addPatch(p, mag, repaint); } synchronized (lock2) { lock2.unlock(); } } public final void remove(final ArrayList<Patch> patches, final double mag) { // WARNING: this method only makes sense of the canceling of the offscreen thread happens before the issuing of the new offscreen thread, which is currently the case. int sum = 0; synchronized (lock) { lock.lock(); for (Patch p : patches) { HashMap<Integer,Tuple> m = map.get(p); if (null == m) { lock.unlock(); continue; } final Tuple tu = m.remove(makeKey(mag)); // if present. //Utils.log2("@@@@ mag is " + mag + " and tu is null == " + (null == tu)); if (null != tu) { tu.invalidate(); // never removed from the queue, just invalidated. Will be removed by the preloader thread itself, when poping from the end. if (m.isEmpty()) map.remove(p); sum++; } } lock.unlock(); } //Utils.log2("@@@@ invalidated " + sum + " for mag " + mag); } private final void removeMapping(final Tuple tu) { final HashMap<Integer,Tuple> m = map.get(tu.patch); if (null == m) return; m.remove(makeKey(tu.mag)); if (m.isEmpty()) map.remove(tu.patch); } public void run() { final int size = imageloader.length; // as many as Preloader threads final ArrayList<Tuple> list = new ArrayList<Tuple>(size); while (go) { try { synchronized (lock2) { lock2.lock(); } // read out a group of imageloader.length patches to load while (true) { // block 1: pop out 'size' valid tuples from the queue (and all invalid in between as well) synchronized (lock) { lock.lock(); int len = queue.size(); //Utils.log2("@@@@@ Queue size: " + len); if (0 == len) { lock.unlock(); break; } // When more than a hundred images, multiply by 10 the remove/read -out batch for preloading. // (if the batch_size is too large, then the removing/invalidating tuples from the queue would not work properly, i.e. they would never get invalidated and thus they'd be preloaded unnecessarily.) final int batch_size = size * (len < 100 ? 1 : 10); // for (int i=0; i<batch_size && i<len; len--) { final Tuple tuple = queue.remove(len-1); // start removing from the end, since those are the latest additions, hence the ones the user wants to see immediately. removeMapping(tuple); if (!tuple.valid) { //Utils.log2("@@@@@ skipping invalid tuple"); continue; } list.add(tuple); i++; } //Utils.log2("@@@@@ Queue size after: " + queue.size()); lock.unlock(); } // changes may occur now to the queue, so work on the list //Utils.log2("@@@@@ list size: " + list.size()); // block 2: now iterate until each tuple in the list has been assigned to a preloader thread while (!list.isEmpty()) { final Iterator<Tuple> it = list.iterator(); while (it.hasNext()) { for (int i=0; i<imageloader.length; i++) { + final Tuple tu = it.next(); if (!imageloader[i].isLoading()) { - final Tuple tu = it.next(); it.remove(); imageloader[i].load(tu.patch, tu.mag, tu.repaint); } } } if (!list.isEmpty()) try { //Utils.log2("@@@@@ list not empty, waiting 50 ms"); Thread.sleep(50); } catch (InterruptedException ie) {} } } } catch (Exception e) { e.printStackTrace(); synchronized (lock) { lock.unlock(); } // just in case ... } } } } static public final void preload(final Patch patch, final double magnification, final boolean repaint) { preloader.add(patch, magnification, repaint); } static public final void preload(final ArrayList<Patch> patches, final double magnification, final boolean repaint) { preloader.add(patches, magnification, repaint); } static public final void quitPreloading(final ArrayList<Patch> patches, final double magnification) { preloader.remove(patches, magnification); } static private class ImageLoaderThread extends Thread { /** Controls access to Patch etc. */ private final Lock lock = new Lock(); /** Limits access to the load method while a previous image is being worked on. */ private final Lock lock2 = new Lock(); private Patch patch = null; private double mag = 1.0; private boolean repaint = false; private boolean go = true; private boolean loading = false; public ImageLoaderThread() { super("T2-Image-Loader"); setPriority(Thread.NORM_PRIORITY); try { setDaemon(true); } catch (Exception e) { e.printStackTrace(); } start(); } public final void quit() { this.go = false; synchronized (lock) { try { this.patch = null; lock.unlock(); } catch (Exception e) {} } synchronized (lock2) { lock2.unlock(); } } /** Sets the given Patch to be loaded, and returns. A second call to this method will wait until the first call has finished, indicating the Thread is busy loading the previous image. */ public final void load(final Patch p, final double mag, final boolean repaint) { synchronized (lock) { try { lock.lock(); this.patch = p; this.mag = mag; this.repaint = repaint; if (null != patch) { synchronized (lock2) { try { lock2.unlock(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } } final boolean isLoading() { return loading; } public void run() { while (go) { Patch p = null; double mag = 1.0; boolean repaint = false; synchronized (lock2) { try { // wait until there's a Patch to preload. lock2.lock(); // ready: catch locally (no need to synch on lock because it can't change, considering the load method. p = this.patch; mag = this.mag; repaint = this.repaint; } catch (Exception e) {} } if (null != p) { try { if (repaint) { // wait a bit in case the user has browsed past Thread.yield(); try { sleep(50); } catch (InterruptedException ie) {} if (Display.willPaint(p, mag)) { loading = true; p.getProject().getLoader().fetchImage(p, mag); Display.repaint(p.getLayer(), p, p.getBoundingBox(null), 1, false); // not the navigator } } else { // just load it into the cache if possible loading = true; p.getProject().getLoader().fetchImage(p, mag); } p = null; } catch (Exception e) { e.printStackTrace(); } } // signal done try { synchronized (lock) { loading = false; lock.unlock(); } } catch (Exception e) {} } } } /** Returns the highest mipmap level for which a mipmap image may have been generated given the dimensions of the Patch. The minimum that this method may return is zero. */ public static final int getHighestMipMapLevel(final Patch p) { // TODO the level value could be computed analytically, not numerically like below int level = 0; int w = (int)p.getWidth(); int h = (int)p.getHeight(); while (w >= 64 && h >= 64) { w /= 2; h /= 2; level++; } return level; } static public final int NEAREST_NEIGHBOR = 0; static public final int BILINEAR = 1; static public final int BICUBIC = 2; static public final int GAUSSIAN = 3; static public final String[] modes = new String[]{"Nearest neighbor", "Bilinear", "Bicubic", "Gaussian"}; static public final int getMode(final String mode) { for (int i=0; i<modes.length; i++) { if (mode.equals(modes[i])) return i; } return 0; } /** Does nothing unless overriden. */ public Bureaucrat generateLayerMipMaps(final Layer[] la, final int starting_level) { return null; } /** Recover from an OutOfMemoryError: release 1/3 of all memory AND execute the garbage collector. */ public void recoverOOME() { releaseToFit(IJ.maxMemory() / 3); long start = System.currentTimeMillis(); long end = start; for (int i=0; i<3; i++) { System.gc(); Thread.yield(); end = System.currentTimeMillis(); if (end - start > 2000) break; // garbage collecion catched and is running. start = end; } } static public boolean canReadAndWriteTo(final String dir) { final File fsf = new File(dir); return fsf.canWrite() && fsf.canRead(); } }
false
true
public void adjustChannels(final Patch p, final int old_channels) { /* if (0xffffffff == old_channels) { // reuse any loaded mipmaps Hashtable<Integer,Image> ht = null; synchronized (db_lock) { lock(); ht = mawts.getAll(p.getId()); unlock(); } for (Map.Entry<Integer,Image> entry : ht.entrySet()) { // key is level, value is awt final int level = entry.getKey(); PatchLoadingLock plock = null; synchronized (db_lock) { lock(); plock = getOrMakePatchLoadingLock(p, level); unlock(); } synchronized (plock) { plock.lock(); // block loading of this file Image awt = null; try { awt = p.adjustChannels(entry.getValue()); } catch (Exception e) { IJError.print(e); if (null == awt) continue; } synchronized (db_lock) { lock(); mawts.replace(p.getId(), awt, level); removePatchLoadingLock(plock); unlock(); } plock.unlock(); } } } else { */ // flush away any loaded mipmap for the id synchronized (db_lock) { lock(); mawts.removeAndFlush(p.getId()); unlock(); } // when reloaded, the channels will be adjusted //} } static public ImageProcessor scaleImage(final ImagePlus imp, double mag, final boolean quality) { if (mag > 1) mag = 1; ImageProcessor ip = imp.getProcessor(); if (Math.abs(mag - 1) < 0.000001) return ip; // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise final int w = ip.getWidth(); final int h = ip.getHeight(); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, getMipMapLevel(mag, Math.max(imp.getWidth(), imp.getHeight()))) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } static public ImageProcessor scaleImage(final ImagePlus imp, final int level, final boolean quality) { if (level <= 0) return imp.getProcessor(); // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise ImageProcessor ip = imp.getProcessor(); final int w = ip.getWidth(); final int h = ip.getHeight(); final double mag = 1 / Math.pow(2, level); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, level) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } /* =========================== */ /** Serializes the given object into the path. Returns false on failure. */ public boolean serialize(final Object ob, final String path) { try { final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { IJError.print(e); } return false; } /** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */ public Object deserialize(final String path) { try { if (!new File(path).exists()) return null; final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); final Object ob = in.readObject(); in.close(); return ob; } catch (Exception e) { //IJError.print(e); // too much output if a whole set is wrong e.printStackTrace(); } return null; } public void insertXMLOptions(StringBuffer sb_body, String indent) {} public Bureaucrat optimizeContrast(final ArrayList al_patches) { final Patch[] pa = new Patch[al_patches.size()]; al_patches.toArray(pa); Worker worker = new Worker("Optimize contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = MultiThreading.newThreads(); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { ///////////////////////// for (int g = ai.getAndIncrement(); g < pa.length; g = ai.getAndIncrement()) { if (wo.hasQuitted()) break; ImagePlus imp = fetchImagePlus(pa[g]); ImageStatistics stats = imp.getStatistics(); int type = imp.getType(); imp = null; // Compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; double min=0, max=0; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } pa[g].setMinAndMax(min, max); } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); } else { // recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); } // flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (int i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } for (int i=0; i<pa.length; i++) { Display.repaint(pa[i].getLayer(), pa[i], 0); } } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final Layer[] la) { return homogenizeContrast(la, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(la, min, max, drift_hist_peak, null); } /** Homogenize contrast layer-wise, for all given layers, in a multithreaded manner. */ public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == la || 0 == la.length) return null; Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = new Thread[1]; // MultiThreading.newThreads(); // USING one single thread, for the locking is so bad, to access // the imps and to releaseToFit, that it's not worth it: same images // are being reloaded many times just because they all don't fit in // at the same time. for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { /////////////////////////////// // when quited, rollback() and Display.repaint(layer) for (int i = ai.getAndIncrement(); i < la.length; i = ai.getAndIncrement()) { if (wo.hasQuitted()) { break; } setTaskName("Homogenizing contrast for layer " + (i+1) + " of " + la.length); ArrayList al = la[i].getDisplayables(Patch.class); Patch[] pa = new Patch[al.size()]; al.toArray(pa); if (!homogenizeContrast(la[i], pa, min, max, drift_hist_peak, null == parent ? wo : parent)) { Utils.log("Could not homogenize contrast for images in layer " + la[i]); } } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); for (int i=0; i<la.length; i++) Display.repaint(la[i]); } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, la[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al) { return homogenizeContrast(al, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(al, min, max, drift_hist_peak, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == al || al.size() < 2) return null; final Patch[] pa = new Patch[al.size()]; al.toArray(pa); Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); try { homogenizeContrast(pa[0].getLayer(), pa, min, max, drift_hist_peak, null == parent ? this : parent); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } /* public boolean homogenizeContrast(final Layer layer, final Patch[] pa) { return homogenizeContrast(layer, pa, -1, -1, true, null); } */ /** Homogenize contrast for all given Patch objects, which must be all of the same size and type. Returns false on failure. Needs a layer to repaint when done. */ public boolean homogenizeContrast(final Layer layer, final Patch[] pa, final double min_, final double max_, final boolean drift_hist_peak, final Worker worker) { try { if (null == pa) return false; // error if (0 == pa.length) return true; // done // 0 - check that all images are of the same size and type int ptype = pa[0].getType(); double pw = pa[0].getWidth(); double ph = pa[0].getHeight(); for (int e=1; e<pa.length; e++) { if (pa[e].getType() != ptype) { // can't continue Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + pa[e]); return false; } if (pa[e].getWidth() != pw || pa[e].getHeight() != ph) { Utils.log("Can't homogenize histograms: images are not all of the same size.\nFirst offending image is: " + pa[e]); return false; } } // Set min and max for all images double min = 0; double max = 0; // 1 - fetch statistics for each image final ArrayList al_st = new ArrayList(); final ArrayList al_p = new ArrayList(); // list of Patch ordered by stdDev ASC int type = -1; for (int i=0; i<pa.length; i++) { if (null != worker && worker.hasQuitted()) { return false; } ImagePlus imp = fetchImagePlus(pa[i]); if (-1 == type) type = imp.getType(); releaseToFit(measureSize(imp)); ImageStatistics i_st = imp.getStatistics(); // insert ordered by stdDev, from small to big int q = 0; for (Iterator it = al_st.iterator(); it.hasNext(); ) { ImageStatistics st = (ImageStatistics)it.next(); q++; if (st.stdDev > i_st.stdDev) break; } if (q == pa.length) { al_st.add(i_st); // append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below al_p.add(pa[i]); } else { al_st.add(q, i_st); al_p.add(q, pa[i]); } } final ArrayList al_p2 = (ArrayList)al_p.clone(); // shallow copy of the ordered list // 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here) if (pa.length > 3) { // under 4 images, use them all int i=0; final int quarter = pa.length / 4; while (i < quarter) { al_p.remove(i); i++; } i = 0; int last = al_p.size() -1; while (i < quarter) { // I know that it can be done better, but this is CLEAR al_p.remove(last); // why doesn't ArrayList have a removeLast() method ?? And why is removeRange() 'protected' ?? last--; i++; } } if (null != worker && worker.hasQuitted()) { return false; } // 3 - compute common histogram for the middle 50% images final Patch[] p50 = new Patch[al_p.size()]; al_p.toArray(p50); final ImageStatistics stats = 1 == p50.length ? p50[0].getImagePlus().getStatistics() : new StackStatistics(new PatchStack(p50, 1)); int n = 1; switch (type) { case ImagePlus.GRAY16: case ImagePlus.GRAY32: n = 2; break; } // 4 - compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } // 5 - compute common mean within min,max range final double target_mean = getMeanOfRange(stats, min, max); //Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean + "\nApplying to " + al_p2.size() + " images."); // override values with given defaults if appropriate if (-1 != min_ && -1 != max_) { min = min_; max = max_; } // 6 - apply to all Utils.log2("Lo HC Using: " + min + ", " + max + ", " + drift_hist_peak); for (i=al_p2.size()-1; i>-1; i--) { if (null != worker && worker.hasQuitted()) { return false; } Patch p = (Patch)al_p2.get(i); // the order is different, thus getting it from the proper list if (drift_hist_peak) { double dm = target_mean - getMeanOfRange((ImageStatistics)al_st.get(i), min, max); p.setMinAndMax(min - dm, max - dm); // displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean } else { p.setMinAndMax(min, max); } synchronized (db_lock) { lock(); try { ImagePlus imp = imps.get(p.getId()); if (null != imp) p.putMinAndMax(imp); // else, it will be put when reloading the file } catch (Exception e) { IJError.print(e); } unlock(); } } // 7 - recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); // not threaded: //for (int k=0; k<pa.length; k++) generateMipMaps(pa[k], true); } // 8 - flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } // problem: if the user starts navigating the display, it will maybe end up recreating mipmaps more than once for a few tiles if (null != layer) Display.repaint(layer, new Rectangle(0, 0, (int)layer.getParent().getLayerWidth(), (int)layer.getParent().getLayerHeight()), 0); } catch (Exception e) { IJError.print(e); return false; } return true; } public long estimateImageFileSize(final Patch p, final int level) { if (0 == level) { return (long)(p.getWidth() * p.getHeight() * 5 + 1024); // conservative } // else, compute scale final double scale = 1 / Math.pow(2, level); return (long)(p.getWidth() * scale * p.getHeight() * scale * 5 + 1024); // conservative } // Dummy class to provide access the notifyListeners from Image static private final class ImagePlusAccess extends ImagePlus { final int CLOSE = CLOSED; // from super class ImagePlus final int OPEN = OPENED; final int UPDATE = UPDATED; private Vector<ij.ImageListener> my_listeners; public ImagePlusAccess() { super(); try { java.lang.reflect.Field f = ImagePlus.class.getDeclaredField("listeners"); f.setAccessible(true); this.my_listeners = (Vector<ij.ImageListener>)f.get(this); } catch (Exception e) { IJError.print(e); } } public final void notifyListeners(final ImagePlus imp, final int action) { try { for (ij.ImageListener listener : my_listeners) { switch (action) { case CLOSED: listener.imageClosed(imp); break; case OPENED: listener.imageOpened(imp); break; case UPDATED: listener.imageUpdated(imp); break; } } } catch (Exception e) {} } } static private final ImagePlusAccess ipa = new ImagePlusAccess(); /** Workaround for ImageJ's ImagePlus.flush() method which calls the System.gc() unnecessarily.<br /> * A null pointer as argument is accepted. */ static public final void flush(final ImagePlus imp) { if (null == imp) return; final Roi roi = imp.getRoi(); if (null != roi) roi.setImage(null); //final ImageProcessor ip = imp.getProcessor(); // the nullifying makes no difference, and in low memory situations some bona fide imagepluses may end up failing on the calling method because of lack of time to grab the processor etc. //if (null != ip) ip.setPixels(null); ipa.notifyListeners(imp, ipa.CLOSE); } /** Returns the user's home folder unless overriden. */ public String getStorageFolder() { return System.getProperty("user.home").replace('\\', '/'); } /** Returns null unless overriden. */ public String getMipMapsFolder() { return null; } public Patch addNewImage(ImagePlus imp) { String filename = imp.getTitle(); if (!filename.toLowerCase().endsWith(".tif")) filename += ".tif"; String path = getStorageFolder() + "/" + filename; new FileSaver(imp).saveAsTiff(path); Patch pa = new Patch(Project.findProject(this), imp.getTitle(), 0, 0, imp); addedPatchFrom(path, pa); if (isMipMapsEnabled()) generateMipMaps(pa); return pa; } public String makeProjectName() { return "Untitled " + ControlWindow.getTabIndex(Project.findProject(this)); } /** Will preload in the background as many as possible of the given images for the given magnification, if and only if (1) there is more than one CPU core available [and only the extra ones will be used], and (2) there is more than 1 image to preload. */ static private ImageLoaderThread[] imageloader = null; static private Preloader preloader = null; static public final void setupPreloader(final ControlWindow master) { if (null == imageloader) { int n = Runtime.getRuntime().availableProcessors()-1; if (0 == n) n = 1; // !@#$%^ imageloader = new ImageLoaderThread[n]; for (int i=0; i<imageloader.length; i++) { imageloader[i] = new ImageLoaderThread(); } } if (null == preloader) preloader = new Preloader(); } static public final void destroyPreloader(final ControlWindow master) { if (null != preloader) { preloader.quit(); preloader = null; } if (null != imageloader) { for (int i=0; i<imageloader.length; i++) { if (null != imageloader[i]) { imageloader[i].quit(); } } imageloader = null; } } // Java is pathetically low level. static private final class Tuple { final Patch patch; double mag; boolean repaint; private boolean valid = true; Tuple(final Patch patch, final double mag, final boolean repaint) { this.patch = patch; this.mag = mag; this.repaint = repaint; } public final boolean equals(final Object ob) { // DISABLED: private class Tuple will never be used in lists that contain objects that are not Tuple as well. //if (ob.getClass() != Tuple.class) return false; final Tuple tu = (Tuple)ob; return patch == tu.patch && mag == tu.mag && repaint == tu.repaint; } final void invalidate() { //Utils.log2("@@@@ called invalidate for mag " + mag); valid = false; } } /** Manages available CPU cores for loading images in the background. */ static private class Preloader extends Thread { private final LinkedList<Tuple> queue = new LinkedList<Tuple>(); /** IdentityHashMap uses ==, not .equals() ! */ private final IdentityHashMap<Patch,HashMap<Integer,Tuple>> map = new IdentityHashMap<Patch,HashMap<Integer,Tuple>>(); private boolean go = true; /** Controls access to the queue. */ private final Lock lock = new Lock(); private final Lock lock2 = new Lock(); Preloader() { super("T2-Preloader"); setPriority(Thread.NORM_PRIORITY); start(); } /** WARNING this method effectively limits zoom out to 0.00000001. */ private final int makeKey(final double mag) { // get the nearest equal or higher power of 2 return (int)(0.000005 + Math.abs(Math.log(mag) / Math.log(2))); } public final void quit() { this.go = false; synchronized (lock) { lock.lock(); queue.clear(); lock.unlock(); } synchronized (lock2) { lock2.unlock(); } } private final void addEntry(final Patch patch, final double mag, final boolean repaint) { synchronized (lock) { lock.lock(); final Tuple tu = new Tuple(patch, mag, repaint); HashMap<Integer,Tuple> m = map.get(patch); final int key = makeKey(mag); if (null == m) { m = new HashMap<Integer,Tuple>(); m.put(key, tu); map.put(patch, m); } else { // invalidate previous entry if any Tuple old = m.get(key); if (null != old) old.invalidate(); // in any case: m.put(key, tu); } queue.add(tu); lock.unlock(); } } private final void addPatch(final Patch patch, final double mag, final boolean repaint) { if (patch.getProject().getLoader().isCached(patch, mag)) return; if (repaint && !Display.willPaint(patch, mag)) return; // else, queue: addEntry(patch, mag, repaint); } public final void add(final Patch patch, final double mag, final boolean repaint) { addPatch(patch, mag, repaint); synchronized (lock2) { lock2.unlock(); } } public final void add(final ArrayList<Patch> patches, final double mag, final boolean repaint) { //Utils.log2("@@@@ Adding " + patches.size() + " for mag " + mag); for (Patch p : patches) { addPatch(p, mag, repaint); } synchronized (lock2) { lock2.unlock(); } } public final void remove(final ArrayList<Patch> patches, final double mag) { // WARNING: this method only makes sense of the canceling of the offscreen thread happens before the issuing of the new offscreen thread, which is currently the case. int sum = 0; synchronized (lock) { lock.lock(); for (Patch p : patches) { HashMap<Integer,Tuple> m = map.get(p); if (null == m) { lock.unlock(); continue; } final Tuple tu = m.remove(makeKey(mag)); // if present. //Utils.log2("@@@@ mag is " + mag + " and tu is null == " + (null == tu)); if (null != tu) { tu.invalidate(); // never removed from the queue, just invalidated. Will be removed by the preloader thread itself, when poping from the end. if (m.isEmpty()) map.remove(p); sum++; } } lock.unlock(); } //Utils.log2("@@@@ invalidated " + sum + " for mag " + mag); } private final void removeMapping(final Tuple tu) { final HashMap<Integer,Tuple> m = map.get(tu.patch); if (null == m) return; m.remove(makeKey(tu.mag)); if (m.isEmpty()) map.remove(tu.patch); } public void run() { final int size = imageloader.length; // as many as Preloader threads final ArrayList<Tuple> list = new ArrayList<Tuple>(size); while (go) { try { synchronized (lock2) { lock2.lock(); } // read out a group of imageloader.length patches to load while (true) { // block 1: pop out 'size' valid tuples from the queue (and all invalid in between as well) synchronized (lock) { lock.lock(); int len = queue.size(); //Utils.log2("@@@@@ Queue size: " + len); if (0 == len) { lock.unlock(); break; } // When more than a hundred images, multiply by 10 the remove/read -out batch for preloading. // (if the batch_size is too large, then the removing/invalidating tuples from the queue would not work properly, i.e. they would never get invalidated and thus they'd be preloaded unnecessarily.) final int batch_size = size * (len < 100 ? 1 : 10); // for (int i=0; i<batch_size && i<len; len--) { final Tuple tuple = queue.remove(len-1); // start removing from the end, since those are the latest additions, hence the ones the user wants to see immediately. removeMapping(tuple); if (!tuple.valid) { //Utils.log2("@@@@@ skipping invalid tuple"); continue; } list.add(tuple); i++; } //Utils.log2("@@@@@ Queue size after: " + queue.size()); lock.unlock(); } // changes may occur now to the queue, so work on the list //Utils.log2("@@@@@ list size: " + list.size()); // block 2: now iterate until each tuple in the list has been assigned to a preloader thread while (!list.isEmpty()) { final Iterator<Tuple> it = list.iterator(); while (it.hasNext()) { for (int i=0; i<imageloader.length; i++) { if (!imageloader[i].isLoading()) { final Tuple tu = it.next(); it.remove(); imageloader[i].load(tu.patch, tu.mag, tu.repaint); } } } if (!list.isEmpty()) try { //Utils.log2("@@@@@ list not empty, waiting 50 ms"); Thread.sleep(50); } catch (InterruptedException ie) {} } } } catch (Exception e) { e.printStackTrace(); synchronized (lock) { lock.unlock(); } // just in case ... } } } } static public final void preload(final Patch patch, final double magnification, final boolean repaint) { preloader.add(patch, magnification, repaint); } static public final void preload(final ArrayList<Patch> patches, final double magnification, final boolean repaint) { preloader.add(patches, magnification, repaint); } static public final void quitPreloading(final ArrayList<Patch> patches, final double magnification) { preloader.remove(patches, magnification); } static private class ImageLoaderThread extends Thread { /** Controls access to Patch etc. */ private final Lock lock = new Lock(); /** Limits access to the load method while a previous image is being worked on. */ private final Lock lock2 = new Lock(); private Patch patch = null; private double mag = 1.0; private boolean repaint = false; private boolean go = true; private boolean loading = false; public ImageLoaderThread() { super("T2-Image-Loader"); setPriority(Thread.NORM_PRIORITY); try { setDaemon(true); } catch (Exception e) { e.printStackTrace(); } start(); } public final void quit() { this.go = false; synchronized (lock) { try { this.patch = null; lock.unlock(); } catch (Exception e) {} } synchronized (lock2) { lock2.unlock(); } } /** Sets the given Patch to be loaded, and returns. A second call to this method will wait until the first call has finished, indicating the Thread is busy loading the previous image. */ public final void load(final Patch p, final double mag, final boolean repaint) { synchronized (lock) { try { lock.lock(); this.patch = p; this.mag = mag; this.repaint = repaint; if (null != patch) { synchronized (lock2) { try { lock2.unlock(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } } final boolean isLoading() { return loading; } public void run() { while (go) { Patch p = null; double mag = 1.0; boolean repaint = false; synchronized (lock2) { try { // wait until there's a Patch to preload. lock2.lock(); // ready: catch locally (no need to synch on lock because it can't change, considering the load method. p = this.patch; mag = this.mag; repaint = this.repaint; } catch (Exception e) {} } if (null != p) { try { if (repaint) { // wait a bit in case the user has browsed past Thread.yield(); try { sleep(50); } catch (InterruptedException ie) {} if (Display.willPaint(p, mag)) { loading = true; p.getProject().getLoader().fetchImage(p, mag); Display.repaint(p.getLayer(), p, p.getBoundingBox(null), 1, false); // not the navigator } } else { // just load it into the cache if possible loading = true; p.getProject().getLoader().fetchImage(p, mag); } p = null; } catch (Exception e) { e.printStackTrace(); } } // signal done try { synchronized (lock) { loading = false; lock.unlock(); } } catch (Exception e) {} } } } /** Returns the highest mipmap level for which a mipmap image may have been generated given the dimensions of the Patch. The minimum that this method may return is zero. */ public static final int getHighestMipMapLevel(final Patch p) { // TODO the level value could be computed analytically, not numerically like below int level = 0; int w = (int)p.getWidth(); int h = (int)p.getHeight(); while (w >= 64 && h >= 64) { w /= 2; h /= 2; level++; } return level; } static public final int NEAREST_NEIGHBOR = 0; static public final int BILINEAR = 1; static public final int BICUBIC = 2; static public final int GAUSSIAN = 3; static public final String[] modes = new String[]{"Nearest neighbor", "Bilinear", "Bicubic", "Gaussian"}; static public final int getMode(final String mode) { for (int i=0; i<modes.length; i++) { if (mode.equals(modes[i])) return i; } return 0; } /** Does nothing unless overriden. */ public Bureaucrat generateLayerMipMaps(final Layer[] la, final int starting_level) { return null; } /** Recover from an OutOfMemoryError: release 1/3 of all memory AND execute the garbage collector. */ public void recoverOOME() { releaseToFit(IJ.maxMemory() / 3); long start = System.currentTimeMillis(); long end = start; for (int i=0; i<3; i++) { System.gc(); Thread.yield(); end = System.currentTimeMillis(); if (end - start > 2000) break; // garbage collecion catched and is running. start = end; } } static public boolean canReadAndWriteTo(final String dir) { final File fsf = new File(dir); return fsf.canWrite() && fsf.canRead(); } }
public void adjustChannels(final Patch p, final int old_channels) { /* if (0xffffffff == old_channels) { // reuse any loaded mipmaps Hashtable<Integer,Image> ht = null; synchronized (db_lock) { lock(); ht = mawts.getAll(p.getId()); unlock(); } for (Map.Entry<Integer,Image> entry : ht.entrySet()) { // key is level, value is awt final int level = entry.getKey(); PatchLoadingLock plock = null; synchronized (db_lock) { lock(); plock = getOrMakePatchLoadingLock(p, level); unlock(); } synchronized (plock) { plock.lock(); // block loading of this file Image awt = null; try { awt = p.adjustChannels(entry.getValue()); } catch (Exception e) { IJError.print(e); if (null == awt) continue; } synchronized (db_lock) { lock(); mawts.replace(p.getId(), awt, level); removePatchLoadingLock(plock); unlock(); } plock.unlock(); } } } else { */ // flush away any loaded mipmap for the id synchronized (db_lock) { lock(); mawts.removeAndFlush(p.getId()); unlock(); } // when reloaded, the channels will be adjusted //} } static public ImageProcessor scaleImage(final ImagePlus imp, double mag, final boolean quality) { if (mag > 1) mag = 1; ImageProcessor ip = imp.getProcessor(); if (Math.abs(mag - 1) < 0.000001) return ip; // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise final int w = ip.getWidth(); final int h = ip.getHeight(); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, getMipMapLevel(mag, Math.max(imp.getWidth(), imp.getHeight()))) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } static public ImageProcessor scaleImage(final ImagePlus imp, final int level, final boolean quality) { if (level <= 0) return imp.getProcessor(); // else, make a properly scaled image: // - gaussian blurred for best quality when resizing with nearest neighbor // - direct nearest neighbor otherwise ImageProcessor ip = imp.getProcessor(); final int w = ip.getWidth(); final int h = ip.getHeight(); final double mag = 1 / Math.pow(2, level); // TODO releseToFit ! if (quality) { // apply proper gaussian filter double sigma = Math.sqrt(Math.pow(2, level) - 0.25); // sigma = sqrt(level^2 - 0.5^2) ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.convertToFloat().getPixels(), w, h), (float)sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax()); ip = ip.resize((int)(w * mag), (int)(h * mag)); // better while float return Utils.convertTo(ip, imp.getType(), false); } else { return ip.resize((int)(w * mag), (int)(h * mag)); } } /* =========================== */ /** Serializes the given object into the path. Returns false on failure. */ public boolean serialize(final Object ob, final String path) { try { final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(path)); out.writeObject(ob); out.close(); return true; } catch (Exception e) { IJError.print(e); } return false; } /** Attempts to find a file containing a serialized object. Returns null if no suitable file is found, or an error occurs while deserializing. */ public Object deserialize(final String path) { try { if (!new File(path).exists()) return null; final ObjectInputStream in = new ObjectInputStream(new FileInputStream(path)); final Object ob = in.readObject(); in.close(); return ob; } catch (Exception e) { //IJError.print(e); // too much output if a whole set is wrong e.printStackTrace(); } return null; } public void insertXMLOptions(StringBuffer sb_body, String indent) {} public Bureaucrat optimizeContrast(final ArrayList al_patches) { final Patch[] pa = new Patch[al_patches.size()]; al_patches.toArray(pa); Worker worker = new Worker("Optimize contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = MultiThreading.newThreads(); for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { ///////////////////////// for (int g = ai.getAndIncrement(); g < pa.length; g = ai.getAndIncrement()) { if (wo.hasQuitted()) break; ImagePlus imp = fetchImagePlus(pa[g]); ImageStatistics stats = imp.getStatistics(); int type = imp.getType(); imp = null; // Compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; double min=0, max=0; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } pa[g].setMinAndMax(min, max); } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); } else { // recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); } // flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (int i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } for (int i=0; i<pa.length; i++) { Display.repaint(pa[i].getLayer(), pa[i], 0); } } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final Layer[] la) { return homogenizeContrast(la, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(la, min, max, drift_hist_peak, null); } /** Homogenize contrast layer-wise, for all given layers, in a multithreaded manner. */ public Bureaucrat homogenizeContrast(final Layer[] la, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == la || 0 == la.length) return null; Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); final Worker wo = this; try { ///////// Multithreading /////// final AtomicInteger ai = new AtomicInteger(0); final Thread[] threads = new Thread[1]; // MultiThreading.newThreads(); // USING one single thread, for the locking is so bad, to access // the imps and to releaseToFit, that it's not worth it: same images // are being reloaded many times just because they all don't fit in // at the same time. for (int ithread = 0; ithread < threads.length; ++ithread) { threads[ithread] = new Thread() { public void run() { /////////////////////////////// // when quited, rollback() and Display.repaint(layer) for (int i = ai.getAndIncrement(); i < la.length; i = ai.getAndIncrement()) { if (wo.hasQuitted()) { break; } setTaskName("Homogenizing contrast for layer " + (i+1) + " of " + la.length); ArrayList al = la[i].getDisplayables(Patch.class); Patch[] pa = new Patch[al.size()]; al.toArray(pa); if (!homogenizeContrast(la[i], pa, min, max, drift_hist_peak, null == parent ? wo : parent)) { Utils.log("Could not homogenize contrast for images in layer " + la[i]); } } ///////////////////////// - where are my lisp macros .. and no, mapping a function with reflection is not elegant, but rather a verbosity and constriction attack } }; } MultiThreading.startAndJoin(threads); ///////////////////////// if (wo.hasQuitted()) { rollback(); for (int i=0; i<la.length; i++) Display.repaint(la[i]); } } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, la[0].getProject()); burro.goHaveBreakfast(); return burro; } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al) { return homogenizeContrast(al, -1, -1, true, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak) { return homogenizeContrast(al, min, max, drift_hist_peak, null); } public Bureaucrat homogenizeContrast(final ArrayList<Patch> al, final double min, final double max, final boolean drift_hist_peak, final Worker parent) { if (null == al || al.size() < 2) return null; final Patch[] pa = new Patch[al.size()]; al.toArray(pa); Worker worker = new Worker("Homogenizing contrast") { public void run() { startedWorking(); try { homogenizeContrast(pa[0].getLayer(), pa, min, max, drift_hist_peak, null == parent ? this : parent); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, pa[0].getProject()); burro.goHaveBreakfast(); return burro; } /* public boolean homogenizeContrast(final Layer layer, final Patch[] pa) { return homogenizeContrast(layer, pa, -1, -1, true, null); } */ /** Homogenize contrast for all given Patch objects, which must be all of the same size and type. Returns false on failure. Needs a layer to repaint when done. */ public boolean homogenizeContrast(final Layer layer, final Patch[] pa, final double min_, final double max_, final boolean drift_hist_peak, final Worker worker) { try { if (null == pa) return false; // error if (0 == pa.length) return true; // done // 0 - check that all images are of the same size and type int ptype = pa[0].getType(); double pw = pa[0].getWidth(); double ph = pa[0].getHeight(); for (int e=1; e<pa.length; e++) { if (pa[e].getType() != ptype) { // can't continue Utils.log("Can't homogenize histograms: images are not all of the same type.\nFirst offending image is: " + pa[e]); return false; } if (pa[e].getWidth() != pw || pa[e].getHeight() != ph) { Utils.log("Can't homogenize histograms: images are not all of the same size.\nFirst offending image is: " + pa[e]); return false; } } // Set min and max for all images double min = 0; double max = 0; // 1 - fetch statistics for each image final ArrayList al_st = new ArrayList(); final ArrayList al_p = new ArrayList(); // list of Patch ordered by stdDev ASC int type = -1; for (int i=0; i<pa.length; i++) { if (null != worker && worker.hasQuitted()) { return false; } ImagePlus imp = fetchImagePlus(pa[i]); if (-1 == type) type = imp.getType(); releaseToFit(measureSize(imp)); ImageStatistics i_st = imp.getStatistics(); // insert ordered by stdDev, from small to big int q = 0; for (Iterator it = al_st.iterator(); it.hasNext(); ) { ImageStatistics st = (ImageStatistics)it.next(); q++; if (st.stdDev > i_st.stdDev) break; } if (q == pa.length) { al_st.add(i_st); // append at the end. WARNING if importing thousands of images, this is a potential source of out of memory errors. I could just recompute it when I needed it again below al_p.add(pa[i]); } else { al_st.add(q, i_st); al_p.add(q, pa[i]); } } final ArrayList al_p2 = (ArrayList)al_p.clone(); // shallow copy of the ordered list // 2 - discard the first and last 25% (TODO: a proper histogram clustering analysis and histogram examination should apply here) if (pa.length > 3) { // under 4 images, use them all int i=0; final int quarter = pa.length / 4; while (i < quarter) { al_p.remove(i); i++; } i = 0; int last = al_p.size() -1; while (i < quarter) { // I know that it can be done better, but this is CLEAR al_p.remove(last); // why doesn't ArrayList have a removeLast() method ?? And why is removeRange() 'protected' ?? last--; i++; } } if (null != worker && worker.hasQuitted()) { return false; } // 3 - compute common histogram for the middle 50% images final Patch[] p50 = new Patch[al_p.size()]; al_p.toArray(p50); final ImageStatistics stats = 1 == p50.length ? p50[0].getImagePlus().getStatistics() : new StackStatistics(new PatchStack(p50, 1)); int n = 1; switch (type) { case ImagePlus.GRAY16: case ImagePlus.GRAY32: n = 2; break; } // 4 - compute autoAdjust min and max values // extracting code from ij.plugin.frame.ContrastAdjuster, method autoAdjust int autoThreshold = 0; // once for 8-bit and color, twice for 16 and 32-bit (thus the 2501 autoThreshold value) int limit = stats.pixelCount/10; int[] histogram = stats.histogram; //if (autoThreshold<10) autoThreshold = 5000; //else autoThreshold /= 2; if (ImagePlus.GRAY16 == type || ImagePlus.GRAY32 == type) autoThreshold = 2500; else autoThreshold = 5000; int threshold = stats.pixelCount / autoThreshold; int i = -1; boolean found = false; int count; do { i++; count = histogram[i]; if (count>limit) count = 0; found = count > threshold; } while (!found && i<255); int hmin = i; i = 256; do { i--; count = histogram[i]; if (count > limit) count = 0; found = count > threshold; } while (!found && i>0); int hmax = i; if (hmax >= hmin) { min = stats.histMin + hmin*stats.binSize; max = stats.histMin + hmax*stats.binSize; if (min == max) { min = stats.min; max = stats.max; } } // 5 - compute common mean within min,max range final double target_mean = getMeanOfRange(stats, min, max); //Utils.log2("Loader min,max: " + min + ", " + max + ", target mean: " + target_mean + "\nApplying to " + al_p2.size() + " images."); // override values with given defaults if appropriate if (-1 != min_ && -1 != max_) { min = min_; max = max_; } // 6 - apply to all Utils.log2("Lo HC Using: " + min + ", " + max + ", " + drift_hist_peak); for (i=al_p2.size()-1; i>-1; i--) { if (null != worker && worker.hasQuitted()) { return false; } Patch p = (Patch)al_p2.get(i); // the order is different, thus getting it from the proper list if (drift_hist_peak) { double dm = target_mean - getMeanOfRange((ImageStatistics)al_st.get(i), min, max); p.setMinAndMax(min - dm, max - dm); // displacing in the opposite direction, makes sense, so that the range is drifted upwards and thus the target 256 range for an awt.Image will be closer to the ideal target_mean } else { p.setMinAndMax(min, max); } synchronized (db_lock) { lock(); try { ImagePlus imp = imps.get(p.getId()); if (null != imp) p.putMinAndMax(imp); // else, it will be put when reloading the file } catch (Exception e) { IJError.print(e); } unlock(); } } // 7 - recreate mipmap files if (isMipMapsEnabled()) { ArrayList al = new ArrayList(); for (int k=0; k<pa.length; k++) al.add(pa[k]); Thread task = generateMipMaps(al, true); // yes, overwrite files! task.join(); // not threaded: //for (int k=0; k<pa.length; k++) generateMipMaps(pa[k], true); } // 8 - flush away any existing awt images, so that they'll be reloaded or recreated synchronized (db_lock) { lock(); for (i=0; i<pa.length; i++) { mawts.removeAndFlush(pa[i].getId()); Utils.log2(i + " removing mawt for " + pa[i].getId()); } unlock(); } // problem: if the user starts navigating the display, it will maybe end up recreating mipmaps more than once for a few tiles if (null != layer) Display.repaint(layer, new Rectangle(0, 0, (int)layer.getParent().getLayerWidth(), (int)layer.getParent().getLayerHeight()), 0); } catch (Exception e) { IJError.print(e); return false; } return true; } public long estimateImageFileSize(final Patch p, final int level) { if (0 == level) { return (long)(p.getWidth() * p.getHeight() * 5 + 1024); // conservative } // else, compute scale final double scale = 1 / Math.pow(2, level); return (long)(p.getWidth() * scale * p.getHeight() * scale * 5 + 1024); // conservative } // Dummy class to provide access the notifyListeners from Image static private final class ImagePlusAccess extends ImagePlus { final int CLOSE = CLOSED; // from super class ImagePlus final int OPEN = OPENED; final int UPDATE = UPDATED; private Vector<ij.ImageListener> my_listeners; public ImagePlusAccess() { super(); try { java.lang.reflect.Field f = ImagePlus.class.getDeclaredField("listeners"); f.setAccessible(true); this.my_listeners = (Vector<ij.ImageListener>)f.get(this); } catch (Exception e) { IJError.print(e); } } public final void notifyListeners(final ImagePlus imp, final int action) { try { for (ij.ImageListener listener : my_listeners) { switch (action) { case CLOSED: listener.imageClosed(imp); break; case OPENED: listener.imageOpened(imp); break; case UPDATED: listener.imageUpdated(imp); break; } } } catch (Exception e) {} } } static private final ImagePlusAccess ipa = new ImagePlusAccess(); /** Workaround for ImageJ's ImagePlus.flush() method which calls the System.gc() unnecessarily.<br /> * A null pointer as argument is accepted. */ static public final void flush(final ImagePlus imp) { if (null == imp) return; final Roi roi = imp.getRoi(); if (null != roi) roi.setImage(null); //final ImageProcessor ip = imp.getProcessor(); // the nullifying makes no difference, and in low memory situations some bona fide imagepluses may end up failing on the calling method because of lack of time to grab the processor etc. //if (null != ip) ip.setPixels(null); ipa.notifyListeners(imp, ipa.CLOSE); } /** Returns the user's home folder unless overriden. */ public String getStorageFolder() { return System.getProperty("user.home").replace('\\', '/'); } /** Returns null unless overriden. */ public String getMipMapsFolder() { return null; } public Patch addNewImage(ImagePlus imp) { String filename = imp.getTitle(); if (!filename.toLowerCase().endsWith(".tif")) filename += ".tif"; String path = getStorageFolder() + "/" + filename; new FileSaver(imp).saveAsTiff(path); Patch pa = new Patch(Project.findProject(this), imp.getTitle(), 0, 0, imp); addedPatchFrom(path, pa); if (isMipMapsEnabled()) generateMipMaps(pa); return pa; } public String makeProjectName() { return "Untitled " + ControlWindow.getTabIndex(Project.findProject(this)); } /** Will preload in the background as many as possible of the given images for the given magnification, if and only if (1) there is more than one CPU core available [and only the extra ones will be used], and (2) there is more than 1 image to preload. */ static private ImageLoaderThread[] imageloader = null; static private Preloader preloader = null; static public final void setupPreloader(final ControlWindow master) { if (null == imageloader) { int n = Runtime.getRuntime().availableProcessors()-1; if (0 == n) n = 1; // !@#$%^ imageloader = new ImageLoaderThread[n]; for (int i=0; i<imageloader.length; i++) { imageloader[i] = new ImageLoaderThread(); } } if (null == preloader) preloader = new Preloader(); } static public final void destroyPreloader(final ControlWindow master) { if (null != preloader) { preloader.quit(); preloader = null; } if (null != imageloader) { for (int i=0; i<imageloader.length; i++) { if (null != imageloader[i]) { imageloader[i].quit(); } } imageloader = null; } } // Java is pathetically low level. static private final class Tuple { final Patch patch; double mag; boolean repaint; private boolean valid = true; Tuple(final Patch patch, final double mag, final boolean repaint) { this.patch = patch; this.mag = mag; this.repaint = repaint; } public final boolean equals(final Object ob) { // DISABLED: private class Tuple will never be used in lists that contain objects that are not Tuple as well. //if (ob.getClass() != Tuple.class) return false; final Tuple tu = (Tuple)ob; return patch == tu.patch && mag == tu.mag && repaint == tu.repaint; } final void invalidate() { //Utils.log2("@@@@ called invalidate for mag " + mag); valid = false; } } /** Manages available CPU cores for loading images in the background. */ static private class Preloader extends Thread { private final LinkedList<Tuple> queue = new LinkedList<Tuple>(); /** IdentityHashMap uses ==, not .equals() ! */ private final IdentityHashMap<Patch,HashMap<Integer,Tuple>> map = new IdentityHashMap<Patch,HashMap<Integer,Tuple>>(); private boolean go = true; /** Controls access to the queue. */ private final Lock lock = new Lock(); private final Lock lock2 = new Lock(); Preloader() { super("T2-Preloader"); setPriority(Thread.NORM_PRIORITY); start(); } /** WARNING this method effectively limits zoom out to 0.00000001. */ private final int makeKey(final double mag) { // get the nearest equal or higher power of 2 return (int)(0.000005 + Math.abs(Math.log(mag) / Math.log(2))); } public final void quit() { this.go = false; synchronized (lock) { lock.lock(); queue.clear(); lock.unlock(); } synchronized (lock2) { lock2.unlock(); } } private final void addEntry(final Patch patch, final double mag, final boolean repaint) { synchronized (lock) { lock.lock(); final Tuple tu = new Tuple(patch, mag, repaint); HashMap<Integer,Tuple> m = map.get(patch); final int key = makeKey(mag); if (null == m) { m = new HashMap<Integer,Tuple>(); m.put(key, tu); map.put(patch, m); } else { // invalidate previous entry if any Tuple old = m.get(key); if (null != old) old.invalidate(); // in any case: m.put(key, tu); } queue.add(tu); lock.unlock(); } } private final void addPatch(final Patch patch, final double mag, final boolean repaint) { if (patch.getProject().getLoader().isCached(patch, mag)) return; if (repaint && !Display.willPaint(patch, mag)) return; // else, queue: addEntry(patch, mag, repaint); } public final void add(final Patch patch, final double mag, final boolean repaint) { addPatch(patch, mag, repaint); synchronized (lock2) { lock2.unlock(); } } public final void add(final ArrayList<Patch> patches, final double mag, final boolean repaint) { //Utils.log2("@@@@ Adding " + patches.size() + " for mag " + mag); for (Patch p : patches) { addPatch(p, mag, repaint); } synchronized (lock2) { lock2.unlock(); } } public final void remove(final ArrayList<Patch> patches, final double mag) { // WARNING: this method only makes sense of the canceling of the offscreen thread happens before the issuing of the new offscreen thread, which is currently the case. int sum = 0; synchronized (lock) { lock.lock(); for (Patch p : patches) { HashMap<Integer,Tuple> m = map.get(p); if (null == m) { lock.unlock(); continue; } final Tuple tu = m.remove(makeKey(mag)); // if present. //Utils.log2("@@@@ mag is " + mag + " and tu is null == " + (null == tu)); if (null != tu) { tu.invalidate(); // never removed from the queue, just invalidated. Will be removed by the preloader thread itself, when poping from the end. if (m.isEmpty()) map.remove(p); sum++; } } lock.unlock(); } //Utils.log2("@@@@ invalidated " + sum + " for mag " + mag); } private final void removeMapping(final Tuple tu) { final HashMap<Integer,Tuple> m = map.get(tu.patch); if (null == m) return; m.remove(makeKey(tu.mag)); if (m.isEmpty()) map.remove(tu.patch); } public void run() { final int size = imageloader.length; // as many as Preloader threads final ArrayList<Tuple> list = new ArrayList<Tuple>(size); while (go) { try { synchronized (lock2) { lock2.lock(); } // read out a group of imageloader.length patches to load while (true) { // block 1: pop out 'size' valid tuples from the queue (and all invalid in between as well) synchronized (lock) { lock.lock(); int len = queue.size(); //Utils.log2("@@@@@ Queue size: " + len); if (0 == len) { lock.unlock(); break; } // When more than a hundred images, multiply by 10 the remove/read -out batch for preloading. // (if the batch_size is too large, then the removing/invalidating tuples from the queue would not work properly, i.e. they would never get invalidated and thus they'd be preloaded unnecessarily.) final int batch_size = size * (len < 100 ? 1 : 10); // for (int i=0; i<batch_size && i<len; len--) { final Tuple tuple = queue.remove(len-1); // start removing from the end, since those are the latest additions, hence the ones the user wants to see immediately. removeMapping(tuple); if (!tuple.valid) { //Utils.log2("@@@@@ skipping invalid tuple"); continue; } list.add(tuple); i++; } //Utils.log2("@@@@@ Queue size after: " + queue.size()); lock.unlock(); } // changes may occur now to the queue, so work on the list //Utils.log2("@@@@@ list size: " + list.size()); // block 2: now iterate until each tuple in the list has been assigned to a preloader thread while (!list.isEmpty()) { final Iterator<Tuple> it = list.iterator(); while (it.hasNext()) { for (int i=0; i<imageloader.length; i++) { final Tuple tu = it.next(); if (!imageloader[i].isLoading()) { it.remove(); imageloader[i].load(tu.patch, tu.mag, tu.repaint); } } } if (!list.isEmpty()) try { //Utils.log2("@@@@@ list not empty, waiting 50 ms"); Thread.sleep(50); } catch (InterruptedException ie) {} } } } catch (Exception e) { e.printStackTrace(); synchronized (lock) { lock.unlock(); } // just in case ... } } } } static public final void preload(final Patch patch, final double magnification, final boolean repaint) { preloader.add(patch, magnification, repaint); } static public final void preload(final ArrayList<Patch> patches, final double magnification, final boolean repaint) { preloader.add(patches, magnification, repaint); } static public final void quitPreloading(final ArrayList<Patch> patches, final double magnification) { preloader.remove(patches, magnification); } static private class ImageLoaderThread extends Thread { /** Controls access to Patch etc. */ private final Lock lock = new Lock(); /** Limits access to the load method while a previous image is being worked on. */ private final Lock lock2 = new Lock(); private Patch patch = null; private double mag = 1.0; private boolean repaint = false; private boolean go = true; private boolean loading = false; public ImageLoaderThread() { super("T2-Image-Loader"); setPriority(Thread.NORM_PRIORITY); try { setDaemon(true); } catch (Exception e) { e.printStackTrace(); } start(); } public final void quit() { this.go = false; synchronized (lock) { try { this.patch = null; lock.unlock(); } catch (Exception e) {} } synchronized (lock2) { lock2.unlock(); } } /** Sets the given Patch to be loaded, and returns. A second call to this method will wait until the first call has finished, indicating the Thread is busy loading the previous image. */ public final void load(final Patch p, final double mag, final boolean repaint) { synchronized (lock) { try { lock.lock(); this.patch = p; this.mag = mag; this.repaint = repaint; if (null != patch) { synchronized (lock2) { try { lock2.unlock(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } } } final boolean isLoading() { return loading; } public void run() { while (go) { Patch p = null; double mag = 1.0; boolean repaint = false; synchronized (lock2) { try { // wait until there's a Patch to preload. lock2.lock(); // ready: catch locally (no need to synch on lock because it can't change, considering the load method. p = this.patch; mag = this.mag; repaint = this.repaint; } catch (Exception e) {} } if (null != p) { try { if (repaint) { // wait a bit in case the user has browsed past Thread.yield(); try { sleep(50); } catch (InterruptedException ie) {} if (Display.willPaint(p, mag)) { loading = true; p.getProject().getLoader().fetchImage(p, mag); Display.repaint(p.getLayer(), p, p.getBoundingBox(null), 1, false); // not the navigator } } else { // just load it into the cache if possible loading = true; p.getProject().getLoader().fetchImage(p, mag); } p = null; } catch (Exception e) { e.printStackTrace(); } } // signal done try { synchronized (lock) { loading = false; lock.unlock(); } } catch (Exception e) {} } } } /** Returns the highest mipmap level for which a mipmap image may have been generated given the dimensions of the Patch. The minimum that this method may return is zero. */ public static final int getHighestMipMapLevel(final Patch p) { // TODO the level value could be computed analytically, not numerically like below int level = 0; int w = (int)p.getWidth(); int h = (int)p.getHeight(); while (w >= 64 && h >= 64) { w /= 2; h /= 2; level++; } return level; } static public final int NEAREST_NEIGHBOR = 0; static public final int BILINEAR = 1; static public final int BICUBIC = 2; static public final int GAUSSIAN = 3; static public final String[] modes = new String[]{"Nearest neighbor", "Bilinear", "Bicubic", "Gaussian"}; static public final int getMode(final String mode) { for (int i=0; i<modes.length; i++) { if (mode.equals(modes[i])) return i; } return 0; } /** Does nothing unless overriden. */ public Bureaucrat generateLayerMipMaps(final Layer[] la, final int starting_level) { return null; } /** Recover from an OutOfMemoryError: release 1/3 of all memory AND execute the garbage collector. */ public void recoverOOME() { releaseToFit(IJ.maxMemory() / 3); long start = System.currentTimeMillis(); long end = start; for (int i=0; i<3; i++) { System.gc(); Thread.yield(); end = System.currentTimeMillis(); if (end - start > 2000) break; // garbage collecion catched and is running. start = end; } } static public boolean canReadAndWriteTo(final String dir) { final File fsf = new File(dir); return fsf.canWrite() && fsf.canRead(); } }
diff --git a/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java b/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java index cb9cf595..bde36395 100644 --- a/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java +++ b/org.ow2.mindEd.ide.ui/src/org/ow2/mindEd/ide/ui/Activator.java @@ -1,139 +1,139 @@ package org.ow2.mindEd.ide.ui; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.emf.common.util.URI; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.IEditorDescriptor; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.ow2.mindEd.ide.core.MindIdeCore; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin { /** * The plug-in ID */ public static final String PLUGIN_ID = "org.ow2.mindEd.ide.ui"; /** * The shared instance */ private static Activator plugin; /** * The constructor */ public Activator() { } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given * plug-in relative path * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } /** * Open the editors associated to the giving file * @param jf a file */ static public void openFile(IFile jf) { if (jf != null) { try { IEditorDescriptor editor = IDE.getDefaultEditor(jf); if (editor == null) { editor = PlatformUI.getWorkbench().getEditorRegistry() .findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID); } - if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.part.MindDiagramEditorID")) { + if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.MindDiagramEditorID")) { // Save model URI, needed if diagram must be created URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString()); // This is the diagram URI jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT)); URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString()); // If diagram file doesn't exist, create it from the model if (!(jf.exists())) { initGmfDiagram(modelURI, diagramURI); } } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage(); IDE.openEditor(activePage, jf, true); } catch (PartInitException e) { MindIdeCore.log(e, "Cannot open file "+jf); } } } public static void initGmfDiagram(URI modelURI, URI diagramURI) { initGmfDiagram(diagramURI, modelURI, new NullProgressMonitor()); } public static void initGmfDiagram(URI diagramURI, URI modelURI, IProgressMonitor monitor) { try { Bundle bundle = Platform.getBundle("org.ow2.mindEd.adl.editor.graphic.ui"); if (bundle == null) { getDefault().getLog().log(new Status(Status.WARNING, PLUGIN_ID, "Cannot find gmf plugin digram")); return; } Class cl = bundle .loadClass("org.ow2.mindEd.adl.editor.graphic.ui.custom.part.CustomMindDiagramEditorUtil"); cl.getMethod("initDiagram",URI.class, URI.class, IProgressMonitor.class).invoke(null, diagramURI, modelURI, monitor); } catch (Throwable e) { getDefault().getLog().log(new Status(Status.ERROR, PLUGIN_ID, "Cannot init gmf digram", e)); } } }
true
true
static public void openFile(IFile jf) { if (jf != null) { try { IEditorDescriptor editor = IDE.getDefaultEditor(jf); if (editor == null) { editor = PlatformUI.getWorkbench().getEditorRegistry() .findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID); } if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.part.MindDiagramEditorID")) { // Save model URI, needed if diagram must be created URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString()); // This is the diagram URI jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT)); URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString()); // If diagram file doesn't exist, create it from the model if (!(jf.exists())) { initGmfDiagram(modelURI, diagramURI); } } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage(); IDE.openEditor(activePage, jf, true); } catch (PartInitException e) { MindIdeCore.log(e, "Cannot open file "+jf); } } }
static public void openFile(IFile jf) { if (jf != null) { try { IEditorDescriptor editor = IDE.getDefaultEditor(jf); if (editor == null) { editor = PlatformUI.getWorkbench().getEditorRegistry() .findEditor(EditorsUI.DEFAULT_TEXT_EDITOR_ID); } if (editor.getId().equals("org.ow2.mindEd.adl.editor.graphic.ui.MindDiagramEditorID")) { // Save model URI, needed if diagram must be created URI modelURI = URI.createFileURI(jf.getFullPath().toPortableString()); // This is the diagram URI jf = jf.getParent().getFile(new Path(jf.getName()+MindIdeCore.DIAGRAM_EXT)); URI diagramURI = URI.createFileURI(jf.getFullPath().toPortableString()); // If diagram file doesn't exist, create it from the model if (!(jf.exists())) { initGmfDiagram(modelURI, diagramURI); } } IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage(); IDE.openEditor(activePage, jf, true); } catch (PartInitException e) { MindIdeCore.log(e, "Cannot open file "+jf); } } }
diff --git a/schemagen/src/com/sun/xml/bind/v2/schemagen/XmlSchemaGenerator.java b/schemagen/src/com/sun/xml/bind/v2/schemagen/XmlSchemaGenerator.java index a5817409..243f4011 100644 --- a/schemagen/src/com/sun/xml/bind/v2/schemagen/XmlSchemaGenerator.java +++ b/schemagen/src/com/sun/xml/bind/v2/schemagen/XmlSchemaGenerator.java @@ -1,1186 +1,1190 @@ package com.sun.xml.bind.v2.schemagen; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.activation.MimeType; import javax.xml.bind.SchemaOutputResolver; import javax.xml.bind.annotation.XmlSchema; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; import com.sun.xml.bind.Util; import com.sun.xml.bind.v2.TODO; import com.sun.xml.bind.v2.WellKnownNamespace; import com.sun.xml.bind.v2.model.core.Adapter; import com.sun.xml.bind.v2.model.core.ArrayInfo; import com.sun.xml.bind.v2.model.core.AttributePropertyInfo; import com.sun.xml.bind.v2.model.core.ClassInfo; import com.sun.xml.bind.v2.model.core.Element; import com.sun.xml.bind.v2.model.core.ElementInfo; import com.sun.xml.bind.v2.model.core.ElementPropertyInfo; import com.sun.xml.bind.v2.model.core.EnumConstant; import com.sun.xml.bind.v2.model.core.EnumLeafInfo; import com.sun.xml.bind.v2.model.core.MapPropertyInfo; import com.sun.xml.bind.v2.model.core.NonElement; import com.sun.xml.bind.v2.model.core.NonElementRef; import com.sun.xml.bind.v2.model.core.PropertyInfo; import com.sun.xml.bind.v2.model.core.ReferencePropertyInfo; import com.sun.xml.bind.v2.model.core.TypeInfo; import com.sun.xml.bind.v2.model.core.TypeInfoSet; import com.sun.xml.bind.v2.model.core.TypeRef; import com.sun.xml.bind.v2.model.core.ValuePropertyInfo; import com.sun.xml.bind.v2.model.core.WildcardMode; import com.sun.xml.bind.v2.model.nav.Navigator; import com.sun.xml.bind.v2.runtime.SchemaGenerator; import com.sun.xml.bind.v2.runtime.SwaRefAdapter; import com.sun.xml.bind.v2.schemagen.xmlschema.Any; import com.sun.xml.bind.v2.schemagen.xmlschema.AttrDecls; import com.sun.xml.bind.v2.schemagen.xmlschema.ComplexExtension; import com.sun.xml.bind.v2.schemagen.xmlschema.ComplexType; import com.sun.xml.bind.v2.schemagen.xmlschema.ComplexTypeHost; import com.sun.xml.bind.v2.schemagen.xmlschema.ExplicitGroup; import com.sun.xml.bind.v2.schemagen.xmlschema.Import; import com.sun.xml.bind.v2.schemagen.xmlschema.LocalAttribute; import com.sun.xml.bind.v2.schemagen.xmlschema.LocalElement; import com.sun.xml.bind.v2.schemagen.xmlschema.Occurs; import com.sun.xml.bind.v2.schemagen.xmlschema.Schema; import com.sun.xml.bind.v2.schemagen.xmlschema.SimpleExtension; import com.sun.xml.bind.v2.schemagen.xmlschema.SimpleRestrictionModel; import com.sun.xml.bind.v2.schemagen.xmlschema.SimpleType; import com.sun.xml.bind.v2.schemagen.xmlschema.SimpleTypeHost; import com.sun.xml.bind.v2.schemagen.xmlschema.TopLevelElement; import com.sun.xml.bind.v2.schemagen.xmlschema.TypeHost; import com.sun.xml.txw2.TXW; import com.sun.xml.txw2.TxwException; import com.sun.xml.txw2.TypedXmlWriter; import com.sun.xml.txw2.output.ResultFactory; import static com.sun.xml.bind.v2.WellKnownNamespace.*; import static com.sun.xml.bind.v2.schemagen.Util.*; /** * Generates a set of W3C XML Schema documents from a set of Java classes. * * <p> * A client must invoke methods in the following order: * <ol> * <li>Create a new {@link XmlSchemaGenerator} * <li>Invoke {@link #add} or {@link #addAllClasses} repeatedly * <li>Invoke {@link #write} * <li>Discard the object * </ol> * * @author Ryan Shoemaker * @author Kohsuke Kawaguchi (kk@kohsuke.org) */ public final class XmlSchemaGenerator<TypeT,ClassDeclT,FieldT,MethodT> implements SchemaGenerator<TypeT,ClassDeclT,FieldT,MethodT> { private static final Logger logger = Util.getClassLogger(); /** * Java classes to be written, organized by their namespace. * * <p> * We use a {@link TreeMap} here so that the suggested names will * be consistent across JVMs. * * @see SchemaOutputResolver#createOutput(String, String) */ private final Map<String,Namespace> namespaces = new TreeMap<String,Namespace>(NAMESPACE_COMPARATOR); /** model navigator **/ private Navigator navigator; public XmlSchemaGenerator( Navigator<TypeT,ClassDeclT,FieldT,MethodT> navigator) { this.navigator = navigator; } public void fill(TypeInfoSet<TypeT,ClassDeclT,FieldT,MethodT> types) { addAllClasses(types.beans().values()); addAllElements(types.getElementMappings(null).values()); addAllEnums(types.enums().values()); addAllArrays(types.arrays().values()); for (Map.Entry<String, Namespace> e : namespaces.entrySet()) e.getValue().xmlNs.putAll( types.getXmlNs(e.getKey()) ); } private Namespace getNamespace(String uri) { Namespace n = namespaces.get(uri); if(n==null) namespaces.put(uri,n=new Namespace(uri)); return n; } /** * Adds a new class to the list of classes to be written. * * <p> * A {@link ClassInfo} may have two namespaces --- one for the element name * and the other for the type name. If they are different, we put the same * {@link ClassInfo} to two {@link Namespace}s. */ public void add( ClassInfo<TypeT,ClassDeclT> clazz ) { assert clazz!=null; String nsUri = null; if(clazz.isElement()) { // put element -> type reference nsUri = clazz.getElementName().getNamespaceURI(); Namespace ns = getNamespace(nsUri); ns.classes.add(clazz); ns.addDependencyTo(clazz.getTypeName()); } QName tn = clazz.getTypeName(); if(tn!=null) { nsUri = tn.getNamespaceURI(); } else { // anonymous type if(nsUri==null) return; } Namespace n = getNamespace(nsUri); n.classes.add(clazz); // search properties for foreign namespace references for( PropertyInfo<TypeT, ClassDeclT> p : clazz.getProperties()) { n.processForeignNamespaces(p); } // recurse on baseTypes to make sure that we can refer to them in the schema ClassInfo<TypeT,ClassDeclT> bc = clazz.getBaseClass(); if (bc != null) add(bc); } /** * Adds all the {@link ClassInfo}s in the given collection. */ public void addAllClasses( Iterable<? extends ClassInfo<TypeT,ClassDeclT>> col ) { for( ClassInfo<TypeT,ClassDeclT> ci : col ) add(ci); } /** * Adds a new element to the list of elements to be written. */ public void add( ElementInfo<TypeT,ClassDeclT> elem ) { assert elem!=null; Namespace n = getNamespace(elem.getElementName().getNamespaceURI()); n.elements.add(elem); // search for foreign namespace references n.processForeignNamespaces(elem.getProperty()); } /** * Adds all the {@link ElementInfo}s in the given collection. */ public void addAllElements( Iterable<? extends ElementInfo<TypeT,ClassDeclT>> col ) { for( ElementInfo<TypeT,ClassDeclT> ei : col ) add(ei); } public void add( EnumLeafInfo<TypeT,ClassDeclT> envm ) { assert envm!=null; final QName typeName = envm.getTypeName(); if (typeName != null) { final String namespaceURI = typeName.getNamespaceURI(); Namespace n = getNamespace(namespaceURI); n.enums.add(envm); // search for foreign namespace references n.addDependencyTo(envm.getBaseType().getTypeName()); } else { //annonymous return; } } /** * Adds all the {@link EnumLeafInfo}s in the given collection. */ public void addAllEnums( Iterable<? extends EnumLeafInfo<TypeT,ClassDeclT>> col ) { for( EnumLeafInfo<TypeT,ClassDeclT> ei : col ) add(ei); } public void add( ArrayInfo<TypeT,ClassDeclT> a ) { assert a!=null; final String namespaceURI = a.getTypeName().getNamespaceURI(); Namespace n = getNamespace(namespaceURI); n.arrays.add(a); // search for foreign namespace references n.addDependencyTo(a.getItemType().getTypeName()); } public void addAllArrays( Iterable<? extends ArrayInfo<TypeT,ClassDeclT>> col ) { for( ArrayInfo<TypeT,ClassDeclT> a : col) add(a); } /** * Adds an additional element declaration. * * @param tagName * The name of the element declaration to be added. * @param type * The type this element refers to. * Can be null, in which case the element refers to an empty anonymous complex type. */ public void add( QName tagName, NonElement<TypeT,ClassDeclT> type ) { Namespace n = getNamespace(tagName.getNamespaceURI()); n.additionalElementDecls.put(tagName.getLocalPart(),type); // search for foreign namespace references if(type!=null) n.addDependencyTo(type.getTypeName()); } /** * Write out the schema documents. */ public void write(SchemaOutputResolver resolver) throws IOException { if(resolver==null) throw new IllegalArgumentException(); // make it fool-proof resolver = new FoolProofResolver(resolver); Map<Namespace,Result> out = new HashMap<Namespace,Result>(); // we create a Namespace object for the XML Schema namespace // as a side-effect, but we don't want to generate it. namespaces.remove(WellKnownNamespace.XML_SCHEMA); // first create the outputs for all so that we can resolve references among // schema files when we write for( Namespace n : namespaces.values() ) { final Result output = resolver.createOutput(n.uri,"schema"+(out.size()+1)+".xsd"); if(output!=null) { // null result means no schema for that namespace out.put(n,output); } } // then write'em all for( Namespace n : namespaces.values() ) { final Result result = out.get(n); if(result!=null) { // null result means no schema for that namespace n.writeTo( result, out ); if(result instanceof StreamResult) { // TODO: handle other Result implementations? // handling StreamResult is at least good enough for schemagen since SchemaGenerator // uses a StreamResult by default. Besides, is anyone ever really going to send the // schema to a DOM tree or SAX events? final OutputStream outputStream = ((StreamResult)result).getOutputStream(); if(outputStream != null) { outputStream.close(); // fix for bugid: 6291301 } else { final Writer writer = ((StreamResult)result).getWriter(); if(writer != null) writer.close(); } } } } } /** * Schema components are organized per namespace. */ private class Namespace { final String uri; final StringBuilder newline = new StringBuilder("\n"); /** * Other {@link Namespace}s that this namespace depends on. */ private final Set<Namespace> depends = new LinkedHashSet<Namespace>(); /** * List of classes in this namespace. */ private final Set<ClassInfo<TypeT,ClassDeclT>> classes = new LinkedHashSet<ClassInfo<TypeT,ClassDeclT>>(); /** * Set of elements in this namespace */ private final Set<ElementInfo<TypeT,ClassDeclT>> elements = new LinkedHashSet<ElementInfo<TypeT,ClassDeclT>>(); /** * Set of enums in this namespace */ private Set<EnumLeafInfo<TypeT,ClassDeclT>> enums = new LinkedHashSet<EnumLeafInfo<TypeT,ClassDeclT>>(); /** * Set of arrays in this namespace */ private Set<ArrayInfo<TypeT,ClassDeclT>> arrays = new LinkedHashSet<ArrayInfo<TypeT,ClassDeclT>>(); /** * Additional element declarations. */ private Map<String,NonElement<TypeT,ClassDeclT>> additionalElementDecls = new HashMap<String, NonElement<TypeT, ClassDeclT>>(); /** * Additional namespace declarations to be made. Taken from {@link XmlSchema#xmlns}. */ private Map<String,String> xmlNs = new HashMap<String, String>(); public Namespace(String uri) { this.uri = uri; assert !XmlSchemaGenerator.this.namespaces.containsKey(uri); XmlSchemaGenerator.this.namespaces.put(uri,this); } /** * Process the given PropertyInfo looking for references to namespaces that * are foreign to the given namespace. Any foreign namespace references * found are added to the given namespaces dependency list and an <import> * is generated for it. * * @param p the PropertyInfo */ private void processForeignNamespaces(PropertyInfo<TypeT, ClassDeclT> p) { for( TypeInfo<TypeT, ClassDeclT> t : p.ref()) { if(t instanceof Element) { addDependencyTo(((Element)t).getElementName()); } if(t instanceof NonElement) { addDependencyTo(((NonElement)t).getTypeName()); } } } private void addDependencyTo(QName qname) { // even though the Element interface says getElementName() returns non-null, // ClassInfo always implements Element (even if an instance of ClassInfo might not be an Element). // so this check is still necessary if(qname==null) return; String nsUri = qname.getNamespaceURI(); if(uri.equals(nsUri) || nsUri.equals(XML_SCHEMA)) return; // found a type in a foreign namespace, so make sure we generate an import for it depends.add(getNamespace(nsUri)); } /** * Writes the schema document to the specified result. */ private void writeTo(Result result, Map<Namespace,Result> out) throws IOException { try { Schema schema = TXW.create(Schema.class,ResultFactory.createSerializer(result)); for (Map.Entry<String, String> e : xmlNs.entrySet()) { schema._namespace(e.getValue(),e.getKey()); } // declare XML Schema namespace to be xs, but allow the user to override it. // if 'xs' is used for other things, we'll just let TXW assign a random prefix if(!xmlNs.containsValue(WellKnownNamespace.XML_SCHEMA) && !xmlNs.containsKey("xs")) schema._namespace(WellKnownNamespace.XML_SCHEMA,"xs"); schema.version("1.0"); if(uri.length()!=0) schema.targetNamespace(uri); schema._pcdata(newline); // refer to other schemas for( Namespace n : depends ) { Import imp = schema._import(); if(n.uri.length()!=0) imp.namespace(n.uri); imp.schemaLocation(relativize(out.get(n).getSystemId(),result.getSystemId())); schema._pcdata(newline); } // then write each component for(ElementInfo<TypeT, ClassDeclT> e : elements) { writeElement(e, schema); schema._pcdata(newline); } for (ClassInfo<TypeT, ClassDeclT> c : classes) { Element<TypeT,ClassDeclT> e = c.asElement(); if (e != null) { // ClassInfo can have two namespaces URIs (one for type, another for element), // so make sure that we want to write this here. if(uri.equals(e.getElementName().getNamespaceURI())) writeTopLevelClass(c, e, schema); } if (c.getTypeName()==null) { // don't generate anything if it's an anonymous type continue; } if(uri.equals(c.getTypeName().getNamespaceURI())) writeClass(c, schema); schema._pcdata(newline); } for (EnumLeafInfo<TypeT, ClassDeclT> e : enums) { if (e.getTypeName()==null) { // don't generate anything if it's an anonymous type continue; } writeEnum(e,schema); schema._pcdata(newline); } for (ArrayInfo<TypeT, ClassDeclT> a : arrays) { writeArray(a,schema); schema._pcdata(newline); } for (Map.Entry<String,NonElement<TypeT,ClassDeclT>> e : additionalElementDecls.entrySet()) { writeElementDecl(e.getKey(),e.getValue(),schema); schema._pcdata(newline); } // close the schema schema.commit(); } catch( TxwException e ) { logger.log(Level.INFO,e.getMessage(),e); throw new IOException(e.getMessage()); } } private void writeElementDecl(String localName, NonElement<TypeT,ClassDeclT> value, Schema schema) { TopLevelElement e = schema.element().name(localName); if(value!=null) writeTypeRef(e,value, "type"); else { e.complexType(); // refer to the nested empty complex type } e.commit(); } /** * Writes a type attribute (if the referenced type is a global type) * or writes out the definition of the anonymous type in place (if the referenced * type is not a global type.) * * Also provides processing for ID/IDREF, MTOM @xmime, and swa:ref * * ComplexTypeHost and SimpleTypeHost don't share an api for creating * and attribute in a type-safe way, so we will compromise for now and * use _attribute(). */ private void writeTypeRef(TypeHost th, NonElementRef<TypeT, ClassDeclT> typeRef, String refAttName) { // ID / IDREF handling switch(typeRef.getSource().id()) { case ID: th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "ID")); return; case IDREF: th._attribute(refAttName, new QName(WellKnownNamespace.XML_SCHEMA, "IDREF")); return; case NONE: // no ID/IDREF, so continue on and generate the type break; default: throw new IllegalStateException(); } // MTOM handling MimeType mimeType = typeRef.getSource().getExpectedMimeType(); if( mimeType != null ) { th._attribute(new QName(WellKnownNamespace.XML_MIME_URI, "expectedContentTypes", "xmime"), mimeType.toString()); } // ref:swaRef handling if(generateSwaRefAdapter(typeRef)) { th._attribute(refAttName, new QName(WellKnownNamespace.SWA_URI, "swaRef", "ref")); return; } // type name override if(typeRef.getSource().getSchemaType()!=null) { th._attribute(refAttName,typeRef.getSource().getSchemaType()); return; } // normal type generation writeTypeRef(th, typeRef.getTarget(), refAttName); } /** * Examine the specified element ref and determine if a swaRef attribute needs to be generated * @param typeRef * @return */ private boolean generateSwaRefAdapter(NonElementRef<TypeT,ClassDeclT> typeRef) { final Adapter<TypeT,ClassDeclT> adapter = typeRef.getSource().getAdapter(); if (adapter == null) return false; final Object o = navigator.asDecl(SwaRefAdapter.class); if (o == null) return false; return (o.equals(adapter.adapterType)); } private int depth; /** * Writes a type attribute (if the referenced type is a global type) * or writes out the definition of the anonymous type in place (if the referenced * type is not a global type.) * * @param th * the TXW interface to which the attribute will be written. * @param type * type to be referenced. * @param refAttName * The name of the attribute used when referencing a type by QName. */ private void writeTypeRef(TypeHost th, NonElement<TypeT,ClassDeclT> type, String refAttName) { if(type.getTypeName()==null) { if(type instanceof ClassInfo) { depth++; for( int i=0; i<depth; i++ ) System.out.print(" "); System.out.println(((ClassInfo<TypeT,ClassDeclT>)type).getClazz()); writeClass( (ClassInfo<TypeT,ClassDeclT>)type, th ); depth--; } else { writeEnum( (EnumLeafInfo<TypeT,ClassDeclT>)type, (SimpleTypeHost)th); } } else { th._attribute(refAttName,type.getTypeName()); } } /** * writes the schema definition for the given array class */ private void writeArray(ArrayInfo<TypeT, ClassDeclT> a, Schema schema) { ComplexType ct = schema.complexType().name(a.getTypeName().getLocalPart()); ct._final("#all"); LocalElement le = ct.sequence().element().name("item"); le.type(a.getItemType().getTypeName()); le.minOccurs(0).maxOccurs("unbounded"); le.nillable(true); ct.commit(); } /** * writes the schema definition for the specified type-safe enum in the given TypeHost */ private void writeEnum(EnumLeafInfo<TypeT, ClassDeclT> e, SimpleTypeHost th) { SimpleType st = th.simpleType(); writeName(e,st); SimpleRestrictionModel base = st.restriction(); writeTypeRef(base, e.getBaseType(), "base"); for (EnumConstant c : e.getConstants()) { base.enumeration().value(c.getLexicalValue()); } st.commit(); } /** * writes the schema definition for the specified element to the schema writer * * @param e the element info * @param schema the schema writer */ private void writeElement(ElementInfo<TypeT, ClassDeclT> e, Schema schema) { TopLevelElement elem = schema.element(); elem.name(e.getElementName().getLocalPart()); writeTypeRef( elem, e.getContentType(), "type"); elem.commit(); } private void writeTopLevelClass(ClassInfo<TypeT, ClassDeclT> c, Element<TypeT, ClassDeclT> e, TypeHost schema) { // ClassInfo objects only represent JAXB beans, not primitives or built-in types // if the class is also mapped to an element (@XmlElement), generate such a decl. // // this processing only applies to top-level ClassInfos QName ename = e.getElementName(); assert ename.getNamespaceURI().equals(uri); // [RESULT] // <element name="foo" type="int"/> // not allowed to tweek min/max occurs on global elements TopLevelElement elem = ((Schema) schema).element(); elem.name(ename.getLocalPart()); writeTypeRef(elem, c, "type"); schema._pcdata(newline); } /** * Writes the schema definition for the specified class to the schema writer. * * @param c the class info * @param parent the writer of the parent element into which the type will be defined */ private void writeClass(ClassInfo<TypeT,ClassDeclT> c, TypeHost parent) { // special handling for value properties if (containsValueProp(c)) { if (c.getProperties().size() == 1) { // [RESULT 2 - simpleType if the value prop is the only prop] // // <simpleType name="foo"> // <xs:restriction base="xs:int"/> // </> ValuePropertyInfo vp = (ValuePropertyInfo)c.getProperties().get(0); SimpleType st = ((SimpleTypeHost)parent).simpleType(); writeName(c, st); - st.restriction().base(vp.getTarget().getTypeName()); + if(vp.isCollection()) { + writeTypeRef(st.list(),vp.getTarget(),"itemType"); + } else { + writeTypeRef(st.restriction(),vp.getTarget(),"base"); + } return; } else { // [RESULT 1 - complexType with simpleContent] // // <complexType name="foo"> // <simpleContent> // <extension base="xs:int"/> // <attribute name="b" type="xs:boolean"/> // </> // </> // </> // ... // <element name="f" type="foo"/> // ... ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); SimpleExtension se = ct.simpleContent().extension(); for (PropertyInfo p : c.getProperties()) { switch (p.kind()) { case ATTRIBUTE: handleAttributeProp((AttributePropertyInfo) p,se); break; case VALUE: TODO.checkSpec("what if vp.isCollection() == true?"); ValuePropertyInfo vp = (ValuePropertyInfo) p; se.base(vp.getTarget().getTypeName()); break; case ELEMENT: // error case REFERENCE: // error default: assert false; throw new IllegalStateException(); } } } TODO.schemaGenerator("figure out what to do if bc != null"); TODO.checkSpec("handle sec 8.9.5.2, bullet #4"); // Java types containing value props can only contain properties of type // ValuePropertyinfo and AttributePropertyInfo which have just been handled, // so return. return; } // we didn't fall into the special case for value props, so we // need to initialize the ct. // generate the complexType ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); // hold the ct open in case we need to generate @mixed below... ct.block(); // either <sequence> or <all> ExplicitGroup compositor = null; // only necessary if this type has a base class we need to extend from ComplexExtension ce = null; // if there is a base class, we need to generate an extension in the schema final ClassInfo<TypeT,ClassDeclT> bc = c.getBaseClass(); if (bc != null) { ce = ct.complexContent().extension(); ce.base(bc.getTypeName()); // TODO: what if the base type is anonymous? // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ce.sequence(); } else { compositor = ce.all(); } } // iterate over the properties if (c.hasProperties()) { if( compositor == null ) { // if there is no extension base, create a top level seq // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ct.sequence(); } else { compositor = ct.all(); } } // block writing the compositor because we might need to // write some out of order attributes to handle min/maxOccurs compositor.block(); for (PropertyInfo p : c.getProperties()) { // handling for <complexType @mixed='true' ...> if(p instanceof ReferencePropertyInfo && ((ReferencePropertyInfo)p).isMixed()) { ct.mixed(true); } if( ce != null ) { writeProperty(p, ce, compositor); } else { writeProperty(p, ct, compositor); } } compositor.commit(); } // look for wildcard attributes if( c.hasAttributeWildcard()) { // TODO: not type safe ct.anyAttribute().namespace("##other").processContents("skip"); } // finally commit the ct ct.commit(); } /** * Writes the name attribute if it's named. */ private void writeName(NonElement<TypeT,ClassDeclT> c, TypedXmlWriter xw) { QName tn = c.getTypeName(); if(tn!=null) xw._attribute("name",tn.getLocalPart()); // named } private boolean containsValueProp(ClassInfo<TypeT, ClassDeclT> c) { for (PropertyInfo p : c.getProperties()) { if (p instanceof ValuePropertyInfo) return true; } return false; } /** * write the schema definition(s) for the specified property */ private void writeProperty(PropertyInfo p, AttrDecls attr, ExplicitGroup compositor) { switch(p.kind()) { case ELEMENT: handleElementProp((ElementPropertyInfo)p, compositor); break; case ATTRIBUTE: handleAttributeProp((AttributePropertyInfo)p, attr); break; case REFERENCE: handleReferenceProp((ReferencePropertyInfo)p, compositor); break; case MAP: handleMapProp((MapPropertyInfo)p, compositor); break; case VALUE: // value props handled above in writeClass() assert false; throw new IllegalStateException(); // break(); default: assert false; throw new IllegalStateException(); } } /** * Generate the proper schema fragment for the given element property into the * specified schema compositor. * * The element property may or may not represent a collection and it may or may * not be wrapped. * * @param ep the element property * @param compositor the schema compositor (sequence or all) */ private void handleElementProp(ElementPropertyInfo<TypeT,ClassDeclT> ep, ExplicitGroup compositor) { QName ename = ep.getXmlName(); Occurs occurs = null; if (ep.isValueList()) { TypeRef t = ep.getTypes().get(0); LocalElement e = compositor.element(); QName tn = t.getTagName(); e.name(tn.getLocalPart()); com.sun.xml.bind.v2.schemagen.xmlschema.List lst = e.simpleType().list(); writeTypeRef(lst,t, "itemType"); if(tn.getNamespaceURI().length()>0) e.form("qualified"); // TODO: what if the URI != tns? return; } if (ep.isCollection()) { if (ename != null) { // wrapped collection LocalElement e = compositor.element(); if(ename.getNamespaceURI().length()>0) e.form("qualified"); // TODO: what if the URI != tns? ComplexType p = e.name(ename.getLocalPart()).complexType(); if(ep.isCollectionNillable()) { e.nillable(true); } else { e.minOccurs(0); } if (ep.getTypes().size() == 1) { compositor = p.sequence(); } else { compositor = p.choice(); occurs = compositor; } } else { // unwrapped collection if (ep.getTypes().size() > 1) { compositor = compositor.choice(); occurs = compositor; } } } boolean allNillable = true; // remain true after the next for loop if all TypeRefs are nillable // fill in the content model for (TypeRef t : ep.getTypes()) { LocalElement e = compositor.element(); if (occurs == null) occurs = e; QName tn = t.getTagName(); e.name(tn.getLocalPart()); writeTypeRef(e,t, "type"); if (t.isNillable()) { e.nillable(true); } else { allNillable = false; } if(t.getDefaultValue()!=null) e._default(t.getDefaultValue()); if(tn.getNamespaceURI().length()>0) e.form("qualified"); // TODO: what if the URI != tns? } if (ep.isCollection()) { // TODO: not type-safe occurs.maxOccurs("unbounded"); occurs.minOccurs(0); } else { if (!ep.isRequired() && !allNillable) { // see Spec table 8-13 occurs.minOccurs(0); } // else minOccurs defaults to 1 } } /** * Generate an attribute for the specified property on the specified complexType * * @param ap the attribute * @param attr the schema definition to which the attribute will be added */ private void handleAttributeProp(AttributePropertyInfo ap, AttrDecls attr) { // attr is either a top-level ComplexType or a ComplexExtension // // [RESULT] // // <complexType ...> // <...>...</> // <attribute name="foo" type="xs:int"/> // </> // // or // // <complexType ...> // <complexContent> // <extension ...> // <...>...</> // </> // </> // <attribute name="foo" type="xs:int"/> // </> // // or it could also be an in-lined type (attr ref) // LocalAttribute localAttribute = attr.attribute(); final String attrURI = ap.getXmlName().getNamespaceURI(); if (attrURI.equals("") || attrURI.equals(uri)) { localAttribute.name(ap.getXmlName().getLocalPart()); TypeHost th; String refAtt; if( ap.isCollection() ) { th = localAttribute.simpleType().list(); refAtt = "itemType"; } else { th = localAttribute; refAtt = "type"; } writeTypeRef(th, ap, refAtt); if (!attrURI.equals("")) { localAttribute.form("qualified"); } } else { // generate an attr ref localAttribute.ref(ap.getXmlName()); } if(ap.isRequired()) { // TODO: not type safe localAttribute.use("required"); } } /** * Generate the proper schema fragment for the given reference property into the * specified schema compositor. * * The reference property may or may not refer to a collection and it may or may * not be wrapped. * * @param rp * @param compositor */ private void handleReferenceProp(ReferencePropertyInfo<TypeT,ClassDeclT> rp, ExplicitGroup compositor) { QName ename = rp.getXmlName(); Occurs occurs = null; if (rp.isCollection()) { if (ename != null) { // wrapped collection LocalElement e = compositor.element(); ComplexType p = e.name(ename.getLocalPart()).complexType(); if(ename.getNamespaceURI().length()>0) e.form("qualified"); // TODO: handle elements from other namespaces more gracefully if(rp.isCollectionNillable()) e.nillable(true); if (rp.getElements().size() == 1) { compositor = p.sequence(); } else { compositor = p.choice(); occurs = compositor; } } else { // unwrapped collection if (rp.getElements().size() > 1) { compositor = compositor.choice(); occurs = compositor; } } } // fill in content model TODO.checkSpec("should we loop in the case of a non-collection ep?"); for (Element<TypeT, ClassDeclT> e : rp.getElements()) { LocalElement eref = compositor.element(); if (occurs == null) occurs = eref; eref.ref(e.getElementName()); } WildcardMode wc = rp.getWildcard(); if( wc != null ) { Any any = compositor.any(); final String pcmode = getProcessContentsModeName(wc); if( pcmode != null ) any.processContents(pcmode); TODO.schemaGenerator("generate @namespace ???"); if( occurs == null ) occurs = any; } if(rp.isCollection()) occurs.maxOccurs("unbounded"); } /** * Generate the proper schema fragment for the given map property into the * specified schema compositor. * * @param mp the map property * @param compositor the schema compositor (sequence or all) */ private void handleMapProp(MapPropertyInfo<TypeT,ClassDeclT> mp, ExplicitGroup compositor) { QName ename = mp.getXmlName(); LocalElement e = compositor.element(); if(ename.getNamespaceURI().length()>0) e.form("qualified"); // TODO: what if the URI != tns? if(mp.isCollectionNillable()) e.nillable(true); ComplexType p = e.name(ename.getLocalPart()).complexType(); // TODO: entry, key, and value are always unqualified. that needs to be fixed, too. e = p.sequence().element(); e.name("entry").minOccurs(0).maxOccurs("unbounded"); ExplicitGroup seq = e.complexType().sequence(); writeKeyOrValue(seq, "key", mp.getKeyType()); writeKeyOrValue(seq, "value", mp.getValueType()); } private void writeKeyOrValue(ExplicitGroup seq, String tagName, NonElement<TypeT, ClassDeclT> typeRef) { LocalElement key = seq.element().name(tagName); key.minOccurs(0); writeTypeRef(key, typeRef, "type"); } } /** * return the string representation of the processContents mode of the * give wildcard, or null if it is the schema default "strict" * */ private static String getProcessContentsModeName(WildcardMode wc) { switch(wc) { case LAX: case SKIP: return wc.name().toLowerCase(); case STRICT: return null; default: throw new IllegalStateException(); } } /** * TODO: JAX-WS dependency on this method - consider moving this method into com.sun.tools.jxc.util.Util * * Relativizes a URI by using another URI (base URI.) * * <p> * For example, {@code relative("http://www.sun.com/abc/def","http://www.sun.com/pqr/stu") => "../abc/def"} * * <p> * This method only works on hierarchical URI's, not opaque URI's (refer to the * <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/URI.html">java.net.URI</a> * javadoc for complete definitions of these terms. * * <p> * This method will not normalize the relative URI. * * @return the relative URI or the original URI if a relative one could not be computed */ protected static String relativize(String uri, String baseUri) { try { assert uri!=null; if(baseUri==null) return uri; URI theUri = new URI(escapeURI(uri)); URI theBaseUri = new URI(escapeURI(baseUri)); if (theUri.isOpaque() || theBaseUri.isOpaque()) return uri; if (!equalsIgnoreCase(theUri.getScheme(), theBaseUri.getScheme()) || !equal(theUri.getAuthority(), theBaseUri.getAuthority())) return uri; String uriPath = theUri.getPath(); String basePath = theBaseUri.getPath(); // normalize base path if (!basePath.endsWith("/")) { basePath = normalizeUriPath(basePath); } if( uriPath.equals(basePath)) return "."; String relPath = calculateRelativePath(uriPath, basePath); if (relPath == null) return uri; // recursion found no commonality in the two uris at all StringBuffer relUri = new StringBuffer(); relUri.append(relPath); if (theUri.getQuery() != null) relUri.append('?' + theUri.getQuery()); if (theUri.getFragment() != null) relUri.append('#' + theUri.getFragment()); return relUri.toString(); } catch (URISyntaxException e) { throw new InternalError("Error escaping one of these uris:\n\t"+uri+"\n\t"+baseUri); } } private static String calculateRelativePath(String uri, String base) { if (base == null) { return null; } if (uri.startsWith(base)) { return uri.substring(base.length()); } else { return "../" + calculateRelativePath(uri, getParentUriPath(base)); } } /** * {@link SchemaOutputResolver} that wraps the user-specified resolver * and makes sure that it's following the contract. * * <p> * This protects the rest of the {@link XmlSchemaGenerator} from client programming * error. */ private static final class FoolProofResolver extends SchemaOutputResolver { private final SchemaOutputResolver resolver; public FoolProofResolver(SchemaOutputResolver resolver) { assert resolver!=null; this.resolver = resolver; } public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { logger.entering(getClass().getName(),"createOutput",new Object[]{namespaceUri,suggestedFileName}); Result r = resolver.createOutput(namespaceUri,suggestedFileName); if(r!=null) { String sysId = r.getSystemId(); logger.finer("system ID = "+sysId); if(sysId!=null) { // TODO: make sure that the system Id is absolute // don't use java.net.URI, because it doesn't allow some characters (like SP) // which can legally used as file names. // but don't use java.net.URL either, because it doesn't allow a made-up URI // like kohsuke://foo/bar/zot } else throw new AssertionError("system ID cannot be null"); } logger.exiting(getClass().getName(),"createOutput",r); return r; } } /** * JAX-RPC wants the namespaces to be sorted in the reverse order * so that the empty namespace "" comes to the very end. Don't ask me why. */ private static final Comparator<String> NAMESPACE_COMPARATOR = new Comparator<String>() { public int compare(String lhs, String rhs) { return -lhs.compareTo(rhs); } }; }
true
true
private void writeClass(ClassInfo<TypeT,ClassDeclT> c, TypeHost parent) { // special handling for value properties if (containsValueProp(c)) { if (c.getProperties().size() == 1) { // [RESULT 2 - simpleType if the value prop is the only prop] // // <simpleType name="foo"> // <xs:restriction base="xs:int"/> // </> ValuePropertyInfo vp = (ValuePropertyInfo)c.getProperties().get(0); SimpleType st = ((SimpleTypeHost)parent).simpleType(); writeName(c, st); st.restriction().base(vp.getTarget().getTypeName()); return; } else { // [RESULT 1 - complexType with simpleContent] // // <complexType name="foo"> // <simpleContent> // <extension base="xs:int"/> // <attribute name="b" type="xs:boolean"/> // </> // </> // </> // ... // <element name="f" type="foo"/> // ... ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); SimpleExtension se = ct.simpleContent().extension(); for (PropertyInfo p : c.getProperties()) { switch (p.kind()) { case ATTRIBUTE: handleAttributeProp((AttributePropertyInfo) p,se); break; case VALUE: TODO.checkSpec("what if vp.isCollection() == true?"); ValuePropertyInfo vp = (ValuePropertyInfo) p; se.base(vp.getTarget().getTypeName()); break; case ELEMENT: // error case REFERENCE: // error default: assert false; throw new IllegalStateException(); } } } TODO.schemaGenerator("figure out what to do if bc != null"); TODO.checkSpec("handle sec 8.9.5.2, bullet #4"); // Java types containing value props can only contain properties of type // ValuePropertyinfo and AttributePropertyInfo which have just been handled, // so return. return; } // we didn't fall into the special case for value props, so we // need to initialize the ct. // generate the complexType ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); // hold the ct open in case we need to generate @mixed below... ct.block(); // either <sequence> or <all> ExplicitGroup compositor = null; // only necessary if this type has a base class we need to extend from ComplexExtension ce = null; // if there is a base class, we need to generate an extension in the schema final ClassInfo<TypeT,ClassDeclT> bc = c.getBaseClass(); if (bc != null) { ce = ct.complexContent().extension(); ce.base(bc.getTypeName()); // TODO: what if the base type is anonymous? // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ce.sequence(); } else { compositor = ce.all(); } } // iterate over the properties if (c.hasProperties()) { if( compositor == null ) { // if there is no extension base, create a top level seq // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ct.sequence(); } else { compositor = ct.all(); } } // block writing the compositor because we might need to // write some out of order attributes to handle min/maxOccurs compositor.block(); for (PropertyInfo p : c.getProperties()) { // handling for <complexType @mixed='true' ...> if(p instanceof ReferencePropertyInfo && ((ReferencePropertyInfo)p).isMixed()) { ct.mixed(true); } if( ce != null ) { writeProperty(p, ce, compositor); } else { writeProperty(p, ct, compositor); } } compositor.commit(); } // look for wildcard attributes if( c.hasAttributeWildcard()) { // TODO: not type safe ct.anyAttribute().namespace("##other").processContents("skip"); } // finally commit the ct ct.commit(); }
private void writeClass(ClassInfo<TypeT,ClassDeclT> c, TypeHost parent) { // special handling for value properties if (containsValueProp(c)) { if (c.getProperties().size() == 1) { // [RESULT 2 - simpleType if the value prop is the only prop] // // <simpleType name="foo"> // <xs:restriction base="xs:int"/> // </> ValuePropertyInfo vp = (ValuePropertyInfo)c.getProperties().get(0); SimpleType st = ((SimpleTypeHost)parent).simpleType(); writeName(c, st); if(vp.isCollection()) { writeTypeRef(st.list(),vp.getTarget(),"itemType"); } else { writeTypeRef(st.restriction(),vp.getTarget(),"base"); } return; } else { // [RESULT 1 - complexType with simpleContent] // // <complexType name="foo"> // <simpleContent> // <extension base="xs:int"/> // <attribute name="b" type="xs:boolean"/> // </> // </> // </> // ... // <element name="f" type="foo"/> // ... ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); SimpleExtension se = ct.simpleContent().extension(); for (PropertyInfo p : c.getProperties()) { switch (p.kind()) { case ATTRIBUTE: handleAttributeProp((AttributePropertyInfo) p,se); break; case VALUE: TODO.checkSpec("what if vp.isCollection() == true?"); ValuePropertyInfo vp = (ValuePropertyInfo) p; se.base(vp.getTarget().getTypeName()); break; case ELEMENT: // error case REFERENCE: // error default: assert false; throw new IllegalStateException(); } } } TODO.schemaGenerator("figure out what to do if bc != null"); TODO.checkSpec("handle sec 8.9.5.2, bullet #4"); // Java types containing value props can only contain properties of type // ValuePropertyinfo and AttributePropertyInfo which have just been handled, // so return. return; } // we didn't fall into the special case for value props, so we // need to initialize the ct. // generate the complexType ComplexType ct = ((ComplexTypeHost)parent).complexType(); writeName(c,ct); if(c.isFinal()) ct._final("extension restriction"); // hold the ct open in case we need to generate @mixed below... ct.block(); // either <sequence> or <all> ExplicitGroup compositor = null; // only necessary if this type has a base class we need to extend from ComplexExtension ce = null; // if there is a base class, we need to generate an extension in the schema final ClassInfo<TypeT,ClassDeclT> bc = c.getBaseClass(); if (bc != null) { ce = ct.complexContent().extension(); ce.base(bc.getTypeName()); // TODO: what if the base type is anonymous? // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ce.sequence(); } else { compositor = ce.all(); } } // iterate over the properties if (c.hasProperties()) { if( compositor == null ) { // if there is no extension base, create a top level seq // ordered props go in a sequence, unordered go in an all if( c.isOrdered() ) { compositor = ct.sequence(); } else { compositor = ct.all(); } } // block writing the compositor because we might need to // write some out of order attributes to handle min/maxOccurs compositor.block(); for (PropertyInfo p : c.getProperties()) { // handling for <complexType @mixed='true' ...> if(p instanceof ReferencePropertyInfo && ((ReferencePropertyInfo)p).isMixed()) { ct.mixed(true); } if( ce != null ) { writeProperty(p, ce, compositor); } else { writeProperty(p, ct, compositor); } } compositor.commit(); } // look for wildcard attributes if( c.hasAttributeWildcard()) { // TODO: not type safe ct.anyAttribute().namespace("##other").processContents("skip"); } // finally commit the ct ct.commit(); }
diff --git a/loci/visbio/data/ArbitrarySlice.java b/loci/visbio/data/ArbitrarySlice.java index a78b03a..06fcb03 100644 --- a/loci/visbio/data/ArbitrarySlice.java +++ b/loci/visbio/data/ArbitrarySlice.java @@ -1,622 +1,637 @@ // // ArbitrarySlice.java // /* VisBio application for visualization of multidimensional biological image data. Copyright (C) 2002-2006 Curtis Rueden. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.visbio.data; import java.rmi.RemoteException; import javax.swing.JComponent; import javax.swing.JOptionPane; import loci.visbio.state.Dynamic; import loci.visbio.state.SaveException; import loci.visbio.util.DataUtil; import loci.visbio.util.XMLUtil; import org.w3c.dom.Element; import visad.*; /** A transform for slicing a stack of images in 3D. */ public class ArbitrarySlice extends DataTransform implements TransformListener { // -- Constants -- private static final double RADIUS3 = Math.sqrt(3); private static final double RADIUS6 = Math.sqrt(6); private static final double THETA1 = 0; private static final double THETA2 = Math.PI / 2; private static final double THETA3 = 3 * Math.PI / 2; private static final double THETA4 = Math.PI; private static final float T1COS = (float) (RADIUS6 * Math.cos(THETA1)); private static final float T1SIN = (float) (RADIUS6 * Math.sin(THETA1)); private static final float T2COS = (float) (RADIUS6 * Math.cos(THETA2)); private static final float T2SIN = (float) (RADIUS6 * Math.sin(THETA2)); private static final float T3COS = (float) (RADIUS6 * Math.cos(THETA3)); private static final float T3SIN = (float) (RADIUS6 * Math.sin(THETA3)); private static final float T4COS = (float) (RADIUS6 * Math.cos(THETA4)); private static final float T4SIN = (float) (RADIUS6 * Math.sin(THETA4)); // -- Fields -- /** Dimensional axis to slice through. */ protected int axis; /** Horizontal rotational angle of slicing line. */ protected float yaw; /** Vertical rotatational angle of slicing line. */ protected float pitch; /** Arbitrary slice's location along slicing line. */ protected float loc; /** Resolution of arbitrary slice. */ protected int res; /** Flag indicating whether slicing line should be shown. */ protected boolean showLine; /** Flag indicating whether arbitrary slice should actually be computed. */ protected boolean compute; /** Controls for the arbitrary slice. */ protected SliceWidget controls; // -- Constructor -- /** Creates an uninitialized arbitrary slice. */ public ArbitrarySlice() { } /** Creates an overlay object for the given transform. */ public ArbitrarySlice(DataTransform parent, String name) { super(parent, name); initState(null); parent.addTransformListener(this); } // -- ArbitrarySlice API methods -- /** * Sets the parameters for the arbitrary slice, * recomputing the slice if the compute flag is set. */ public synchronized void setParameters(int axis, float yaw, float pitch, float loc, int res, boolean showLine, boolean compute) { if (this.axis != axis) { this.axis = axis; computeLengths(); } if (this.yaw == yaw && this.pitch == pitch && this.loc == loc && this.res == res && this.showLine == showLine && this.compute == compute) { return; } this.yaw = yaw; this.pitch = pitch; this.loc = loc; this.res = res; this.showLine = showLine; this.compute = compute; controls.refreshWidget(); notifyListeners(new TransformEvent(this)); } /** Sets the axis through which to slice. */ public void setAxis(int axis) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets the yaw for the slicing line. */ public void setYaw(float yaw) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets the pitch for the slicing line. */ public void setPitch(float pitch) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets the location for the arbitrary slice. */ public void setLocation(float loc) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets the resolution for the slicing line. */ public void setResolution(int res) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets whether white line is shown. */ public void setLineVisible(boolean showLine) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Sets whether arbitrary slice is computed. */ public void setSliceComputed(boolean compute) { setParameters(axis, yaw, pitch, loc, res, showLine, compute); } /** Gets the axis through which to slice. */ public int getAxis() { return axis; } /** Gets the yaw for the slicing line. */ public float getYaw() { return yaw; } /** Gets the pitch for the slicing line. */ public float getPitch() { return pitch; } /** Gets the location for the arbitrary slice. */ public float getLocation() { return loc; } /** Gets the resolution for the slicing line. */ public int getResolution() { return res; } /** Gets whether slicing line is shown. */ public boolean isLineVisible() { return showLine; } /** Gets whether arbitary slice is computed. */ public boolean isSliceComputed() { return compute; } // -- Static DataTransform API methods -- /** Creates a new set of overlays, with user interaction. */ public static DataTransform makeTransform(DataManager dm) { DataTransform dt = dm.getSelectedData(); if (!isValidParent(dt)) return null; String n = (String) JOptionPane.showInputDialog(dm.getControls(), "Title of slice:", "Create arbitrary slice", JOptionPane.INFORMATION_MESSAGE, null, null, dt.getName() + " slice"); if (n == null) return null; return new ArbitrarySlice(dt, n); } /** * Indicates whether this transform type would accept * the given transform as its parent transform. */ public static boolean isValidParent(DataTransform data) { return data != null && data instanceof ImageTransform && data.getLengths().length > 0; } /** Indicates whether this transform type requires a parent transform. */ public static boolean isParentRequired() { return true; } // -- DataTransform API methods -- /** * Retrieves the data corresponding to the given dimensional position, * for the given display dimensionality. * * @return null if the transform does not provide data of that dimensionality */ public synchronized Data getData(int[] pos, int dim, DataCache cache) { if (dim != 3) { System.err.println(name + ": invalid dimensionality (" + dim + ")"); return null; } // get some info from the parent transform ImageTransform it = (ImageTransform) parent; int w = it.getImageWidth(); int h = it.getImageHeight(); int n = parent.getLengths()[axis]; RealType xType = it.getXType(); RealType yType = it.getYType(); RealType zType = it.getZType(); RealType[] range = it.getRangeTypes(); FunctionType imageType = it.getType(); Unit[] imageUnits = it.getImageUnits(); Unit zUnit = it.getZUnit(axis); Unit[] xyzUnits = {imageUnits[0], imageUnits[1], zUnit}; RealTupleType xy = null, xyz = null; try { xy = new RealTupleType(xType, yType); xyz = new RealTupleType(xType, yType, zType); } catch (VisADException exc) { exc.printStackTrace(); } // convert spherical polar coordinates to cartesian coordinates for line double yawRadians = Math.PI * yaw / 180; double yawCos = Math.cos(yawRadians); double yawSin = Math.sin(yawRadians); double pitchRadians = Math.PI * (90 - pitch) / 180; double pitchCos = Math.cos(pitchRadians); double pitchSin = Math.sin(pitchRadians); // Let P1 = (x, y, z), P2 = -P1 float x = (float) (RADIUS3 * pitchSin * yawCos); float y = (float) (RADIUS3 * pitchSin * yawSin); float z = (float) (RADIUS3 * pitchCos); // compute location along P1-P2 line float q = (loc - 50) / 50; float lx = q * x; float ly = q * y; float lz = q * z; // choose a point P which doesn't lie on the line through P1 and P2 float px = 1, py = 1, pz = 1; float ax = x < 0 ? -x : x; float ay = y < 0 ? -y : y; float az = z < 0 ? -z : z; if (ax - ay < 0.1) py = -1; if (ax - az < 0.1) pz = -1; // calculate the vector R as the cross product between P - P1 and P2 - P1 float pp1x = px - x, pp1y = py - y, pp1z = pz - z; float p2p1x = -x - x, p2p1y = -y - y, p2p1z = -z - z; float rz = pp1x * p2p1y - pp1y * p2p1x; float rx = pp1y * p2p1z - pp1z * p2p1y; float ry = pp1z * p2p1x - pp1x * p2p1z; // R is now perpendicular to P2 - P1 // calculate the vector S as the cross product between R and P2 - P1 float sz = rx * p2p1y - ry * p2p1x; float sx = ry * p2p1z - rz * p2p1y; float sy = rz * p2p1x - rx * p2p1z; // S is now perpendicular to both R and the P2 - P1 // normalize R and S float rlen = (float) Math.sqrt(rx * rx + ry * ry + rz * rz); rx /= rlen; ry /= rlen; rz /= rlen; float slen = (float) Math.sqrt(sx * sx + sy * sy + sz * sz); sx /= slen; sy /= slen; sz /= slen; // now R and S are an orthonormal basis for the plane Gridded3DSet line = null; if (showLine) { // convert x=[-1,1] y=[-1,1] z=[-1,1] to x=[0,w] y=[0,h] z=[0,n] float[][] lineSamples = { {w * (x + 1) / 2, w * (-x + 1) / 2}, {h * (y + 1) / 2, h * (-y + 1) / 2}, {n * (z + 1) / 2, n * (-z + 1) / 2} }; // construct line data object try { line = new Gridded3DSet(xyz, lineSamples, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } // compute slice data Data slice = null; if (compute) { // interpolate from parent data // compute plane corners from orthonormal basis float q1x = w * (lx + T1COS * rx + T1SIN * sx + 1) / 2; float q1y = h * (ly + T1COS * ry + T1SIN * sy + 1) / 2; float q1z = n * (lz + T1COS * rz + T1SIN * sz + 1) / 2; float q2x = w * (lx + T2COS * rx + T2SIN * sx + 1) / 2; float q2y = h * (ly + T2COS * ry + T2SIN * sy + 1) / 2; float q2z = n * (lz + T2COS * rz + T2SIN * sz + 1) / 2; float q3x = w * (lx + T3COS * rx + T3SIN * sx + 1) / 2; float q3y = h * (ly + T3COS * ry + T3SIN * sy + 1) / 2; float q3z = n * (lz + T3COS * rz + T3SIN * sz + 1) / 2; float q4x = w * (lx + T4COS * rx + T4SIN * sx + 1) / 2; float q4y = h * (ly + T4COS * ry + T4SIN * sy + 1) / 2; float q4z = n * (lz + T4COS * rz + T4SIN * sz + 1) / 2; // retrieve parent data from data cache int[] npos = getParentPos(pos); FlatField[] fields = new FlatField[n]; for (int i=0; i<n; i++) { npos[axis] = i; Data data = parent.getData(npos, 2, cache); if (data == null || !(data instanceof FlatField)) { System.err.println(name + ": parent image plane #" + (i + 1) + " is not valid"); return null; } fields[i] = (FlatField) data; } try { // use image transform's recommended MathType and Units for (int i=0; i<n; i++) { fields[i] = DataUtil.switchType(fields[i], imageType, imageUnits); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } // generate planar domain samples and corresponding interpolated values int res1 = res - 1; + float[][][] fieldSamples = new float[fields.length][][];//TEMP float[][] planeSamples = new float[3][res * res]; float[][] planeValues = new float[range.length][res * res]; for (int r=0; r<res; r++) { float rr = (float) r / res1; float xmin = (1 - rr) * q1x + rr * q3x; float ymin = (1 - rr) * q1y + rr * q3y; float zmin = (1 - rr) * q1z + rr * q3z; float xmax = (1 - rr) * q2x + rr * q4x; float ymax = (1 - rr) * q2y + rr * q4y; float zmax = (1 - rr) * q2z + rr * q4z; for (int c=0; c<res; c++) { float cc = (float) c / res1; int ndx = r * res + c; + //float xs = planeSamples[0][ndx] = (1 - cc) * xmin + cc * xmax; float xs = planeSamples[0][ndx] = (1 - cc) * xmin + cc * xmax; float ys = planeSamples[1][ndx] = (1 - cc) * ymin + cc * ymax; + ys = h - ys; // lines are flipped float zs = planeSamples[2][ndx] = (1 - cc) * zmin + cc * zmax; if (xs < 0 || ys < 0 || zs < 0 || xs > w - 1 || ys > h - 1 || zs > n - 1) { // this pixel is outside the range of the data (missing) for (int k=0; k<planeValues.length; k++) { - planeValues[k][ndx] = Float.NaN; + planeValues[k][ndx] = c;//Float.NaN; } } else { // interpolate the value of this pixel for each range component int xx = (int) xs, yy = (int) ys, zz = (int) zs; float wx = xs - xx, wy = ys - yy, wz = zs - zz; float[][] values0 = null, values1 = null; FlatField field0, field1; if (wz == 0) { // interpolate from a single field (z0 == z1) - try { values0 = values1 = fields[zz].getFloats(false); } + try { + if (fieldSamples[zz] == null) {//TEMP + fieldSamples[zz] = fields[zz].getFloats(false);//TEMP + }//TEMP + values0 = values1 = fieldSamples[zz]; + } catch (VisADException exc) { exc.printStackTrace(); } } else { // interpolate between two fields try { - values0 = fields[zz].getFloats(false); - values1 = fields[zz + 1].getFloats(false); + if (fieldSamples[zz] == null) {//TEMP + fieldSamples[zz] = fields[zz].getFloats(false);//TEMP + }//TEMP + if (fieldSamples[zz + 1] == null) {//TEMP + fieldSamples[zz + 1] = fields[zz + 1].getFloats(false);//TEMP + }//TEMP + values0 = fieldSamples[zz]; + values1 = fieldSamples[zz + 1]; } catch (VisADException exc) { exc.printStackTrace(); } } int ndx00 = w * yy + xx; int ndx10 = w * yy + xx + 1; int ndx01 = w * (yy + 1) + xx; int ndx11 = w * (yy + 1) + xx + 1; for (int k=0; k<range.length; k++) { // tri-linear interpolation (x, then y, then z) float v000 = values0[k][ndx00]; float v100 = values0[k][ndx10]; float v010 = values0[k][ndx01]; float v110 = values0[k][ndx11]; float v001 = values1[k][ndx00]; float v101 = values1[k][ndx10]; float v011 = values1[k][ndx01]; float v111 = values1[k][ndx11]; float vx00 = (1 - wx) * v000 + wx * v100; float vx10 = (1 - wx) * v010 + wx * v110; float vx01 = (1 - wx) * v001 + wx * v101; float vx11 = (1 - wx) * v011 + wx * v111; float vxy0 = (1 - wy) * vx00 + wy * vx10; float vxy1 = (1 - wy) * vx01 + wy * vx11; float vxyz = (1 - wz) * vxy0 + wz * vxy1; planeValues[k][ndx] = vxyz; } } } } try { FunctionType planeType = new FunctionType(xyz, imageType.getRange()); + // set must be gridded, not linear, because ManifoldDimension is 2 Gridded3DSet planeSet = new Gridded3DSet(xyz, planeSamples, res, res, null, xyzUnits, null, false); FlatField ff = new FlatField(planeType, planeSet); ff.setSamples(planeValues, false); slice = ff; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else { // construct bounding circle // compute circle coordinates from orthonormal basis int num = 32; float[][] samples = new float[3][num]; for (int i=0; i<num; i++) { double theta = i * 2 * Math.PI / num; float tcos = (float) (RADIUS3 * Math.cos(theta)); float tsin = (float) (RADIUS3 * Math.sin(theta)); float qx = lx + tcos * rx + tsin * sx; float qy = ly + tcos * ry + tsin * sy; float qz = lz + tcos * rz + tsin * sz; int ndx = (i < num / 2) ? i : (3 * num / 2 - i - 1); samples[0][ndx] = w * (qx + 1) / 2; samples[1][ndx] = h * (qy + 1) / 2; samples[2][ndx] = n * (qz + 1) / 2; } // construct bounding circle data object try { slice = new Gridded3DSet(xyz, samples, num / 2, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } Data[] data = showLine ? new Data[] {slice, line} : new Data[] {slice}; try { return new Tuple(data, false); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; } /** Gets whether this transform provides data of the given dimensionality. */ public boolean isValidDimension(int dim) { return dim == 3; } /** Retrieves a set of mappings for displaying this transform effectively. */ public ScalarMap[] getSuggestedMaps() { // Slice XYZ types piggyback on the parent, so that two sets of XYZ // coordinates don't show up during cursor probes (and so that the slice // is placed properly without an extra set of setRange calls). return parent.getSuggestedMaps(); } /** * Gets a string id uniquely describing this data transform at the given * dimensional position, for the purposes of thumbnail caching. * If global flag is true, the id is suitable for use in the default, * global cache file. */ public String getCacheId(int[] pos, boolean global) { return null; } /** * Arbitrary slices are rendered immediately, * due to frequent user interaction. */ public boolean isImmediate() { return true; } /** Gets associated GUI controls for this transform. */ public JComponent getControls() { return controls; } // -- Dynamic API methods -- /** Tests whether two dynamic objects are equivalent. */ public boolean matches(Dynamic dyn) { if (!super.matches(dyn) || !isCompatible(dyn)) return false; ArbitrarySlice data = (ArbitrarySlice) dyn; // CTR TODO return true iff data matches this object return false; } /** * Tests whether the given dynamic object can be used as an argument to * initState, for initializing this dynamic object. */ public boolean isCompatible(Dynamic dyn) { return dyn instanceof ArbitrarySlice; } /** * Modifies this object's state to match that of the given object. * If the argument is null, the object is initialized according to * its current state instead. */ public void initState(Dynamic dyn) { if (dyn != null && !isCompatible(dyn)) return; super.initState(dyn); ArbitrarySlice data = (ArbitrarySlice) dyn; if (data == null) { axis = -1; yaw = 0; pitch = 45; loc = 50; res = 64; showLine = true; compute = true; } else { axis = data.axis; yaw = data.yaw; pitch = data.pitch; loc = data.loc; res = data.res; showLine = data.showLine; compute = data.compute; } computeLengths(); controls = new SliceWidget(this); } // -- Saveable API methods -- /** Writes the current state to the given DOM element ("DataTransforms"). */ public void saveState(Element el) throws SaveException { Element child = XMLUtil.createChild(el, "ArbitrarySlice"); super.saveState(child); child.setAttribute("axis", "" + axis); child.setAttribute("yaw", "" + yaw); child.setAttribute("pitch", "" + pitch); child.setAttribute("location", "" + loc); child.setAttribute("resolution", "" + res); child.setAttribute("showLine", "" + showLine); child.setAttribute("onTheFly", "" + compute); } /** * Restores the current state from the given DOM element ("ArbitrarySlice"). */ public void restoreState(Element el) throws SaveException { super.restoreState(el); axis = Integer.parseInt(el.getAttribute("axis")); yaw = Float.parseFloat(el.getAttribute("yaw")); pitch = Float.parseFloat(el.getAttribute("pitch")); loc = Float.parseFloat(el.getAttribute("location")); res = Integer.parseInt(el.getAttribute("resolution")); showLine = "true".equals(el.getAttribute("showLine")); compute = "true".equals(el.getAttribute("onTheFly")); } // -- TransformListener API methods -- /** Called when parent data transform's parameters are updated. */ public void transformChanged(TransformEvent e) { int id = e.getId(); if (id == TransformEvent.DATA_CHANGED) { initState(null); notifyListeners(new TransformEvent(this)); } } // -- Helper methods -- /** Computes lengths and dims based on dimensional axis to be sliced. */ private void computeLengths() { int[] plens = parent.getLengths(); String[] pdims = parent.getDimTypes(); if (axis < 0) { axis = 0; for (int i=0; i<pdims.length; i++) { if (pdims[i].equals("Slice")) { axis = i; break; } } } lengths = new int[plens.length - 1]; System.arraycopy(plens, 0, lengths, 0, axis); System.arraycopy(plens, axis + 1, lengths, axis, lengths.length - axis); dims = new String[pdims.length - 1]; System.arraycopy(pdims, 0, dims, 0, axis); System.arraycopy(pdims, axis + 1, dims, axis, dims.length - axis); makeLabels(); } /** Gets dimensional position for parent transform. */ private int[] getParentPos(int[] pos) { int[] npos = new int[pos.length + 1]; System.arraycopy(pos, 0, npos, 0, axis); System.arraycopy(pos, axis, npos, axis + 1, pos.length - axis); return npos; } }
false
true
public synchronized Data getData(int[] pos, int dim, DataCache cache) { if (dim != 3) { System.err.println(name + ": invalid dimensionality (" + dim + ")"); return null; } // get some info from the parent transform ImageTransform it = (ImageTransform) parent; int w = it.getImageWidth(); int h = it.getImageHeight(); int n = parent.getLengths()[axis]; RealType xType = it.getXType(); RealType yType = it.getYType(); RealType zType = it.getZType(); RealType[] range = it.getRangeTypes(); FunctionType imageType = it.getType(); Unit[] imageUnits = it.getImageUnits(); Unit zUnit = it.getZUnit(axis); Unit[] xyzUnits = {imageUnits[0], imageUnits[1], zUnit}; RealTupleType xy = null, xyz = null; try { xy = new RealTupleType(xType, yType); xyz = new RealTupleType(xType, yType, zType); } catch (VisADException exc) { exc.printStackTrace(); } // convert spherical polar coordinates to cartesian coordinates for line double yawRadians = Math.PI * yaw / 180; double yawCos = Math.cos(yawRadians); double yawSin = Math.sin(yawRadians); double pitchRadians = Math.PI * (90 - pitch) / 180; double pitchCos = Math.cos(pitchRadians); double pitchSin = Math.sin(pitchRadians); // Let P1 = (x, y, z), P2 = -P1 float x = (float) (RADIUS3 * pitchSin * yawCos); float y = (float) (RADIUS3 * pitchSin * yawSin); float z = (float) (RADIUS3 * pitchCos); // compute location along P1-P2 line float q = (loc - 50) / 50; float lx = q * x; float ly = q * y; float lz = q * z; // choose a point P which doesn't lie on the line through P1 and P2 float px = 1, py = 1, pz = 1; float ax = x < 0 ? -x : x; float ay = y < 0 ? -y : y; float az = z < 0 ? -z : z; if (ax - ay < 0.1) py = -1; if (ax - az < 0.1) pz = -1; // calculate the vector R as the cross product between P - P1 and P2 - P1 float pp1x = px - x, pp1y = py - y, pp1z = pz - z; float p2p1x = -x - x, p2p1y = -y - y, p2p1z = -z - z; float rz = pp1x * p2p1y - pp1y * p2p1x; float rx = pp1y * p2p1z - pp1z * p2p1y; float ry = pp1z * p2p1x - pp1x * p2p1z; // R is now perpendicular to P2 - P1 // calculate the vector S as the cross product between R and P2 - P1 float sz = rx * p2p1y - ry * p2p1x; float sx = ry * p2p1z - rz * p2p1y; float sy = rz * p2p1x - rx * p2p1z; // S is now perpendicular to both R and the P2 - P1 // normalize R and S float rlen = (float) Math.sqrt(rx * rx + ry * ry + rz * rz); rx /= rlen; ry /= rlen; rz /= rlen; float slen = (float) Math.sqrt(sx * sx + sy * sy + sz * sz); sx /= slen; sy /= slen; sz /= slen; // now R and S are an orthonormal basis for the plane Gridded3DSet line = null; if (showLine) { // convert x=[-1,1] y=[-1,1] z=[-1,1] to x=[0,w] y=[0,h] z=[0,n] float[][] lineSamples = { {w * (x + 1) / 2, w * (-x + 1) / 2}, {h * (y + 1) / 2, h * (-y + 1) / 2}, {n * (z + 1) / 2, n * (-z + 1) / 2} }; // construct line data object try { line = new Gridded3DSet(xyz, lineSamples, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } // compute slice data Data slice = null; if (compute) { // interpolate from parent data // compute plane corners from orthonormal basis float q1x = w * (lx + T1COS * rx + T1SIN * sx + 1) / 2; float q1y = h * (ly + T1COS * ry + T1SIN * sy + 1) / 2; float q1z = n * (lz + T1COS * rz + T1SIN * sz + 1) / 2; float q2x = w * (lx + T2COS * rx + T2SIN * sx + 1) / 2; float q2y = h * (ly + T2COS * ry + T2SIN * sy + 1) / 2; float q2z = n * (lz + T2COS * rz + T2SIN * sz + 1) / 2; float q3x = w * (lx + T3COS * rx + T3SIN * sx + 1) / 2; float q3y = h * (ly + T3COS * ry + T3SIN * sy + 1) / 2; float q3z = n * (lz + T3COS * rz + T3SIN * sz + 1) / 2; float q4x = w * (lx + T4COS * rx + T4SIN * sx + 1) / 2; float q4y = h * (ly + T4COS * ry + T4SIN * sy + 1) / 2; float q4z = n * (lz + T4COS * rz + T4SIN * sz + 1) / 2; // retrieve parent data from data cache int[] npos = getParentPos(pos); FlatField[] fields = new FlatField[n]; for (int i=0; i<n; i++) { npos[axis] = i; Data data = parent.getData(npos, 2, cache); if (data == null || !(data instanceof FlatField)) { System.err.println(name + ": parent image plane #" + (i + 1) + " is not valid"); return null; } fields[i] = (FlatField) data; } try { // use image transform's recommended MathType and Units for (int i=0; i<n; i++) { fields[i] = DataUtil.switchType(fields[i], imageType, imageUnits); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } // generate planar domain samples and corresponding interpolated values int res1 = res - 1; float[][] planeSamples = new float[3][res * res]; float[][] planeValues = new float[range.length][res * res]; for (int r=0; r<res; r++) { float rr = (float) r / res1; float xmin = (1 - rr) * q1x + rr * q3x; float ymin = (1 - rr) * q1y + rr * q3y; float zmin = (1 - rr) * q1z + rr * q3z; float xmax = (1 - rr) * q2x + rr * q4x; float ymax = (1 - rr) * q2y + rr * q4y; float zmax = (1 - rr) * q2z + rr * q4z; for (int c=0; c<res; c++) { float cc = (float) c / res1; int ndx = r * res + c; float xs = planeSamples[0][ndx] = (1 - cc) * xmin + cc * xmax; float ys = planeSamples[1][ndx] = (1 - cc) * ymin + cc * ymax; float zs = planeSamples[2][ndx] = (1 - cc) * zmin + cc * zmax; if (xs < 0 || ys < 0 || zs < 0 || xs > w - 1 || ys > h - 1 || zs > n - 1) { // this pixel is outside the range of the data (missing) for (int k=0; k<planeValues.length; k++) { planeValues[k][ndx] = Float.NaN; } } else { // interpolate the value of this pixel for each range component int xx = (int) xs, yy = (int) ys, zz = (int) zs; float wx = xs - xx, wy = ys - yy, wz = zs - zz; float[][] values0 = null, values1 = null; FlatField field0, field1; if (wz == 0) { // interpolate from a single field (z0 == z1) try { values0 = values1 = fields[zz].getFloats(false); } catch (VisADException exc) { exc.printStackTrace(); } } else { // interpolate between two fields try { values0 = fields[zz].getFloats(false); values1 = fields[zz + 1].getFloats(false); } catch (VisADException exc) { exc.printStackTrace(); } } int ndx00 = w * yy + xx; int ndx10 = w * yy + xx + 1; int ndx01 = w * (yy + 1) + xx; int ndx11 = w * (yy + 1) + xx + 1; for (int k=0; k<range.length; k++) { // tri-linear interpolation (x, then y, then z) float v000 = values0[k][ndx00]; float v100 = values0[k][ndx10]; float v010 = values0[k][ndx01]; float v110 = values0[k][ndx11]; float v001 = values1[k][ndx00]; float v101 = values1[k][ndx10]; float v011 = values1[k][ndx01]; float v111 = values1[k][ndx11]; float vx00 = (1 - wx) * v000 + wx * v100; float vx10 = (1 - wx) * v010 + wx * v110; float vx01 = (1 - wx) * v001 + wx * v101; float vx11 = (1 - wx) * v011 + wx * v111; float vxy0 = (1 - wy) * vx00 + wy * vx10; float vxy1 = (1 - wy) * vx01 + wy * vx11; float vxyz = (1 - wz) * vxy0 + wz * vxy1; planeValues[k][ndx] = vxyz; } } } } try { FunctionType planeType = new FunctionType(xyz, imageType.getRange()); Gridded3DSet planeSet = new Gridded3DSet(xyz, planeSamples, res, res, null, xyzUnits, null, false); FlatField ff = new FlatField(planeType, planeSet); ff.setSamples(planeValues, false); slice = ff; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else { // construct bounding circle // compute circle coordinates from orthonormal basis int num = 32; float[][] samples = new float[3][num]; for (int i=0; i<num; i++) { double theta = i * 2 * Math.PI / num; float tcos = (float) (RADIUS3 * Math.cos(theta)); float tsin = (float) (RADIUS3 * Math.sin(theta)); float qx = lx + tcos * rx + tsin * sx; float qy = ly + tcos * ry + tsin * sy; float qz = lz + tcos * rz + tsin * sz; int ndx = (i < num / 2) ? i : (3 * num / 2 - i - 1); samples[0][ndx] = w * (qx + 1) / 2; samples[1][ndx] = h * (qy + 1) / 2; samples[2][ndx] = n * (qz + 1) / 2; } // construct bounding circle data object try { slice = new Gridded3DSet(xyz, samples, num / 2, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } Data[] data = showLine ? new Data[] {slice, line} : new Data[] {slice}; try { return new Tuple(data, false); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; }
public synchronized Data getData(int[] pos, int dim, DataCache cache) { if (dim != 3) { System.err.println(name + ": invalid dimensionality (" + dim + ")"); return null; } // get some info from the parent transform ImageTransform it = (ImageTransform) parent; int w = it.getImageWidth(); int h = it.getImageHeight(); int n = parent.getLengths()[axis]; RealType xType = it.getXType(); RealType yType = it.getYType(); RealType zType = it.getZType(); RealType[] range = it.getRangeTypes(); FunctionType imageType = it.getType(); Unit[] imageUnits = it.getImageUnits(); Unit zUnit = it.getZUnit(axis); Unit[] xyzUnits = {imageUnits[0], imageUnits[1], zUnit}; RealTupleType xy = null, xyz = null; try { xy = new RealTupleType(xType, yType); xyz = new RealTupleType(xType, yType, zType); } catch (VisADException exc) { exc.printStackTrace(); } // convert spherical polar coordinates to cartesian coordinates for line double yawRadians = Math.PI * yaw / 180; double yawCos = Math.cos(yawRadians); double yawSin = Math.sin(yawRadians); double pitchRadians = Math.PI * (90 - pitch) / 180; double pitchCos = Math.cos(pitchRadians); double pitchSin = Math.sin(pitchRadians); // Let P1 = (x, y, z), P2 = -P1 float x = (float) (RADIUS3 * pitchSin * yawCos); float y = (float) (RADIUS3 * pitchSin * yawSin); float z = (float) (RADIUS3 * pitchCos); // compute location along P1-P2 line float q = (loc - 50) / 50; float lx = q * x; float ly = q * y; float lz = q * z; // choose a point P which doesn't lie on the line through P1 and P2 float px = 1, py = 1, pz = 1; float ax = x < 0 ? -x : x; float ay = y < 0 ? -y : y; float az = z < 0 ? -z : z; if (ax - ay < 0.1) py = -1; if (ax - az < 0.1) pz = -1; // calculate the vector R as the cross product between P - P1 and P2 - P1 float pp1x = px - x, pp1y = py - y, pp1z = pz - z; float p2p1x = -x - x, p2p1y = -y - y, p2p1z = -z - z; float rz = pp1x * p2p1y - pp1y * p2p1x; float rx = pp1y * p2p1z - pp1z * p2p1y; float ry = pp1z * p2p1x - pp1x * p2p1z; // R is now perpendicular to P2 - P1 // calculate the vector S as the cross product between R and P2 - P1 float sz = rx * p2p1y - ry * p2p1x; float sx = ry * p2p1z - rz * p2p1y; float sy = rz * p2p1x - rx * p2p1z; // S is now perpendicular to both R and the P2 - P1 // normalize R and S float rlen = (float) Math.sqrt(rx * rx + ry * ry + rz * rz); rx /= rlen; ry /= rlen; rz /= rlen; float slen = (float) Math.sqrt(sx * sx + sy * sy + sz * sz); sx /= slen; sy /= slen; sz /= slen; // now R and S are an orthonormal basis for the plane Gridded3DSet line = null; if (showLine) { // convert x=[-1,1] y=[-1,1] z=[-1,1] to x=[0,w] y=[0,h] z=[0,n] float[][] lineSamples = { {w * (x + 1) / 2, w * (-x + 1) / 2}, {h * (y + 1) / 2, h * (-y + 1) / 2}, {n * (z + 1) / 2, n * (-z + 1) / 2} }; // construct line data object try { line = new Gridded3DSet(xyz, lineSamples, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } // compute slice data Data slice = null; if (compute) { // interpolate from parent data // compute plane corners from orthonormal basis float q1x = w * (lx + T1COS * rx + T1SIN * sx + 1) / 2; float q1y = h * (ly + T1COS * ry + T1SIN * sy + 1) / 2; float q1z = n * (lz + T1COS * rz + T1SIN * sz + 1) / 2; float q2x = w * (lx + T2COS * rx + T2SIN * sx + 1) / 2; float q2y = h * (ly + T2COS * ry + T2SIN * sy + 1) / 2; float q2z = n * (lz + T2COS * rz + T2SIN * sz + 1) / 2; float q3x = w * (lx + T3COS * rx + T3SIN * sx + 1) / 2; float q3y = h * (ly + T3COS * ry + T3SIN * sy + 1) / 2; float q3z = n * (lz + T3COS * rz + T3SIN * sz + 1) / 2; float q4x = w * (lx + T4COS * rx + T4SIN * sx + 1) / 2; float q4y = h * (ly + T4COS * ry + T4SIN * sy + 1) / 2; float q4z = n * (lz + T4COS * rz + T4SIN * sz + 1) / 2; // retrieve parent data from data cache int[] npos = getParentPos(pos); FlatField[] fields = new FlatField[n]; for (int i=0; i<n; i++) { npos[axis] = i; Data data = parent.getData(npos, 2, cache); if (data == null || !(data instanceof FlatField)) { System.err.println(name + ": parent image plane #" + (i + 1) + " is not valid"); return null; } fields[i] = (FlatField) data; } try { // use image transform's recommended MathType and Units for (int i=0; i<n; i++) { fields[i] = DataUtil.switchType(fields[i], imageType, imageUnits); } } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } // generate planar domain samples and corresponding interpolated values int res1 = res - 1; float[][][] fieldSamples = new float[fields.length][][];//TEMP float[][] planeSamples = new float[3][res * res]; float[][] planeValues = new float[range.length][res * res]; for (int r=0; r<res; r++) { float rr = (float) r / res1; float xmin = (1 - rr) * q1x + rr * q3x; float ymin = (1 - rr) * q1y + rr * q3y; float zmin = (1 - rr) * q1z + rr * q3z; float xmax = (1 - rr) * q2x + rr * q4x; float ymax = (1 - rr) * q2y + rr * q4y; float zmax = (1 - rr) * q2z + rr * q4z; for (int c=0; c<res; c++) { float cc = (float) c / res1; int ndx = r * res + c; //float xs = planeSamples[0][ndx] = (1 - cc) * xmin + cc * xmax; float xs = planeSamples[0][ndx] = (1 - cc) * xmin + cc * xmax; float ys = planeSamples[1][ndx] = (1 - cc) * ymin + cc * ymax; ys = h - ys; // lines are flipped float zs = planeSamples[2][ndx] = (1 - cc) * zmin + cc * zmax; if (xs < 0 || ys < 0 || zs < 0 || xs > w - 1 || ys > h - 1 || zs > n - 1) { // this pixel is outside the range of the data (missing) for (int k=0; k<planeValues.length; k++) { planeValues[k][ndx] = c;//Float.NaN; } } else { // interpolate the value of this pixel for each range component int xx = (int) xs, yy = (int) ys, zz = (int) zs; float wx = xs - xx, wy = ys - yy, wz = zs - zz; float[][] values0 = null, values1 = null; FlatField field0, field1; if (wz == 0) { // interpolate from a single field (z0 == z1) try { if (fieldSamples[zz] == null) {//TEMP fieldSamples[zz] = fields[zz].getFloats(false);//TEMP }//TEMP values0 = values1 = fieldSamples[zz]; } catch (VisADException exc) { exc.printStackTrace(); } } else { // interpolate between two fields try { if (fieldSamples[zz] == null) {//TEMP fieldSamples[zz] = fields[zz].getFloats(false);//TEMP }//TEMP if (fieldSamples[zz + 1] == null) {//TEMP fieldSamples[zz + 1] = fields[zz + 1].getFloats(false);//TEMP }//TEMP values0 = fieldSamples[zz]; values1 = fieldSamples[zz + 1]; } catch (VisADException exc) { exc.printStackTrace(); } } int ndx00 = w * yy + xx; int ndx10 = w * yy + xx + 1; int ndx01 = w * (yy + 1) + xx; int ndx11 = w * (yy + 1) + xx + 1; for (int k=0; k<range.length; k++) { // tri-linear interpolation (x, then y, then z) float v000 = values0[k][ndx00]; float v100 = values0[k][ndx10]; float v010 = values0[k][ndx01]; float v110 = values0[k][ndx11]; float v001 = values1[k][ndx00]; float v101 = values1[k][ndx10]; float v011 = values1[k][ndx01]; float v111 = values1[k][ndx11]; float vx00 = (1 - wx) * v000 + wx * v100; float vx10 = (1 - wx) * v010 + wx * v110; float vx01 = (1 - wx) * v001 + wx * v101; float vx11 = (1 - wx) * v011 + wx * v111; float vxy0 = (1 - wy) * vx00 + wy * vx10; float vxy1 = (1 - wy) * vx01 + wy * vx11; float vxyz = (1 - wz) * vxy0 + wz * vxy1; planeValues[k][ndx] = vxyz; } } } } try { FunctionType planeType = new FunctionType(xyz, imageType.getRange()); // set must be gridded, not linear, because ManifoldDimension is 2 Gridded3DSet planeSet = new Gridded3DSet(xyz, planeSamples, res, res, null, xyzUnits, null, false); FlatField ff = new FlatField(planeType, planeSet); ff.setSamples(planeValues, false); slice = ff; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } } else { // construct bounding circle // compute circle coordinates from orthonormal basis int num = 32; float[][] samples = new float[3][num]; for (int i=0; i<num; i++) { double theta = i * 2 * Math.PI / num; float tcos = (float) (RADIUS3 * Math.cos(theta)); float tsin = (float) (RADIUS3 * Math.sin(theta)); float qx = lx + tcos * rx + tsin * sx; float qy = ly + tcos * ry + tsin * sy; float qz = lz + tcos * rz + tsin * sz; int ndx = (i < num / 2) ? i : (3 * num / 2 - i - 1); samples[0][ndx] = w * (qx + 1) / 2; samples[1][ndx] = h * (qy + 1) / 2; samples[2][ndx] = n * (qz + 1) / 2; } // construct bounding circle data object try { slice = new Gridded3DSet(xyz, samples, num / 2, 2, null, xyzUnits, null, false); } catch (VisADException exc) { exc.printStackTrace(); } } Data[] data = showLine ? new Data[] {slice, line} : new Data[] {slice}; try { return new Tuple(data, false); } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; }
diff --git a/src/com/android/phone/DataUsageListener.java b/src/com/android/phone/DataUsageListener.java index 6122a8ec..a72c088a 100644 --- a/src/com/android/phone/DataUsageListener.java +++ b/src/com/android/phone/DataUsageListener.java @@ -1,231 +1,233 @@ /* * Copyright (C) 2010 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.phone; import com.android.phone.R; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.net.Uri; import android.net.ThrottleManager; import android.util.Log; import java.util.Calendar; import java.util.GregorianCalendar; import java.text.DateFormat; /** * Listener for broadcasts from ThrottleManager */ public class DataUsageListener { private ThrottleManager mThrottleManager; private Preference mCurrentUsagePref = null; private Preference mTimeFramePref = null; private Preference mThrottleRatePref = null; private Preference mSummaryPref = null; private PreferenceScreen mPrefScreen = null; private boolean mSummaryPrefEnabled = false; private final Context mContext; private IntentFilter mFilter; private BroadcastReceiver mReceiver; private int mPolicyThrottleValue; //in kbps private long mPolicyThreshold; private int mCurrentThrottleRate; private long mDataUsed; private Calendar mStart; private Calendar mEnd; public DataUsageListener(Context context, Preference summary, PreferenceScreen prefScreen) { mContext = context; mSummaryPref = summary; mPrefScreen = prefScreen; mSummaryPrefEnabled = true; initialize(); } public DataUsageListener(Context context, Preference currentUsage, Preference timeFrame, Preference throttleRate) { mContext = context; mCurrentUsagePref = currentUsage; mTimeFramePref = timeFrame; mThrottleRatePref = throttleRate; initialize(); } private void initialize() { mThrottleManager = (ThrottleManager) mContext.getSystemService(Context.THROTTLE_SERVICE); mStart = GregorianCalendar.getInstance(); mEnd = GregorianCalendar.getInstance(); mFilter = new IntentFilter(); mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION); mFilter.addAction(ThrottleManager.THROTTLE_ACTION); mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) { updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START, 0), intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END, 0)); } else if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) { updatePolicy(); } else if (ThrottleManager.THROTTLE_ACTION.equals(action)) { updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1)); } } }; } void resume() { mContext.registerReceiver(mReceiver, mFilter); updatePolicy(); } void pause() { mContext.unregisterReceiver(mReceiver); } private void updatePolicy() { /* Fetch values for default interface */ mPolicyThrottleValue = mThrottleManager.getCliffLevel(null, 1); mPolicyThreshold = mThrottleManager.getCliffThreshold(null, 1); if (mSummaryPref != null) { /* Settings preference */ /** * Remove data usage preference in settings * if policy change disables throttling */ if (mPolicyThreshold == 0) { if (mSummaryPrefEnabled) { mPrefScreen.removePreference(mSummaryPref); mSummaryPrefEnabled = false; } } else { if (!mSummaryPrefEnabled) { mSummaryPrefEnabled = true; mPrefScreen.addPreference(mSummaryPref); } } } updateUI(); } private void updateThrottleRate(int throttleRate) { mCurrentThrottleRate = throttleRate; updateUI(); } private void updateUsageStats(long readByteCount, long writeByteCount, long startTime, long endTime) { mDataUsed = readByteCount + writeByteCount; mStart.setTimeInMillis(startTime); mEnd.setTimeInMillis(endTime); updateUI(); } private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); + //cal.get() returns 365 for less than a day + if (daysLeft >= 365) daysLeft = 0; if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } } private String toReadable (long data) { long KB = 1024; long MB = 1024 * KB; long GB = 1024 * MB; long TB = 1024 * GB; String ret; if (data < KB) { ret = data + " bytes"; } else if (data < MB) { ret = (data / KB) + " KB"; } else if (data < GB) { ret = (data / MB) + " MB"; } else if (data < TB) { ret = (data / GB) + " GB"; } else { ret = (data / TB) + " TB"; } return ret; } }
true
true
private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } }
private void updateUI() { if (mPolicyThreshold == 0) return; int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold); long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis(); long currentTime = GregorianCalendar.getInstance().getTimeInMillis() - mStart.getTimeInMillis(); int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(cycleTime - currentTime); int daysLeft = cal.get(Calendar.DAY_OF_YEAR); //cal.get() returns 365 for less than a day if (daysLeft >= 365) daysLeft = 0; if (mCurrentUsagePref != null) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mCurrentUsagePref.setSummary(mContext.getString( R.string.throttle_data_usage_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold))); } } if (mTimeFramePref != null) { mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext, cycleThroughPercent, daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } if (mThrottleRatePref != null) { mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext, mPolicyThrottleValue)); } if (mSummaryPref != null && mSummaryPrefEnabled) { /* Update the UI based on whether we are in a throttled state */ if (mCurrentThrottleRate > 0) { mSummaryPref.setSummary(mContext.getString( R.string.throttle_data_rate_reduced_subtext, toReadable(mPolicyThreshold), mCurrentThrottleRate)); } else { mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext, toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold), daysLeft, DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime()))); } } }
diff --git a/src/de/dhbw/wbs/Lecturer.java b/src/de/dhbw/wbs/Lecturer.java index 447cb2f..2220868 100644 --- a/src/de/dhbw/wbs/Lecturer.java +++ b/src/de/dhbw/wbs/Lecturer.java @@ -1,25 +1,25 @@ package de.dhbw.wbs; public class Lecturer { private String name; public Lecturer(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object aLecturer) { if (!(aLecturer instanceof Lecturer)) return false; - return ((Lecturer) aLecturer).name == this.name; + return ((Lecturer) aLecturer).name.equals(this.name); } }
true
true
public boolean equals(Object aLecturer) { if (!(aLecturer instanceof Lecturer)) return false; return ((Lecturer) aLecturer).name == this.name; }
public boolean equals(Object aLecturer) { if (!(aLecturer instanceof Lecturer)) return false; return ((Lecturer) aLecturer).name.equals(this.name); }
diff --git a/ContactManagerImpl.java b/ContactManagerImpl.java index 3374af0..c3ab89d 100644 --- a/ContactManagerImpl.java +++ b/ContactManagerImpl.java @@ -1,962 +1,962 @@ /** *The purpose of this assignment it writing a program to keep track of contacts and *meetings. The application will keep track of contacts, past and future meetings, etc. *When the application is closed, all data must be stored in a text file called *”contacts.txt”. This file must be read at startup to recover all data introduced in a *former session. */ import java.util.*; import java.io.*; public class ContactManagerImpl implements ContactManager { private IllegalArgumentException illegalArgEx = new IllegalArgumentException(); private NullPointerException nullPointerEx = new NullPointerException(); private IllegalStateException illegalStateEx = new IllegalStateException(); private Set<Contact> contactList = new HashSet<Contact>(); //contacts added to this via addContact() private Set<Contact> attendeeList = new HashSet<Contact>(); //contacts attending a specific meeting; may be removed to be replaced with more temporary set in main method private Set<Meeting> pastMeetings = new HashSet<Meeting>();//list of past meetings private Set<Meeting> futureMeetings = new HashSet<Meeting>(); public int addFutureMeeting(Set<Contact> contacts, Calendar date) { boolean isEmpty = false; //these booleans facilitate display of pertinent error message boolean falseContact = false; boolean falseDate = false; Contact element = null;//to keep track of contacts being iterated String unknownContacts = "The following contacts do not exist in your contact list: ";//for multiple unknowns Meeting futureMeeting = null; try { if (contacts.isEmpty()) { isEmpty = true; } Iterator<Contact> iterator = contacts.iterator();//check that contacts are known/existent against central contact list while (iterator.hasNext()) { element = iterator.next(); if (!contactList.contains(element)) { falseContact = true; unknownContacts = unknownContacts + "\n" + element.getName(); } } Calendar now = Calendar.getInstance(); //what about scheduling a meeting for today? if (date.before(now)) { falseDate = true; } if (isEmpty || falseContact || falseDate) { throw illegalArgEx; } } catch (IllegalArgumentException illegalArgEx) { if (isEmpty == true) { System.out.println("Error: No contacts have been specified."); } if (falseContact == true) { System.out.println("Error: " + unknownContacts); //Need to consider the users options after exception is thrown - retry the creation of meeting/allow reentry of contacts } if (falseDate == true) { System.out.println("Error: Invalid date. Please ensure the date and time are in the future."); } } futureMeeting = new FutureMeetingImpl(contacts, date); futureMeetings.add(futureMeeting); int meetingID = futureMeeting.getId(); return meetingID; } /** * Returns the PAST meeting with the requested ID, or null if it there is none. * * @param id the ID for the meeting * @return the meeting with the requested ID, or null if it there is none. * @throws IllegalArgumentException if there is a meeting with that ID happening in the future */ public PastMeeting getPastMeeting(int id) { try { Iterator<Meeting> iteratorFM = futureMeetings.iterator(); Meeting meeting = null; while (iteratorFM.hasNext()) { meeting = iteratorFM.next(); if (meeting.getId() == id) { throw illegalArgEx; } } } catch (IllegalArgumentException ex) { System.out.print("Error: The meeting with this ID has not taken place yet!"); return null; //confirm returning null is best course of action } Iterator<Meeting> iteratorPM = pastMeetings.iterator(); Meeting meeting = null; while (iteratorPM.hasNext()) { meeting = iteratorPM.next(); if (meeting.getId() == id) { PastMeeting pastMeeting = (PastMeeting) meeting; return pastMeeting; } } return null; } /** * Returns the FUTURE meeting with the requested ID, or null if there is none. * * @param id the ID for the meeting * @return the meeting with the requested ID, or null if it there is none. * @throws IllegalArgumentException if there is a meeting with that ID happening in the past */ public FutureMeeting getFutureMeeting(int id) { try { Iterator<Meeting> iteratorPM = pastMeetings.iterator(); Meeting meeting = null; while (iteratorPM.hasNext()) { meeting = iteratorPM.next(); if (meeting.getId() == id) { throw illegalArgEx; } } } catch (IllegalArgumentException ex) { System.out.print("Error: The meeting with this ID has already taken place!"); return null; //what action to take? - safest is to go back to main menu } Iterator<Meeting> iteratorFM = futureMeetings.iterator(); Meeting meeting = null; while (iteratorFM.hasNext()) { meeting = iteratorFM.next(); if (meeting.getId() == id) { FutureMeeting futureMeeting = (FutureMeeting) meeting; return futureMeeting; } } return null; } public Meeting getMeeting(int id) { Iterator<Meeting> iteratorPM = pastMeetings.iterator(); Meeting meeting = null; while(iteratorPM.hasNext()) { meeting = iteratorPM.next(); if (meeting.getId() == id) { return meeting; } } Iterator<Meeting> iteratorFM = futureMeetings.iterator(); meeting = null; while (iteratorFM.hasNext()) { meeting = iteratorFM.next(); if (meeting.getId() == id) { return meeting; } } return null; } /** * Returns the list of future meetings scheduled with this contact. * * If there are none, the returned list will be empty. Otherwise, * the list will be chronologically sorted and will not contain any * duplicates. * * @param contact one of the user’s contacts * @return the list of future meeting(s) scheduled with this contact (may be empty) * @throws IllegalArgumentException if the contact does not exist */ public List<Meeting> getFutureMeetingList(Contact contact) { List<Meeting> list = new ArrayList<Meeting>();//list to contain meetings attended by specified contact try { if (!contactList.contains(contact)) {//may need to use id to identify -> iterator required throw illegalArgEx; } Iterator<Meeting> iterator = futureMeetings.iterator(); Meeting meeting = null; while (iterator.hasNext()) { //goes through all future meetings meeting = iterator.next(); Iterator<Contact> conIterator = meeting.getContacts().iterator(); Contact item = null; while (conIterator.hasNext()) { //goes through contacts associated with a meeting item = conIterator.next(); if (item.getId() == contact.getId()) { list.add(meeting); } } } list = sort(list);//elimination of duplicates? With sets, there shouldn't be any... return list; } catch (IllegalArgumentException ex) { System.out.println("Error: The specified contact doesn't exist!"); } return list; //may be empty } /** * Sorts a list into chronological order */ public List<Meeting> sort(List<Meeting> list) { Meeting tempMeeting1 = null; Meeting tempMeeting2 = null; boolean sorted = true; for (int j = 0; j < list.size() - 1; j++) { tempMeeting1 = list.get(j); tempMeeting2 = list.get(j + 1); if (tempMeeting1.getDate().after(tempMeeting2.getDate())) { //swaps elements over if first element has later date than second list.set(j, tempMeeting2); //replaced add with set to avoid list growing when rearranging elements list.set(j + 1, tempMeeting1); } } for (int i = 0; i < list.size() - 1; i++) { //loop that checks whether list is sorted if (list.get(i).getDate().after(list.get(i + 1).getDate())) { sorted = false; } } if (!sorted) { list = sort(list);//recursively calls this method until the list is sorted } return list; } /** * Returns the list of meetings that are scheduled for, or that took * place on, the specified date * * If there are none, the returned list will be empty. Otherwise, * the list will be chronologically sorted and will not contain any * duplicates. * * @param date the date * @return the list of meetings */ public List<Meeting> getMeetingList(Calendar date) { List<Meeting> meetingList = new ArrayList<Meeting>(); //go through future meetings and past meetings, unless all meetings are also added to allMeetings? Iterator<Meeting> iteratorPM = pastMeetings.iterator(); Meeting pastMeeting = null; while (iteratorPM.hasNext()) { pastMeeting = iteratorPM.next(); if (pastMeeting.getDate().equals(date)) { //or futureMeeting.getDate().get(Calendar.YEAR) == date.get(Calendar.YEAR) etc meetingList.add(pastMeeting); } } Iterator<Meeting> iteratorFM = futureMeetings.iterator(); Meeting futureMeeting = null; while (iteratorFM.hasNext()) { futureMeeting = iteratorFM.next(); if (futureMeeting.getDate().equals(date)) { meetingList.add(futureMeeting); } } meetingList = sort(meetingList); return meetingList; } /** * Returns the list of past meetings in which this contact has participated. * * If there are none, the returned list will be empty. Otherwise, * the list will be chronologically sorted and will not contain any * duplicates. * * @param contact one of the user’s contacts * @return the list of past meeting(s) scheduled with this contact (maybe empty). * @throws IllegalArgumentException if the contact does not exist */ public List<PastMeeting> getPastMeetingList(Contact contact) { List<Meeting> meetingList = new ArrayList<Meeting>(); List<PastMeeting> pastMeetingList = new ArrayList<PastMeeting>(); try { if (!contactList.contains(contact)) { throw illegalArgEx; } Iterator<Meeting> iterator = pastMeetings.iterator(); Meeting meeting = null; while (iterator.hasNext()) { meeting = iterator.next(); if (meeting.getContacts().contains(contact)) { meetingList.add(meeting); } } meetingList = sort(meetingList); for (int i = 0; i < meetingList.size(); i++) {//convert List<Meeting> to List<PastMeeting> Meeting m = meetingList.get(i); PastMeeting pm = (PastMeeting) m; pastMeetingList.add(pm); } return pastMeetingList; } catch (IllegalArgumentException ex) { System.out.println("Error: The specified contact doesn't exist."); } return null;//or return an empty list? } /** * Create a new record for a meeting that took place in the past. * * @param contacts a list of participants * @param date the date on which the meeting took place * @param text messages to be added about the meeting. * @throws IllegalArgumentException if the list of contacts is * empty, or any of the contacts does not exist * @throws NullPointerException if any of the arguments is null */ //what about an exception for a date that's in the future? public void addNewPastMeeting(Set<Contact> contacts, Calendar date, String text) { boolean emptyContacts = false;//to allow simultaneous error correction for user boolean nullContacts = false; boolean nullDate = false; boolean nullText = false; boolean falseContact = false; String unknownContacts = "The following contacts are not on your contact list: "; try { if (contacts.isEmpty()) { emptyContacts = true; } Iterator<Contact> iterator = contacts.iterator(); Contact contact = null; while (iterator.hasNext()) { contact = iterator.next(); if (!contactList.contains(contact)) { falseContact = true; unknownContacts = unknownContacts + "\n" + contact.getName(); } } if (contacts == null) { nullContacts = true; } if (date == null) { nullDate = true; } if (text == null) { nullText = true; } if (emptyContacts || falseContact) { throw illegalArgEx; } if (nullContacts || nullDate || nullText) { throw nullPointerEx; } Meeting pastMeeting = new PastMeetingImpl(contacts, date, text); pastMeetings.add(pastMeeting); } catch (IllegalArgumentException ex) { if (emptyContacts) { System.out.println("Error: No contacts specified!"); } if (falseContact) { System.out.println("Error: " + unknownContacts); } } catch (NullPointerException nex) { if (nullText) { System.out.println("Error: No meeting notes specified!"); } if (nullContacts) { System.out.println("Error: No contacts specified!"); } if (nullDate) { System.out.println("Error: No date specified!"); } } } /** * Add notes to a meeting. * * This method is used when a future meeting takes place, and is * then converted to a past meeting (with notes). * * It can be also used to add notes to a past meeting at a later date. * * @param id the ID of the meeting * @param text messages to be added about the meeting. * @throws IllegalArgumentException if the meeting does not exist * @throws IllegalStateException if the meeting is set for a date in the future * @throws NullPointerException if the notes are null */ public void addMeetingNotes(int id, String text) { Iterator<Meeting> pmIterator = pastMeetings.iterator(); Meeting pMeeting = null; boolean pastMeetingFound = false;//to determine whether program should proceed to look through futureMeetings if no matching meeting //is found in pastMeetings. while (pmIterator.hasNext()) { pMeeting = pmIterator.next(); if (pMeeting.getId() == id) { PastMeetingImpl pmi = (PastMeetingImpl) pMeeting; pmi.addNotes(text); pastMeetingFound = true; System.out.println("Notes for meeting ID No. " + id + " updated successfully."); } break; } if (!pastMeetingFound) { boolean containsMeeting = false; boolean futureDate = false; Calendar now = Calendar.getInstance(); Meeting meeting = null;//to allow the meeting matching the id to be used throughout the method try { Iterator<Meeting> iterator = futureMeetings.iterator(); while (iterator.hasNext()) { meeting = iterator.next(); if (meeting.getId() == id) { containsMeeting = true; } break; } System.out.println("Meeting ID: " + meeting.getId()); //is being updated. if (meeting.getDate().after(now)) { futureDate = true; } if (text == null) { throw nullPointerEx; } if (!containsMeeting) { throw illegalArgEx; } if (futureDate) { throw illegalStateEx; } Meeting pastMeeting = new PastMeetingImpl(meeting.getContacts(), meeting.getDate(), text, meeting.getId()); pastMeetings.add(pastMeeting); futureMeetings.remove(meeting); } catch (IllegalArgumentException aEx) { System.out.println("Error: No meeting with that ID exists!"); } catch (IllegalStateException sEx) { System.out.println("Error: The meeting with this ID has not taken place yet!"); } catch (NullPointerException pEx) { System.out.println("Error: No notes have been specified!"); } } } /** * Create a new contact with the specified name and notes. * * @param name the name of the contact. * @param notes notes to be added about the contact. * @throws NullPointerException if the name or the notes are null */ public void addNewContact(String name, String notes) { try { if (name == null || notes == null) { throw nullPointerEx; } Contact contact = new ContactImpl(name); contact.addNotes(notes); contactList.add(contact); } catch (NullPointerException nex) { System.out.println("Error: Please ensure that BOTH the NAME and NOTES fields are filled in."); } } /** * Returns a list containing the contacts that correspond to the IDs * * @param ids an arbitrary number of contact IDs * @return a list containing the contacts that correspond to the IDs. * @throws IllegalArgumentException if any of the IDs does not correspond to a real contact */ public Set<Contact> getContacts(int... ids) { Set<Contact> idMatches = new HashSet<Contact>(); int id = 0; String idString = "";//to facilitate an error message that lists all invalid IDs boolean found; try { for (int i = 0; i < ids.length; i++) {//boolean needs to be reset to false here for each iteration //otherwise it will stay true after one id is matched! found = false; id = ids[i]; Contact contact = null; Iterator<Contact> iterator = contactList.iterator(); while (iterator.hasNext()) { contact = iterator.next(); if (contact.getId() == id) { idMatches.add(contact); found = true; } } if (found == false) { idString = idString + id + "\n"; //throw illegalArgEx; } } if (idString.length() > 0) { throw illegalArgEx; } return idMatches; } catch (IllegalArgumentException ex) { System.out.println("Note: The following IDs were not found and haven't " + "been added to the attendee list:" + "\n" + idString); //user's next option? Return to main? } return idMatches; } /* * Returns a single contact matching an ID. */ public Contact getContact(int id) { for (Contact c : contactList) {//matches against list of contacts if (c.getId() == id) { return c; } } System.out.println("ID not found!"); return null; } /** * Returns a list with the contacts whose name contains that string. * * @param name the string to search for * @return a list with the contacts whose name contains that string. * @throws NullPointerException if the parameter is null */ public Set<Contact> getContacts(String name) { Set<Contact> contactSet = new HashSet<Contact>(); Contact contact = null; try { if (name == null) { throw nullPointerEx; } Iterator<Contact> iterator = contactList.iterator(); while (iterator.hasNext()) { contact = iterator.next(); if (contact.getName() == name) { contactSet.add(contact); } } } catch (NullPointerException nex) { System.out.println("Error: Please ensure that you enter a name."); System.out.println("Contact name: "); String name2 = System.console().readLine(); if (name2.equals("back")) { return null;//allow user to exit rather than get stuck } return getContacts(name2); } return contactSet; } //if nothing is found, say so -> do this in launch /** * Save all data to disk. * * This method must be executed when the program is * closed and when/if the user requests it. */ public void flush() { IdStore ids = new IdStoreImpl(); ids.saveContactIdAssigner(ContactImpl.getIdAssigner()); ids.saveMeetingIdAssigner(MeetingImpl.getIdAssigner()); try { FileOutputStream fos = new FileOutputStream("contacts.txt"); System.out.println("Saving data..."); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ids);//saves IdStore object containing idAssigners Iterator<Contact> contactIterator = contactList.iterator(); while (contactIterator.hasNext()) {//write contents of contactList to file Contact c = contactIterator.next(); oos.writeObject(c); } Iterator<Meeting> iteratorPM = pastMeetings.iterator(); while (iteratorPM.hasNext()) {//writes contents of pastMeetings to file Meeting m = iteratorPM.next(); oos.writeObject(m); } Iterator<Meeting> iteratorFM = futureMeetings.iterator(); while (iteratorFM.hasNext()) {//writes contents of futureMeetings to file Meeting m = iteratorFM.next(); oos.writeObject(m); } oos.close(); System.out.println("Saved."); } catch (FileNotFoundException ex) { System.out.println("Creating contacts.txt file for data storage..."); File contactsTxt = new File("./contacts.txt"); flush(); } catch (IOException ex) { ex.printStackTrace();//need to be more explicit? } } //Loads data from file upon opening program public void loadData() { System.out.println("Loading data from file..."); try { File contactsFile = new File("./contacts.txt"); if (contactsFile.length() == 0) { System.out.println("No saved data found."); return; } FileInputStream fis = new FileInputStream("contacts.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Object obj = null; while ((obj = ois.readObject()) != null) { //read to end of file if (obj instanceof IdStore) { IdStore ids = (IdStoreImpl) obj; ContactImpl.restoreIdAssigner(ids.getContactIdAssigner()); MeetingImpl.restoreIdAssigner(ids.getMeetingIdAssigner()); } if (obj instanceof Contact) { Contact contact = (ContactImpl) obj; contactList.add(contact); } if (obj instanceof FutureMeeting) { Meeting meeting = (FutureMeetingImpl) obj; futureMeetings.add(meeting); } if (obj instanceof PastMeeting) { Meeting meeting = (PastMeetingImpl) obj; pastMeetings.add(meeting); } } ois.close(); } catch (EOFException ex) { System.out.println("Data from previous session loaded."); } catch (FileNotFoundException ex) { System.out.println("File not found! Please ensure contacts.txt is in the same directory."); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } } public static void main(String[] args) { ContactManagerImpl cm = new ContactManagerImpl(); cm.launch(); } private void launch() { ContactManagerUtilities.displayWelcome(); loadData(); boolean finished = false; while (!finished) { int userSelection = ContactManagerUtilities.chooseMainMenuOption(); switch (userSelection) { case 1: System.out.println("\n"); System.out.println("*** ADD A FUTURE MEETING"); int[] attendeeArray = ContactManagerUtilities.selectAttendees(contactList); if (attendeeArray == null) {//occurs if user opts to quit, or if contactList is empty break; } Set<Contact> attendees = getContacts(attendeeArray); Calendar date = ContactManagerUtilities.createDate(); if (date == null) { break; } this.addFutureMeeting(attendees, date); break; case 2: System.out.println("\n"); System.out.println("*** LOOK UP A MEETING"); int userChoice = ContactManagerUtilities.lookUpMeetingOptions(); switch (userChoice) { case 1: System.out.println("*** LOOK UP MEETING -- Search by Date"); System.out.println("Please enter a date: "); date = ContactManagerUtilities.createDate(); if (date == null) { break;//go back to main menu, TEST THIS } List<Meeting> foundMeetings = getMeetingList(date); ContactManagerUtilities.printMeetingList(foundMeetings); break; case 2: System.out.println("*** LOOK UP MEETING -- Search by Meeting ID"); System.out.println("Please enter a meeting ID: "); String entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } int id = ContactManagerUtilities.validateNumber(entry); Meeting meeting = getMeeting(id); if (meeting != null) { - ContactManagerUtilities.printMeetingDetails(); + ContactManagerUtilities.printMeetingDetails(meeting); break;//go back to main menu } else { System.out.println("No meetings matching that date found!"); break;//go back to main menu } break; case 3: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by Contact"); int userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<Meeting> fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 3: break; } break; case 4: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by Contact"); userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<PastMeeting> pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 3: break; } break; //LOOK UP MEETING MENU case 5: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); PastMeeting pastMeeting = this.getPastMeeting(id); if (pastMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(pastMeeting); break; //LOOK UP MEETING MENU case 6: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); FutureMeeting futureMeeting = getFutureMeeting(id); if (futureMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(futureMeeting); break; //LOOK UP MEETING MENU case 7: break; } break; case 3: //create record of past meeting case 4: //add notes to a meeting that has taken place case 5: System.out.println("\n"); System.out.println("*** ADD NEW CONTACT"); case 6: //look up contact case 7: flush(); break; case 8: flush(); finished = true; System.out.println("\n" + "Closing..."); break; } } //after an option is selected, the option should be followed through, and then the main //menu should be displayed again. The only times this doesn't happen is when the user //opts to save and quit: after data has been saved, the program exits. //for each option that is selected, give the user a chance to return to main menu by //typing 0 -- an if clause that says if entry is 0, display main menu. For this reason, //perhaps put main menu method into this class (whist keeping checking in util)... //put the whole thing inside a while loop? Then, when save and quit is called, carry out //the action and break from the loop. //to go back to main menu -- if something is null? Or enter 0 //when a user has to enter something, it'll most likely be read initially as a String... //so if the user enters 'back' or 'quit', return to main menu. } } //ask user for dates in specific format, which can then be converted to create a new Calendar //make sure that if wrong format is entered, you throw an exception. //update dates to include time? /** * Returns the list of meetings that are scheduled for, or that took * place on, the specified date * * If there are none, the returned list will be empty. Otherwise, * the list will be chronologically sorted and will not contain any * duplicates. * * @param date the date * @return the list of meetings */ //if returned list is empty, write empty? in main: if list.isEmpty(), print <empty> for //user clarity //when users specify a date, should they also include a time? //how does before/after affect dates which are the same? //contains -- may have to do this in more detail with an iterator, as the naming of //Contact variables may not allow for contactList.contains(contact); new contacts will probably //be just called contact each time they are created, with their name and id the only things to //identify them by. //initialise notes variable as null in launch so that if user enters nothing, relevant //method is still found //when saved, contents of file will be overwritten - alert user of this
true
true
private void launch() { ContactManagerUtilities.displayWelcome(); loadData(); boolean finished = false; while (!finished) { int userSelection = ContactManagerUtilities.chooseMainMenuOption(); switch (userSelection) { case 1: System.out.println("\n"); System.out.println("*** ADD A FUTURE MEETING"); int[] attendeeArray = ContactManagerUtilities.selectAttendees(contactList); if (attendeeArray == null) {//occurs if user opts to quit, or if contactList is empty break; } Set<Contact> attendees = getContacts(attendeeArray); Calendar date = ContactManagerUtilities.createDate(); if (date == null) { break; } this.addFutureMeeting(attendees, date); break; case 2: System.out.println("\n"); System.out.println("*** LOOK UP A MEETING"); int userChoice = ContactManagerUtilities.lookUpMeetingOptions(); switch (userChoice) { case 1: System.out.println("*** LOOK UP MEETING -- Search by Date"); System.out.println("Please enter a date: "); date = ContactManagerUtilities.createDate(); if (date == null) { break;//go back to main menu, TEST THIS } List<Meeting> foundMeetings = getMeetingList(date); ContactManagerUtilities.printMeetingList(foundMeetings); break; case 2: System.out.println("*** LOOK UP MEETING -- Search by Meeting ID"); System.out.println("Please enter a meeting ID: "); String entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } int id = ContactManagerUtilities.validateNumber(entry); Meeting meeting = getMeeting(id); if (meeting != null) { ContactManagerUtilities.printMeetingDetails(); break;//go back to main menu } else { System.out.println("No meetings matching that date found!"); break;//go back to main menu } break; case 3: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by Contact"); int userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<Meeting> fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 3: break; } break; case 4: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by Contact"); userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<PastMeeting> pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 3: break; } break; //LOOK UP MEETING MENU case 5: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); PastMeeting pastMeeting = this.getPastMeeting(id); if (pastMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(pastMeeting); break; //LOOK UP MEETING MENU case 6: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); FutureMeeting futureMeeting = getFutureMeeting(id); if (futureMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(futureMeeting); break; //LOOK UP MEETING MENU case 7: break; } break; case 3: //create record of past meeting case 4: //add notes to a meeting that has taken place case 5: System.out.println("\n"); System.out.println("*** ADD NEW CONTACT"); case 6: //look up contact case 7: flush(); break; case 8: flush(); finished = true; System.out.println("\n" + "Closing..."); break; } } //after an option is selected, the option should be followed through, and then the main //menu should be displayed again. The only times this doesn't happen is when the user //opts to save and quit: after data has been saved, the program exits. //for each option that is selected, give the user a chance to return to main menu by //typing 0 -- an if clause that says if entry is 0, display main menu. For this reason, //perhaps put main menu method into this class (whist keeping checking in util)... //put the whole thing inside a while loop? Then, when save and quit is called, carry out //the action and break from the loop. //to go back to main menu -- if something is null? Or enter 0 //when a user has to enter something, it'll most likely be read initially as a String... //so if the user enters 'back' or 'quit', return to main menu. }
private void launch() { ContactManagerUtilities.displayWelcome(); loadData(); boolean finished = false; while (!finished) { int userSelection = ContactManagerUtilities.chooseMainMenuOption(); switch (userSelection) { case 1: System.out.println("\n"); System.out.println("*** ADD A FUTURE MEETING"); int[] attendeeArray = ContactManagerUtilities.selectAttendees(contactList); if (attendeeArray == null) {//occurs if user opts to quit, or if contactList is empty break; } Set<Contact> attendees = getContacts(attendeeArray); Calendar date = ContactManagerUtilities.createDate(); if (date == null) { break; } this.addFutureMeeting(attendees, date); break; case 2: System.out.println("\n"); System.out.println("*** LOOK UP A MEETING"); int userChoice = ContactManagerUtilities.lookUpMeetingOptions(); switch (userChoice) { case 1: System.out.println("*** LOOK UP MEETING -- Search by Date"); System.out.println("Please enter a date: "); date = ContactManagerUtilities.createDate(); if (date == null) { break;//go back to main menu, TEST THIS } List<Meeting> foundMeetings = getMeetingList(date); ContactManagerUtilities.printMeetingList(foundMeetings); break; case 2: System.out.println("*** LOOK UP MEETING -- Search by Meeting ID"); System.out.println("Please enter a meeting ID: "); String entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } int id = ContactManagerUtilities.validateNumber(entry); Meeting meeting = getMeeting(id); if (meeting != null) { ContactManagerUtilities.printMeetingDetails(meeting); break;//go back to main menu } else { System.out.println("No meetings matching that date found!"); break;//go back to main menu } break; case 3: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by Contact"); int userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<Meeting> fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } fMeetings = getFutureMeetingList(contact); if (fMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(fMeetings);//print details of meetings break; case 3: break; } break; case 4: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by Contact"); userSubChoice = ContactManagerUtilities.searchByContactOptions(); switch (userSubChoice) { case 1: System.out.println("Please enter a contact's ID:"); entry = System.console().readLine(); if (entry.equals("back")) { break;//go back to main menu } id = ContactManagerUtilities.validateNumber(entry); Contact contact = getContact(id); if (contact == null) { break;//go back to main menu } List<PastMeeting> pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 2: System.out.println("Please enter a contact's name:"); entry = System.console().readLine(); Set<Contact> contacts = getContacts(entry); if (contacts.isEmpty()) { System.out.println("No contacts found."); break; } System.out.println("Contacts matching this name: "); for (Contact c : contacts) { System.out.println(c.getName() + "\t" + "ID: " + c.getId()); } System.out.println("Enter the ID of the contact you wish to select: "); entry = System.console().readLine(); id = ContactManagerUtilities.validateNumber(entry); contact = getContact(id); if (contact == null) { break;//go back to main menu } pMeetings = getPastMeetingList(contact); if (pMeetings.isEmpty()) { System.out.println("No meetings found."); break;//go back to main menu } ContactManagerUtilities.printMeetingList(pMeetings);//print details of meetings break; case 3: break; } break; //LOOK UP MEETING MENU case 5: System.out.println("*** LOOK UP MEETING -- Search Past Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); PastMeeting pastMeeting = this.getPastMeeting(id); if (pastMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(pastMeeting); break; //LOOK UP MEETING MENU case 6: System.out.println("*** LOOK UP MEETING -- Search Future Meetings by ID"); id = ContactManagerUtilities.validateNumber(entry); FutureMeeting futureMeeting = getFutureMeeting(id); if (futureMeeting == null) { break;//return to main } ContactManagerUtilities.printMeetingDetails(futureMeeting); break; //LOOK UP MEETING MENU case 7: break; } break; case 3: //create record of past meeting case 4: //add notes to a meeting that has taken place case 5: System.out.println("\n"); System.out.println("*** ADD NEW CONTACT"); case 6: //look up contact case 7: flush(); break; case 8: flush(); finished = true; System.out.println("\n" + "Closing..."); break; } } //after an option is selected, the option should be followed through, and then the main //menu should be displayed again. The only times this doesn't happen is when the user //opts to save and quit: after data has been saved, the program exits. //for each option that is selected, give the user a chance to return to main menu by //typing 0 -- an if clause that says if entry is 0, display main menu. For this reason, //perhaps put main menu method into this class (whist keeping checking in util)... //put the whole thing inside a while loop? Then, when save and quit is called, carry out //the action and break from the loop. //to go back to main menu -- if something is null? Or enter 0 //when a user has to enter something, it'll most likely be read initially as a String... //so if the user enters 'back' or 'quit', return to main menu. }
diff --git a/src/samples/ProcrunService.java b/src/samples/ProcrunService.java index 190fcc5..3dbdb47 100644 --- a/src/samples/ProcrunService.java +++ b/src/samples/ProcrunService.java @@ -1,240 +1,240 @@ import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; /* * 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. * */ /** * Sample service implementation for use with Windows Procrun. * <p> * Use the main() method for running as a Java (external) service. * Use the start() and stop() methods for running as a jvm (in-process) service */ public class ProcrunService implements Runnable { private static final int DEFAULT_PAUSE = 60; // Wait 1 minute private static final long MS_PER_SEC = 1000L; // Milliseconds in a second private static volatile Thread thrd; // start and stop are called from different threads private final long pause; // How long to pause in service loop private final File stopFile; /** * * @param wait seconds to wait in loop * @param filename optional filename - if non-null, run loop will stop when it disappears * @throws IOException */ private ProcrunService(long wait, File file) { pause=wait; stopFile = file; } private static File tmpFile(String filename) { return new File(System.getProperty("java.io.tmpdir"), filename != null ? filename : "ProcrunService.tmp"); } private static void usage(){ System.err.println("Must supply the argument 'start' or 'stop'"); } /** * Helper method for process args with defaults. * * @param args array of string arguments, may be empty * @param argnum which argument to extract * @return the argument or null */ private static String getArg(String[] args, int argnum){ if (args.length > argnum) { return args[argnum]; } else { return null; } } private static void logSystemEnvironment() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) log("Missing currentThread context ClassLoader"); else log("Using context ClassLoader : " + cl.toString()); log("Program environment: "); Map em = System.getenv(); TreeSet es = new TreeSet(em.keySet()); for (Iterator i = es.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + em.get(n)); } log("System properties: "); Properties ps = System.getProperties(); TreeSet ts = new TreeSet(ps.keySet()); for (Iterator i = ts.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + ps.get(n)); } log("Network interfaces: "); log("LVPMU (L)oopback (V)irtual (P)ointToPoint (M)multicastSupport (U)p"); try { for (Enumeration e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) { NetworkInterface n = (NetworkInterface)e.nextElement(); char [] flags = { '-', '-', '-', '-', '-'}; if (n.isLoopback()) flags[0] = 'x'; if (n.isVirtual()) flags[1] = 'x'; if (n.isPointToPoint()) flags[2] = 'x'; if (n.supportsMulticast()) flags[3] = 'x'; if (n.isUp()) flags[4] = 'x'; - String neti = new String(flags) + "\t" + n.getName() + "\t"; + String neti = new String(flags) + " " + n.getName() + "\t"; for (Enumeration i = n.getSubInterfaces(); i.hasMoreElements();) { NetworkInterface s = (NetworkInterface)i.nextElement(); neti += " [" + s.getName() + "]"; } log(neti + " -> " + n.getDisplayName()); List i = n.getInterfaceAddresses(); if (!i.isEmpty()) { for (int x = 0; x < i.size(); x++) { InterfaceAddress a = (InterfaceAddress)i.get(x); - log("\t" + a.toString()); + log(" " + a.toString()); } } } } catch (SocketException e) { // Ignore } } /** * Common entry point for start and stop service functions. * To allow for use with Java mode, a temporary file is created * by the start service, and a deleted by the stop service. * * @param args [start [pause time] | stop] * @throws IOException if there are problems creating or deleting the temporary file */ public static void main(String[] args) throws IOException { final int argc = args.length; log("ProcrunService called with "+argc+" arguments from thread: "+Thread.currentThread()); for(int i=0; i < argc; i++) { System.out.println("["+i+"] "+args[i]); } String mode=getArg(args, 0); if ("start".equals(mode)){ File f = tmpFile(getArg(args, 2)); log("Creating file: "+f.getPath()); f.createNewFile(); startThread(getArg(args, 1), f); } else if ("stop".equals(mode)) { final File tmpFile = tmpFile(getArg(args, 1)); log("Deleting file: "+tmpFile.getPath()); tmpFile.delete(); } else { usage(); } } /** * Start the jvm version of the service, and waits for it to complete. * * @param args optional, arg[0] = timeout (seconds) */ public static void start(String [] args) { startThread(getArg(args, 0), null); while(thrd.isAlive()){ try { thrd.join(); } catch (InterruptedException ie){ // Ignored } } } private static void startThread(String waitParam, File file) { long wait = DEFAULT_PAUSE; if (waitParam != null) { wait = Integer.valueOf(waitParam).intValue(); } log("Starting the thread, wait(seconds): "+wait); thrd = new Thread(new ProcrunService(wait*MS_PER_SEC,file)); thrd.start(); } /** * Stop the JVM version of the service. * * @param args ignored */ public static void stop(String [] args){ if (thrd != null) { log("Interrupting the thread"); thrd.interrupt(); } else { log("No thread to interrupt"); } } /** * This method performs the work of the service. * In this case, it just logs a message every so often. */ public void run() { log("Started thread in "+System.getProperty("user.dir")); logSystemEnvironment(); while(stopFile == null || stopFile.exists()){ try { log("pausing..."); Thread.sleep(pause); } catch (InterruptedException e) { log("Exitting"); break; } } } private static void log(String msg){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss "); System.out.println(df.format(new Date())+msg); } protected void finalize(){ log("Finalize called from thread "+Thread.currentThread()); } }
false
true
private static void logSystemEnvironment() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) log("Missing currentThread context ClassLoader"); else log("Using context ClassLoader : " + cl.toString()); log("Program environment: "); Map em = System.getenv(); TreeSet es = new TreeSet(em.keySet()); for (Iterator i = es.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + em.get(n)); } log("System properties: "); Properties ps = System.getProperties(); TreeSet ts = new TreeSet(ps.keySet()); for (Iterator i = ts.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + ps.get(n)); } log("Network interfaces: "); log("LVPMU (L)oopback (V)irtual (P)ointToPoint (M)multicastSupport (U)p"); try { for (Enumeration e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) { NetworkInterface n = (NetworkInterface)e.nextElement(); char [] flags = { '-', '-', '-', '-', '-'}; if (n.isLoopback()) flags[0] = 'x'; if (n.isVirtual()) flags[1] = 'x'; if (n.isPointToPoint()) flags[2] = 'x'; if (n.supportsMulticast()) flags[3] = 'x'; if (n.isUp()) flags[4] = 'x'; String neti = new String(flags) + "\t" + n.getName() + "\t"; for (Enumeration i = n.getSubInterfaces(); i.hasMoreElements();) { NetworkInterface s = (NetworkInterface)i.nextElement(); neti += " [" + s.getName() + "]"; } log(neti + " -> " + n.getDisplayName()); List i = n.getInterfaceAddresses(); if (!i.isEmpty()) { for (int x = 0; x < i.size(); x++) { InterfaceAddress a = (InterfaceAddress)i.get(x); log("\t" + a.toString()); } } } } catch (SocketException e) { // Ignore } }
private static void logSystemEnvironment() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) log("Missing currentThread context ClassLoader"); else log("Using context ClassLoader : " + cl.toString()); log("Program environment: "); Map em = System.getenv(); TreeSet es = new TreeSet(em.keySet()); for (Iterator i = es.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + em.get(n)); } log("System properties: "); Properties ps = System.getProperties(); TreeSet ts = new TreeSet(ps.keySet()); for (Iterator i = ts.iterator(); i.hasNext();) { String n = (String)i.next(); log(n + " -> " + ps.get(n)); } log("Network interfaces: "); log("LVPMU (L)oopback (V)irtual (P)ointToPoint (M)multicastSupport (U)p"); try { for (Enumeration e = NetworkInterface.getNetworkInterfaces(); e.hasMoreElements();) { NetworkInterface n = (NetworkInterface)e.nextElement(); char [] flags = { '-', '-', '-', '-', '-'}; if (n.isLoopback()) flags[0] = 'x'; if (n.isVirtual()) flags[1] = 'x'; if (n.isPointToPoint()) flags[2] = 'x'; if (n.supportsMulticast()) flags[3] = 'x'; if (n.isUp()) flags[4] = 'x'; String neti = new String(flags) + " " + n.getName() + "\t"; for (Enumeration i = n.getSubInterfaces(); i.hasMoreElements();) { NetworkInterface s = (NetworkInterface)i.nextElement(); neti += " [" + s.getName() + "]"; } log(neti + " -> " + n.getDisplayName()); List i = n.getInterfaceAddresses(); if (!i.isEmpty()) { for (int x = 0; x < i.size(); x++) { InterfaceAddress a = (InterfaceAddress)i.get(x); log(" " + a.toString()); } } } } catch (SocketException e) { // Ignore } }
diff --git a/src/cl/votainteligente/inspector/client/inject/ServiceModule.java b/src/cl/votainteligente/inspector/client/inject/ServiceModule.java index a5d15c9..79e1d3d 100644 --- a/src/cl/votainteligente/inspector/client/inject/ServiceModule.java +++ b/src/cl/votainteligente/inspector/client/inject/ServiceModule.java @@ -1,29 +1,30 @@ package cl.votainteligente.inspector.client.inject; import cl.votainteligente.inspector.client.services.*; import com.google.gwt.inject.client.AbstractGinModule; public class ServiceModule extends AbstractGinModule { @Override protected void configure() { bind(BillServiceAsync.class).asEagerSingleton(); bind(BillTypeServiceAsync.class).asEagerSingleton(); bind(CategoryServiceAsync.class).asEagerSingleton(); bind(ChamberServiceAsync.class).asEagerSingleton(); bind(CommissionServiceAsync.class).asEagerSingleton(); bind(DistrictServiceAsync.class).asEagerSingleton(); bind(DistrictTypeServiceAsync.class).asEagerSingleton(); bind(InitiativeTypeServiceAsync.class).asEagerSingleton(); bind(NotaryServiceAsync.class).asEagerSingleton(); bind(ParlamentarianServiceAsync.class).asEagerSingleton(); + bind(ParlamentarianCommentServiceAsync.class).asEagerSingleton(); bind(PartyServiceAsync.class).asEagerSingleton(); bind(PersonServiceAsync.class).asEagerSingleton(); bind(SocietyServiceAsync.class).asEagerSingleton(); bind(SocietyTypeServiceAsync.class).asEagerSingleton(); bind(StockServiceAsync.class).asEagerSingleton(); bind(SubscriberServiceAsync.class).asEagerSingleton(); bind(StageServiceAsync.class).asEagerSingleton(); bind(UrgencyServiceAsync.class).asEagerSingleton(); } }
true
true
protected void configure() { bind(BillServiceAsync.class).asEagerSingleton(); bind(BillTypeServiceAsync.class).asEagerSingleton(); bind(CategoryServiceAsync.class).asEagerSingleton(); bind(ChamberServiceAsync.class).asEagerSingleton(); bind(CommissionServiceAsync.class).asEagerSingleton(); bind(DistrictServiceAsync.class).asEagerSingleton(); bind(DistrictTypeServiceAsync.class).asEagerSingleton(); bind(InitiativeTypeServiceAsync.class).asEagerSingleton(); bind(NotaryServiceAsync.class).asEagerSingleton(); bind(ParlamentarianServiceAsync.class).asEagerSingleton(); bind(PartyServiceAsync.class).asEagerSingleton(); bind(PersonServiceAsync.class).asEagerSingleton(); bind(SocietyServiceAsync.class).asEagerSingleton(); bind(SocietyTypeServiceAsync.class).asEagerSingleton(); bind(StockServiceAsync.class).asEagerSingleton(); bind(SubscriberServiceAsync.class).asEagerSingleton(); bind(StageServiceAsync.class).asEagerSingleton(); bind(UrgencyServiceAsync.class).asEagerSingleton(); }
protected void configure() { bind(BillServiceAsync.class).asEagerSingleton(); bind(BillTypeServiceAsync.class).asEagerSingleton(); bind(CategoryServiceAsync.class).asEagerSingleton(); bind(ChamberServiceAsync.class).asEagerSingleton(); bind(CommissionServiceAsync.class).asEagerSingleton(); bind(DistrictServiceAsync.class).asEagerSingleton(); bind(DistrictTypeServiceAsync.class).asEagerSingleton(); bind(InitiativeTypeServiceAsync.class).asEagerSingleton(); bind(NotaryServiceAsync.class).asEagerSingleton(); bind(ParlamentarianServiceAsync.class).asEagerSingleton(); bind(ParlamentarianCommentServiceAsync.class).asEagerSingleton(); bind(PartyServiceAsync.class).asEagerSingleton(); bind(PersonServiceAsync.class).asEagerSingleton(); bind(SocietyServiceAsync.class).asEagerSingleton(); bind(SocietyTypeServiceAsync.class).asEagerSingleton(); bind(StockServiceAsync.class).asEagerSingleton(); bind(SubscriberServiceAsync.class).asEagerSingleton(); bind(StageServiceAsync.class).asEagerSingleton(); bind(UrgencyServiceAsync.class).asEagerSingleton(); }
diff --git a/src/de/schildbach/pte/AbstractEfaProvider.java b/src/de/schildbach/pte/AbstractEfaProvider.java index 3cfeced..3345364 100644 --- a/src/de/schildbach/pte/AbstractEfaProvider.java +++ b/src/de/schildbach/pte/AbstractEfaProvider.java @@ -1,2055 +1,2058 @@ /* * Copyright 2010, 2011 the original author or authors. * * 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.schildbach.pte; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Currency; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import de.schildbach.pte.dto.Connection; import de.schildbach.pte.dto.Departure; import de.schildbach.pte.dto.Fare; import de.schildbach.pte.dto.Fare.Type; import de.schildbach.pte.dto.GetConnectionDetailsResult; import de.schildbach.pte.dto.Line; import de.schildbach.pte.dto.LineDestination; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.LocationType; import de.schildbach.pte.dto.NearbyStationsResult; import de.schildbach.pte.dto.Point; import de.schildbach.pte.dto.QueryConnectionsResult; import de.schildbach.pte.dto.QueryConnectionsResult.Status; import de.schildbach.pte.dto.QueryDeparturesResult; import de.schildbach.pte.dto.StationDepartures; import de.schildbach.pte.dto.Stop; import de.schildbach.pte.exception.ParserException; import de.schildbach.pte.exception.SessionExpiredException; import de.schildbach.pte.util.Color; import de.schildbach.pte.util.ParserUtils; import de.schildbach.pte.util.XmlPullUtil; /** * @author Andreas Schildbach */ public abstract class AbstractEfaProvider implements NetworkProvider { private final String apiBase; private final String additionalQueryParameter; private final boolean canAcceptPoiID; private final XmlPullParserFactory parserFactory; public AbstractEfaProvider() { this(null, null); } public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter) { this(apiBase, additionalQueryParameter, false); } public AbstractEfaProvider(final String apiBase, final String additionalQueryParameter, final boolean canAcceptPoiID) { try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } this.apiBase = apiBase; this.additionalQueryParameter = additionalQueryParameter; this.canAcceptPoiID = canAcceptPoiID; } protected TimeZone timeZone() { return TimeZone.getTimeZone("Europe/Berlin"); } private final void appendCommonRequestParams(final StringBuilder uri) { uri.append("?outputFormat=XML"); uri.append("&coordOutputFormat=WGS84"); if (additionalQueryParameter != null) uri.append('&').append(additionalQueryParameter); } protected List<Location> xmlStopfinderRequest(final Location constraint) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XML_STOPFINDER_REQUEST"); appendCommonRequestParams(uri); uri.append("&locationServerActive=1"); appendLocation(uri, constraint, "sf"); if (constraint.type == LocationType.ANY) { uri.append("&SpEncId=0"); uri.append("&anyObjFilter_sf=126"); // 1=place 2=stop 4=street 8=address 16=crossing 32=poi 64=postcode uri.append("&reducedAnyPostcodeObjFilter_sf=64&reducedAnyTooManyObjFilter_sf=2"); uri.append("&useHouseNumberList=true&regionID_sf=1"); } InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); final List<Location> results = new ArrayList<Location>(); XmlPullUtil.enter(pp, "itdStopFinderRequest"); XmlPullUtil.require(pp, "itdOdv"); if (!"sf".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"sf\" />"); XmlPullUtil.enter(pp, "itdOdv"); XmlPullUtil.require(pp, "itdOdvPlace"); XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); if ("identified".equals(nameState) || "list".equals(nameState)) { while (XmlPullUtil.test(pp, "odvNameElem")) results.add(processOdvNameElem(pp, null)); } else if ("notidentified".equals(nameState)) { // do nothing } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } XmlPullUtil.exit(pp, "itdOdvName"); XmlPullUtil.exit(pp, "itdOdv"); XmlPullUtil.exit(pp, "itdStopFinderRequest"); return results; } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } protected List<Location> xmlCoordRequest(final int lat, final int lon, final int maxDistance, final int maxStations) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XML_COORD_REQUEST"); appendCommonRequestParams(uri); uri.append("&coord=").append(String.format(Locale.ENGLISH, "%2.6f:%2.6f:WGS84", latLonToDouble(lon), latLonToDouble(lat))); uri.append("&coordListOutputFormat=STRING"); uri.append("&max=").append(maxStations != 0 ? maxStations : 50); uri.append("&inclFilter=1&radius_1=").append(maxDistance != 0 ? maxDistance : 1320); uri.append("&type_1=STOP"); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); XmlPullUtil.enter(pp, "itdCoordInfoRequest"); XmlPullUtil.enter(pp, "itdCoordInfo"); XmlPullUtil.enter(pp, "coordInfoRequest"); XmlPullUtil.exit(pp, "coordInfoRequest"); final List<Location> results = new ArrayList<Location>(); if (XmlPullUtil.test(pp, "coordInfoItemList")) { XmlPullUtil.enter(pp, "coordInfoItemList"); while (XmlPullUtil.test(pp, "coordInfoItem")) { if (!"STOP".equals(pp.getAttributeValue(null, "type"))) throw new RuntimeException("unknown type"); final int id = XmlPullUtil.intAttr(pp, "id"); final String name = normalizeLocationName(XmlPullUtil.attr(pp, "name")); final String place = normalizeLocationName(XmlPullUtil.attr(pp, "locality")); XmlPullUtil.enter(pp, "coordInfoItem"); // FIXME this is always only one coordinate final Point coord = processItdPathCoordinates(pp).get(0); XmlPullUtil.exit(pp, "coordInfoItem"); results.add(new Location(LocationType.STATION, id, coord.lat, coord.lon, place, name)); } XmlPullUtil.exit(pp, "coordInfoItemList"); } return results; } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } public List<Location> autocompleteStations(final CharSequence constraint) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XSLT_TRIP_REQUEST2"); appendCommonRequestParams(uri); uri.append("&type_origin=any"); uri.append("&name_origin=").append(ParserUtils.urlEncode(constraint.toString(), "ISO-8859-1")); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); final List<Location> results = new ArrayList<Location>(); // parse odv name elements if (!XmlPullUtil.jumpToStartTag(pp, null, "itdOdv") || !"origin".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"origin\" />"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); if (!XmlPullUtil.test(pp, "itdOdvName")) throw new IllegalStateException("cannot find <itdOdvName />"); final String nameState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); if ("identified".equals(nameState) || "list".equals(nameState)) while (XmlPullUtil.test(pp, "odvNameElem")) results.add(processOdvNameElem(pp, place)); // parse assigned stops if (XmlPullUtil.jumpToStartTag(pp, null, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final Location location = processItdOdvAssignedStop(pp); if (!results.contains(location)) results.add(location); } } return results; } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } private String processItdOdvPlace(final XmlPullParser pp) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "itdOdvPlace")) throw new IllegalStateException("expecting <itdOdvPlace />"); final String placeState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvPlace"); String place = null; if ("identified".equals(placeState)) { if (XmlPullUtil.test(pp, "odvPlaceElem")) { XmlPullUtil.enter(pp, "odvPlaceElem"); place = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "odvPlaceElem"); } } XmlPullUtil.exit(pp, "itdOdvPlace"); return place; } private Location processOdvNameElem(final XmlPullParser pp, final String defaultPlace) throws XmlPullParserException, IOException { if (!XmlPullUtil.test(pp, "odvNameElem")) throw new IllegalStateException("expecting <odvNameElem />"); final String anyType = pp.getAttributeValue(null, "anyType"); final String idStr = pp.getAttributeValue(null, "id"); final String stopIdStr = pp.getAttributeValue(null, "stopID"); final String poiIdStr = pp.getAttributeValue(null, "poiID"); final String streetIdStr = pp.getAttributeValue(null, "streetID"); final String place = !"loc".equals(anyType) ? normalizeLocationName(pp.getAttributeValue(null, "locality")) : null; final String name = normalizeLocationName(pp.getAttributeValue(null, "objectName")); int lat = 0, lon = 0; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Integer.parseInt(pp.getAttributeValue(null, "y")); lon = Integer.parseInt(pp.getAttributeValue(null, "x")); } LocationType type; int id; if ("stop".equals(anyType)) { type = LocationType.STATION; id = Integer.parseInt(idStr); } else if ("poi".equals(anyType) || "poiHierarchy".equals(anyType)) { type = LocationType.POI; id = Integer.parseInt(idStr); } else if ("loc".equals(anyType)) { type = LocationType.ANY; id = 0; } else if ("postcode".equals(anyType) || "street".equals(anyType) || "crossing".equals(anyType) || "address".equals(anyType) || "singlehouse".equals(anyType) || "buildingname".equals(anyType)) { type = LocationType.ADDRESS; id = 0; } else if (stopIdStr != null) { type = LocationType.STATION; id = Integer.parseInt(stopIdStr); } else if (poiIdStr != null) { type = LocationType.POI; id = Integer.parseInt(poiIdStr); } else if (stopIdStr == null && idStr == null && (lat != 0 || lon != 0)) { type = LocationType.ADDRESS; id = 0; } else if (streetIdStr != null) { type = LocationType.ADDRESS; id = Integer.parseInt(streetIdStr); } else { throw new IllegalArgumentException("unknown type: " + anyType + " " + idStr + " " + stopIdStr); } XmlPullUtil.enter(pp, "odvNameElem"); final String longName = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "odvNameElem"); return new Location(type, id, lat, lon, place != null ? place : defaultPlace, name != null ? name : longName); } private Location processItdOdvAssignedStop(final XmlPullParser pp) throws XmlPullParserException, IOException { final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID")); int lat = 0, lon = 0; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Integer.parseInt(pp.getAttributeValue(null, "y")); lon = Integer.parseInt(pp.getAttributeValue(null, "x")); } final String place = normalizeLocationName(XmlPullUtil.attr(pp, "place")); XmlPullUtil.enter(pp, "itdOdvAssignedStop"); final String name = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); return new Location(LocationType.STATION, id, lat, lon, place, name); } protected abstract String nearbyStationUri(int stationId); public NearbyStationsResult queryNearbyStations(final Location location, final int maxDistance, final int maxStations) throws IOException { if (location.hasLocation()) return new NearbyStationsResult(xmlCoordRequest(location.lat, location.lon, maxDistance, maxStations)); if (location.type != LocationType.STATION) throw new IllegalArgumentException("cannot handle: " + location.type); if (!location.hasId()) throw new IllegalArgumentException("at least one of stationId or lat/lon must be given"); final String uri = nearbyStationUri(location.id); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); if (!XmlPullUtil.jumpToStartTag(pp, null, "itdOdv") || !"dm".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if ("identified".equals(nameState)) { final Location ownLocation = processOdvNameElem(pp, place); final Location ownStation = ownLocation.type == LocationType.STATION ? ownLocation : null; final List<Location> stations = new ArrayList<Location>(); if (XmlPullUtil.jumpToStartTag(pp, null, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final String parsedMapName = pp.getAttributeValue(null, "mapName"); if (parsedMapName != null) { final int parsedLocationId = XmlPullUtil.intAttr(pp, "stopID"); // final String parsedLongName = normalizeLocationName(XmlPullUtil.attr(pp, // "nameWithPlace")); final String parsedPlace = normalizeLocationName(XmlPullUtil.attr(pp, "place")); final int parsedLon = XmlPullUtil.intAttr(pp, "x"); final int parsedLat = XmlPullUtil.intAttr(pp, "y"); XmlPullUtil.enter(pp, "itdOdvAssignedStop"); final String parsedName = normalizeLocationName(pp.getText()); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); if (!"WGS84".equals(parsedMapName)) throw new IllegalStateException("unknown mapName: " + parsedMapName); final Location newStation = new Location(LocationType.STATION, parsedLocationId, parsedLat, parsedLon, parsedPlace, parsedName); if (!stations.contains(newStation)) stations.add(newStation); } else { if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdOdvAssignedStop"); XmlPullUtil.exit(pp, "itdOdvAssignedStop"); } else { XmlPullUtil.next(pp); } } } } if (ownStation != null && !stations.contains(ownStation)) stations.add(ownStation); if (maxStations == 0 || maxStations >= stations.size()) return new NearbyStationsResult(stations); else return new NearbyStationsResult(stations.subList(0, maxStations)); } else if ("list".equals(nameState)) { final List<Location> stations = new ArrayList<Location>(); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); while (XmlPullUtil.test(pp, "odvNameElem")) { final Location newLocation = processOdvNameElem(pp, place); if (newLocation.type == LocationType.STATION && !stations.contains(newLocation)) stations.add(newLocation); } return new NearbyStationsResult(stations); } else if ("notidentified".equals(nameState)) { return new NearbyStationsResult(NearbyStationsResult.Status.INVALID_STATION); } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } // XmlPullUtil.exit(pp, "itdOdvName"); } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } private static final Pattern P_LINE_IRE = Pattern.compile("IRE\\d+"); private static final Pattern P_LINE_RE = Pattern.compile("RE\\d+"); private static final Pattern P_LINE_RB = Pattern.compile("RB\\d+"); private static final Pattern P_LINE_VB = Pattern.compile("VB\\d+"); private static final Pattern P_LINE_OE = Pattern.compile("OE\\d+"); private static final Pattern P_LINE_R = Pattern.compile("R\\d+(/R\\d+|\\(z\\))?"); private static final Pattern P_LINE_U = Pattern.compile("U\\d+"); private static final Pattern P_LINE_S = Pattern.compile("^(?:%)?(S\\d+)"); private static final Pattern P_LINE_NUMBER = Pattern.compile("\\d+"); private static final Pattern P_LINE_Y = Pattern.compile("\\d+Y"); protected String parseLine(final String mot, final String name, final String longName, final String noTrainName) { if (mot == null) { if (noTrainName != null) { final String str = name != null ? name : ""; if (noTrainName.equals("S-Bahn")) return 'S' + str; if (noTrainName.equals("U-Bahn")) return 'U' + str; if (noTrainName.equals("Straßenbahn")) return 'T' + str; if (noTrainName.equals("Badner Bahn")) return 'T' + str; if (noTrainName.equals("Stadtbus")) return 'B' + str; if (noTrainName.equals("Citybus")) return 'B' + str; if (noTrainName.equals("Regionalbus")) return 'B' + str; if (noTrainName.equals("ÖBB-Postbus")) return 'B' + str; if (noTrainName.equals("Autobus")) return 'B' + str; if (noTrainName.equals("Discobus")) return 'B' + str; if (noTrainName.equals("Nachtbus")) return 'B' + str; if (noTrainName.equals("Anrufsammeltaxi")) return 'B' + str; if (noTrainName.equals("Ersatzverkehr")) return 'B' + str; if (noTrainName.equals("Vienna Airport Lines")) return 'B' + str; } throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } final int t = Integer.parseInt(mot); if (t == 0) { final String[] parts = longName.split(" ", 3); final String type = parts[0]; final String num = parts.length >= 2 ? parts[1] : null; final String str = type + (num != null ? num : ""); if (type.equals("EC")) // Eurocity return 'I' + str; if (type.equals("EN")) // Euronight return 'I' + str; if (type.equals("IC")) // Intercity return 'I' + str; if (type.equals("ICE")) // Intercity Express return 'I' + str; if (type.equals("X")) // InterConnex return 'I' + str; if (type.equals("CNL")) // City Night Line return 'I' + str; if (type.equals("THA")) // Thalys return 'I' + str; if (type.equals("TGV")) // TGV return 'I' + str; if (type.equals("RJ")) // railjet return 'I' + str; if (type.equals("OEC")) // ÖBB-EuroCity return 'I' + str; if (type.equals("OIC")) // ÖBB-InterCity return 'I' + str; if (type.equals("HT")) // First Hull Trains, GB return 'I' + str; if (type.equals("MT")) // Müller Touren, Schnee Express return 'I' + str; if (type.equals("HKX")) // Hamburg-Koeln-Express return 'I' + str; if (type.equals("DNZ")) // Nachtzug Basel-Moskau return 'I' + str; if (type.equals("IR")) // Interregio return 'R' + str; if (type.equals("IRE")) // Interregio-Express return 'R' + str; if (P_LINE_IRE.matcher(type).matches()) return 'R' + str; if (type.equals("RE")) // Regional-Express return 'R' + str; if (type.equals("R-Bahn")) // Regional-Express, VRR return 'R' + str; if (type.equals("REX")) // RegionalExpress, Österreich return 'R' + str; if ("EZ".equals(type)) // ÖBB ErlebnisBahn return 'R' + str; if (P_LINE_RE.matcher(type).matches()) return 'R' + str; if (type.equals("RB")) // Regionalbahn return 'R' + str; if (P_LINE_RB.matcher(type).matches()) return 'R' + str; if (type.equals("R")) // Regionalzug return 'R' + str; if (P_LINE_R.matcher(type).matches()) return 'R' + str; if (type.equals("Bahn")) return 'R' + str; if (type.equals("Regionalbahn")) return 'R' + str; if (type.equals("D")) // Schnellzug return 'R' + str; if (type.equals("E")) // Eilzug return 'R' + str; if (type.equals("S")) // ~Innsbruck return 'R' + str; if (type.equals("WFB")) // Westfalenbahn return 'R' + str; if ("Westfalenbahn".equals(type)) // Westfalenbahn return 'R' + name; if (type.equals("NWB")) // NordWestBahn return 'R' + str; if (type.equals("NordWestBahn")) return 'R' + str; if (type.equals("ME")) // Metronom return 'R' + str; if (type.equals("ERB")) // eurobahn return 'R' + str; if (type.equals("CAN")) // cantus return 'R' + str; if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt return 'R' + str; if (type.equals("EB")) // Erfurter Bahn return 'R' + str; if (type.equals("MRB")) // Mittelrheinbahn return 'R' + str; if (type.equals("ABR")) // ABELLIO Rail NRW return 'R' + str; if (type.equals("NEB")) // Niederbarnimer Eisenbahn return 'R' + str; if (type.equals("OE")) // Ostdeutsche Eisenbahn return 'R' + str; if (P_LINE_OE.matcher(type).matches()) return 'R' + str; if (type.equals("MR")) // Märkische Regiobahn return 'R' + str; if (type.equals("OLA")) // Ostseeland Verkehr return 'R' + str; if (type.equals("UBB")) // Usedomer Bäderbahn return 'R' + str; if (type.equals("EVB")) // Elbe-Weser return 'R' + str; if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("RTB")) // Rurtalbahn return 'R' + str; if (type.equals("STB")) // Süd-Thüringen-Bahn return 'R' + str; if (type.equals("HTB")) // Hellertalbahn return 'R' + str; if (type.equals("VBG")) // Vogtlandbahn return 'R' + str; if (type.equals("VB")) // Vogtlandbahn return 'R' + str; if (P_LINE_VB.matcher(type).matches()) return 'R' + str; if (type.equals("VX")) // Vogtland Express return 'R' + str; if (type.equals("CB")) // City-Bahn Chemnitz return 'R' + str; if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft return 'R' + str; if (type.equals("HzL")) // Hohenzollerische Landesbahn return 'R' + str; if (type.equals("OSB")) // Ortenau-S-Bahn return 'R' + str; if (type.equals("SBB")) // SBB return 'R' + str; if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli return 'R' + str; if (type.equals("OS")) // Regionalbahn return 'R' + str; if (type.equals("SP")) return 'R' + str; if (type.equals("Dab")) // Daadetalbahn return 'R' + str; if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft return 'R' + str; if (type.equals("ARR")) // ARRIVA return 'R' + str; if (type.equals("HSB")) // Harzer Schmalspurbahn return 'R' + str; if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft return 'R' + str; if (type.equals("ALX")) // Arriva-Länderbahn-Express return 'R' + str; if (type.equals("EX")) // ALX verwandelt sich return 'R' + str; if (type.equals("MEr")) // metronom regional return 'R' + str; if (type.equals("AKN")) // AKN Eisenbahn return 'R' + str; if (type.equals("ZUG")) // Regionalbahn return 'R' + str; if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("VIA")) // VIAS return 'R' + str; if (type.equals("BRB")) // Bayerische Regiobahn return 'R' + str; if (type.equals("BLB")) // Berchtesgadener Land Bahn return 'R' + str; if (type.equals("HLB")) // Hessische Landesbahn return 'R' + str; if (type.equals("NOB")) // NordOstseeBahn return 'R' + str; if (type.equals("WEG")) // Wieslauftalbahn return 'R' + str; if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft return 'R' + str; if (type.equals("VEN")) // Rhenus Veniro return 'R' + str; if (type.equals("DPN")) // Nahreisezug return 'R' + str; if (type.equals("SHB")) // Schleswig-Holstein-Bahn return 'R' + str; if (type.equals("RBG")) // Regental Bahnbetriebs GmbH return 'R' + str; if (type.equals("BOB")) // Bayerische Oberlandbahn return 'R' + str; if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG return 'R' + str; if (type.equals("VE")) // Vetter return 'R' + str; if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft return 'R' + str; if (type.equals("PRE")) // Pressnitztalbahn return 'R' + str; if (type.equals("VEB")) // Vulkan-Eifel-Bahn return 'R' + str; if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft return 'R' + str; if (type.equals("AVG")) // Felsenland-Express return 'R' + str; if (type.equals("ABG")) // Anhaltische Bahngesellschaft return 'R' + str; if (type.equals("LGB")) // Lößnitzgrundbahn return 'R' + str; if (type.equals("LEO")) // Chiemgauer Lokalbahn return 'R' + str; if (type.equals("WTB")) // Weißeritztalbahn return 'R' + str; if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle return 'R' + str; if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen return 'R' + str; if (type.equals("MBS")) // Montafonerbahn return 'R' + str; if (type.equals("EGP")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SBS")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SES")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("agi")) // agilis return 'R' + str; if (type.equals("ag")) // agilis return 'R' + str; if (type.equals("TLX")) // Trilex (Vogtlandbahn) return 'R' + str; if (type.equals("BE")) // Grensland-Express, Niederlande return 'R' + str; if (type.equals("MEL")) // Museums-Eisenbahn Losheim return 'R' + str; if (type.equals("Abellio-Zug")) // Abellio return 'R' + str; if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn? return 'R' + str; if (type.equals("KBS")) // Kursbuchstrecke return 'R' + str; if (type.equals("Zug")) return 'R' + str; if (type.equals("ÖBB")) return 'R' + str; if (type.equals("CAT")) // City Airport Train Wien return 'R' + str; if (type.equals("DZ")) // Dampfzug, STV return 'R' + str; if (type.equals("CD")) return 'R' + str; if (type.equals("PR")) return 'R' + str; if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn) return 'R' + str; if (type.equals("VIAMO")) return 'R' + str; if (type.equals("SE")) // Southeastern, GB return 'R' + str; if (type.equals("SW")) // South West Trains, GB return 'R' + str; if (type.equals("SN")) // Southern, GB return 'R' + str; if (type.equals("NT")) // Northern Rail, GB return 'R' + str; if (type.equals("CH")) // Chiltern Railways, GB return 'R' + str; if (type.equals("EA")) // National Express East Anglia, GB return 'R' + str; if (type.equals("FC")) // First Capital Connect, GB return 'R' + str; if (type.equals("GW")) // First Great Western, GB return 'R' + str; if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("HC")) // Heathrow Connect, GB return 'R' + str; if (type.equals("HX")) // Heathrow Express, GB return 'R' + str; if (type.equals("GX")) // Gatwick Express, GB return 'R' + str; if (type.equals("C2C")) // c2c, GB return 'R' + str; if (type.equals("LM")) // London Midland, GB return 'R' + str; if (type.equals("EM")) // East Midlands Trains, GB return 'R' + str; if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("AW")) // Arriva Trains Wales, GB return 'R' + str; if (type.equals("WS")) // Wrexham & Shropshire, GB return 'R' + str; if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("GC")) // Grand Central, GB return 'R' + str; if (type.equals("IL")) // Island Line, GB return 'R' + str; if (type.equals("BR")) // ??, GB return 'R' + str; if (type.equals("OO")) // ??, GB return 'R' + str; if (type.equals("XX")) // ??, GB return 'R' + str; if (type.equals("XZ")) // ??, GB return 'R' + str; if (type.equals("DB-Zug")) // VRR return 'R' + name; if (type.equals("Regionalexpress")) // VRR return 'R' + name; if ("CAPITOL".equals(name)) // San Francisco return 'R' + name; if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco return "R" + name; if ("Regional Train :".equals(longName)) return "R"; if ("Regional Train".equals(noTrainName)) // Melbourne return "R" + name; if ("Regional".equals(type)) // Melbourne return "R" + name; if (type.equals("ATB")) // Autoschleuse Tauernbahn return 'R' + name; if ("Chiemsee-Bahn".equals(type)) return 'R' + name; if (type.equals("BSB")) // Breisgau-S-Bahn return 'S' + str; if (type.equals("RER")) // Réseau Express Régional, Frankreich return 'S' + str; if (type.equals("LO")) // London Overground, GB return 'S' + str; if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES return 'S' + str; + final Matcher m = P_LINE_S.matcher(name); + if (m.find()) + return 'S' + m.group(1); if (P_LINE_U.matcher(type).matches()) return 'U' + str; if ("Underground".equals(type)) // London Underground, GB return 'U' + str; if ("Millbrae / Richmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Millbrae".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / RIchmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART return 'U' + name; if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART return 'U' + name; if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if (type.equals("RT")) // RegioTram return 'T' + str; if (type.equals("STR")) // Nordhausen return 'T' + str; if ("California Cable Car".equals(name)) // San Francisco return 'T' + name; if ("Muni".equals(type)) // San Francisco return 'T' + name; if ("Cable".equals(type)) // San Francisco return 'T' + name; if ("Muni Rail".equals(noTrainName)) // San Francisco return 'T' + name; if ("Cable Car".equals(noTrainName)) // San Francisco return 'T' + name; if (type.equals("BUS")) return 'B' + str; if ("SEV-Bus".equals(type)) return 'B' + str; if ("Bex".equals(type)) // Bayern Express return 'B' + str; if (type.length() == 0) return "?"; if (P_LINE_NUMBER.matcher(type).matches()) return "?"; if (P_LINE_Y.matcher(name).matches()) return "?" + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "' type '" + type + "' str '" + str + "'"); } if (t == 1) { final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); else return 'S' + name; } if (t == 2) return 'U' + name; if (t == 3 || t == 4) return 'T' + name; if (t == 5 || t == 6 || t == 7 || t == 10) { if (name.equals("Schienenersatzverkehr")) return "BSEV"; else return 'B' + name; } if (t == 8) return 'C' + name; if (t == 9) return 'F' + name; if (t == 11 || t == -1) return '?' + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } public QueryDeparturesResult queryDepartures(final int stationId, final int maxDepartures, final boolean equivs) throws IOException { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XSLT_DM_REQUEST"); appendCommonRequestParams(uri); uri.append("&type_dm=stop&useRealtime=1&mode=direct"); uri.append("&name_dm=").append(stationId); uri.append("&deleteAssignedStops_dm=").append(equivs ? '0' : '1'); if (maxDepartures > 0) uri.append("&limit=").append(maxDepartures); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri.toString()); final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); enterItdRequest(pp); XmlPullUtil.enter(pp, "itdDepartureMonitorRequest"); if (!XmlPullUtil.test(pp, "itdOdv") || !"dm".equals(XmlPullUtil.attr(pp, "usage"))) throw new IllegalStateException("cannot find <itdOdv usage=\"dm\" />"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); XmlPullUtil.require(pp, "itdOdvName"); final String nameState = pp.getAttributeValue(null, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if ("identified".equals(nameState)) { final QueryDeparturesResult result = new QueryDeparturesResult(); final Location location = processOdvNameElem(pp, place); result.stationDepartures.add(new StationDepartures(location, new LinkedList<Departure>(), new LinkedList<LineDestination>())); XmlPullUtil.exit(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdOdvAssignedStops")) { XmlPullUtil.enter(pp, "itdOdvAssignedStops"); while (XmlPullUtil.test(pp, "itdOdvAssignedStop")) { final Location assignedLocation = processItdOdvAssignedStop(pp); if (findStationDepartures(result.stationDepartures, assignedLocation.id) == null) result.stationDepartures.add(new StationDepartures(assignedLocation, new LinkedList<Departure>(), new LinkedList<LineDestination>())); } XmlPullUtil.exit(pp, "itdOdvAssignedStops"); } XmlPullUtil.exit(pp, "itdOdv"); if (XmlPullUtil.test(pp, "itdDateTime")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdDateRange")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdTripOptions")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); final Calendar plannedDepartureTime = new GregorianCalendar(timeZone()); final Calendar predictedDepartureTime = new GregorianCalendar(timeZone()); XmlPullUtil.require(pp, "itdServingLines"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdServingLines"); while (XmlPullUtil.test(pp, "itdServingLine")) { final String assignedStopIdStr = pp.getAttributeValue(null, "assignedStopID"); final int assignedStopId = assignedStopIdStr != null ? Integer.parseInt(assignedStopIdStr) : 0; final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction")); final String destinationIdStr = pp.getAttributeValue(null, "destID"); final int destinationId = destinationIdStr.length() > 0 ? Integer.parseInt(destinationIdStr) : 0; final LineDestination line = new LineDestination(processItdServingLine(pp), destinationId, destination); StationDepartures assignedStationDepartures; if (assignedStopId == 0) assignedStationDepartures = result.stationDepartures.get(0); else assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId), new LinkedList<Departure>(), new LinkedList<LineDestination>()); if (!assignedStationDepartures.lines.contains(line)) assignedStationDepartures.lines.add(line); } XmlPullUtil.exit(pp, "itdServingLines"); } else { XmlPullUtil.next(pp); } XmlPullUtil.require(pp, "itdDepartureList"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdDepartureList"); while (XmlPullUtil.test(pp, "itdDeparture")) { final int assignedStopId = XmlPullUtil.intAttr(pp, "stopID"); StationDepartures assignedStationDepartures = findStationDepartures(result.stationDepartures, assignedStopId); if (assignedStationDepartures == null) { final String mapName = pp.getAttributeValue(null, "mapName"); if (mapName == null || !"WGS84".equals(mapName)) throw new IllegalStateException("unknown mapName: " + mapName); final int lon = XmlPullUtil.intAttr(pp, "x"); final int lat = XmlPullUtil.intAttr(pp, "y"); // final String name = normalizeLocationName(XmlPullUtil.attr(pp, "nameWO")); assignedStationDepartures = new StationDepartures(new Location(LocationType.STATION, assignedStopId, lat, lon), new LinkedList<Departure>(), new LinkedList<LineDestination>()); } final String position = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdDeparture"); XmlPullUtil.require(pp, "itdDateTime"); plannedDepartureTime.clear(); processItdDateTime(pp, plannedDepartureTime); predictedDepartureTime.clear(); if (XmlPullUtil.test(pp, "itdRTDateTime")) processItdDateTime(pp, predictedDepartureTime); if (XmlPullUtil.test(pp, "itdFrequencyInfo")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdServingLine"); final boolean isRealtime = pp.getAttributeValue(null, "realtime").equals("1"); final String destination = normalizeLocationName(pp.getAttributeValue(null, "direction")); final int destinationId = Integer.parseInt(pp.getAttributeValue(null, "destID")); final Line line = processItdServingLine(pp); if (isRealtime && !predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY)) predictedDepartureTime.setTimeInMillis(plannedDepartureTime.getTimeInMillis()); final Departure departure = new Departure(plannedDepartureTime.getTime(), predictedDepartureTime.isSet(Calendar.HOUR_OF_DAY) ? predictedDepartureTime.getTime() : null, line, position, destinationId, destination, null, null); assignedStationDepartures.departures.add(departure); XmlPullUtil.exit(pp, "itdDeparture"); } XmlPullUtil.exit(pp, "itdDepartureList"); } return result; } else if ("notidentified".equals(nameState)) { return new QueryDeparturesResult(QueryDeparturesResult.Status.INVALID_STATION); } else { throw new RuntimeException("unknown nameState '" + nameState + "' on " + uri); } } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } private StationDepartures findStationDepartures(final List<StationDepartures> stationDepartures, final int id) { for (final StationDepartures stationDeparture : stationDepartures) if (stationDeparture.location.id == id) return stationDeparture; return null; } private Location processItdPointAttributes(final XmlPullParser pp) { final int id = Integer.parseInt(pp.getAttributeValue(null, "stopID")); final String place = normalizeLocationName(pp.getAttributeValue(null, "locality")); String name = normalizeLocationName(pp.getAttributeValue(null, "nameWO")); if (name == null) name = normalizeLocationName(pp.getAttributeValue(null, "name")); final int lat, lon; if ("WGS84".equals(pp.getAttributeValue(null, "mapName"))) { lat = Integer.parseInt(pp.getAttributeValue(null, "y")); lon = Integer.parseInt(pp.getAttributeValue(null, "x")); } else { lat = 0; lon = 0; } return new Location(LocationType.STATION, id, lat, lon, place, name); } private boolean processItdDateTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp); calendar.clear(); final boolean success = processItdDate(pp, calendar); if (success) processItdTime(pp, calendar); XmlPullUtil.exit(pp); return success; } private boolean processItdDate(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdDate"); final int year = Integer.parseInt(pp.getAttributeValue(null, "year")); final int month = Integer.parseInt(pp.getAttributeValue(null, "month")) - 1; final int day = Integer.parseInt(pp.getAttributeValue(null, "day")); XmlPullUtil.next(pp); if (year == 0) return false; calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, day); return true; } private void processItdTime(final XmlPullParser pp, final Calendar calendar) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdTime"); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(pp.getAttributeValue(null, "hour"))); calendar.set(Calendar.MINUTE, Integer.parseInt(pp.getAttributeValue(null, "minute"))); XmlPullUtil.next(pp); } private Line processItdServingLine(final XmlPullParser pp) throws XmlPullParserException, IOException { XmlPullUtil.require(pp, "itdServingLine"); final String motType = pp.getAttributeValue(null, "motType"); final String number = pp.getAttributeValue(null, "number"); final String id = pp.getAttributeValue(null, "stateless"); XmlPullUtil.enter(pp, "itdServingLine"); String noTrainName = null; if (XmlPullUtil.test(pp, "itdNoTrain")) noTrainName = pp.getAttributeValue(null, "name"); XmlPullUtil.exit(pp, "itdServingLine"); final String label = parseLine(motType, number, number, noTrainName); return new Line(id, label, lineColors(label)); } private static final Pattern P_STATION_NAME_WHITESPACE = Pattern.compile("\\s+"); protected String normalizeLocationName(final String name) { if (name == null || name.length() == 0) return null; return P_STATION_NAME_WHITESPACE.matcher(name).replaceAll(" "); } protected static double latLonToDouble(final int value) { return (double) value / 1000000; } private String xsltTripRequest2Uri(final Location from, final Location via, final Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) { final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd"); final DateFormat TIME_FORMAT = new SimpleDateFormat("HHmm"); final StringBuilder uri = new StringBuilder(apiBase); uri.append("XSLT_TRIP_REQUEST2"); appendCommonRequestParams(uri); uri.append("&sessionID=0"); uri.append("&requestID=0"); uri.append("&language=de"); appendCommonXsltTripRequest2Params(uri); appendLocation(uri, from, "origin"); appendLocation(uri, to, "destination"); if (via != null) appendLocation(uri, via, "via"); uri.append("&itdDate=").append(ParserUtils.urlEncode(DATE_FORMAT.format(date))); uri.append("&itdTime=").append(ParserUtils.urlEncode(TIME_FORMAT.format(date))); uri.append("&itdTripDateTimeDepArr=").append(dep ? "dep" : "arr"); uri.append("&ptOptionsActive=1"); uri.append("&changeSpeed=").append(WALKSPEED_MAP.get(walkSpeed)); if (products != null) { uri.append("&includedMeans=checkbox"); boolean hasI = false; for (final char p : products.toCharArray()) { if (p == 'I' || p == 'R') { uri.append("&inclMOT_0=on"); if (p == 'I') hasI = true; } if (p == 'S') uri.append("&inclMOT_1=on"); if (p == 'U') uri.append("&inclMOT_2=on"); if (p == 'T') uri.append("&inclMOT_3=on&inclMOT_4=on"); if (p == 'B') uri.append("&inclMOT_5=on&inclMOT_6=on&inclMOT_7=on"); if (p == 'P') uri.append("&inclMOT_10=on"); if (p == 'F') uri.append("&inclMOT_9=on"); if (p == 'C') uri.append("&inclMOT_8=on"); uri.append("&inclMOT_11=on"); // TODO always show 'others', for now } // workaround for highspeed trains: fails when you want highspeed, but not regional if (!hasI) uri.append("&lineRestriction=403"); // means: all but ice } uri.append("&locationServerActive=1"); uri.append("&useRealtime=1"); uri.append("&useProxFootSearch=1"); // walk if it makes journeys quicker return uri.toString(); } private String commandLink(final String sessionId, final String requestId, final String command) { final StringBuilder uri = new StringBuilder(apiBase); uri.append("XSLT_TRIP_REQUEST2"); uri.append("?sessionID=").append(sessionId); uri.append("&requestID=").append(requestId); appendCommonXsltTripRequest2Params(uri); uri.append("&command=").append(command); return uri.toString(); } private static final void appendCommonXsltTripRequest2Params(final StringBuilder uri) { uri.append("&coordListOutputFormat=STRING"); uri.append("&calcNumberOfTrips=4"); } public QueryConnectionsResult queryConnections(final Location from, final Location via, final Location to, final Date date, final boolean dep, final String products, final WalkSpeed walkSpeed) throws IOException { final String uri = xsltTripRequest2Uri(from, via, to, date, dep, products, walkSpeed); InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri, null, "HASESSIONID", 3); return queryConnections(uri, is); } catch (final XmlPullParserException x) { throw new ParserException(x); } finally { if (is != null) is.close(); } } public QueryConnectionsResult queryMoreConnections(final String uri) throws IOException { InputStream is = null; try { is = ParserUtils.scrapeInputStream(uri, null, "HASESSIONID", 3); return queryConnections(uri, is); } catch (final XmlPullParserException x) { if (x.getMessage().startsWith("expected: START_TAG {null}itdRequest")) throw new SessionExpiredException(); else throw new ParserException(x); } finally { if (is != null) is.close(); } } private QueryConnectionsResult queryConnections(final String uri, final InputStream is) throws XmlPullParserException, IOException { final XmlPullParser pp = parserFactory.newPullParser(); pp.setInput(is, null); final String sessionId = enterItdRequest(pp); XmlPullUtil.require(pp, "itdTripRequest"); final String requestId = XmlPullUtil.attr(pp, "requestID"); XmlPullUtil.enter(pp, "itdTripRequest"); if (XmlPullUtil.test(pp, "itdMessage")) { final int code = XmlPullUtil.intAttr(pp, "code"); if (code == -4000) // no connection return new QueryConnectionsResult(Status.NO_CONNECTIONS); XmlPullUtil.next(pp); } if (XmlPullUtil.test(pp, "itdPrintConfiguration")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdAddress")) XmlPullUtil.next(pp); // parse odv name elements List<Location> ambiguousFrom = null, ambiguousTo = null, ambiguousVia = null; Location from = null, via = null, to = null; while (XmlPullUtil.test(pp, "itdOdv")) { final String usage = XmlPullUtil.attr(pp, "usage"); XmlPullUtil.enter(pp, "itdOdv"); final String place = processItdOdvPlace(pp); if (!XmlPullUtil.test(pp, "itdOdvName")) throw new IllegalStateException("cannot find <itdOdvName /> inside " + usage); final String nameState = XmlPullUtil.attr(pp, "state"); XmlPullUtil.enter(pp, "itdOdvName"); if (XmlPullUtil.test(pp, "itdMessage")) XmlPullUtil.next(pp); if ("list".equals(nameState)) { if ("origin".equals(usage)) { ambiguousFrom = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousFrom.add(processOdvNameElem(pp, place)); } else if ("via".equals(usage)) { ambiguousVia = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousVia.add(processOdvNameElem(pp, place)); } else if ("destination".equals(usage)) { ambiguousTo = new ArrayList<Location>(); while (XmlPullUtil.test(pp, "odvNameElem")) ambiguousTo.add(processOdvNameElem(pp, place)); } else { throw new IllegalStateException("unknown usage: " + usage); } } else if ("identified".equals(nameState)) { if (!XmlPullUtil.test(pp, "odvNameElem")) throw new IllegalStateException("cannot find <odvNameElem /> inside " + usage); if ("origin".equals(usage)) from = processOdvNameElem(pp, place); else if ("via".equals(usage)) via = processOdvNameElem(pp, place); else if ("destination".equals(usage)) to = processOdvNameElem(pp, place); else throw new IllegalStateException("unknown usage: " + usage); } XmlPullUtil.exit(pp, "itdOdvName"); XmlPullUtil.exit(pp, "itdOdv"); } if (ambiguousFrom != null || ambiguousTo != null || ambiguousVia != null) return new QueryConnectionsResult(ambiguousFrom, ambiguousVia, ambiguousTo); XmlPullUtil.enter(pp, "itdTripDateTime"); XmlPullUtil.enter(pp, "itdDateTime"); if (!XmlPullUtil.test(pp, "itdDate")) throw new IllegalStateException("cannot find <itdDate />"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdDate"); if (!XmlPullUtil.test(pp, "itdMessage")) throw new IllegalStateException("cannot find <itdMessage />"); final String message = pp.nextText(); if (message.equals("invalid date")) return new QueryConnectionsResult(Status.INVALID_DATE); XmlPullUtil.exit(pp, "itdDate"); } XmlPullUtil.exit(pp, "itdDateTime"); final Calendar time = new GregorianCalendar(timeZone()); final List<Connection> connections = new ArrayList<Connection>(); if (XmlPullUtil.jumpToStartTag(pp, null, "itdRouteList")) { XmlPullUtil.enter(pp, "itdRouteList"); while (XmlPullUtil.test(pp, "itdRoute")) { final String id = pp.getAttributeValue(null, "routeIndex") + "-" + pp.getAttributeValue(null, "routeTripIndex"); XmlPullUtil.enter(pp, "itdRoute"); while (XmlPullUtil.test(pp, "itdDateTime")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.enter(pp, "itdPartialRouteList"); final List<Connection.Part> parts = new LinkedList<Connection.Part>(); Location firstDeparture = null; Date firstDepartureTime = null; Location lastArrival = null; Date lastArrivalTime = null; while (XmlPullUtil.test(pp, "itdPartialRoute")) { XmlPullUtil.enter(pp, "itdPartialRoute"); XmlPullUtil.test(pp, "itdPoint"); if (!"departure".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException(); final Location departure = processItdPointAttributes(pp); if (firstDeparture == null) firstDeparture = departure; final String departurePosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdDateTime"); processItdDateTime(pp, time); final Date departureTime = time.getTime(); if (firstDepartureTime == null) firstDepartureTime = departureTime; final Date departureTargetTime; if (XmlPullUtil.test(pp, "itdDateTimeTarget")) { processItdDateTime(pp, time); departureTargetTime = time.getTime(); } else { departureTargetTime = null; } XmlPullUtil.exit(pp, "itdPoint"); XmlPullUtil.test(pp, "itdPoint"); if (!"arrival".equals(pp.getAttributeValue(null, "usage"))) throw new IllegalStateException(); final Location arrival = processItdPointAttributes(pp); lastArrival = arrival; final String arrivalPosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); if (XmlPullUtil.test(pp, "itdMapItemList")) XmlPullUtil.next(pp); XmlPullUtil.require(pp, "itdDateTime"); processItdDateTime(pp, time); final Date arrivalTime = time.getTime(); lastArrivalTime = arrivalTime; final Date arrivalTargetTime; if (XmlPullUtil.test(pp, "itdDateTimeTarget")) { processItdDateTime(pp, time); arrivalTargetTime = time.getTime(); } else { arrivalTargetTime = null; } XmlPullUtil.exit(pp, "itdPoint"); XmlPullUtil.test(pp, "itdMeansOfTransport"); final String productName = pp.getAttributeValue(null, "productName"); if ("Fussweg".equals(productName) || "Taxi".equals(productName)) { final int min = (int) (arrivalTime.getTime() - departureTime.getTime()) / 1000 / 60; XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); if (XmlPullUtil.test(pp, "itdStopSeq")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdFootPathInfo")) XmlPullUtil.next(pp); List<Point> path = null; if (XmlPullUtil.test(pp, "itdPathCoordinates")) path = processItdPathCoordinates(pp); if (parts.size() > 0 && parts.get(parts.size() - 1) instanceof Connection.Footway) { final Connection.Footway lastFootway = (Connection.Footway) parts.remove(parts.size() - 1); if (path != null && lastFootway.path != null) path.addAll(0, lastFootway.path); parts.add(new Connection.Footway(lastFootway.min + min, lastFootway.departure, arrival, path)); } else { parts.add(new Connection.Footway(min, departure, arrival, path)); } } else if ("gesicherter Anschluss".equals(productName) || "nicht umsteigen".equals(productName)) // type97 { // ignore XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); } else { final String destinationIdStr = pp.getAttributeValue(null, "destID"); final String destinationName = normalizeLocationName(pp.getAttributeValue(null, "destination")); final Location destination = destinationIdStr.length() > 0 ? new Location(LocationType.STATION, Integer.parseInt(destinationIdStr), null, destinationName) : new Location(LocationType.ANY, 0, null, destinationName); final String lineLabel; if ("AST".equals(pp.getAttributeValue(null, "symbol"))) lineLabel = "BAST"; else lineLabel = parseLine(pp.getAttributeValue(null, "motType"), pp.getAttributeValue(null, "shortname"), pp.getAttributeValue(null, "name"), null); XmlPullUtil.enter(pp, "itdMeansOfTransport"); XmlPullUtil.require(pp, "motDivaParams"); final String lineId = XmlPullUtil.attr(pp, "network") + ':' + XmlPullUtil.attr(pp, "line") + ':' + XmlPullUtil.attr(pp, "supplement") + ':' + XmlPullUtil.attr(pp, "direction") + ':' + XmlPullUtil.attr(pp, "project"); XmlPullUtil.exit(pp, "itdMeansOfTransport"); final Line line = new Line(lineId, lineLabel, lineColors(lineLabel)); if (XmlPullUtil.test(pp, "itdRBLControlled")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdInfoTextList")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdFootPathInfo")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "infoLink")) XmlPullUtil.next(pp); List<Stop> intermediateStops = null; if (XmlPullUtil.test(pp, "itdStopSeq")) { XmlPullUtil.enter(pp, "itdStopSeq"); intermediateStops = new LinkedList<Stop>(); while (XmlPullUtil.test(pp, "itdPoint")) { final Location stopLocation = processItdPointAttributes(pp); final String stopPosition = normalizePlatform(pp.getAttributeValue(null, "platform"), pp.getAttributeValue(null, "platformName")); XmlPullUtil.enter(pp, "itdPoint"); XmlPullUtil.require(pp, "itdDateTime"); final boolean success1 = processItdDateTime(pp, time); final boolean success2 = XmlPullUtil.test(pp, "itdDateTime") ? processItdDateTime(pp, time) : false; XmlPullUtil.exit(pp, "itdPoint"); if (success1 || success2) intermediateStops.add(new Stop(stopLocation, stopPosition, time.getTime())); } XmlPullUtil.exit(pp, "itdStopSeq"); // remove first and last, because they are not intermediate final int size = intermediateStops.size(); if (size >= 2) { if (intermediateStops.get(size - 1).location.id != arrival.id) throw new IllegalStateException(); intermediateStops.remove(size - 1); if (intermediateStops.get(0).location.id != departure.id) throw new IllegalStateException(); intermediateStops.remove(0); } } List<Point> path = null; if (XmlPullUtil.test(pp, "itdPathCoordinates")) path = processItdPathCoordinates(pp); parts.add(new Connection.Trip(line, destination, departureTime, departurePosition, departure, arrivalTime, arrivalPosition, arrival, intermediateStops, path)); } XmlPullUtil.exit(pp, "itdPartialRoute"); } XmlPullUtil.exit(pp, "itdPartialRouteList"); final List<Fare> fares = new ArrayList<Fare>(2); if (XmlPullUtil.test(pp, "itdFare") && !pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdFare"); if (XmlPullUtil.test(pp, "itdSingleTicket")) { final String net = XmlPullUtil.attr(pp, "net"); final Currency currency = parseCurrency(XmlPullUtil.attr(pp, "currency")); final String fareAdult = XmlPullUtil.attr(pp, "fareAdult"); final String fareChild = XmlPullUtil.attr(pp, "fareChild"); final String unitName = XmlPullUtil.attr(pp, "unitName"); final String unitsAdult = XmlPullUtil.attr(pp, "unitsAdult"); final String unitsChild = XmlPullUtil.attr(pp, "unitsChild"); if (fareAdult != null && fareAdult.length() > 0) fares.add(new Fare(net, Type.ADULT, currency, Float.parseFloat(fareAdult), unitName, unitsAdult)); if (fareChild != null && fareChild.length() > 0) fares.add(new Fare(net, Type.CHILD, currency, Float.parseFloat(fareChild), unitName, unitsChild)); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "itdSingleTicket"); if (XmlPullUtil.test(pp, "itdGenericTicketList")) { XmlPullUtil.enter(pp, "itdGenericTicketList"); while (XmlPullUtil.test(pp, "itdGenericTicketGroup")) { final Fare fare = processItdGenericTicketGroup(pp, net, currency); if (fare != null) fares.add(fare); } XmlPullUtil.exit(pp, "itdGenericTicketList"); } XmlPullUtil.exit(pp, "itdSingleTicket"); } } XmlPullUtil.exit(pp, "itdFare"); } connections.add(new Connection(id, uri, firstDepartureTime, lastArrivalTime, firstDeparture, lastArrival, parts, fares.isEmpty() ? null : fares, null)); XmlPullUtil.exit(pp, "itdRoute"); } XmlPullUtil.exit(pp, "itdRouteList"); return new QueryConnectionsResult(uri, from, via, to, commandLink(sessionId, requestId, "tripNext"), connections); } else { return new QueryConnectionsResult(Status.NO_CONNECTIONS); } } private List<Point> processItdPathCoordinates(final XmlPullParser pp) throws XmlPullParserException, IOException { final List<Point> path = new LinkedList<Point>(); XmlPullUtil.enter(pp, "itdPathCoordinates"); XmlPullUtil.enter(pp, "coordEllipsoid"); final String ellipsoid = pp.getText(); XmlPullUtil.exit(pp, "coordEllipsoid"); if (!"WGS84".equals(ellipsoid)) throw new IllegalStateException("unknown ellipsoid: " + ellipsoid); XmlPullUtil.enter(pp, "coordType"); final String type = pp.getText(); XmlPullUtil.exit(pp, "coordType"); if (!"GEO_DECIMAL".equals(type)) throw new IllegalStateException("unknown type: " + type); XmlPullUtil.enter(pp, "itdCoordinateString"); for (final String coordStr : pp.getText().split(" ")) { final String[] coordsStr = coordStr.split(","); path.add(new Point(Integer.parseInt(coordsStr[1]), Integer.parseInt(coordsStr[0]))); } XmlPullUtil.exit(pp, "itdCoordinateString"); XmlPullUtil.exit(pp, "itdPathCoordinates"); return path; } private Fare processItdGenericTicketGroup(final XmlPullParser pp, final String net, final Currency currency) throws XmlPullParserException, IOException { XmlPullUtil.enter(pp, "itdGenericTicketGroup"); Type type = null; float fare = 0; while (XmlPullUtil.test(pp, "itdGenericTicket")) { XmlPullUtil.enter(pp, "itdGenericTicket"); XmlPullUtil.enter(pp, "ticket"); final String key = pp.getText().trim(); XmlPullUtil.exit(pp, "ticket"); String value = null; XmlPullUtil.require(pp, "value"); if (!pp.isEmptyElementTag()) { XmlPullUtil.enter(pp, "value"); value = pp.getText(); if (value != null) value = value.trim(); XmlPullUtil.exit(pp, "value"); } if (key.equals("FOR_RIDER")) { final String typeStr = value.split(" ")[0].toUpperCase(); if (typeStr.equals("REGULAR")) type = Type.ADULT; else type = Type.valueOf(typeStr); } else if (key.equals("PRICE")) { fare = Float.parseFloat(value) * (currency.getCurrencyCode().equals("USD") ? 0.01f : 1); } XmlPullUtil.exit(pp, "itdGenericTicket"); } XmlPullUtil.exit(pp, "itdGenericTicketGroup"); if (type != null) return new Fare(net, type, currency, fare, null, null); else return null; } private Currency parseCurrency(final String currencyStr) { if (currencyStr.equals("US$")) return Currency.getInstance("USD"); if (currencyStr.equals("Dirham")) return Currency.getInstance("AED"); return Currency.getInstance(currencyStr); } private static final Pattern P_PLATFORM = Pattern.compile("#?(\\d+)", Pattern.CASE_INSENSITIVE); private static final Pattern P_PLATFORM_NAME = Pattern.compile("(?:Gleis|Gl\\.|Bstg\\.)?\\s*" + // "(\\d+)\\s*" + // "(?:([A-Z])\\s*(?:-\\s*([A-Z]))?)?", Pattern.CASE_INSENSITIVE); private static final String normalizePlatform(final String platform, final String platformName) { if (platform != null && platform.length() > 0) { final Matcher m = P_PLATFORM.matcher(platform); if (m.matches()) { return Integer.toString(Integer.parseInt(m.group(1))); } else { return platform; } } if (platformName != null && platformName.length() > 0) { final Matcher m = P_PLATFORM_NAME.matcher(platformName); if (m.matches()) { final String simple = Integer.toString(Integer.parseInt(m.group(1))); if (m.group(2) != null && m.group(3) != null) return simple + m.group(2) + "-" + m.group(3); else if (m.group(2) != null) return simple + m.group(2); else return simple; } else { return platformName; } } return null; } public GetConnectionDetailsResult getConnectionDetails(final String connectionUri) throws IOException { throw new UnsupportedOperationException(); } private void appendLocation(final StringBuilder uri, final Location location, final String paramSuffix) { if (canAcceptPoiID && location.type == LocationType.POI && location.hasId()) { uri.append("&type_").append(paramSuffix).append("=poiID"); uri.append("&name_").append(paramSuffix).append("=").append(location.id); } else if ((location.type == LocationType.POI || location.type == LocationType.ADDRESS) && location.hasLocation()) { uri.append("&type_").append(paramSuffix).append("=coord"); uri.append("&name_").append(paramSuffix).append("=") .append(String.format(Locale.ENGLISH, "%.6f:%.6f", location.lon / 1E6, location.lat / 1E6)).append(":WGS84"); } else { uri.append("&type_").append(paramSuffix).append("=").append(locationTypeValue(location)); uri.append("&name_").append(paramSuffix).append("=").append(ParserUtils.urlEncode(locationValue(location), "ISO-8859-1")); } } protected static final String locationTypeValue(final Location location) { final LocationType type = location.type; if (type == LocationType.STATION) return "stop"; if (type == LocationType.ADDRESS) return "any"; // strange, matches with anyObjFilter if (type == LocationType.POI) return "poi"; if (type == LocationType.ANY) return "any"; throw new IllegalArgumentException(type.toString()); } protected static final String locationValue(final Location location) { if ((location.type == LocationType.STATION || location.type == LocationType.POI) && location.hasId()) return Integer.toString(location.id); else return location.name; } protected static final Map<WalkSpeed, String> WALKSPEED_MAP = new HashMap<WalkSpeed, String>(); static { WALKSPEED_MAP.put(WalkSpeed.SLOW, "slow"); WALKSPEED_MAP.put(WalkSpeed.NORMAL, "normal"); WALKSPEED_MAP.put(WalkSpeed.FAST, "fast"); } private static final Map<Character, int[]> LINES = new HashMap<Character, int[]>(); static { LINES.put('I', new int[] { Color.WHITE, Color.RED, Color.RED }); LINES.put('R', new int[] { Color.GRAY, Color.WHITE }); LINES.put('S', new int[] { Color.parseColor("#006e34"), Color.WHITE }); LINES.put('U', new int[] { Color.parseColor("#003090"), Color.WHITE }); LINES.put('T', new int[] { Color.parseColor("#cc0000"), Color.WHITE }); LINES.put('B', new int[] { Color.parseColor("#993399"), Color.WHITE }); LINES.put('F', new int[] { Color.BLUE, Color.WHITE }); LINES.put('?', new int[] { Color.DKGRAY, Color.WHITE }); } public int[] lineColors(final String line) { if (line.length() == 0) return null; return LINES.get(line.charAt(0)); } private String enterItdRequest(final XmlPullParser pp) throws XmlPullParserException, IOException { if (pp.getEventType() == XmlPullParser.START_DOCUMENT) pp.next(); XmlPullUtil.require(pp, "itdRequest"); final String sessionId = XmlPullUtil.attr(pp, "sessionID"); XmlPullUtil.enter(pp, "itdRequest"); if (XmlPullUtil.test(pp, "clientHeaderLines")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdVersionInfo")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "itdInfoLinkList")) XmlPullUtil.next(pp); if (XmlPullUtil.test(pp, "serverMetaInfo")) XmlPullUtil.next(pp); return sessionId; } }
true
true
protected String parseLine(final String mot, final String name, final String longName, final String noTrainName) { if (mot == null) { if (noTrainName != null) { final String str = name != null ? name : ""; if (noTrainName.equals("S-Bahn")) return 'S' + str; if (noTrainName.equals("U-Bahn")) return 'U' + str; if (noTrainName.equals("Straßenbahn")) return 'T' + str; if (noTrainName.equals("Badner Bahn")) return 'T' + str; if (noTrainName.equals("Stadtbus")) return 'B' + str; if (noTrainName.equals("Citybus")) return 'B' + str; if (noTrainName.equals("Regionalbus")) return 'B' + str; if (noTrainName.equals("ÖBB-Postbus")) return 'B' + str; if (noTrainName.equals("Autobus")) return 'B' + str; if (noTrainName.equals("Discobus")) return 'B' + str; if (noTrainName.equals("Nachtbus")) return 'B' + str; if (noTrainName.equals("Anrufsammeltaxi")) return 'B' + str; if (noTrainName.equals("Ersatzverkehr")) return 'B' + str; if (noTrainName.equals("Vienna Airport Lines")) return 'B' + str; } throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } final int t = Integer.parseInt(mot); if (t == 0) { final String[] parts = longName.split(" ", 3); final String type = parts[0]; final String num = parts.length >= 2 ? parts[1] : null; final String str = type + (num != null ? num : ""); if (type.equals("EC")) // Eurocity return 'I' + str; if (type.equals("EN")) // Euronight return 'I' + str; if (type.equals("IC")) // Intercity return 'I' + str; if (type.equals("ICE")) // Intercity Express return 'I' + str; if (type.equals("X")) // InterConnex return 'I' + str; if (type.equals("CNL")) // City Night Line return 'I' + str; if (type.equals("THA")) // Thalys return 'I' + str; if (type.equals("TGV")) // TGV return 'I' + str; if (type.equals("RJ")) // railjet return 'I' + str; if (type.equals("OEC")) // ÖBB-EuroCity return 'I' + str; if (type.equals("OIC")) // ÖBB-InterCity return 'I' + str; if (type.equals("HT")) // First Hull Trains, GB return 'I' + str; if (type.equals("MT")) // Müller Touren, Schnee Express return 'I' + str; if (type.equals("HKX")) // Hamburg-Koeln-Express return 'I' + str; if (type.equals("DNZ")) // Nachtzug Basel-Moskau return 'I' + str; if (type.equals("IR")) // Interregio return 'R' + str; if (type.equals("IRE")) // Interregio-Express return 'R' + str; if (P_LINE_IRE.matcher(type).matches()) return 'R' + str; if (type.equals("RE")) // Regional-Express return 'R' + str; if (type.equals("R-Bahn")) // Regional-Express, VRR return 'R' + str; if (type.equals("REX")) // RegionalExpress, Österreich return 'R' + str; if ("EZ".equals(type)) // ÖBB ErlebnisBahn return 'R' + str; if (P_LINE_RE.matcher(type).matches()) return 'R' + str; if (type.equals("RB")) // Regionalbahn return 'R' + str; if (P_LINE_RB.matcher(type).matches()) return 'R' + str; if (type.equals("R")) // Regionalzug return 'R' + str; if (P_LINE_R.matcher(type).matches()) return 'R' + str; if (type.equals("Bahn")) return 'R' + str; if (type.equals("Regionalbahn")) return 'R' + str; if (type.equals("D")) // Schnellzug return 'R' + str; if (type.equals("E")) // Eilzug return 'R' + str; if (type.equals("S")) // ~Innsbruck return 'R' + str; if (type.equals("WFB")) // Westfalenbahn return 'R' + str; if ("Westfalenbahn".equals(type)) // Westfalenbahn return 'R' + name; if (type.equals("NWB")) // NordWestBahn return 'R' + str; if (type.equals("NordWestBahn")) return 'R' + str; if (type.equals("ME")) // Metronom return 'R' + str; if (type.equals("ERB")) // eurobahn return 'R' + str; if (type.equals("CAN")) // cantus return 'R' + str; if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt return 'R' + str; if (type.equals("EB")) // Erfurter Bahn return 'R' + str; if (type.equals("MRB")) // Mittelrheinbahn return 'R' + str; if (type.equals("ABR")) // ABELLIO Rail NRW return 'R' + str; if (type.equals("NEB")) // Niederbarnimer Eisenbahn return 'R' + str; if (type.equals("OE")) // Ostdeutsche Eisenbahn return 'R' + str; if (P_LINE_OE.matcher(type).matches()) return 'R' + str; if (type.equals("MR")) // Märkische Regiobahn return 'R' + str; if (type.equals("OLA")) // Ostseeland Verkehr return 'R' + str; if (type.equals("UBB")) // Usedomer Bäderbahn return 'R' + str; if (type.equals("EVB")) // Elbe-Weser return 'R' + str; if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("RTB")) // Rurtalbahn return 'R' + str; if (type.equals("STB")) // Süd-Thüringen-Bahn return 'R' + str; if (type.equals("HTB")) // Hellertalbahn return 'R' + str; if (type.equals("VBG")) // Vogtlandbahn return 'R' + str; if (type.equals("VB")) // Vogtlandbahn return 'R' + str; if (P_LINE_VB.matcher(type).matches()) return 'R' + str; if (type.equals("VX")) // Vogtland Express return 'R' + str; if (type.equals("CB")) // City-Bahn Chemnitz return 'R' + str; if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft return 'R' + str; if (type.equals("HzL")) // Hohenzollerische Landesbahn return 'R' + str; if (type.equals("OSB")) // Ortenau-S-Bahn return 'R' + str; if (type.equals("SBB")) // SBB return 'R' + str; if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli return 'R' + str; if (type.equals("OS")) // Regionalbahn return 'R' + str; if (type.equals("SP")) return 'R' + str; if (type.equals("Dab")) // Daadetalbahn return 'R' + str; if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft return 'R' + str; if (type.equals("ARR")) // ARRIVA return 'R' + str; if (type.equals("HSB")) // Harzer Schmalspurbahn return 'R' + str; if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft return 'R' + str; if (type.equals("ALX")) // Arriva-Länderbahn-Express return 'R' + str; if (type.equals("EX")) // ALX verwandelt sich return 'R' + str; if (type.equals("MEr")) // metronom regional return 'R' + str; if (type.equals("AKN")) // AKN Eisenbahn return 'R' + str; if (type.equals("ZUG")) // Regionalbahn return 'R' + str; if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("VIA")) // VIAS return 'R' + str; if (type.equals("BRB")) // Bayerische Regiobahn return 'R' + str; if (type.equals("BLB")) // Berchtesgadener Land Bahn return 'R' + str; if (type.equals("HLB")) // Hessische Landesbahn return 'R' + str; if (type.equals("NOB")) // NordOstseeBahn return 'R' + str; if (type.equals("WEG")) // Wieslauftalbahn return 'R' + str; if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft return 'R' + str; if (type.equals("VEN")) // Rhenus Veniro return 'R' + str; if (type.equals("DPN")) // Nahreisezug return 'R' + str; if (type.equals("SHB")) // Schleswig-Holstein-Bahn return 'R' + str; if (type.equals("RBG")) // Regental Bahnbetriebs GmbH return 'R' + str; if (type.equals("BOB")) // Bayerische Oberlandbahn return 'R' + str; if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG return 'R' + str; if (type.equals("VE")) // Vetter return 'R' + str; if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft return 'R' + str; if (type.equals("PRE")) // Pressnitztalbahn return 'R' + str; if (type.equals("VEB")) // Vulkan-Eifel-Bahn return 'R' + str; if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft return 'R' + str; if (type.equals("AVG")) // Felsenland-Express return 'R' + str; if (type.equals("ABG")) // Anhaltische Bahngesellschaft return 'R' + str; if (type.equals("LGB")) // Lößnitzgrundbahn return 'R' + str; if (type.equals("LEO")) // Chiemgauer Lokalbahn return 'R' + str; if (type.equals("WTB")) // Weißeritztalbahn return 'R' + str; if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle return 'R' + str; if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen return 'R' + str; if (type.equals("MBS")) // Montafonerbahn return 'R' + str; if (type.equals("EGP")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SBS")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SES")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("agi")) // agilis return 'R' + str; if (type.equals("ag")) // agilis return 'R' + str; if (type.equals("TLX")) // Trilex (Vogtlandbahn) return 'R' + str; if (type.equals("BE")) // Grensland-Express, Niederlande return 'R' + str; if (type.equals("MEL")) // Museums-Eisenbahn Losheim return 'R' + str; if (type.equals("Abellio-Zug")) // Abellio return 'R' + str; if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn? return 'R' + str; if (type.equals("KBS")) // Kursbuchstrecke return 'R' + str; if (type.equals("Zug")) return 'R' + str; if (type.equals("ÖBB")) return 'R' + str; if (type.equals("CAT")) // City Airport Train Wien return 'R' + str; if (type.equals("DZ")) // Dampfzug, STV return 'R' + str; if (type.equals("CD")) return 'R' + str; if (type.equals("PR")) return 'R' + str; if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn) return 'R' + str; if (type.equals("VIAMO")) return 'R' + str; if (type.equals("SE")) // Southeastern, GB return 'R' + str; if (type.equals("SW")) // South West Trains, GB return 'R' + str; if (type.equals("SN")) // Southern, GB return 'R' + str; if (type.equals("NT")) // Northern Rail, GB return 'R' + str; if (type.equals("CH")) // Chiltern Railways, GB return 'R' + str; if (type.equals("EA")) // National Express East Anglia, GB return 'R' + str; if (type.equals("FC")) // First Capital Connect, GB return 'R' + str; if (type.equals("GW")) // First Great Western, GB return 'R' + str; if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("HC")) // Heathrow Connect, GB return 'R' + str; if (type.equals("HX")) // Heathrow Express, GB return 'R' + str; if (type.equals("GX")) // Gatwick Express, GB return 'R' + str; if (type.equals("C2C")) // c2c, GB return 'R' + str; if (type.equals("LM")) // London Midland, GB return 'R' + str; if (type.equals("EM")) // East Midlands Trains, GB return 'R' + str; if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("AW")) // Arriva Trains Wales, GB return 'R' + str; if (type.equals("WS")) // Wrexham & Shropshire, GB return 'R' + str; if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("GC")) // Grand Central, GB return 'R' + str; if (type.equals("IL")) // Island Line, GB return 'R' + str; if (type.equals("BR")) // ??, GB return 'R' + str; if (type.equals("OO")) // ??, GB return 'R' + str; if (type.equals("XX")) // ??, GB return 'R' + str; if (type.equals("XZ")) // ??, GB return 'R' + str; if (type.equals("DB-Zug")) // VRR return 'R' + name; if (type.equals("Regionalexpress")) // VRR return 'R' + name; if ("CAPITOL".equals(name)) // San Francisco return 'R' + name; if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco return "R" + name; if ("Regional Train :".equals(longName)) return "R"; if ("Regional Train".equals(noTrainName)) // Melbourne return "R" + name; if ("Regional".equals(type)) // Melbourne return "R" + name; if (type.equals("ATB")) // Autoschleuse Tauernbahn return 'R' + name; if ("Chiemsee-Bahn".equals(type)) return 'R' + name; if (type.equals("BSB")) // Breisgau-S-Bahn return 'S' + str; if (type.equals("RER")) // Réseau Express Régional, Frankreich return 'S' + str; if (type.equals("LO")) // London Overground, GB return 'S' + str; if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES return 'S' + str; if (P_LINE_U.matcher(type).matches()) return 'U' + str; if ("Underground".equals(type)) // London Underground, GB return 'U' + str; if ("Millbrae / Richmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Millbrae".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / RIchmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART return 'U' + name; if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART return 'U' + name; if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if (type.equals("RT")) // RegioTram return 'T' + str; if (type.equals("STR")) // Nordhausen return 'T' + str; if ("California Cable Car".equals(name)) // San Francisco return 'T' + name; if ("Muni".equals(type)) // San Francisco return 'T' + name; if ("Cable".equals(type)) // San Francisco return 'T' + name; if ("Muni Rail".equals(noTrainName)) // San Francisco return 'T' + name; if ("Cable Car".equals(noTrainName)) // San Francisco return 'T' + name; if (type.equals("BUS")) return 'B' + str; if ("SEV-Bus".equals(type)) return 'B' + str; if ("Bex".equals(type)) // Bayern Express return 'B' + str; if (type.length() == 0) return "?"; if (P_LINE_NUMBER.matcher(type).matches()) return "?"; if (P_LINE_Y.matcher(name).matches()) return "?" + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "' type '" + type + "' str '" + str + "'"); } if (t == 1) { final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); else return 'S' + name; } if (t == 2) return 'U' + name; if (t == 3 || t == 4) return 'T' + name; if (t == 5 || t == 6 || t == 7 || t == 10) { if (name.equals("Schienenersatzverkehr")) return "BSEV"; else return 'B' + name; } if (t == 8) return 'C' + name; if (t == 9) return 'F' + name; if (t == 11 || t == -1) return '?' + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); }
protected String parseLine(final String mot, final String name, final String longName, final String noTrainName) { if (mot == null) { if (noTrainName != null) { final String str = name != null ? name : ""; if (noTrainName.equals("S-Bahn")) return 'S' + str; if (noTrainName.equals("U-Bahn")) return 'U' + str; if (noTrainName.equals("Straßenbahn")) return 'T' + str; if (noTrainName.equals("Badner Bahn")) return 'T' + str; if (noTrainName.equals("Stadtbus")) return 'B' + str; if (noTrainName.equals("Citybus")) return 'B' + str; if (noTrainName.equals("Regionalbus")) return 'B' + str; if (noTrainName.equals("ÖBB-Postbus")) return 'B' + str; if (noTrainName.equals("Autobus")) return 'B' + str; if (noTrainName.equals("Discobus")) return 'B' + str; if (noTrainName.equals("Nachtbus")) return 'B' + str; if (noTrainName.equals("Anrufsammeltaxi")) return 'B' + str; if (noTrainName.equals("Ersatzverkehr")) return 'B' + str; if (noTrainName.equals("Vienna Airport Lines")) return 'B' + str; } throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); } final int t = Integer.parseInt(mot); if (t == 0) { final String[] parts = longName.split(" ", 3); final String type = parts[0]; final String num = parts.length >= 2 ? parts[1] : null; final String str = type + (num != null ? num : ""); if (type.equals("EC")) // Eurocity return 'I' + str; if (type.equals("EN")) // Euronight return 'I' + str; if (type.equals("IC")) // Intercity return 'I' + str; if (type.equals("ICE")) // Intercity Express return 'I' + str; if (type.equals("X")) // InterConnex return 'I' + str; if (type.equals("CNL")) // City Night Line return 'I' + str; if (type.equals("THA")) // Thalys return 'I' + str; if (type.equals("TGV")) // TGV return 'I' + str; if (type.equals("RJ")) // railjet return 'I' + str; if (type.equals("OEC")) // ÖBB-EuroCity return 'I' + str; if (type.equals("OIC")) // ÖBB-InterCity return 'I' + str; if (type.equals("HT")) // First Hull Trains, GB return 'I' + str; if (type.equals("MT")) // Müller Touren, Schnee Express return 'I' + str; if (type.equals("HKX")) // Hamburg-Koeln-Express return 'I' + str; if (type.equals("DNZ")) // Nachtzug Basel-Moskau return 'I' + str; if (type.equals("IR")) // Interregio return 'R' + str; if (type.equals("IRE")) // Interregio-Express return 'R' + str; if (P_LINE_IRE.matcher(type).matches()) return 'R' + str; if (type.equals("RE")) // Regional-Express return 'R' + str; if (type.equals("R-Bahn")) // Regional-Express, VRR return 'R' + str; if (type.equals("REX")) // RegionalExpress, Österreich return 'R' + str; if ("EZ".equals(type)) // ÖBB ErlebnisBahn return 'R' + str; if (P_LINE_RE.matcher(type).matches()) return 'R' + str; if (type.equals("RB")) // Regionalbahn return 'R' + str; if (P_LINE_RB.matcher(type).matches()) return 'R' + str; if (type.equals("R")) // Regionalzug return 'R' + str; if (P_LINE_R.matcher(type).matches()) return 'R' + str; if (type.equals("Bahn")) return 'R' + str; if (type.equals("Regionalbahn")) return 'R' + str; if (type.equals("D")) // Schnellzug return 'R' + str; if (type.equals("E")) // Eilzug return 'R' + str; if (type.equals("S")) // ~Innsbruck return 'R' + str; if (type.equals("WFB")) // Westfalenbahn return 'R' + str; if ("Westfalenbahn".equals(type)) // Westfalenbahn return 'R' + name; if (type.equals("NWB")) // NordWestBahn return 'R' + str; if (type.equals("NordWestBahn")) return 'R' + str; if (type.equals("ME")) // Metronom return 'R' + str; if (type.equals("ERB")) // eurobahn return 'R' + str; if (type.equals("CAN")) // cantus return 'R' + str; if (type.equals("HEX")) // Veolia Verkehr Sachsen-Anhalt return 'R' + str; if (type.equals("EB")) // Erfurter Bahn return 'R' + str; if (type.equals("MRB")) // Mittelrheinbahn return 'R' + str; if (type.equals("ABR")) // ABELLIO Rail NRW return 'R' + str; if (type.equals("NEB")) // Niederbarnimer Eisenbahn return 'R' + str; if (type.equals("OE")) // Ostdeutsche Eisenbahn return 'R' + str; if (P_LINE_OE.matcher(type).matches()) return 'R' + str; if (type.equals("MR")) // Märkische Regiobahn return 'R' + str; if (type.equals("OLA")) // Ostseeland Verkehr return 'R' + str; if (type.equals("UBB")) // Usedomer Bäderbahn return 'R' + str; if (type.equals("EVB")) // Elbe-Weser return 'R' + str; if (type.equals("PEG")) // Prignitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("RTB")) // Rurtalbahn return 'R' + str; if (type.equals("STB")) // Süd-Thüringen-Bahn return 'R' + str; if (type.equals("HTB")) // Hellertalbahn return 'R' + str; if (type.equals("VBG")) // Vogtlandbahn return 'R' + str; if (type.equals("VB")) // Vogtlandbahn return 'R' + str; if (P_LINE_VB.matcher(type).matches()) return 'R' + str; if (type.equals("VX")) // Vogtland Express return 'R' + str; if (type.equals("CB")) // City-Bahn Chemnitz return 'R' + str; if (type.equals("VEC")) // VECTUS Verkehrsgesellschaft return 'R' + str; if (type.equals("HzL")) // Hohenzollerische Landesbahn return 'R' + str; if (type.equals("OSB")) // Ortenau-S-Bahn return 'R' + str; if (type.equals("SBB")) // SBB return 'R' + str; if (type.equals("MBB")) // Mecklenburgische Bäderbahn Molli return 'R' + str; if (type.equals("OS")) // Regionalbahn return 'R' + str; if (type.equals("SP")) return 'R' + str; if (type.equals("Dab")) // Daadetalbahn return 'R' + str; if (type.equals("FEG")) // Freiberger Eisenbahngesellschaft return 'R' + str; if (type.equals("ARR")) // ARRIVA return 'R' + str; if (type.equals("HSB")) // Harzer Schmalspurbahn return 'R' + str; if (type.equals("SBE")) // Sächsisch-Böhmische Eisenbahngesellschaft return 'R' + str; if (type.equals("ALX")) // Arriva-Länderbahn-Express return 'R' + str; if (type.equals("EX")) // ALX verwandelt sich return 'R' + str; if (type.equals("MEr")) // metronom regional return 'R' + str; if (type.equals("AKN")) // AKN Eisenbahn return 'R' + str; if (type.equals("ZUG")) // Regionalbahn return 'R' + str; if (type.equals("SOE")) // Sächsisch-Oberlausitzer Eisenbahngesellschaft return 'R' + str; if (type.equals("VIA")) // VIAS return 'R' + str; if (type.equals("BRB")) // Bayerische Regiobahn return 'R' + str; if (type.equals("BLB")) // Berchtesgadener Land Bahn return 'R' + str; if (type.equals("HLB")) // Hessische Landesbahn return 'R' + str; if (type.equals("NOB")) // NordOstseeBahn return 'R' + str; if (type.equals("WEG")) // Wieslauftalbahn return 'R' + str; if (type.equals("NBE")) // Nordbahn Eisenbahngesellschaft return 'R' + str; if (type.equals("VEN")) // Rhenus Veniro return 'R' + str; if (type.equals("DPN")) // Nahreisezug return 'R' + str; if (type.equals("SHB")) // Schleswig-Holstein-Bahn return 'R' + str; if (type.equals("RBG")) // Regental Bahnbetriebs GmbH return 'R' + str; if (type.equals("BOB")) // Bayerische Oberlandbahn return 'R' + str; if (type.equals("SWE")) // Südwestdeutsche Verkehrs AG return 'R' + str; if (type.equals("VE")) // Vetter return 'R' + str; if (type.equals("SDG")) // Sächsische Dampfeisenbahngesellschaft return 'R' + str; if (type.equals("PRE")) // Pressnitztalbahn return 'R' + str; if (type.equals("VEB")) // Vulkan-Eifel-Bahn return 'R' + str; if (type.equals("neg")) // Norddeutsche Eisenbahn Gesellschaft return 'R' + str; if (type.equals("AVG")) // Felsenland-Express return 'R' + str; if (type.equals("ABG")) // Anhaltische Bahngesellschaft return 'R' + str; if (type.equals("LGB")) // Lößnitzgrundbahn return 'R' + str; if (type.equals("LEO")) // Chiemgauer Lokalbahn return 'R' + str; if (type.equals("WTB")) // Weißeritztalbahn return 'R' + str; if (type.equals("P")) // Kasbachtalbahn, Wanderbahn im Regental, Rhön-Zügle return 'R' + str; if (type.equals("ÖBA")) // Eisenbahn-Betriebsgesellschaft Ochsenhausen return 'R' + str; if (type.equals("MBS")) // Montafonerbahn return 'R' + str; if (type.equals("EGP")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SBS")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("SES")) // EGP - die Städtebahn GmbH return 'R' + str; if (type.equals("agi")) // agilis return 'R' + str; if (type.equals("ag")) // agilis return 'R' + str; if (type.equals("TLX")) // Trilex (Vogtlandbahn) return 'R' + str; if (type.equals("BE")) // Grensland-Express, Niederlande return 'R' + str; if (type.equals("MEL")) // Museums-Eisenbahn Losheim return 'R' + str; if (type.equals("Abellio-Zug")) // Abellio return 'R' + str; if ("SWEG-Zug".equals(type)) // Südwestdeutschen Verkehrs-Aktiengesellschaft, evtl. S-Bahn? return 'R' + str; if (type.equals("KBS")) // Kursbuchstrecke return 'R' + str; if (type.equals("Zug")) return 'R' + str; if (type.equals("ÖBB")) return 'R' + str; if (type.equals("CAT")) // City Airport Train Wien return 'R' + str; if (type.equals("DZ")) // Dampfzug, STV return 'R' + str; if (type.equals("CD")) return 'R' + str; if (type.equals("PR")) return 'R' + str; if (type.equals("KD")) // Koleje Dolnośląskie (Niederschlesische Eisenbahn) return 'R' + str; if (type.equals("VIAMO")) return 'R' + str; if (type.equals("SE")) // Southeastern, GB return 'R' + str; if (type.equals("SW")) // South West Trains, GB return 'R' + str; if (type.equals("SN")) // Southern, GB return 'R' + str; if (type.equals("NT")) // Northern Rail, GB return 'R' + str; if (type.equals("CH")) // Chiltern Railways, GB return 'R' + str; if (type.equals("EA")) // National Express East Anglia, GB return 'R' + str; if (type.equals("FC")) // First Capital Connect, GB return 'R' + str; if (type.equals("GW")) // First Great Western, GB return 'R' + str; if (type.equals("XC")) // Cross Country, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("HC")) // Heathrow Connect, GB return 'R' + str; if (type.equals("HX")) // Heathrow Express, GB return 'R' + str; if (type.equals("GX")) // Gatwick Express, GB return 'R' + str; if (type.equals("C2C")) // c2c, GB return 'R' + str; if (type.equals("LM")) // London Midland, GB return 'R' + str; if (type.equals("EM")) // East Midlands Trains, GB return 'R' + str; if (type.equals("VT")) // Virgin Trains, GB, evtl. auch highspeed? return 'R' + str; if (type.equals("SR")) // ScotRail, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("AW")) // Arriva Trains Wales, GB return 'R' + str; if (type.equals("WS")) // Wrexham & Shropshire, GB return 'R' + str; if (type.equals("TP")) // First TransPennine Express, GB, evtl. auch long-distance? return 'R' + str; if (type.equals("GC")) // Grand Central, GB return 'R' + str; if (type.equals("IL")) // Island Line, GB return 'R' + str; if (type.equals("BR")) // ??, GB return 'R' + str; if (type.equals("OO")) // ??, GB return 'R' + str; if (type.equals("XX")) // ??, GB return 'R' + str; if (type.equals("XZ")) // ??, GB return 'R' + str; if (type.equals("DB-Zug")) // VRR return 'R' + name; if (type.equals("Regionalexpress")) // VRR return 'R' + name; if ("CAPITOL".equals(name)) // San Francisco return 'R' + name; if ("Train".equals(noTrainName) || "Train".equals(type)) // San Francisco return "R" + name; if ("Regional Train :".equals(longName)) return "R"; if ("Regional Train".equals(noTrainName)) // Melbourne return "R" + name; if ("Regional".equals(type)) // Melbourne return "R" + name; if (type.equals("ATB")) // Autoschleuse Tauernbahn return 'R' + name; if ("Chiemsee-Bahn".equals(type)) return 'R' + name; if (type.equals("BSB")) // Breisgau-S-Bahn return 'S' + str; if (type.equals("RER")) // Réseau Express Régional, Frankreich return 'S' + str; if (type.equals("LO")) // London Overground, GB return 'S' + str; if ("A".equals(name) || "B".equals(name) || "C".equals(name)) // SES return 'S' + str; final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); if (P_LINE_U.matcher(type).matches()) return 'U' + str; if ("Underground".equals(type)) // London Underground, GB return 'U' + str; if ("Millbrae / Richmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Millbrae".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / RIchmond".equals(name)) // San Francisco, BART return 'U' + name; if ("Richmond / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if ("Pittsburg Bay Point / SFO".equals(name)) // San Francisco, BART return 'U' + name; if ("SFO / Pittsburg Bay Point".equals(name)) // San Francisco, BART return 'U' + name; if ("Dublin Pleasanton / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Dublin Pleasanton".equals(name)) // San Francisco, BART return 'U' + name; if ("Fremont / Daly City".equals(name)) // San Francisco, BART return 'U' + name; if ("Daly City / Fremont".equals(name)) // San Francisco, BART return 'U' + name; if (type.equals("RT")) // RegioTram return 'T' + str; if (type.equals("STR")) // Nordhausen return 'T' + str; if ("California Cable Car".equals(name)) // San Francisco return 'T' + name; if ("Muni".equals(type)) // San Francisco return 'T' + name; if ("Cable".equals(type)) // San Francisco return 'T' + name; if ("Muni Rail".equals(noTrainName)) // San Francisco return 'T' + name; if ("Cable Car".equals(noTrainName)) // San Francisco return 'T' + name; if (type.equals("BUS")) return 'B' + str; if ("SEV-Bus".equals(type)) return 'B' + str; if ("Bex".equals(type)) // Bayern Express return 'B' + str; if (type.length() == 0) return "?"; if (P_LINE_NUMBER.matcher(type).matches()) return "?"; if (P_LINE_Y.matcher(name).matches()) return "?" + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "' type '" + type + "' str '" + str + "'"); } if (t == 1) { final Matcher m = P_LINE_S.matcher(name); if (m.find()) return 'S' + m.group(1); else return 'S' + name; } if (t == 2) return 'U' + name; if (t == 3 || t == 4) return 'T' + name; if (t == 5 || t == 6 || t == 7 || t == 10) { if (name.equals("Schienenersatzverkehr")) return "BSEV"; else return 'B' + name; } if (t == 8) return 'C' + name; if (t == 9) return 'F' + name; if (t == 11 || t == -1) return '?' + name; throw new IllegalStateException("cannot normalize mot '" + mot + "' name '" + name + "' long '" + longName + "' noTrainName '" + noTrainName + "'"); }
diff --git a/src/main/java/mikera/gui/BackgroundPanel.java b/src/main/java/mikera/gui/BackgroundPanel.java index a7ea7f2..cbf7153 100644 --- a/src/main/java/mikera/gui/BackgroundPanel.java +++ b/src/main/java/mikera/gui/BackgroundPanel.java @@ -1,49 +1,49 @@ package mikera.gui; import java.awt.Graphics; import java.awt.LayoutManager; import java.awt.Rectangle; import java.awt.image.BufferedImage; import javax.swing.JPanel; /** * Simple GUI component - panel with a tiled background * @author Mike * */ public class BackgroundPanel extends JPanel { private BufferedImage image=null; public BackgroundPanel() { super(); } public void setImage(BufferedImage b) { this.image=b; } public BufferedImage getImage() { return this.image; } public BackgroundPanel(LayoutManager layout) { super(layout); } @Override public void paintComponent(Graphics g) { if (image==null) return; Rectangle r=g.getClipBounds(); int w=image.getWidth(); int h=image.getHeight(); - for (int x=r.x/w; x<(r.x+r.width); x+=w) { - for (int y=r.y/h; y<(r.y+r.height); y+=h) { + for (int x=(r.x/w)*w; x<(r.x+r.width); x+=w) { + for (int y=(r.y/h)*h; y<(r.y+r.height); y+=h) { g.drawImage(image, x, y, null); } } } }
true
true
public void paintComponent(Graphics g) { if (image==null) return; Rectangle r=g.getClipBounds(); int w=image.getWidth(); int h=image.getHeight(); for (int x=r.x/w; x<(r.x+r.width); x+=w) { for (int y=r.y/h; y<(r.y+r.height); y+=h) { g.drawImage(image, x, y, null); } } }
public void paintComponent(Graphics g) { if (image==null) return; Rectangle r=g.getClipBounds(); int w=image.getWidth(); int h=image.getHeight(); for (int x=(r.x/w)*w; x<(r.x+r.width); x+=w) { for (int y=(r.y/h)*h; y<(r.y+r.height); y+=h) { g.drawImage(image, x, y, null); } } }
diff --git a/src/main/java/com/ctlok/springframework/web/servlet/view/rythm/tag/CookieValue.java b/src/main/java/com/ctlok/springframework/web/servlet/view/rythm/tag/CookieValue.java index ce2dd68..814112c 100644 --- a/src/main/java/com/ctlok/springframework/web/servlet/view/rythm/tag/CookieValue.java +++ b/src/main/java/com/ctlok/springframework/web/servlet/view/rythm/tag/CookieValue.java @@ -1,47 +1,47 @@ package com.ctlok.springframework.web.servlet.view.rythm.tag; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.rythmengine.template.JavaTagBase; import com.ctlok.springframework.web.servlet.view.rythm.Helper; /** * * @author Lawrence Cheung * */ public class CookieValue extends JavaTagBase { @Override public String __getName() { return "cookieValue"; } @Override protected void call(__ParameterList params, __Body body) { final HttpServletRequest request = Helper.getCurrentRequest(); final String name = (String) params.getDefault(); String value = ""; - if (request!= null){ + if (request != null && request.getCookies() != null){ for (final Cookie cookie: request.getCookies()){ if (cookie.getName().equals(name)){ value = cookie.getValue(); } } } this.p(value); } }
true
true
protected void call(__ParameterList params, __Body body) { final HttpServletRequest request = Helper.getCurrentRequest(); final String name = (String) params.getDefault(); String value = ""; if (request!= null){ for (final Cookie cookie: request.getCookies()){ if (cookie.getName().equals(name)){ value = cookie.getValue(); } } } this.p(value); }
protected void call(__ParameterList params, __Body body) { final HttpServletRequest request = Helper.getCurrentRequest(); final String name = (String) params.getDefault(); String value = ""; if (request != null && request.getCookies() != null){ for (final Cookie cookie: request.getCookies()){ if (cookie.getName().equals(name)){ value = cookie.getValue(); } } } this.p(value); }
diff --git a/htroot/ViewFile.java b/htroot/ViewFile.java index bdcb397aa..fe4e76ecc 100644 --- a/htroot/ViewFile.java +++ b/htroot/ViewFile.java @@ -1,417 +1,417 @@ //ViewFile.java //----------------------- //part of YaCy //(C) by Michael Peter Christen; mc@anomic.de //first published on http://www.anomic.de //Frankfurt, Germany, 2004 //last major change: 12.07.2004 //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 //Using this software in any meaning (reading, learning, copying, compiling, //running) means that you agree that the Author(s) is (are) not responsible //for cost, loss of data or any harm that may be caused directly or indirectly //by usage of this softare or this documentation. The usage of this software //is on your own risk. The installation and usage (starting/running) of this //software may allow other people or application to access your computer and //any attached devices and is highly dependent on the configuration of the //software which must be done by the user of the software; the author(s) is //(are) also not responsible for proper configuration and usage of the //software, even if provoked by documentation provided together with //the software. //Any changes to this file according to the GPL as documented in the file //gpl.txt aside this file in the shipment you received can be done to the //lines that follows this copyright notice here, but changes must not be //done inside the copyright notive above. A re-distribution must contain //the intact and unchanged copyright notice. //Contributions and changes to the program code must be marked as such. //you must compile this file with //javac -classpath .:../Classes Status.java //if the shell's current path is HTROOT import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import de.anomic.data.wikiCode; import de.anomic.htmlFilter.htmlFilterImageEntry; import de.anomic.http.httpHeader; import de.anomic.http.httpc; import de.anomic.index.indexURLEntry; import de.anomic.net.URL; import de.anomic.plasma.plasmaCondenser; import de.anomic.plasma.plasmaHTCache; import de.anomic.plasma.plasmaParserDocument; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.plasma.cache.IResourceInfo; import de.anomic.plasma.crawler.plasmaCrawlerException; import de.anomic.plasma.parser.ParserException; import de.anomic.server.serverFileUtils; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; public class ViewFile { public static final int VIEW_MODE_NO_TEXT = 0; public static final int VIEW_MODE_AS_PLAIN_TEXT = 1; public static final int VIEW_MODE_AS_PARSED_TEXT = 2; public static final int VIEW_MODE_AS_PARSED_SENTENCES = 3; public static final int VIEW_MODE_AS_IFRAME = 4; public static final int VIEW_MODE_AS_LINKLIST = 5; private static final String HIGHLIGHT_CSS = "searchHighlight"; private static final int MAX_HIGHLIGHTS = 6; public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard sb = (plasmaSwitchboard)env; if (post != null && post.containsKey("words")) prop.put("error_words", wikiCode.replaceHTMLonly((String)post.get("words"))); else { prop.put("error", 1); prop.put("viewmode", 0); return prop; } String viewMode = post.get("viewMode","sentences"); prop.put("error_vMode-" + viewMode, 1); URL url = null; String descr = ""; int wordCount = 0; int size = 0; boolean pre = false; // getting the url hash from which the content should be loaded String urlHash = post.get("urlHash",""); if (urlHash.length() > 0) { // getting the urlEntry that belongs to the url hash indexURLEntry urlEntry = null; urlEntry = sb.wordIndex.loadedURL.load(urlHash, null); if (urlEntry == null) { prop.put("error",2); prop.put("viewMode",VIEW_MODE_NO_TEXT); return prop; } // gettin the url that belongs to the entry indexURLEntry.Components comp = urlEntry.comp(); if ((comp == null) || (comp.url() == null)) { prop.put("error", 3); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } url = comp.url(); descr = comp.descr(); urlEntry.wordCount(); size = urlEntry.size(); pre = urlEntry.flags().get(plasmaCondenser.flag_cat_indexof); } // alternatively, get the url simply from a url String // this can be used as a simple tool to test the text parser String urlString = post.get("url", ""); if (urlString.length() > 0) try { // this call forces the peer to download web pages // it is therefore protected by the admin password if (!sb.verifyAuthentication(header, false)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // define an url by post parameter url = new URL(urlString); pre = post.get("pre", "false").equals("true"); } catch (MalformedURLException e) {} if (url == null) { prop.put("error", 1); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } // loading the resource content as byte array InputStream resource = null; long resourceLength = -1; IResourceInfo resInfo = null; String resMime = null; try { // trying to load the resource body resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); // if the resource body was not cached we try to load it from web if (resource == null) { plasmaHTCache.Entry entry = null; try { entry = sb.snippetCache.loadResourceFromWeb(url, 5000, false, true); } catch (plasmaCrawlerException e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (entry != null) { resInfo = entry.getDocumentInfo(); resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); } if (resource == null) { prop.put("error", 4); prop.put("error_errorText", "No resource available"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } // try to load resource metadata if (resInfo == null) { // try to load the metadata from cache try { resInfo = sb.cacheManager.loadResourceInfo(url); } catch (Exception e) { /* ignore this */ } // if the metadata was not cached try to load it from web if (resInfo == null) { String protocol = url.getProtocol(); if (!((protocol.equals("http") || protocol.equals("https")))) { prop.put("error", 6); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } httpHeader responseHeader = httpc.whead(url, url.getHost(), 5000, null, null, sb.remoteProxyConfig); if (responseHeader == null) { prop.put("error", 4); prop.put("error_errorText", "Unable to load resource metadata."); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } try { resInfo = sb.cacheManager.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } resMime = responseHeader.mime(); } } else { resMime = resInfo.getMimeType(); } } catch (IOException e) { if (resource != null) try { resource.close(); } catch (Exception ex) { /* ignore this */ } prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (viewMode.equals("plain")) { // TODO: how to handle very large files here ? String content; try { content = new String(serverFileUtils.read(resource), "UTF-8"); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } content = wikiCode.replaceHTMLonly( content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")); prop.put("error", 0); prop.put("viewMode", VIEW_MODE_AS_PLAIN_TEXT); prop.put("viewMode_plainText", content); } else if (viewMode.equals("iframe")) { prop.put("viewMode", VIEW_MODE_AS_IFRAME); prop.put("viewMode_url", wikiCode.replaceHTMLonly(url.toNormalform())); } else if (viewMode.equals("parsed") || viewMode.equals("sentences") || viewMode.equals("links")) { // parsing the resource content plasmaParserDocument document = null; try { document = sb.snippetCache.parseDocument(url, resourceLength, resource, resInfo); if (document == null) { prop.put("error", 5); prop.put("error_errorText", "Unknown error"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } catch (ParserException e) { prop.put("error", 5); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } resMime = document.getMimeType(); String[] wordArray = wordArray(post.get("words", null)); if (viewMode.equals("parsed")) { String content = new String(document.getTextBytes()); content = wikiCode.replaceHTML(content); // added by Marc Nause content = content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); prop.put("viewMode", VIEW_MODE_AS_PARSED_TEXT); prop.put("viewMode_parsedText", markup(wordArray, content)); } else if (viewMode.equals("sentences")) { prop.put("viewMode", VIEW_MODE_AS_PARSED_SENTENCES); final Iterator sentences = document.getSentences(pre); boolean dark = true; int i = 0; String sentence; if (sentences != null) { // Search word highlighting while (sentences.hasNext()) { sentence = (String)sentences.next(); if (sentence.trim().length() > 0) { prop.put("viewMode_sentences_" + i + "_nr", Integer.toString(i + 1)); - prop.put("viewMode_sentences_" + i + "_text", markup(wordArray, (String) sentences.next())); + prop.put("viewMode_sentences_" + i + "_text", markup(wordArray, sentence)); prop.put("viewMode_sentences_" + i + "_dark", ((dark) ? 1 : 0)); dark = !dark; i++; } } } prop.put("viewMode_sentences", i); } else if (viewMode.equals("links")) { prop.put("viewMode", VIEW_MODE_AS_LINKLIST); boolean dark = true; int i = 0; i += putMediaInfo(prop, wordArray, i, document.getVideolinks(), "video", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getAudiolinks(), "audio", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getApplinks(), "app", (i % 2 == 0)); dark = (i % 2 == 0); TreeSet ts = document.getImages(); Iterator tsi = ts.iterator(); htmlFilterImageEntry entry; while (tsi.hasNext()) { entry = (htmlFilterImageEntry) tsi.next(); prop.put("viewMode_links_" + i + "_nr", i); prop.put("viewMode_links_" + i + "_dark", ((dark) ? 1 : 0)); prop.put("viewMode_links_" + i + "_type", "image"); prop.put("viewMode_links_" + i + "_text", markup(wordArray, entry.alt())); prop.put("viewMode_links_" + i + "_link", "<a href=\"" + (String) entry.url().toNormalform() + "\">" + markup(wordArray, (String) entry.url().toNormalform()) + "</a>"); prop.put("viewMode_links_" + i + "_attr", entry.width() + "&nbsp;x&nbsp;" + entry.height()); dark = !dark; i++; } prop.put("viewMode_links", i); } if (document != null) document.close(); } prop.put("error", 0); prop.put("error_url", wikiCode.replaceHTMLonly(url.toNormalform())); prop.put("error_hash", urlHash); prop.put("error_wordCount", Integer.toString(wordCount)); prop.put("error_desc", descr); prop.put("error_size", size); prop.put("error_mimeTypeAvailable", (resMime == null) ? 0 : 1); prop.put("error_mimeTypeAvailable_mimeType", resMime); return prop; } private static final String[] wordArray(String words) { String[] w = null; if (words != null) try { words = URLDecoder.decode(words, "UTF-8"); w = words.substring(1, words.length() - 1).split(","); if (w.length == 0) return null; } catch (UnsupportedEncodingException e) {} return w; } private static final String markup(String[] wordArray, String message) { message = wikiCode.replaceHTML(message); if (wordArray != null) for (int j = 0; j < wordArray.length; j++) { String currentWord = wordArray[j].trim(); message = message.replaceAll(currentWord, "<span class=\"" + HIGHLIGHT_CSS + ((j % MAX_HIGHLIGHTS) + 1) + "\">" + currentWord + "</span>"); } return message; } private static int putMediaInfo(serverObjects prop, String[] wordArray, int c, Map media, String name, boolean dark) { Iterator mi = media.entrySet().iterator(); Map.Entry entry; int i = 0; while (mi.hasNext()) { entry = (Map.Entry) mi.next(); prop.put("viewMode_links_" + c + "_nr", c); prop.put("viewMode_links_" + c + "_dark", ((dark) ? 1 : 0)); prop.put("viewMode_links_" + c + "_type", name); prop.put("viewMode_links_" + c + "_text", markup(wordArray, (String) entry.getValue())); prop.put("viewMode_links_" + c + "_link", "<a href=\"" + (String) entry.getKey() + "\">" + markup(wordArray, (String) entry.getKey()) + "</a>"); prop.put("viewMode_links_" + c + "_attr", ""); dark = !dark; c++; i++; } return i; } }
true
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard sb = (plasmaSwitchboard)env; if (post != null && post.containsKey("words")) prop.put("error_words", wikiCode.replaceHTMLonly((String)post.get("words"))); else { prop.put("error", 1); prop.put("viewmode", 0); return prop; } String viewMode = post.get("viewMode","sentences"); prop.put("error_vMode-" + viewMode, 1); URL url = null; String descr = ""; int wordCount = 0; int size = 0; boolean pre = false; // getting the url hash from which the content should be loaded String urlHash = post.get("urlHash",""); if (urlHash.length() > 0) { // getting the urlEntry that belongs to the url hash indexURLEntry urlEntry = null; urlEntry = sb.wordIndex.loadedURL.load(urlHash, null); if (urlEntry == null) { prop.put("error",2); prop.put("viewMode",VIEW_MODE_NO_TEXT); return prop; } // gettin the url that belongs to the entry indexURLEntry.Components comp = urlEntry.comp(); if ((comp == null) || (comp.url() == null)) { prop.put("error", 3); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } url = comp.url(); descr = comp.descr(); urlEntry.wordCount(); size = urlEntry.size(); pre = urlEntry.flags().get(plasmaCondenser.flag_cat_indexof); } // alternatively, get the url simply from a url String // this can be used as a simple tool to test the text parser String urlString = post.get("url", ""); if (urlString.length() > 0) try { // this call forces the peer to download web pages // it is therefore protected by the admin password if (!sb.verifyAuthentication(header, false)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // define an url by post parameter url = new URL(urlString); pre = post.get("pre", "false").equals("true"); } catch (MalformedURLException e) {} if (url == null) { prop.put("error", 1); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } // loading the resource content as byte array InputStream resource = null; long resourceLength = -1; IResourceInfo resInfo = null; String resMime = null; try { // trying to load the resource body resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); // if the resource body was not cached we try to load it from web if (resource == null) { plasmaHTCache.Entry entry = null; try { entry = sb.snippetCache.loadResourceFromWeb(url, 5000, false, true); } catch (plasmaCrawlerException e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (entry != null) { resInfo = entry.getDocumentInfo(); resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); } if (resource == null) { prop.put("error", 4); prop.put("error_errorText", "No resource available"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } // try to load resource metadata if (resInfo == null) { // try to load the metadata from cache try { resInfo = sb.cacheManager.loadResourceInfo(url); } catch (Exception e) { /* ignore this */ } // if the metadata was not cached try to load it from web if (resInfo == null) { String protocol = url.getProtocol(); if (!((protocol.equals("http") || protocol.equals("https")))) { prop.put("error", 6); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } httpHeader responseHeader = httpc.whead(url, url.getHost(), 5000, null, null, sb.remoteProxyConfig); if (responseHeader == null) { prop.put("error", 4); prop.put("error_errorText", "Unable to load resource metadata."); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } try { resInfo = sb.cacheManager.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } resMime = responseHeader.mime(); } } else { resMime = resInfo.getMimeType(); } } catch (IOException e) { if (resource != null) try { resource.close(); } catch (Exception ex) { /* ignore this */ } prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (viewMode.equals("plain")) { // TODO: how to handle very large files here ? String content; try { content = new String(serverFileUtils.read(resource), "UTF-8"); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } content = wikiCode.replaceHTMLonly( content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")); prop.put("error", 0); prop.put("viewMode", VIEW_MODE_AS_PLAIN_TEXT); prop.put("viewMode_plainText", content); } else if (viewMode.equals("iframe")) { prop.put("viewMode", VIEW_MODE_AS_IFRAME); prop.put("viewMode_url", wikiCode.replaceHTMLonly(url.toNormalform())); } else if (viewMode.equals("parsed") || viewMode.equals("sentences") || viewMode.equals("links")) { // parsing the resource content plasmaParserDocument document = null; try { document = sb.snippetCache.parseDocument(url, resourceLength, resource, resInfo); if (document == null) { prop.put("error", 5); prop.put("error_errorText", "Unknown error"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } catch (ParserException e) { prop.put("error", 5); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } resMime = document.getMimeType(); String[] wordArray = wordArray(post.get("words", null)); if (viewMode.equals("parsed")) { String content = new String(document.getTextBytes()); content = wikiCode.replaceHTML(content); // added by Marc Nause content = content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); prop.put("viewMode", VIEW_MODE_AS_PARSED_TEXT); prop.put("viewMode_parsedText", markup(wordArray, content)); } else if (viewMode.equals("sentences")) { prop.put("viewMode", VIEW_MODE_AS_PARSED_SENTENCES); final Iterator sentences = document.getSentences(pre); boolean dark = true; int i = 0; String sentence; if (sentences != null) { // Search word highlighting while (sentences.hasNext()) { sentence = (String)sentences.next(); if (sentence.trim().length() > 0) { prop.put("viewMode_sentences_" + i + "_nr", Integer.toString(i + 1)); prop.put("viewMode_sentences_" + i + "_text", markup(wordArray, (String) sentences.next())); prop.put("viewMode_sentences_" + i + "_dark", ((dark) ? 1 : 0)); dark = !dark; i++; } } } prop.put("viewMode_sentences", i); } else if (viewMode.equals("links")) { prop.put("viewMode", VIEW_MODE_AS_LINKLIST); boolean dark = true; int i = 0; i += putMediaInfo(prop, wordArray, i, document.getVideolinks(), "video", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getAudiolinks(), "audio", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getApplinks(), "app", (i % 2 == 0)); dark = (i % 2 == 0); TreeSet ts = document.getImages(); Iterator tsi = ts.iterator(); htmlFilterImageEntry entry; while (tsi.hasNext()) { entry = (htmlFilterImageEntry) tsi.next(); prop.put("viewMode_links_" + i + "_nr", i); prop.put("viewMode_links_" + i + "_dark", ((dark) ? 1 : 0)); prop.put("viewMode_links_" + i + "_type", "image"); prop.put("viewMode_links_" + i + "_text", markup(wordArray, entry.alt())); prop.put("viewMode_links_" + i + "_link", "<a href=\"" + (String) entry.url().toNormalform() + "\">" + markup(wordArray, (String) entry.url().toNormalform()) + "</a>"); prop.put("viewMode_links_" + i + "_attr", entry.width() + "&nbsp;x&nbsp;" + entry.height()); dark = !dark; i++; } prop.put("viewMode_links", i); } if (document != null) document.close(); } prop.put("error", 0); prop.put("error_url", wikiCode.replaceHTMLonly(url.toNormalform())); prop.put("error_hash", urlHash); prop.put("error_wordCount", Integer.toString(wordCount)); prop.put("error_desc", descr); prop.put("error_size", size); prop.put("error_mimeTypeAvailable", (resMime == null) ? 0 : 1); prop.put("error_mimeTypeAvailable_mimeType", resMime); return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard sb = (plasmaSwitchboard)env; if (post != null && post.containsKey("words")) prop.put("error_words", wikiCode.replaceHTMLonly((String)post.get("words"))); else { prop.put("error", 1); prop.put("viewmode", 0); return prop; } String viewMode = post.get("viewMode","sentences"); prop.put("error_vMode-" + viewMode, 1); URL url = null; String descr = ""; int wordCount = 0; int size = 0; boolean pre = false; // getting the url hash from which the content should be loaded String urlHash = post.get("urlHash",""); if (urlHash.length() > 0) { // getting the urlEntry that belongs to the url hash indexURLEntry urlEntry = null; urlEntry = sb.wordIndex.loadedURL.load(urlHash, null); if (urlEntry == null) { prop.put("error",2); prop.put("viewMode",VIEW_MODE_NO_TEXT); return prop; } // gettin the url that belongs to the entry indexURLEntry.Components comp = urlEntry.comp(); if ((comp == null) || (comp.url() == null)) { prop.put("error", 3); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } url = comp.url(); descr = comp.descr(); urlEntry.wordCount(); size = urlEntry.size(); pre = urlEntry.flags().get(plasmaCondenser.flag_cat_indexof); } // alternatively, get the url simply from a url String // this can be used as a simple tool to test the text parser String urlString = post.get("url", ""); if (urlString.length() > 0) try { // this call forces the peer to download web pages // it is therefore protected by the admin password if (!sb.verifyAuthentication(header, false)) { prop.put("AUTHENTICATE", "admin log-in"); // force log-in return prop; } // define an url by post parameter url = new URL(urlString); pre = post.get("pre", "false").equals("true"); } catch (MalformedURLException e) {} if (url == null) { prop.put("error", 1); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } // loading the resource content as byte array InputStream resource = null; long resourceLength = -1; IResourceInfo resInfo = null; String resMime = null; try { // trying to load the resource body resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); // if the resource body was not cached we try to load it from web if (resource == null) { plasmaHTCache.Entry entry = null; try { entry = sb.snippetCache.loadResourceFromWeb(url, 5000, false, true); } catch (plasmaCrawlerException e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (entry != null) { resInfo = entry.getDocumentInfo(); resource = sb.cacheManager.getResourceContentStream(url); resourceLength = sb.cacheManager.getResourceContentLength(url); } if (resource == null) { prop.put("error", 4); prop.put("error_errorText", "No resource available"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } // try to load resource metadata if (resInfo == null) { // try to load the metadata from cache try { resInfo = sb.cacheManager.loadResourceInfo(url); } catch (Exception e) { /* ignore this */ } // if the metadata was not cached try to load it from web if (resInfo == null) { String protocol = url.getProtocol(); if (!((protocol.equals("http") || protocol.equals("https")))) { prop.put("error", 6); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } httpHeader responseHeader = httpc.whead(url, url.getHost(), 5000, null, null, sb.remoteProxyConfig); if (responseHeader == null) { prop.put("error", 4); prop.put("error_errorText", "Unable to load resource metadata."); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } try { resInfo = sb.cacheManager.getResourceInfoFactory().buildResourceInfoObj(url, responseHeader); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } resMime = responseHeader.mime(); } } else { resMime = resInfo.getMimeType(); } } catch (IOException e) { if (resource != null) try { resource.close(); } catch (Exception ex) { /* ignore this */ } prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } if (viewMode.equals("plain")) { // TODO: how to handle very large files here ? String content; try { content = new String(serverFileUtils.read(resource), "UTF-8"); } catch (Exception e) { prop.put("error", 4); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } content = wikiCode.replaceHTMLonly( content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;")); prop.put("error", 0); prop.put("viewMode", VIEW_MODE_AS_PLAIN_TEXT); prop.put("viewMode_plainText", content); } else if (viewMode.equals("iframe")) { prop.put("viewMode", VIEW_MODE_AS_IFRAME); prop.put("viewMode_url", wikiCode.replaceHTMLonly(url.toNormalform())); } else if (viewMode.equals("parsed") || viewMode.equals("sentences") || viewMode.equals("links")) { // parsing the resource content plasmaParserDocument document = null; try { document = sb.snippetCache.parseDocument(url, resourceLength, resource, resInfo); if (document == null) { prop.put("error", 5); prop.put("error_errorText", "Unknown error"); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } } catch (ParserException e) { prop.put("error", 5); prop.put("error_errorText", e.getMessage()); prop.put("viewMode", VIEW_MODE_NO_TEXT); return prop; } finally { if (resource != null) try { resource.close(); } catch (Exception e) { /* ignore this */ } } resMime = document.getMimeType(); String[] wordArray = wordArray(post.get("words", null)); if (viewMode.equals("parsed")) { String content = new String(document.getTextBytes()); content = wikiCode.replaceHTML(content); // added by Marc Nause content = content.replaceAll("\n", "<br />").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;"); prop.put("viewMode", VIEW_MODE_AS_PARSED_TEXT); prop.put("viewMode_parsedText", markup(wordArray, content)); } else if (viewMode.equals("sentences")) { prop.put("viewMode", VIEW_MODE_AS_PARSED_SENTENCES); final Iterator sentences = document.getSentences(pre); boolean dark = true; int i = 0; String sentence; if (sentences != null) { // Search word highlighting while (sentences.hasNext()) { sentence = (String)sentences.next(); if (sentence.trim().length() > 0) { prop.put("viewMode_sentences_" + i + "_nr", Integer.toString(i + 1)); prop.put("viewMode_sentences_" + i + "_text", markup(wordArray, sentence)); prop.put("viewMode_sentences_" + i + "_dark", ((dark) ? 1 : 0)); dark = !dark; i++; } } } prop.put("viewMode_sentences", i); } else if (viewMode.equals("links")) { prop.put("viewMode", VIEW_MODE_AS_LINKLIST); boolean dark = true; int i = 0; i += putMediaInfo(prop, wordArray, i, document.getVideolinks(), "video", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getAudiolinks(), "audio", (i % 2 == 0)); i += putMediaInfo(prop, wordArray, i, document.getApplinks(), "app", (i % 2 == 0)); dark = (i % 2 == 0); TreeSet ts = document.getImages(); Iterator tsi = ts.iterator(); htmlFilterImageEntry entry; while (tsi.hasNext()) { entry = (htmlFilterImageEntry) tsi.next(); prop.put("viewMode_links_" + i + "_nr", i); prop.put("viewMode_links_" + i + "_dark", ((dark) ? 1 : 0)); prop.put("viewMode_links_" + i + "_type", "image"); prop.put("viewMode_links_" + i + "_text", markup(wordArray, entry.alt())); prop.put("viewMode_links_" + i + "_link", "<a href=\"" + (String) entry.url().toNormalform() + "\">" + markup(wordArray, (String) entry.url().toNormalform()) + "</a>"); prop.put("viewMode_links_" + i + "_attr", entry.width() + "&nbsp;x&nbsp;" + entry.height()); dark = !dark; i++; } prop.put("viewMode_links", i); } if (document != null) document.close(); } prop.put("error", 0); prop.put("error_url", wikiCode.replaceHTMLonly(url.toNormalform())); prop.put("error_hash", urlHash); prop.put("error_wordCount", Integer.toString(wordCount)); prop.put("error_desc", descr); prop.put("error_size", size); prop.put("error_mimeTypeAvailable", (resMime == null) ? 0 : 1); prop.put("error_mimeTypeAvailable_mimeType", resMime); return prop; }
diff --git a/Project/src/projectrts/model/pathfinding/AStar.java b/Project/src/projectrts/model/pathfinding/AStar.java index 9fce9e2..fd7d721 100644 --- a/Project/src/projectrts/model/pathfinding/AStar.java +++ b/Project/src/projectrts/model/pathfinding/AStar.java @@ -1,156 +1,156 @@ package projectrts.model.pathfinding; import java.util.ArrayList; import java.util.Collections; import java.util.List; import projectrts.model.utils.Position; /** * A* pathfinding algorithm. * @author Bjorn Persson Mattsson * */ public class AStar { private static World world; /** * Initializes the A* class * @param world Game world */ public static void initialize(World world) { AStar.world = world; } /** * Creates a new A* instance. AStar must have been initialized, * otherwise an IllegalStateException will be thrown. */ public AStar() { if (world == null) { throw new IllegalStateException("You must initialize the AStar class before you can use it"); } } /** * Calculates a path using the A* algorithm. * @param startPos Start position. * @param targetPos End position. * @paran occupyingEntityID ID of occupying entity. * @return An AStarPath from startPos to targetPos. */ public AStarPath calculatePath(Position startPos, Position targetPos, int occupyingEntityID) { // TODO Plankton: Add support for different heuristic priorities // TODO Plankton: Take entity size into account when calculating path // TODO Plankton: Use threads or something to not "freeze" the game when calculating? AStarNode startNode = new AStarNode(world.getNodeAt(startPos)); AStarNode endNode = new AStarNode(world.getNodeAt(targetPos)); List<AStarNode> openList = new ArrayList<AStarNode>(); List<AStarNode> closedList = new ArrayList<AStarNode>(); if (endNode.isObstacle(occupyingEntityID)) { // Use A* "backwards" from the end node to find the closest walkable node. // Probably not the best way of dealing with it, but it will do for now. List<AStarNode> endClosedList = new ArrayList<AStarNode>(); List<AStarNode> endOpenList = new ArrayList<AStarNode>(); endOpenList.add(endNode); - while (endOpenList.isEmpty()) + while (endOpenList.size() > 0) { Collections.sort(endOpenList); AStarNode currentNode = endOpenList.get(0); if (!currentNode.isObstacle(occupyingEntityID)) { endNode = currentNode; break; } endOpenList.remove(currentNode); endClosedList.add(currentNode); List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!endOpenList.contains(node) && !endClosedList.contains(node)) { endOpenList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(startNode); } } } } // A* algorithm starts here openList.add(startNode); - while (openList.isEmpty()) // while open list is not empty + while (openList.size() > 0) // while open list is not empty { // current node = node from the open list with the lowest cost Collections.sort(openList); AStarNode currentNode = openList.get(0); if (currentNode.equals(endNode)) { return generatePath(startPos, startNode, currentNode); } else { // http://www.policyalmanac.org/games/aStarTutorial.htm // move current node to the closed list openList.remove(0); closedList.add(currentNode); // examine each node adjacent to the current node List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!node.isObstacle(occupyingEntityID)) // if not an obstacle { // TODO Plankton: These nested if statements could be combined if (!closedList.contains(node)) // and not on closed list { // TODO Avoid if (x!=y) ..; else ..; if (!openList.contains(node)) // and not on open list { // move to open list and calculate cost openList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(endNode); } else // if on open list, check to see if new path is better { node.calculateCostFromStart(currentNode, true); } } } } } } // path not found, return path to the closest node instead. Collections.sort(closedList, AStarNode.getHeuristicComparator()); return generatePath(startPos, startNode, closedList.get(1)); // the second element in closedList since the first one is the start node } private AStarPath generatePath(Position myPos, AStarNode startNode, AStarNode endNode) { AStarPath path = new AStarPath(); AStarNode nextNode = endNode; while (!nextNode.equals(startNode)) { path.addPosToPath(nextNode.getPosition()); nextNode = nextNode.getParent(); } path.addPosToPath(myPos); return path; } }
false
true
public AStarPath calculatePath(Position startPos, Position targetPos, int occupyingEntityID) { // TODO Plankton: Add support for different heuristic priorities // TODO Plankton: Take entity size into account when calculating path // TODO Plankton: Use threads or something to not "freeze" the game when calculating? AStarNode startNode = new AStarNode(world.getNodeAt(startPos)); AStarNode endNode = new AStarNode(world.getNodeAt(targetPos)); List<AStarNode> openList = new ArrayList<AStarNode>(); List<AStarNode> closedList = new ArrayList<AStarNode>(); if (endNode.isObstacle(occupyingEntityID)) { // Use A* "backwards" from the end node to find the closest walkable node. // Probably not the best way of dealing with it, but it will do for now. List<AStarNode> endClosedList = new ArrayList<AStarNode>(); List<AStarNode> endOpenList = new ArrayList<AStarNode>(); endOpenList.add(endNode); while (endOpenList.isEmpty()) { Collections.sort(endOpenList); AStarNode currentNode = endOpenList.get(0); if (!currentNode.isObstacle(occupyingEntityID)) { endNode = currentNode; break; } endOpenList.remove(currentNode); endClosedList.add(currentNode); List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!endOpenList.contains(node) && !endClosedList.contains(node)) { endOpenList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(startNode); } } } } // A* algorithm starts here openList.add(startNode); while (openList.isEmpty()) // while open list is not empty { // current node = node from the open list with the lowest cost Collections.sort(openList); AStarNode currentNode = openList.get(0); if (currentNode.equals(endNode)) { return generatePath(startPos, startNode, currentNode); } else { // http://www.policyalmanac.org/games/aStarTutorial.htm // move current node to the closed list openList.remove(0); closedList.add(currentNode); // examine each node adjacent to the current node List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!node.isObstacle(occupyingEntityID)) // if not an obstacle { // TODO Plankton: These nested if statements could be combined if (!closedList.contains(node)) // and not on closed list { // TODO Avoid if (x!=y) ..; else ..; if (!openList.contains(node)) // and not on open list { // move to open list and calculate cost openList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(endNode); } else // if on open list, check to see if new path is better { node.calculateCostFromStart(currentNode, true); } } } } } } // path not found, return path to the closest node instead. Collections.sort(closedList, AStarNode.getHeuristicComparator()); return generatePath(startPos, startNode, closedList.get(1)); // the second element in closedList since the first one is the start node }
public AStarPath calculatePath(Position startPos, Position targetPos, int occupyingEntityID) { // TODO Plankton: Add support for different heuristic priorities // TODO Plankton: Take entity size into account when calculating path // TODO Plankton: Use threads or something to not "freeze" the game when calculating? AStarNode startNode = new AStarNode(world.getNodeAt(startPos)); AStarNode endNode = new AStarNode(world.getNodeAt(targetPos)); List<AStarNode> openList = new ArrayList<AStarNode>(); List<AStarNode> closedList = new ArrayList<AStarNode>(); if (endNode.isObstacle(occupyingEntityID)) { // Use A* "backwards" from the end node to find the closest walkable node. // Probably not the best way of dealing with it, but it will do for now. List<AStarNode> endClosedList = new ArrayList<AStarNode>(); List<AStarNode> endOpenList = new ArrayList<AStarNode>(); endOpenList.add(endNode); while (endOpenList.size() > 0) { Collections.sort(endOpenList); AStarNode currentNode = endOpenList.get(0); if (!currentNode.isObstacle(occupyingEntityID)) { endNode = currentNode; break; } endOpenList.remove(currentNode); endClosedList.add(currentNode); List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!endOpenList.contains(node) && !endClosedList.contains(node)) { endOpenList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(startNode); } } } } // A* algorithm starts here openList.add(startNode); while (openList.size() > 0) // while open list is not empty { // current node = node from the open list with the lowest cost Collections.sort(openList); AStarNode currentNode = openList.get(0); if (currentNode.equals(endNode)) { return generatePath(startPos, startNode, currentNode); } else { // http://www.policyalmanac.org/games/aStarTutorial.htm // move current node to the closed list openList.remove(0); closedList.add(currentNode); // examine each node adjacent to the current node List<AStarNode> adjacentNodes = currentNode.getNeighbours(); for (AStarNode node : adjacentNodes) { if (!node.isObstacle(occupyingEntityID)) // if not an obstacle { // TODO Plankton: These nested if statements could be combined if (!closedList.contains(node)) // and not on closed list { // TODO Avoid if (x!=y) ..; else ..; if (!openList.contains(node)) // and not on open list { // move to open list and calculate cost openList.add(node); node.calculateCostFromStart(currentNode, false); node.calculateHeuristic(endNode); } else // if on open list, check to see if new path is better { node.calculateCostFromStart(currentNode, true); } } } } } } // path not found, return path to the closest node instead. Collections.sort(closedList, AStarNode.getHeuristicComparator()); return generatePath(startPos, startNode, closedList.get(1)); // the second element in closedList since the first one is the start node }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java index 390b09d13..aad17ee6f 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java @@ -1,1020 +1,1020 @@ /* * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.core; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetAddress; import java.text.ParseException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.sip.SipErrorEvent; import javax.servlet.sip.SipErrorListener; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletContextEvent; import javax.servlet.sip.SipServletListener; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipURI; import javax.servlet.sip.ar.SipApplicationRouter; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.servlet.sip.ar.SipRouteModifier; import javax.servlet.sip.ar.spi.SipApplicationRouterProvider; import javax.sip.ClientTransaction; import javax.sip.Dialog; import javax.sip.DialogTerminatedEvent; import javax.sip.IOExceptionEvent; import javax.sip.ListeningPoint; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.ServerTransaction; import javax.sip.SipProvider; import javax.sip.TimeoutEvent; import javax.sip.Transaction; import javax.sip.TransactionAlreadyExistsException; import javax.sip.TransactionTerminatedEvent; import javax.sip.TransactionUnavailableException; import javax.sip.address.Address; import javax.sip.header.CSeqHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.catalina.Container; import org.apache.catalina.LifecycleException; import org.apache.catalina.Wrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.modeler.Registry; import org.jboss.web.tomcat.service.session.ConvergedSessionReplicationContext; import org.jboss.web.tomcat.service.session.SnapshotSipManager; import org.mobicents.servlet.sip.GenericUtils; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.address.AddressImpl; import org.mobicents.servlet.sip.core.dispatchers.DispatcherException; import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher; import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcherFactory; import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession; import org.mobicents.servlet.sip.core.session.MobicentsSipSession; import org.mobicents.servlet.sip.core.session.SessionManagerUtil; import org.mobicents.servlet.sip.core.session.SipListenersHolder; import org.mobicents.servlet.sip.core.session.SipManager; import org.mobicents.servlet.sip.message.SipFactoryImpl; import org.mobicents.servlet.sip.message.SipServletMessageImpl; import org.mobicents.servlet.sip.message.SipServletRequestImpl; import org.mobicents.servlet.sip.message.SipServletRequestReadOnly; import org.mobicents.servlet.sip.message.SipServletResponseImpl; import org.mobicents.servlet.sip.message.TransactionApplicationData; import org.mobicents.servlet.sip.router.ManageableApplicationRouter; import org.mobicents.servlet.sip.startup.SipContext; import sun.misc.Service; /** * Implementation of the SipApplicationDispatcher interface. * Central point getting the sip messages from the different stacks for a Tomcat Service(Engine), * translating jain sip SIP messages to sip servlets SIP messages, creating a MessageRouter responsible * for choosing which Dispatcher will be used for routing the message and * dispatches the messages. * @author Jean Deruelle */ public class SipApplicationDispatcherImpl implements SipApplicationDispatcher, MBeanRegistration { //the logger private static transient Log logger = LogFactory .getLog(SipApplicationDispatcherImpl.class); //the sip factory implementation, it is not clear if the sip factory should be the same instance //for all applications private SipFactoryImpl sipFactoryImpl = null; //the sip application router responsible for the routing logic of sip messages to //sip servlet applications private SipApplicationRouter sipApplicationRouter = null; //map of applications deployed private Map<String, SipContext> applicationDeployed = null; //map hashes to app names private Map<String, String> mdToApplicationName = null; //List of host names managed by the container private List<String> hostNames = null; private SessionManagerUtil sessionManager = null; private Boolean started = Boolean.FALSE; private SipNetworkInterfaceManager sipNetworkInterfaceManager; /** * */ public SipApplicationDispatcherImpl() { applicationDeployed = new ConcurrentHashMap<String, SipContext>(); mdToApplicationName = new ConcurrentHashMap<String, String>(); sipFactoryImpl = new SipFactoryImpl(this); sessionManager = new SessionManagerUtil(); hostNames = new CopyOnWriteArrayList<String>(); sipNetworkInterfaceManager = new SipNetworkInterfaceManager(); } /** * {@inheritDoc} */ public void init() throws LifecycleException { //load the sip application router from the javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property //and initializes it if present String sipApplicationRouterProviderClassName = System.getProperty("javax.servlet.sip.ar.spi.SipApplicationRouterProvider"); if(sipApplicationRouterProviderClassName != null && sipApplicationRouterProviderClassName.length() > 0) { if(logger.isInfoEnabled()) { logger.info("Using the javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property to load the application router provider"); } try { sipApplicationRouter = (SipApplicationRouter) Class.forName(sipApplicationRouterProviderClassName).newInstance(); } catch (InstantiationException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (IllegalAccessException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (ClassNotFoundException e) { throw new LifecycleException("Impossible to load the Sip Application Router",e); } catch (ClassCastException e) { throw new LifecycleException("Sip Application Router defined does not implement " + SipApplicationRouter.class.getName(),e); } } else { if(logger.isInfoEnabled()) { logger.info("Using the Service Provider Framework to load the application router provider"); } Iterator<SipApplicationRouterProvider> providers = Service.providers(SipApplicationRouterProvider.class); if(providers.hasNext()) { sipApplicationRouter = providers.next().getSipApplicationRouter(); } } if(sipApplicationRouter == null) { throw new LifecycleException("No Sip Application Router Provider could be loaded. " + "No jar compliant with JSR 289 Section Section 15.4.2 could be found on the classpath " + "and no javax.servlet.sip.ar.spi.SipApplicationRouterProvider system property set"); } if(logger.isInfoEnabled()) { logger.info("Using the following Application Router : " + sipApplicationRouter.getClass().getName()); } sipApplicationRouter.init(); sipApplicationRouter.applicationDeployed(new ArrayList<String>(applicationDeployed.keySet())); if( oname == null ) { try { oname=new ObjectName(domain + ":type=SipApplicationDispatcher"); Registry.getRegistry(null, null) .registerComponent(this, oname, null); if(logger.isInfoEnabled()) { logger.info("Sip Application dispatcher registered under following name " + oname); } } catch (Exception e) { logger.error("Impossible to register the Sip Application dispatcher in domain" + domain, e); } } } /** * {@inheritDoc} */ public void start() { synchronized (started) { if(started) { return; } started = Boolean.TRUE; } if(logger.isDebugEnabled()) { logger.debug("Sip Application Dispatcher started"); } // outbound interfaces set here and not in sipstandardcontext because // depending on jboss or tomcat context can be started before or after // connectors resetOutboundInterfaces(); //JSR 289 Section 2.1.1 Step 4.If present invoke SipServletListener.servletInitialized() on each of initialized Servlet's listeners. for (SipContext sipContext : applicationDeployed.values()) { notifySipServletsListeners(sipContext); } } /** * Notifies the sip servlet listeners that the servlet has been initialized * and that it is ready for service * @param sipContext the sip context of the application where the listeners reside. * @return true if all listeners have been notified correctly */ private static boolean notifySipServletsListeners(SipContext sipContext) { boolean ok = true; SipListenersHolder sipListenersHolder = sipContext.getListeners(); List<SipServletListener> sipServletListeners = sipListenersHolder.getSipServletsListeners(); if(logger.isDebugEnabled()) { logger.debug(sipServletListeners.size() + " SipServletListener to notify of servlet initialization"); } Container[] children = sipContext.findChildren(); if(logger.isDebugEnabled()) { logger.debug(children.length + " container to notify of servlet initialization"); } for (Container container : children) { if(logger.isDebugEnabled()) { logger.debug("container " + container.getName() + ", class : " + container.getClass().getName()); } if(container instanceof Wrapper) { Wrapper wrapper = (Wrapper) container; Servlet sipServlet = null; try { sipServlet = wrapper.allocate(); if(sipServlet instanceof SipServlet) { SipServletContextEvent sipServletContextEvent = new SipServletContextEvent(sipContext.getServletContext(), (SipServlet)sipServlet); for (SipServletListener sipServletListener : sipServletListeners) { sipServletListener.servletInitialized(sipServletContextEvent); } } } catch (ServletException e) { logger.error("Cannot allocate the servlet "+ wrapper.getServletClass() +" for notifying the listener " + "that it has been initialized", e); ok = false; } catch (Throwable e) { logger.error("An error occured when initializing the servlet " + wrapper.getServletClass(), e); ok = false; } try { if(sipServlet != null) { wrapper.deallocate(sipServlet); } } catch (ServletException e) { logger.error("Deallocate exception for servlet" + wrapper.getName(), e); ok = false; } catch (Throwable e) { logger.error("Deallocate exception for servlet" + wrapper.getName(), e); ok = false; } } } return ok; } /** * {@inheritDoc} */ public void stop() { synchronized (started) { if(!started) { return; } started = Boolean.FALSE; } sipApplicationRouter.destroy(); if(oname != null) { Registry.getRegistry(null, null).unregisterComponent(oname); } } /** * {@inheritDoc} */ public void addSipApplication(String sipApplicationName, SipContext sipApplication) { if(logger.isDebugEnabled()) { logger.debug("Adding the following sip servlet application " + sipApplicationName + ", SipContext=" + sipApplication); } applicationDeployed.put(sipApplicationName, sipApplication); mdToApplicationName.put(GenericUtils.hashString(sipApplicationName), sipApplicationName); List<String> newlyApplicationsDeployed = new ArrayList<String>(); newlyApplicationsDeployed.add(sipApplicationName); sipApplicationRouter.applicationDeployed(newlyApplicationsDeployed); //if the ApplicationDispatcher is started, notification is sent that the servlets are ready for service //otherwise the notification will be delayed until the ApplicationDispatcher has started synchronized (started) { if(started) { notifySipServletsListeners(sipApplication); } } if(logger.isInfoEnabled()) { logger.info("the following sip servlet application has been added : " + sipApplicationName); } if(logger.isInfoEnabled()) { logger.info("It contains the following Sip Servlets : "); for(String servletName : sipApplication.getChildrenMap().keySet()) { logger.info("SipApplicationName : " + sipApplicationName + "/ServletName : " + servletName); } } } /** * {@inheritDoc} */ public SipContext removeSipApplication(String sipApplicationName) { SipContext sipContext = applicationDeployed.remove(sipApplicationName); List<String> applicationsUndeployed = new ArrayList<String>(); applicationsUndeployed.add(sipApplicationName); sipApplicationRouter.applicationUndeployed(applicationsUndeployed); ((SipManager)sipContext.getManager()).removeAllSessions(); mdToApplicationName.remove(GenericUtils.hashString(sipApplicationName)); if(logger.isInfoEnabled()) { logger.info("the following sip servlet application has been removed : " + sipApplicationName); } return sipContext; } /* * (non-Javadoc) * @see javax.sip.SipListener#processIOException(javax.sip.IOExceptionEvent) */ public void processIOException(IOExceptionEvent arg0) { // TODO Auto-generated method stub } /* * (non-Javadoc) * @see javax.sip.SipListener#processRequest(javax.sip.RequestEvent) */ public void processRequest(RequestEvent requestEvent) { SipProvider sipProvider = (SipProvider)requestEvent.getSource(); ServerTransaction transaction = requestEvent.getServerTransaction(); Request request = requestEvent.getRequest(); try { if(logger.isInfoEnabled()) { logger.info("Got a request event " + request.toString()); } if (!Request.ACK.equals(request.getMethod()) && transaction == null ) { try { //folsson fix : Workaround broken Cisco 7940/7912 if(request.getHeader(MaxForwardsHeader.NAME)==null){ request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70)); } transaction = sipProvider.getNewServerTransaction(request); } catch ( TransactionUnavailableException tae) { - tae.printStackTrace(); + logger.error("cannot get a new Server transaction for this request " + request, tae); // Sends a 500 Internal server error and stops processing. MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return; } catch ( TransactionAlreadyExistsException taex ) { // Already processed this request so just return. return; } } if(logger.isInfoEnabled()) { logger.info("ServerTx ref " + transaction); logger.info("Dialog ref " + requestEvent.getDialog()); } SipServletRequestImpl sipServletRequest = new SipServletRequestImpl( request, sipFactoryImpl, null, transaction, requestEvent.getDialog(), JainSipUtils.dialogCreatingMethods.contains(request.getMethod())); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialRemoteHostAddress() == null) { ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME); transactionApplicationData.setInitialRemoteHostAddress(viaHeader.getHost()); transactionApplicationData.setInitialRemotePort(viaHeader.getPort()); transactionApplicationData.setInitialRemoteTransport(viaHeader.getTransport()); } } sipServletRequest.setLocalAddr(InetAddress.getByName(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getIPAddress())); sipServletRequest.setLocalPort(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getPort()); // Check if the request is meant for me. If so, strip the topmost // Route header. RouteHeader routeHeader = (RouteHeader) request .getHeader(RouteHeader.NAME); if(routeHeader == null && !isExternal(((javax.sip.address.SipURI)request.getRequestURI()).getHost(), ((javax.sip.address.SipURI)request.getRequestURI()).getPort(), ((javax.sip.address.SipURI)request.getRequestURI()).getTransportParam())) { ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME); String arText = toHeader.getTag(); ApplicationRoutingHeaderComposer ar = new ApplicationRoutingHeaderComposer(this.mdToApplicationName, arText); javax.sip.address.SipURI localUri = JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), JainSipUtils.findTransport(request)); if(arText != null) { localUri.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, ar.getLast().getApplication()); javax.sip.address.Address address = SipFactories.addressFactory.createAddress(localUri); routeHeader = SipFactories.headerFactory.createRouteHeader(address); } } //Popping the router header if it's for the container as //specified in JSR 289 - Section 15.8 if(!isRouteExternal(routeHeader)) { request.removeFirst(RouteHeader.NAME); sipServletRequest.setPoppedRoute(routeHeader); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) { transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false)); } } } if(logger.isInfoEnabled()) { logger.info("Routing State " + sipServletRequest.getRoutingState()); } MessageDispatcherFactory.getRequestDispatcher(sipServletRequest, this). dispatchMessage(sipProvider, sipServletRequest); } catch (DispatcherException e) { logger.error("Unexpected exception while processing request " + request,e); // Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(e.getErrorCode(), transaction, request, sipProvider); } return; } catch (Throwable e) { logger.error("Unexpected exception while processing request " + request,e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return; } } /* * (non-Javadoc) * @see javax.sip.SipListener#processResponse(javax.sip.ResponseEvent) */ public void processResponse(ResponseEvent responseEvent) { if(logger.isInfoEnabled()) { logger.info("Response " + responseEvent.getResponse().toString()); } Response response = responseEvent.getResponse(); CSeqHeader cSeqHeader = (CSeqHeader)response.getHeader(CSeqHeader.NAME); //if this is a response to a cancel, the response is dropped if(Request.CANCEL.equalsIgnoreCase(cSeqHeader.getMethod())) { if(logger.isDebugEnabled()) { logger.debug("the response is dropped accordingly to JSR 289 " + "since this a response to a CANCEL"); } return; } //if this is a trying response, the response is dropped if(Response.TRYING == response.getStatusCode()) { if(logger.isDebugEnabled()) { logger.debug("the response is dropped accordingly to JSR 289 " + "since this a 100"); } return; } if(responseEvent.getClientTransaction() == null && responseEvent.getDialog() == null) { if(logger.isDebugEnabled()) { logger.debug("the following response is dropped since there is no client transaction nor dialog for it : " + response); } return; } ClientTransaction clientTransaction = responseEvent.getClientTransaction(); Dialog dialog = responseEvent.getDialog(); // Transate the response to SipServletResponse SipServletResponseImpl sipServletResponse = new SipServletResponseImpl( response, sipFactoryImpl, clientTransaction, null, dialog); try { MessageDispatcherFactory.getResponseDispatcher(sipServletResponse, this). dispatchMessage(null, sipServletResponse); } catch (Throwable e) { logger.error("An unexpected exception happened while routing the response " + response, e); return; } } /* * (non-Javadoc) * @see javax.sip.SipListener#processDialogTerminated(javax.sip.DialogTerminatedEvent) */ public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { // TODO FIXME if(logger.isInfoEnabled()) { logger.info("Dialog Terminated => " + dialogTerminatedEvent.getDialog().getCallId().getCallId()); } Dialog dialog = dialogTerminatedEvent.getDialog(); TransactionApplicationData tad = (TransactionApplicationData) dialog.getApplicationData(); SipServletMessageImpl sipServletMessageImpl = tad.getSipServletMessage(); MobicentsSipSession sipSessionImpl = sipServletMessageImpl.getSipSession(); tryToInvalidateSession(sipSessionImpl); } /** * @param sipSessionImpl */ private void tryToInvalidateSession(MobicentsSipSession sipSessionImpl) { SipContext sipContext = findSipApplication(sipSessionImpl.getKey().getApplicationName()); boolean isDistributable = sipContext.getDistributable(); if(isDistributable) { ConvergedSessionReplicationContext.enterSipapp(null, null, true); } try { if(logger.isInfoEnabled()) { logger.info("session " + sipSessionImpl.getId() + " already invalidated ? :" + sipSessionImpl.isValid()); } if(sipSessionImpl.isValid()) { if(logger.isInfoEnabled()) { logger.info("Sip session " + sipSessionImpl.getId() + " is ready to be invalidated ? :" + sipSessionImpl.isReadyToInvalidate()); } } MobicentsSipApplicationSession sipApplicationSession = sipSessionImpl.getSipApplicationSession(); if(sipSessionImpl.isValid() && sipSessionImpl.isReadyToInvalidate()) { sipSessionImpl.onTerminatedState(); } if(sipApplicationSession.isValid() && sipApplicationSession.isReadyToInvalidate()) { sipApplicationSession.tryToInvalidate(); } } finally { if (isDistributable) { if(logger.isInfoEnabled()) { logger.info("We are now after the servlet invocation, We replicate no matter what"); } try { ConvergedSessionReplicationContext ctx = ConvergedSessionReplicationContext .exitSipapp(); if(logger.isInfoEnabled()) { logger.info("Snapshot Manager " + ctx.getSoleSnapshotManager()); } if (ctx.getSoleSnapshotManager() != null) { ((SnapshotSipManager)ctx.getSoleSnapshotManager()).snapshot( ctx.getSoleSipSession()); ((SnapshotSipManager)ctx.getSoleSnapshotManager()).snapshot( ctx.getSoleSipApplicationSession()); } } finally { ConvergedSessionReplicationContext.finishSipCacheActivity(); } } } } /* * (non-Javadoc) * @see javax.sip.SipListener#processTimeout(javax.sip.TimeoutEvent) */ public void processTimeout(TimeoutEvent timeoutEvent) { Transaction transaction = null; if(timeoutEvent.isServerTransaction()) { transaction = timeoutEvent.getServerTransaction(); } else { transaction = timeoutEvent.getClientTransaction(); } if(logger.isInfoEnabled()) { logger.info("transaction " + transaction + " terminated => " + transaction.getRequest().toString()); } TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); if(tad != null) { SipServletMessageImpl sipServletMessage = tad.getSipServletMessage(); MobicentsSipSession sipSession = sipServletMessage.getSipSession(); if(sipSession != null) { sipSession.removeOngoingTransaction(transaction); //notifying SipErrorListener that no ACK has been received for a UAS only if(sipServletMessage instanceof SipServletRequestImpl && tad.getProxy() == null && ((SipServletRequestImpl)sipServletMessage).getLastFinalResponse() != null) { List<SipErrorListener> sipErrorListeners = sipSession.getSipApplicationSession().getSipContext().getListeners().getSipErrorListeners(); SipErrorEvent sipErrorEvent = new SipErrorEvent( (SipServletRequest)sipServletMessage, ((SipServletRequestImpl)sipServletMessage).getLastFinalResponse()); for (SipErrorListener sipErrorListener : sipErrorListeners) { try { sipErrorListener.noAckReceived(sipErrorEvent); } catch (Throwable t) { logger.error("SipErrorListener threw exception", t); } } } tryToInvalidateSession(sipSession); } } } /* * (non-Javadoc) * @see javax.sip.SipListener#processTransactionTerminated(javax.sip.TransactionTerminatedEvent) */ public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { Transaction transaction = null; if(transactionTerminatedEvent.isServerTransaction()) { transaction = transactionTerminatedEvent.getServerTransaction(); } else { transaction = transactionTerminatedEvent.getClientTransaction(); } if(logger.isInfoEnabled()) { logger.info("transaction " + transaction + " terminated => " + transaction.getRequest().toString()); } TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData(); if(tad != null) { MobicentsSipSession sipSessionImpl = tad.getSipServletMessage().getSipSession(); if(sipSessionImpl == null) { if(logger.isInfoEnabled()) { logger.info("no sip session were returned for this transaction " + transaction); } } else { if(logger.isInfoEnabled()) { logger.info("sip session " + sipSessionImpl.getId() + " returned for this transaction " + transaction); } // sipSessionImpl.removeOngoingTransaction(transaction); tryToInvalidateSession(sipSessionImpl); } } else { if(logger.isDebugEnabled()) { logger.debug("TransactionApplicationData not available on the following request " + transaction.getRequest().toString()); } } } public Map<String, String> getMdToApplicationName() { return mdToApplicationName; } /** * Check if the route is external * @param routeHeader the route to check * @return true if the route is external, false otherwise */ public final boolean isRouteExternal(RouteHeader routeHeader) { if (routeHeader != null) { javax.sip.address.SipURI routeUri = (javax.sip.address.SipURI) routeHeader.getAddress().getURI(); String routeTransport = routeUri.getTransportParam(); if(routeTransport == null) { routeTransport = ListeningPoint.UDP; } return isExternal(routeUri.getHost(), routeUri.getPort(), routeTransport); } return true; } /** * Check if the via header is external * @param viaHeader the via header to check * @return true if the via header is external, false otherwise */ public final boolean isViaHeaderExternal(ViaHeader viaHeader) { if (viaHeader != null) { return isExternal(viaHeader.getHost(), viaHeader.getPort(), viaHeader.getTransport()); } return true; } /** * Check whether or not the triplet host, port and transport are corresponding to an interface * @param host can be hostname or ipaddress * @param port port number * @param transport transport used * @return true if the triplet host, port and transport are corresponding to an interface * false otherwise */ public final boolean isExternal(String host, int port, String transport) { boolean isExternal = true; ExtendedListeningPoint listeningPoint = sipNetworkInterfaceManager.findMatchingListeningPoint(host, port, transport); if((hostNames.contains(host) || listeningPoint != null)) { if(logger.isDebugEnabled()) { logger.debug("hostNames.contains(host)=" + hostNames.contains(host) + " | listeningPoint found = " + listeningPoint); } isExternal = false; } if(logger.isDebugEnabled()) { logger.debug("the triplet host/port/transport : " + host + "/" + port + "/" + transport + " is external : " + isExternal); } return isExternal; } /** * @return the sipApplicationRouter */ public SipApplicationRouter getSipApplicationRouter() { return sipApplicationRouter; } /** * @param sipApplicationRouter the sipApplicationRouter to set */ public void setSipApplicationRouter(SipApplicationRouter sipApplicationRouter) { this.sipApplicationRouter = sipApplicationRouter; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipNetworkInterfaceManager() */ public SipNetworkInterfaceManager getSipNetworkInterfaceManager() { return this.sipNetworkInterfaceManager; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getSipFactory() */ public SipFactoryImpl getSipFactory() { return sipFactoryImpl; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#getOutboundInterfaces() */ public List<SipURI> getOutboundInterfaces() { return sipNetworkInterfaceManager.getOutboundInterfaces(); } /** * set the outbound interfaces on all servlet context of applications deployed */ private void resetOutboundInterfaces() { List<SipURI> outboundInterfaces = sipNetworkInterfaceManager.getOutboundInterfaces(); for (SipContext sipContext : applicationDeployed.values()) { sipContext.getServletContext().setAttribute(javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES, outboundInterfaces); } } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#addHostName(java.lang.String) */ public void addHostName(String hostName) { if(logger.isDebugEnabled()) { logger.debug(this); logger.debug("Adding hostname "+ hostName); } hostNames.add(hostName); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findHostNames() */ public List<String> findHostNames() { return hostNames; } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#removeHostName(java.lang.String) */ public void removeHostName(String hostName) { if(logger.isDebugEnabled()) { logger.debug("Removing hostname "+ hostName); } hostNames.remove(hostName); } /** * @return the sessionManager */ public SessionManagerUtil getSessionManager() { return sessionManager; } /** * */ public SipApplicationRouterInfo getNextInterestedApplication( SipServletRequestImpl sipServletRequest) { SipApplicationRoutingRegion routingRegion = null; Serializable stateInfo = null; if(sipServletRequest.getSipSession() != null) { //we serialize and deserailize in memory to get the same state info object but with a new reference routingRegion = sipServletRequest.getSipSession().getRegionInternal(); // so that the AR will not change the stateinfo, since this check is just to see if we have to route back to the //container and not a "real" call to the AR to select an application - needed by TCK AR test cases stateInfo = serializeStateInfo(sipServletRequest.getSipSession().getStateInfo()); } Request request = (Request) sipServletRequest.getMessage(); SipServletRequestReadOnly sipServletRequestReadOnly = new SipServletRequestReadOnly(sipServletRequest); SipApplicationRouterInfo applicationRouterInfo = sipApplicationRouter.getNextApplication( sipServletRequestReadOnly, routingRegion, sipServletRequest.getRoutingDirective(), null, stateInfo); sipServletRequestReadOnly = null; // 15.4.1 Procedure : point 2 SipRouteModifier sipRouteModifier = applicationRouterInfo.getRouteModifier(); String[] routes = applicationRouterInfo.getRoutes(); try { // ROUTE modifier indicates that SipApplicationRouterInfo.getRoute() returns a valid route, // it is up to container to decide whether it is external or internal. if(SipRouteModifier.ROUTE.equals(sipRouteModifier)) { Address routeAddress = null; RouteHeader applicationRouterInfoRouteHeader = null; routeAddress = SipFactories.addressFactory.createAddress(routes[0]); applicationRouterInfoRouteHeader = SipFactories.headerFactory.createRouteHeader(routeAddress); if(isRouteExternal(applicationRouterInfoRouteHeader)) { // push all of the routes on the Route header stack of the request and // send the request externally for (int i = routes.length-1 ; i >= 0; i--) { Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]); request.addHeader(routeHeader); } } } else if (SipRouteModifier.ROUTE_BACK.equals(sipRouteModifier)) { // Push container Route, pick up the first outbound interface SipURI sipURI = getOutboundInterfaces().get(0); sipURI.setParameter("modifier", "route_back"); Header routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, sipURI.toString()); request.addHeader(routeHeader); // push all of the routes on the Route header stack of the request and // send the request externally for (int i = routes.length-1 ; i >= 0; i--) { routeHeader = SipFactories.headerFactory.createHeader(RouteHeader.NAME, routes[i]); request.addHeader(routeHeader); } } } catch (ParseException e) { logger.error("Impossible to parse the route returned by the application router " + "into a compliant address",e); } return applicationRouterInfo; } /** * Serialize the state info in memory and deserialize it and return the new object. * Since there is no clone method this is the only way to get the same object with a new reference * @param stateInfo the state info to serialize * @return the state info serialized and deserialized */ private Serializable serializeStateInfo(Serializable stateInfo) { ByteArrayOutputStream baos = null; ObjectOutputStream out = null; ByteArrayInputStream bais = null; ObjectInputStream in = null; try{ baos = new ByteArrayOutputStream(); out = new ObjectOutputStream(baos); out.writeObject(stateInfo); bais = new ByteArrayInputStream(baos.toByteArray()); in =new ObjectInputStream(bais); return (Serializable)in.readObject(); } catch (IOException e) { logger.error("Impossible to serialize the state info", e); return stateInfo; } catch (ClassNotFoundException e) { logger.error("Impossible to serialize the state info", e); return stateInfo; } finally { try { if(out != null) { out.close(); } if(in != null) { in.close(); } if(baos != null) { baos.close(); } if(bais != null) { bais.close(); } } catch (IOException e) { logger.error("Impossible to close the streams after serializing state info", e); } } } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplications() */ public Iterator<SipContext> findSipApplications() { return applicationDeployed.values().iterator(); } /* * (non-Javadoc) * @see org.mobicents.servlet.sip.core.SipApplicationDispatcher#findSipApplication(java.lang.String) */ public SipContext findSipApplication(String applicationName) { return applicationDeployed.get(applicationName); } // -------------------- JMX and Registration -------------------- protected String domain; protected ObjectName oname; protected MBeanServer mserver; public ObjectName getObjectName() { return oname; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } /* * (non-Javadoc) * @see javax.management.MBeanRegistration#postDeregister() */ public void postDeregister() {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#postRegister(java.lang.Boolean) */ public void postRegister(Boolean registrationDone) {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#preDeregister() */ public void preDeregister() throws Exception {} /* * (non-Javadoc) * @see javax.management.MBeanRegistration#preRegister(javax.management.MBeanServer, javax.management.ObjectName) */ public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname=name; mserver=server; domain=name.getDomain(); return name; } /* Exposed methods for the management console. Some of these duplicate existing methods, but * with JMX friendly types. */ public String[] findInstalledSipApplications() { Iterator<SipContext> apps = findSipApplications(); ArrayList<String> appList = new ArrayList<String>(); while(apps.hasNext()){ SipContext ctx = apps.next(); appList.add(ctx.getApplicationName()); } String[] ret = new String[appList.size()]; for(int q=0; q<appList.size(); q++) ret[q] = appList.get(q); return ret; } public Object retrieveApplicationRouterConfiguration() { if(this.sipApplicationRouter instanceof ManageableApplicationRouter) { ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter; return router.getCurrentConfiguration(); } else { throw new RuntimeException("This application router is not manageable"); } } public void updateApplicationRouterConfiguration(Object configuration) { if(this.sipApplicationRouter instanceof ManageableApplicationRouter) { ManageableApplicationRouter router = (ManageableApplicationRouter) this.sipApplicationRouter; router.configure(configuration); } else { throw new RuntimeException("This application router is not manageable"); } } }
true
true
public void processRequest(RequestEvent requestEvent) { SipProvider sipProvider = (SipProvider)requestEvent.getSource(); ServerTransaction transaction = requestEvent.getServerTransaction(); Request request = requestEvent.getRequest(); try { if(logger.isInfoEnabled()) { logger.info("Got a request event " + request.toString()); } if (!Request.ACK.equals(request.getMethod()) && transaction == null ) { try { //folsson fix : Workaround broken Cisco 7940/7912 if(request.getHeader(MaxForwardsHeader.NAME)==null){ request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70)); } transaction = sipProvider.getNewServerTransaction(request); } catch ( TransactionUnavailableException tae) { tae.printStackTrace(); // Sends a 500 Internal server error and stops processing. MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return; } catch ( TransactionAlreadyExistsException taex ) { // Already processed this request so just return. return; } } if(logger.isInfoEnabled()) { logger.info("ServerTx ref " + transaction); logger.info("Dialog ref " + requestEvent.getDialog()); } SipServletRequestImpl sipServletRequest = new SipServletRequestImpl( request, sipFactoryImpl, null, transaction, requestEvent.getDialog(), JainSipUtils.dialogCreatingMethods.contains(request.getMethod())); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialRemoteHostAddress() == null) { ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME); transactionApplicationData.setInitialRemoteHostAddress(viaHeader.getHost()); transactionApplicationData.setInitialRemotePort(viaHeader.getPort()); transactionApplicationData.setInitialRemoteTransport(viaHeader.getTransport()); } } sipServletRequest.setLocalAddr(InetAddress.getByName(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getIPAddress())); sipServletRequest.setLocalPort(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getPort()); // Check if the request is meant for me. If so, strip the topmost // Route header. RouteHeader routeHeader = (RouteHeader) request .getHeader(RouteHeader.NAME); if(routeHeader == null && !isExternal(((javax.sip.address.SipURI)request.getRequestURI()).getHost(), ((javax.sip.address.SipURI)request.getRequestURI()).getPort(), ((javax.sip.address.SipURI)request.getRequestURI()).getTransportParam())) { ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME); String arText = toHeader.getTag(); ApplicationRoutingHeaderComposer ar = new ApplicationRoutingHeaderComposer(this.mdToApplicationName, arText); javax.sip.address.SipURI localUri = JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), JainSipUtils.findTransport(request)); if(arText != null) { localUri.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, ar.getLast().getApplication()); javax.sip.address.Address address = SipFactories.addressFactory.createAddress(localUri); routeHeader = SipFactories.headerFactory.createRouteHeader(address); } } //Popping the router header if it's for the container as //specified in JSR 289 - Section 15.8 if(!isRouteExternal(routeHeader)) { request.removeFirst(RouteHeader.NAME); sipServletRequest.setPoppedRoute(routeHeader); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) { transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false)); } } } if(logger.isInfoEnabled()) { logger.info("Routing State " + sipServletRequest.getRoutingState()); } MessageDispatcherFactory.getRequestDispatcher(sipServletRequest, this). dispatchMessage(sipProvider, sipServletRequest); } catch (DispatcherException e) { logger.error("Unexpected exception while processing request " + request,e); // Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(e.getErrorCode(), transaction, request, sipProvider); } return; } catch (Throwable e) { logger.error("Unexpected exception while processing request " + request,e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return; } }
public void processRequest(RequestEvent requestEvent) { SipProvider sipProvider = (SipProvider)requestEvent.getSource(); ServerTransaction transaction = requestEvent.getServerTransaction(); Request request = requestEvent.getRequest(); try { if(logger.isInfoEnabled()) { logger.info("Got a request event " + request.toString()); } if (!Request.ACK.equals(request.getMethod()) && transaction == null ) { try { //folsson fix : Workaround broken Cisco 7940/7912 if(request.getHeader(MaxForwardsHeader.NAME)==null){ request.setHeader(SipFactories.headerFactory.createMaxForwardsHeader(70)); } transaction = sipProvider.getNewServerTransaction(request); } catch ( TransactionUnavailableException tae) { logger.error("cannot get a new Server transaction for this request " + request, tae); // Sends a 500 Internal server error and stops processing. MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); return; } catch ( TransactionAlreadyExistsException taex ) { // Already processed this request so just return. return; } } if(logger.isInfoEnabled()) { logger.info("ServerTx ref " + transaction); logger.info("Dialog ref " + requestEvent.getDialog()); } SipServletRequestImpl sipServletRequest = new SipServletRequestImpl( request, sipFactoryImpl, null, transaction, requestEvent.getDialog(), JainSipUtils.dialogCreatingMethods.contains(request.getMethod())); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialRemoteHostAddress() == null) { ViaHeader viaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME); transactionApplicationData.setInitialRemoteHostAddress(viaHeader.getHost()); transactionApplicationData.setInitialRemotePort(viaHeader.getPort()); transactionApplicationData.setInitialRemoteTransport(viaHeader.getTransport()); } } sipServletRequest.setLocalAddr(InetAddress.getByName(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getIPAddress())); sipServletRequest.setLocalPort(sipProvider.getListeningPoint(JainSipUtils.findTransport(request)).getPort()); // Check if the request is meant for me. If so, strip the topmost // Route header. RouteHeader routeHeader = (RouteHeader) request .getHeader(RouteHeader.NAME); if(routeHeader == null && !isExternal(((javax.sip.address.SipURI)request.getRequestURI()).getHost(), ((javax.sip.address.SipURI)request.getRequestURI()).getPort(), ((javax.sip.address.SipURI)request.getRequestURI()).getTransportParam())) { ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME); String arText = toHeader.getTag(); ApplicationRoutingHeaderComposer ar = new ApplicationRoutingHeaderComposer(this.mdToApplicationName, arText); javax.sip.address.SipURI localUri = JainSipUtils.createRecordRouteURI( sipFactoryImpl.getSipNetworkInterfaceManager(), JainSipUtils.findTransport(request)); if(arText != null) { localUri.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, ar.getLast().getApplication()); javax.sip.address.Address address = SipFactories.addressFactory.createAddress(localUri); routeHeader = SipFactories.headerFactory.createRouteHeader(address); } } //Popping the router header if it's for the container as //specified in JSR 289 - Section 15.8 if(!isRouteExternal(routeHeader)) { request.removeFirst(RouteHeader.NAME); sipServletRequest.setPoppedRoute(routeHeader); if(transaction != null) { TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData(); if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) { transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, false)); } } } if(logger.isInfoEnabled()) { logger.info("Routing State " + sipServletRequest.getRoutingState()); } MessageDispatcherFactory.getRequestDispatcher(sipServletRequest, this). dispatchMessage(sipProvider, sipServletRequest); } catch (DispatcherException e) { logger.error("Unexpected exception while processing request " + request,e); // Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(e.getErrorCode(), transaction, request, sipProvider); } return; } catch (Throwable e) { logger.error("Unexpected exception while processing request " + request,e); // Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing. if(!Request.ACK.equalsIgnoreCase(request.getMethod())) { MessageDispatcher.sendErrorResponse(Response.SERVER_INTERNAL_ERROR, transaction, request, sipProvider); } return; } }
diff --git a/app/models/utils/SurveyDuplicator.java b/app/models/utils/SurveyDuplicator.java index d2819b4..0021fb3 100644 --- a/app/models/utils/SurveyDuplicator.java +++ b/app/models/utils/SurveyDuplicator.java @@ -1,127 +1,128 @@ /* * Nokia Data Gathering * * Copyright (C) 2011 Nokia Corporation * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/ */ package models.utils; import controllers.util.Constants; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import models.Category; import models.DefaultAnswer; import models.NdgUser; import models.Question; import models.QuestionOption; import models.Survey; public class SurveyDuplicator { public static Survey plainCopy(Survey origin, String newId) { Survey copy = new Survey(); copy.available = Constants.SURVEY_BUILDING; copy.lang = origin.lang; copy.ndgUser = origin.ndgUser; copy.surveyId = newId; copy.title = origin.title; copy.uploadDate = new Date(); copy.categoryCollection = copyCategories(origin.categoryCollection, copy); return copy; } public static Survey addDemoSurveyToNewUser(Survey origin, String newId, NdgUser user) { Survey copy = new Survey(); copy.available = Constants.SURVEY_BUILDING; copy.lang = origin.lang; copy.ndgUser = user; copy.surveyId = newId; copy.title = origin.title; copy.uploadDate = new Date(); copy.categoryCollection = copyCategories(origin.categoryCollection, copy); return copy; } private static List<Category> copyCategories(List<Category> origin, Survey newSurvey){ List<Category> copy = new ArrayList<Category>(); Category copiedCategory = null; for(Category category : origin){ copiedCategory = new Category(); copiedCategory.survey = newSurvey; copiedCategory.label = category.label; copiedCategory.objectName = category.objectName; copiedCategory.categoryIndex = category.categoryIndex; copiedCategory.questionCollection = copyQuestions(category.questionCollection, copiedCategory); copy.add(copiedCategory); } return copy; } private static List<Question> copyQuestions(List<Question> origin, Category newCategory) { List<Question> copy = new ArrayList<Question>(); for (Question question : origin) { Question copiedQuestion = new Question(); copiedQuestion.constraintText = question.constraintText; copiedQuestion.relevant = question.relevant; copiedQuestion.hint = question.hint; copiedQuestion.label = question.label; copiedQuestion.objectName = question.objectName; + copiedQuestion.questionIndex = question.questionIndex; copiedQuestion.questionType = question.questionType; copiedQuestion.readonly = question.readonly; copiedQuestion.required = question.required; copiedQuestion.category = newCategory; copiedQuestion.questionOptionCollection = copyQuestionOptions(question.questionOptionCollection, copiedQuestion); if( question.defaultAnswer != null ){ copiedQuestion.defaultAnswer = copyDefaultAnswer( question.defaultAnswer, copiedQuestion ); } copy.add(copiedQuestion); } return copy; } private static Collection<QuestionOption> copyQuestionOptions(Collection<QuestionOption> origin, Question newQuestion) { Collection<QuestionOption> copy = new ArrayList<QuestionOption>(); for (QuestionOption questionOption : origin) { QuestionOption copiedOption = new QuestionOption(); copiedOption.optionIndex = questionOption.optionIndex; copiedOption.label = questionOption.label; copiedOption.optionValue = questionOption.optionValue; copiedOption.question = newQuestion; copy.add(copiedOption); } return copy; } private static DefaultAnswer copyDefaultAnswer(DefaultAnswer origin, Question newQuestion ){ DefaultAnswer newAnswer = new DefaultAnswer(); newAnswer.binaryData = origin.binaryData; newAnswer.textData = origin.textData; newAnswer.questionCollection.add( newQuestion ); newAnswer.save(); return newAnswer; } }
true
true
private static List<Question> copyQuestions(List<Question> origin, Category newCategory) { List<Question> copy = new ArrayList<Question>(); for (Question question : origin) { Question copiedQuestion = new Question(); copiedQuestion.constraintText = question.constraintText; copiedQuestion.relevant = question.relevant; copiedQuestion.hint = question.hint; copiedQuestion.label = question.label; copiedQuestion.objectName = question.objectName; copiedQuestion.questionType = question.questionType; copiedQuestion.readonly = question.readonly; copiedQuestion.required = question.required; copiedQuestion.category = newCategory; copiedQuestion.questionOptionCollection = copyQuestionOptions(question.questionOptionCollection, copiedQuestion); if( question.defaultAnswer != null ){ copiedQuestion.defaultAnswer = copyDefaultAnswer( question.defaultAnswer, copiedQuestion ); } copy.add(copiedQuestion); } return copy; }
private static List<Question> copyQuestions(List<Question> origin, Category newCategory) { List<Question> copy = new ArrayList<Question>(); for (Question question : origin) { Question copiedQuestion = new Question(); copiedQuestion.constraintText = question.constraintText; copiedQuestion.relevant = question.relevant; copiedQuestion.hint = question.hint; copiedQuestion.label = question.label; copiedQuestion.objectName = question.objectName; copiedQuestion.questionIndex = question.questionIndex; copiedQuestion.questionType = question.questionType; copiedQuestion.readonly = question.readonly; copiedQuestion.required = question.required; copiedQuestion.category = newCategory; copiedQuestion.questionOptionCollection = copyQuestionOptions(question.questionOptionCollection, copiedQuestion); if( question.defaultAnswer != null ){ copiedQuestion.defaultAnswer = copyDefaultAnswer( question.defaultAnswer, copiedQuestion ); } copy.add(copiedQuestion); } return copy; }
diff --git a/genomix/genomix-data/src/main/java/edu/uci/ics/genomix/type/KmerUtil.java b/genomix/genomix-data/src/main/java/edu/uci/ics/genomix/type/KmerUtil.java index 7982c1495..d796d19bd 100644 --- a/genomix/genomix-data/src/main/java/edu/uci/ics/genomix/type/KmerUtil.java +++ b/genomix/genomix-data/src/main/java/edu/uci/ics/genomix/type/KmerUtil.java @@ -1,209 +1,211 @@ package edu.uci.ics.genomix.type; public class KmerUtil { public static int countNumberOfBitSet(int i) { int c = 0; for (; i != 0; c++) { i &= i - 1; } return c; } public static int inDegree(byte bitmap) { return countNumberOfBitSet((bitmap >> 4) & 0x0f); } public static int outDegree(byte bitmap) { return countNumberOfBitSet(bitmap & 0x0f); } /** * Get last kmer from kmer-chain. * e.g. kmerChain is AAGCTA, if k =5, it will * return AGCTA * @param k * @param kInChain * @param kmerChain * @return LastKmer bytes array */ public static byte[] getLastKmerFromChain(int k, int kInChain, byte[] kmerChain) { if (k > kInChain) { return null; } if (k == kInChain) { return kmerChain.clone(); } int byteNum = Kmer.getByteNumFromK(k); byte[] kmer = new byte[byteNum]; /** from end to start */ int byteInChain = kmerChain.length - 1 - (kInChain - k) / 4; int posInByteOfChain = ((kInChain - k) % 4) << 1; // *2 int byteInKmer = byteNum - 1; for (; byteInKmer >= 0 && byteInChain > 0; byteInKmer--, byteInChain--) { kmer[byteInKmer] = (byte) ((0xff & kmerChain[byteInChain]) >> posInByteOfChain); kmer[byteInKmer] |= ((kmerChain[byteInChain - 1] << (8 - posInByteOfChain))); } /** last kmer byte */ if (byteInKmer == 0) { kmer[0] = (byte) ((kmerChain[0] & 0xff) >> posInByteOfChain); } return kmer; } /** * Get first kmer from kmer-chain e.g. kmerChain is AAGCTA, if k=5, it will * return AAGCT * * @param k * @param kInChain * @param kmerChain * @return FirstKmer bytes array */ public static byte[] getFirstKmerFromChain(int k, int kInChain, byte[] kmerChain) { if (k > kInChain) { return null; } if (k == kInChain) { return kmerChain.clone(); } int byteNum = Kmer.getByteNumFromK(k); byte[] kmer = new byte[byteNum]; int i = 1; for (; i < kmer.length; i++) { kmer[kmer.length - i] = kmerChain[kmerChain.length - i]; } int posInByteOfChain = (k % 4) << 1; // *2 if (posInByteOfChain == 0) { kmer[0] = kmerChain[kmerChain.length - i]; } else { kmer[0] = (byte) (kmerChain[kmerChain.length - i] & ((1 << posInByteOfChain) - 1)); } return kmer; } /** * Merge kmer with next neighbor in gene-code format. * The k of new kmer will increase by 1 * e.g. AAGCT merge with A => AAGCTA * @param k :input k of kmer * @param kmer : input bytes of kmer * @param nextCode: next neighbor in gene-code format * @return the merged Kmer, this K of this Kmer is k+1 */ public static byte[] mergeKmerWithNextCode(int k, byte[] kmer, byte nextCode) { int byteNum = kmer.length; if (k % 4 == 0) { byteNum++; } byte[] mergedKmer = new byte[byteNum]; for (int i = 1; i <= kmer.length; i++) { mergedKmer[mergedKmer.length - i] = kmer[kmer.length - i]; } if (mergedKmer.length > kmer.length) { mergedKmer[0] = (byte) (nextCode & 0x3); } else { mergedKmer[0] = (byte) (kmer[0] | ((nextCode & 0x3) << ((k % 4) << 1))); } return mergedKmer; } /** * Merge kmer with previous neighbor in gene-code format. * The k of new kmer will increase by 1 * e.g. AAGCT merge with A => AAAGCT * @param k :input k of kmer * @param kmer : input bytes of kmer * @param preCode: next neighbor in gene-code format * @return the merged Kmer,this K of this Kmer is k+1 */ public static byte[] mergeKmerWithPreCode(int k, byte[] kmer, byte preCode) { int byteNum = kmer.length; byte[] mergedKmer = null; int byteInMergedKmer = 0; if (k % 4 == 0) { byteNum++; mergedKmer = new byte[byteNum]; mergedKmer[0] = (byte) ((kmer[0] >> 6) & 0x3); byteInMergedKmer++; } else { mergedKmer = new byte[byteNum]; } for (int i = 0; i < kmer.length - 1; i++, byteInMergedKmer++) { mergedKmer[byteInMergedKmer] = (byte) ((kmer[i] << 2) | ((kmer[i + 1] >> 6) & 0x3)); } mergedKmer[byteInMergedKmer] = (byte) ((kmer[kmer.length - 1] << 2) | (preCode & 0x3)); return mergedKmer; } /** * Merge two kmer to one kmer * e.g. ACTA + ACCGT => ACTAACCGT * @param preK : previous k of kmer * @param kmerPre : bytes array of previous kmer * @param nextK : next k of kmer * @param kmerNext : bytes array of next kmer * @return merged kmer, the new k is @preK + @nextK */ public static byte[] mergeTwoKmer(int preK, byte[] kmerPre, int nextK, byte[] kmerNext) { int byteNum = Kmer.getByteNumFromK(preK + nextK); byte[] mergedKmer = new byte[byteNum]; int i = 1; for (; i <= kmerPre.length; i++) { mergedKmer[byteNum - i] = kmerPre[kmerPre.length - i]; } - i--; + if ( i > 1){ + i--; + } if (preK % 4 == 0) { for (int j = 1; j <= kmerNext.length; j++) { mergedKmer[byteNum - i - j] = kmerNext[kmerNext.length - j]; } } else { int posNeedToMove = ((preK % 4) << 1); mergedKmer[byteNum - i] |= kmerNext[kmerNext.length - 1] << posNeedToMove; for (int j = 1; j < kmerNext.length; j++) { mergedKmer[byteNum - i - j] = (byte) (((kmerNext[kmerNext.length - j] & 0xff) >> (8 - posNeedToMove)) | (kmerNext[kmerNext.length - j - 1] << posNeedToMove)); } if ( (nextK % 4) * 2 + posNeedToMove > 8) { mergedKmer[0] = (byte) (kmerNext[0] >> (8 - posNeedToMove)); } } return mergedKmer; } /** * Safely shifted the kmer forward without change the input kmer * e.g. AGCGC shift with T => GCGCT * @param k: kmer length * @param kmer: input kmer * @param afterCode: input genecode * @return new created kmer that shifted by afterCode, the K will not change */ public static byte[] shiftKmerWithNextCode(int k, final byte[] kmer, byte afterCode){ byte[] shifted = kmer.clone(); Kmer.moveKmer(k, shifted, Kmer.GENE_CODE.getSymbolFromCode(afterCode)); return shifted; } /** * Safely shifted the kmer backward without change the input kmer * e.g. AGCGC shift with T => TAGCG * @param k: kmer length * @param kmer: input kmer * @param preCode: input genecode * @return new created kmer that shifted by preCode, the K will not change */ public static byte[] shiftKmerWithPreCode(int k, final byte[] kmer, byte preCode){ byte[] shifted = kmer.clone(); Kmer.moveKmerReverse(k, shifted, Kmer.GENE_CODE.getSymbolFromCode(preCode)); return shifted; } }
true
true
public static byte[] mergeTwoKmer(int preK, byte[] kmerPre, int nextK, byte[] kmerNext) { int byteNum = Kmer.getByteNumFromK(preK + nextK); byte[] mergedKmer = new byte[byteNum]; int i = 1; for (; i <= kmerPre.length; i++) { mergedKmer[byteNum - i] = kmerPre[kmerPre.length - i]; } i--; if (preK % 4 == 0) { for (int j = 1; j <= kmerNext.length; j++) { mergedKmer[byteNum - i - j] = kmerNext[kmerNext.length - j]; } } else { int posNeedToMove = ((preK % 4) << 1); mergedKmer[byteNum - i] |= kmerNext[kmerNext.length - 1] << posNeedToMove; for (int j = 1; j < kmerNext.length; j++) { mergedKmer[byteNum - i - j] = (byte) (((kmerNext[kmerNext.length - j] & 0xff) >> (8 - posNeedToMove)) | (kmerNext[kmerNext.length - j - 1] << posNeedToMove)); } if ( (nextK % 4) * 2 + posNeedToMove > 8) { mergedKmer[0] = (byte) (kmerNext[0] >> (8 - posNeedToMove)); } } return mergedKmer; }
public static byte[] mergeTwoKmer(int preK, byte[] kmerPre, int nextK, byte[] kmerNext) { int byteNum = Kmer.getByteNumFromK(preK + nextK); byte[] mergedKmer = new byte[byteNum]; int i = 1; for (; i <= kmerPre.length; i++) { mergedKmer[byteNum - i] = kmerPre[kmerPre.length - i]; } if ( i > 1){ i--; } if (preK % 4 == 0) { for (int j = 1; j <= kmerNext.length; j++) { mergedKmer[byteNum - i - j] = kmerNext[kmerNext.length - j]; } } else { int posNeedToMove = ((preK % 4) << 1); mergedKmer[byteNum - i] |= kmerNext[kmerNext.length - 1] << posNeedToMove; for (int j = 1; j < kmerNext.length; j++) { mergedKmer[byteNum - i - j] = (byte) (((kmerNext[kmerNext.length - j] & 0xff) >> (8 - posNeedToMove)) | (kmerNext[kmerNext.length - j - 1] << posNeedToMove)); } if ( (nextK % 4) * 2 + posNeedToMove > 8) { mergedKmer[0] = (byte) (kmerNext[0] >> (8 - posNeedToMove)); } } return mergedKmer; }
diff --git a/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java b/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java index 9827cf267..01e1ccc2f 100644 --- a/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java +++ b/src/main/java/org/mozilla/gecko/sync/net/BaseResource.java @@ -1,412 +1,415 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.sync.net; import java.io.BufferedReader; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.net.ssl.SSLContext; import org.mozilla.gecko.sync.Logger; import ch.boye.httpclientandroidlib.Header; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.HttpVersion; import ch.boye.httpclientandroidlib.auth.Credentials; import ch.boye.httpclientandroidlib.auth.UsernamePasswordCredentials; import ch.boye.httpclientandroidlib.client.AuthCache; import ch.boye.httpclientandroidlib.client.ClientProtocolException; import ch.boye.httpclientandroidlib.client.methods.HttpDelete; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.client.methods.HttpPut; import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase; import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest; import ch.boye.httpclientandroidlib.client.protocol.ClientContext; import ch.boye.httpclientandroidlib.conn.ClientConnectionManager; import ch.boye.httpclientandroidlib.conn.scheme.PlainSocketFactory; import ch.boye.httpclientandroidlib.conn.scheme.Scheme; import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry; import ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory; import ch.boye.httpclientandroidlib.impl.auth.BasicScheme; import ch.boye.httpclientandroidlib.impl.client.BasicAuthCache; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.conn.tsccm.ThreadSafeClientConnManager; import ch.boye.httpclientandroidlib.params.HttpConnectionParams; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.params.HttpProtocolParams; import ch.boye.httpclientandroidlib.protocol.BasicHttpContext; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.EntityUtils; /** * Provide simple HTTP access to a Sync server or similar. * Implements Basic Auth by asking its delegate for credentials. * Communicates with a ResourceDelegate to asynchronously return responses and errors. * Exposes simple get/post/put/delete methods. */ public class BaseResource implements Resource { private static final String ANDROID_LOOPBACK_IP = "10.0.2.2"; private static final int MAX_TOTAL_CONNECTIONS = 20; private static final int MAX_CONNECTIONS_PER_ROUTE = 10; private boolean retryOnFailedRequest = true; public static boolean rewriteLocalhost = true; private static final String LOG_TAG = "BaseResource"; protected URI uri; protected BasicHttpContext context; protected DefaultHttpClient client; public ResourceDelegate delegate; protected HttpRequestBase request; public String charset = "utf-8"; protected static WeakReference<HttpResponseObserver> httpResponseObserver = null; public BaseResource(String uri) throws URISyntaxException { this(uri, rewriteLocalhost); } public BaseResource(URI uri) { this(uri, rewriteLocalhost); } public BaseResource(String uri, boolean rewrite) throws URISyntaxException { this(new URI(uri), rewrite); } public BaseResource(URI uri, boolean rewrite) { if (rewrite && uri.getHost().equals("localhost")) { // Rewrite localhost URIs to refer to the special Android emulator loopback passthrough interface. Logger.debug(LOG_TAG, "Rewriting " + uri + " to point to " + ANDROID_LOOPBACK_IP + "."); try { this.uri = new URI(uri.getScheme(), uri.getUserInfo(), ANDROID_LOOPBACK_IP, uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { Logger.error(LOG_TAG, "Got error rewriting URI for Android emulator.", e); } } else { this.uri = uri; } } public static synchronized HttpResponseObserver getHttpResponseObserver() { if (httpResponseObserver == null) { return null; } return httpResponseObserver.get(); } public static synchronized void setHttpResponseObserver(HttpResponseObserver newHttpResponseObserver) { if (httpResponseObserver != null) { httpResponseObserver.clear(); } httpResponseObserver = new WeakReference<HttpResponseObserver>(newHttpResponseObserver); } public URI getURI() { return this.uri; } /** * This shuts up HttpClient, which will otherwise debug log about there * being no auth cache in the context. */ private static void addAuthCacheToContext(HttpUriRequest request, HttpContext context) { AuthCache authCache = new BasicAuthCache(); // Not thread safe. context.setAttribute(ClientContext.AUTH_CACHE, authCache); } /** * Return a Header object representing an Authentication header for HTTP Basic. */ public static Header getBasicAuthHeader(final String credentials) { Credentials creds = new UsernamePasswordCredentials(credentials); // This must be UTF-8 to generate the same Basic Auth headers as desktop for non-ASCII passwords. return BasicScheme.authenticate(creds, "UTF-8", false); } /** * Apply the provided credentials string to the provided request. * @param credentials a string, "user:pass". */ private static void applyCredentials(String credentials, HttpUriRequest request, HttpContext context) { request.addHeader(getBasicAuthHeader(credentials)); Logger.trace(LOG_TAG, "Adding Basic Auth header."); } /** * Invoke this after delegate and request have been set. * @throws NoSuchAlgorithmException * @throws KeyManagementException */ private void prepareClient() throws KeyManagementException, NoSuchAlgorithmException { context = new BasicHttpContext(); // We could reuse these client instances, except that we mess around // with their parameters… so we'd need a pool of some kind. client = new DefaultHttpClient(getConnectionManager()); // TODO: Eventually we should use Apache HttpAsyncClient. It's not out of alpha yet. // Until then, we synchronously make the request, then invoke our delegate's callback. String credentials = delegate.getCredentials(); if (credentials != null) { BaseResource.applyCredentials(credentials, request, context); } addAuthCacheToContext(request, context); HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, delegate.connectionTimeout()); HttpConnectionParams.setSoTimeout(params, delegate.socketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpProtocolParams.setContentCharset(params, charset); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); delegate.addHeaders(request, client); } private static Object connManagerMonitor = new Object(); private static ClientConnectionManager connManager; /** * This method exists for test code. */ public static ClientConnectionManager enablePlainHTTPConnectionManager() { synchronized (connManagerMonitor) { ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(); connManager = cm; return cm; } } // Call within a synchronized block on connManagerMonitor. private static ClientConnectionManager enableTLSConnectionManager() throws KeyManagementException, NoSuchAlgorithmException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, new SecureRandom()); SSLSocketFactory sf = new TLSSocketFactory(sslContext); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sf)); schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory())); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry); cm.setMaxTotal(MAX_TOTAL_CONNECTIONS); cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE); connManager = cm; return cm; } public static ClientConnectionManager getConnectionManager() throws KeyManagementException, NoSuchAlgorithmException { // TODO: shutdown. synchronized (connManagerMonitor) { if (connManager != null) { return connManager; } return enableTLSConnectionManager(); } } /** * Do some cleanup, so we don't need the stale connection check. */ public static void closeExpiredConnections() { ClientConnectionManager connectionManager; synchronized (connManagerMonitor) { connectionManager = connManager; } if (connectionManager == null) { return; } Logger.trace(LOG_TAG, "Closing expired connections."); connectionManager.closeExpiredConnections(); } public static void shutdownConnectionManager() { ClientConnectionManager connectionManager; synchronized (connManagerMonitor) { connectionManager = connManager; connManager = null; } if (connectionManager == null) { return; } Logger.debug(LOG_TAG, "Shutting down connection manager."); connectionManager.shutdown(); } private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { - delegate.handleHttpIOException(new IOException(e)); + // Bug 769671: IOException(Throwable cause) was added only in API level 9. + final IOException ex = new IOException(); + ex.initCause(e); + delegate.handleHttpIOException(ex); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); } private void retryRequest() { // Only retry once. retryOnFailedRequest = false; Logger.debug(LOG_TAG, "Retrying request..."); this.execute(); } private void go(HttpRequestBase request) { if (delegate == null) { throw new IllegalArgumentException("No delegate provided."); } this.request = request; try { this.prepareClient(); } catch (KeyManagementException e) { Logger.error(LOG_TAG, "Couldn't prepare client.", e); delegate.handleTransportException(e); return; } catch (NoSuchAlgorithmException e) { Logger.error(LOG_TAG, "Couldn't prepare client.", e); delegate.handleTransportException(e); return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. delegate.handleTransportException(new GeneralSecurityException(e)); return; } this.execute(); } @Override public void get() { Logger.debug(LOG_TAG, "HTTP GET " + this.uri.toASCIIString()); this.go(new HttpGet(this.uri)); } @Override public void delete() { Logger.debug(LOG_TAG, "HTTP DELETE " + this.uri.toASCIIString()); this.go(new HttpDelete(this.uri)); } @Override public void post(HttpEntity body) { Logger.debug(LOG_TAG, "HTTP POST " + this.uri.toASCIIString()); HttpPost request = new HttpPost(this.uri); request.setEntity(body); this.go(request); } @Override public void put(HttpEntity body) { Logger.debug(LOG_TAG, "HTTP PUT " + this.uri.toASCIIString()); HttpPut request = new HttpPut(this.uri); request.setEntity(body); this.go(request); } /** * Best-effort attempt to ensure that the entity has been fully consumed and * that the underlying stream has been closed. * * This releases the connection back to the connection pool. * * @param entity The HttpEntity to be consumed. */ public static void consumeEntity(HttpEntity entity) { try { EntityUtils.consume(entity); } catch (IOException e) { // Doesn't matter. } } /** * Best-effort attempt to ensure that the entity corresponding to the given * HTTP response has been fully consumed and that the underlying stream has * been closed. * * This releases the connection back to the connection pool. * * @param response * The HttpResponse to be consumed. */ public static void consumeEntity(HttpResponse response) { if (response == null) { return; } try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { } } /** * Best-effort attempt to ensure that the entity corresponding to the given * Sync storage response has been fully consumed and that the underlying * stream has been closed. * * This releases the connection back to the connection pool. * * @param response * The SyncStorageResponse to be consumed. */ public static void consumeEntity(SyncStorageResponse response) { if (response.httpResponse() == null) { return; } consumeEntity(response.httpResponse()); } /** * Best-effort attempt to ensure that the reader has been fully consumed, so * that the underlying stream will be closed. * * This should allow the connection to be released back to the connection pool. * * @param reader The BufferedReader to be consumed. */ public static void consumeReader(BufferedReader reader) { try { reader.close(); } catch (IOException e) { // Do nothing. } } }
true
true
private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { delegate.handleHttpIOException(new IOException(e)); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); }
private void execute() { HttpResponse response; try { response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); return; } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } return; } catch (Exception e) { // Bug 740731: Don't let an exception fall through. Wrapping isn't // optimal, but often the exception is treated as an Exception anyway. if (!retryOnFailedRequest) { // Bug 769671: IOException(Throwable cause) was added only in API level 9. final IOException ex = new IOException(); ex.initCause(e); delegate.handleHttpIOException(ex); } else { retryRequest(); } return; } // Don't retry if the observer or delegate throws! HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); }
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardService.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardService.java index cb13cb7cc..459e3c4b3 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardService.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/startup/SipStandardService.java @@ -1,1103 +1,1101 @@ /* * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.servlet.sip.startup; import gov.nist.core.net.AddressResolver; import gov.nist.javax.sip.SipStackExt; import gov.nist.javax.sip.message.MessageFactoryExt; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import java.util.TooManyListenersException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.sip.SipStack; import javax.sip.header.ServerHeader; import javax.sip.header.UserAgentHeader; import org.apache.catalina.Engine; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardService; import org.apache.coyote.ProtocolHandler; import org.apache.log4j.Logger; import org.apache.tomcat.util.modeler.Registry; import org.mobicents.ha.javax.sip.ClusteredSipStack; import org.mobicents.ha.javax.sip.LoadBalancerHeartBeatingListener; import org.mobicents.ha.javax.sip.LoadBalancerHeartBeatingService; import org.mobicents.ha.javax.sip.LoadBalancerHeartBeatingServiceImpl; import org.mobicents.servlet.sip.JainSipUtils; import org.mobicents.servlet.sip.SipConnector; import org.mobicents.servlet.sip.SipFactories; import org.mobicents.servlet.sip.annotation.ConcurrencyControlMode; import org.mobicents.servlet.sip.core.CongestionControlPolicy; import org.mobicents.servlet.sip.core.DNSAddressResolver; import org.mobicents.servlet.sip.core.ExtendedListeningPoint; import org.mobicents.servlet.sip.core.SipApplicationDispatcher; /** * Sip Servlet implementation of the <code>SipService</code> interface. * This class inherits from the Tomcat StandardService. It adds a SipApplicationDispatcher * that will be listen for sip messages received by the sip stacks started by * the sip connectors associated with this context. * This has one attribute which is the sipApplicationDispatcherClassName allowing one * to specify the class name of the sipApplicationDispacther to easily replace * the default sipApplicationDispatcher with a custom one. * * @author <A HREF="mailto:jean.deruelle@gmail.com">Jean Deruelle</A> */ public class SipStandardService extends StandardService implements SipService { //the logger private static final Logger logger = Logger.getLogger(SipStandardService.class); private static final String DEFAULT_SIP_PATH_NAME = "gov.nist"; private static final String PASS_INVITE_NON_2XX_ACK_TO_LISTENER = "gov.nist.javax.sip.PASS_INVITE_NON_2XX_ACK_TO_LISTENER"; private static final String TCP_POST_PARSING_THREAD_POOL_SIZE = "gov.nist.javax.sip.TCP_POST_PARSING_THREAD_POOL_SIZE"; private static final String AUTOMATIC_DIALOG_SUPPORT_STACK_PROP = "javax.sip.AUTOMATIC_DIALOG_SUPPORT"; private static final String LOOSE_DIALOG_VALIDATION = "gov.nist.javax.sip.LOOSE_DIALOG_VALIDATION"; private static final String SERVER_LOG_STACK_PROP = "gov.nist.javax.sip.SERVER_LOG"; private static final String DEBUG_LOG_STACK_PROP = "gov.nist.javax.sip.DEBUG_LOG"; private static final String SERVER_HEADER = "org.mobicents.servlet.sip.SERVER_HEADER"; private static final String USER_AGENT_HEADER = "org.mobicents.servlet.sip.USER_AGENT_HEADER"; private static final String JVM_ROUTE = "jvmRoute"; /** * The descriptive information string for this implementation. */ private static final String INFO = "org.mobicents.servlet.sip.startup.SipStandardService/1.0"; //the sip application dispatcher class name defined in the server.xml protected String sipApplicationDispatcherClassName; //instatiated class from the sipApplicationDispatcherClassName of the sip application dispatcher protected SipApplicationDispatcher sipApplicationDispatcher; private boolean gatherStatistics = true; protected int sipMessageQueueSize = 1500; private int backToNormalSipMessageQueueSize = 1300; protected int memoryThreshold = 95; private int backToNormalMemoryThreshold = 90; protected String outboundProxy; protected long congestionControlCheckingInterval = 30000; // base timer interval for jain sip tx private int baseTimerInterval = 500; private int t2Interval = 4000; private int t4Interval = 5000; private int timerDInterval = 32000; protected int dispatcherThreadPoolSize = 4; protected String concurrencyControlMode = ConcurrencyControlMode.None.toString(); protected String congestionControlPolicy = CongestionControlPolicy.ErrorResponse.toString(); protected String additionalParameterableHeaders; protected boolean bypassResponseExecutor = true; protected boolean bypassRequestExecutor = true; //the sip application router class name defined in the server.xml // private String sipApplicationRouterClassName; //this should be made available to the application router as a system prop protected String darConfigurationFileLocation; // protected boolean connectorsStartedExternally = false; protected boolean dialogPendingRequestChecking = false; /** * the sip stack path name. Since the sip factory is per classloader it should be set here for all underlying stacks */ private String sipPathName; /* * use Pretty Encoding */ private boolean usePrettyEncoding = true; private SipStack sipStack; // defining sip stack properties private Properties sipStackProperties; private String sipStackPropertiesFileLocation; private String addressResolverClass = DNSAddressResolver.class.getName(); //the balancers to send heartbeat to and our health info @Deprecated private String balancers; @Override public String getInfo() { return (INFO); } @Override public void addConnector(Connector connector) { ExtendedListeningPoint extendedListeningPoint = (ExtendedListeningPoint) connector.getProtocolHandler().getAttribute(ExtendedListeningPoint.class.getSimpleName()); if(extendedListeningPoint != null) { try { extendedListeningPoint.getSipProvider().addSipListener(sipApplicationDispatcher); sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint); } catch (TooManyListenersException e) { logger.error("Connector.initialize", e); } } ProtocolHandler protocolHandler = connector.getProtocolHandler(); if(protocolHandler instanceof SipProtocolHandler) { connector.setPort(((SipProtocolHandler)protocolHandler).getPort()); ((SipProtocolHandler)protocolHandler).setSipStack(sipStack); protocolHandler.setAttribute(SipApplicationDispatcher.class.getSimpleName(), sipApplicationDispatcher); if(balancers != null) { protocolHandler.setAttribute("balancers", balancers); } registerSipConnector(connector); } super.addConnector(connector); } /** * Register the sip connector under a different name than HTTP Connector and we add the transport to avoid clashing with 2 connectors having the same port and address * @param connector connector to register */ protected void registerSipConnector(Connector connector) { try { ObjectName objectName = createSipConnectorObjectName(connector, getName(), "SipConnector"); Registry.getRegistry(null, null) .registerComponent(connector, objectName, null); connector.setController(objectName); } catch (Exception e) { logger.error( "Error registering connector ", e); } if(logger.isDebugEnabled()) logger.debug("Creating name for connector " + oname); } @Override public void removeConnector(Connector connector) { ExtendedListeningPoint extendedListeningPoint = (ExtendedListeningPoint) connector.getProtocolHandler().getAttribute(ExtendedListeningPoint.class.getSimpleName()); if(extendedListeningPoint != null) { extendedListeningPoint.getSipProvider().removeSipListener(sipApplicationDispatcher); sipApplicationDispatcher.getSipNetworkInterfaceManager().removeExtendedListeningPoint(extendedListeningPoint); } super.removeConnector(connector); } @Override public void initialize() throws LifecycleException { //load the sip application disptacher from the class name specified in the server.xml file //and initializes it StaticServiceHolder.sipStandardService = this; try { sipApplicationDispatcher = (SipApplicationDispatcher) Class.forName(sipApplicationDispatcherClassName).newInstance(); } catch (InstantiationException e) { throw new LifecycleException("Impossible to load the Sip Application Dispatcher",e); } catch (IllegalAccessException e) { throw new LifecycleException("Impossible to load the Sip Application Dispatcher",e); } catch (ClassNotFoundException e) { throw new LifecycleException("Impossible to load the Sip Application Dispatcher",e); } catch (ClassCastException e) { throw new LifecycleException("Sip Application Dispatcher defined does not implement " + SipApplicationDispatcher.class.getName(),e); } if(logger.isInfoEnabled()) { logger.info("Pretty encoding of headers enabled ? " + usePrettyEncoding); } if(sipPathName == null) { sipPathName = DEFAULT_SIP_PATH_NAME; } if(logger.isInfoEnabled()) { logger.info("Sip Stack path name : " + sipPathName); } SipFactories.initialize(sipPathName, usePrettyEncoding); if(darConfigurationFileLocation != null) { if(!darConfigurationFileLocation.startsWith("file:///")) { darConfigurationFileLocation = "file:///" + System.getProperty("catalina.home").replace(File.separatorChar, '/') + "/" + darConfigurationFileLocation; } System.setProperty("javax.servlet.sip.dar", darConfigurationFileLocation); } super.initialize(); sipApplicationDispatcher.setDomain(this.getName()); if(baseTimerInterval < 1) { throw new LifecycleException("It's forbidden to set the Base Timer Interval to a non positive value"); } initSipStack(); sipApplicationDispatcher.setBaseTimerInterval(baseTimerInterval); sipApplicationDispatcher.setT2Interval(t2Interval); sipApplicationDispatcher.setT4Interval(t4Interval); sipApplicationDispatcher.setTimerDInterval(timerDInterval); sipApplicationDispatcher.setMemoryThreshold(getMemoryThreshold()); sipApplicationDispatcher.setBackToNormalMemoryThreshold(backToNormalMemoryThreshold); sipApplicationDispatcher.setCongestionControlCheckingInterval(getCongestionControlCheckingInterval()); sipApplicationDispatcher.setCongestionControlPolicyByName(getCongestionControlPolicy()); sipApplicationDispatcher.setQueueSize(getSipMessageQueueSize()); sipApplicationDispatcher.setBackToNormalQueueSize(backToNormalSipMessageQueueSize); sipApplicationDispatcher.setGatherStatistics(gatherStatistics); sipApplicationDispatcher.setConcurrencyControlMode(ConcurrencyControlMode.valueOf(getConcurrencyControlMode())); sipApplicationDispatcher.setBypassRequestExecutor(bypassRequestExecutor); sipApplicationDispatcher.setBypassResponseExecutor(bypassResponseExecutor); sipApplicationDispatcher.setSipStack(sipStack); sipApplicationDispatcher.init(); } @Override public void start() throws LifecycleException { super.start(); synchronized (connectors) { for (Connector connector : connectors) { final ProtocolHandler protocolHandler = connector.getProtocolHandler(); //Jboss sepcific loading case Boolean isSipConnector = (Boolean) protocolHandler.getAttribute(SipProtocolHandler.IS_SIP_CONNECTOR); if(isSipConnector != null && isSipConnector) { if(logger.isDebugEnabled()) { logger.debug("Attaching the sip application dispatcher " + "as a sip listener to connector listening on port " + connector.getPort()); } protocolHandler.setAttribute(SipApplicationDispatcher.class.getSimpleName(), sipApplicationDispatcher); ((SipProtocolHandler)protocolHandler).setSipStack(sipStack); if(balancers != null) { protocolHandler.setAttribute("balancers", balancers); } connectorsStartedExternally = true; } //Tomcat specific loading case ExtendedListeningPoint extendedListeningPoint = (ExtendedListeningPoint) protocolHandler.getAttribute(ExtendedListeningPoint.class.getSimpleName()); SipStack sipStack = (SipStack) protocolHandler.getAttribute(SipStack.class.getSimpleName()); if(extendedListeningPoint != null && sipStack != null) { // for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups if(sipStack instanceof SipStackExt && addressResolverClass != null && addressResolverClass.trim().length() > 0) { if(logger.isDebugEnabled()) { logger.debug("Sip Stack " + sipStack.getStackName() +" will be using " + addressResolverClass + " as AddressResolver"); } try { extendedListeningPoint.getSipProvider().addSipListener(sipApplicationDispatcher); sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint); connectorsStartedExternally = false; //setting up the Address Resolver : // get constructor of AddressResolver in order to instantiate Class[] paramTypes = new Class[1]; paramTypes[0] = SipApplicationDispatcher.class; Constructor addressResolverConstructor = Class.forName(addressResolverClass).getConstructor( paramTypes); // Wrap properties object in order to pass to constructor of AddressResolver Object[] conArgs = new Object[1]; conArgs[0] = sipApplicationDispatcher; // Creates a new instance of AddressResolver Class with the supplied sipApplicationDispatcher. AddressResolver addressResolver = (AddressResolver) addressResolverConstructor.newInstance(conArgs); ((SipStackExt) sipStack).setAddressResolver(addressResolver); } catch (Exception e) { throw new LifecycleException("Couldn't set the AddressResolver " + addressResolverClass, e); } } else { if(logger.isInfoEnabled()) { logger.info("no AddressResolver will be used since none has been specified."); } } } } } if(!connectorsStartedExternally) { sipApplicationDispatcher.start(); } if(this.getSipMessageQueueSize() <= 0) throw new IllegalArgumentException("Message queue size can not be 0 or less"); } protected void initSipStack() throws LifecycleException { try { if(logger.isDebugEnabled()) { logger.debug("Initializing SIP stack"); } // This simply puts HTTP and SSL port numbers in JVM properties menat to be read by jsip ha when sending heart beats with Node description. StaticServiceHolder.sipStandardService.initializeSystemPortProperties(); String catalinaHome = System.getProperty("catalina.home"); if (catalinaHome == null) { catalinaHome = System.getProperty("catalina.base"); } if(catalinaHome == null) { catalinaHome = "."; } if(sipStackPropertiesFileLocation != null && !sipStackPropertiesFileLocation.startsWith("file:///")) { sipStackPropertiesFileLocation = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFileLocation; } boolean isPropsLoaded = false; if(sipStackProperties == null) { sipStackProperties = new Properties(); } else { isPropsLoaded = true; } if (logger.isDebugEnabled()) { logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFileLocation); } if(sipStackPropertiesFileLocation != null) { //hack to get around space char in path see http://weblogs.java.net/blog/kohsuke/archive/2007/04/how_to_convert.html, // we create a URL since it's permissive enough File sipStackPropertiesFile = null; URL url = null; try { url = new URL(sipStackPropertiesFileLocation); } catch (MalformedURLException e) { logger.fatal("Cannot find the sip stack properties file ! ",e); throw new IllegalArgumentException("The Default Application Router file Location : "+sipStackPropertiesFileLocation+" is not valid ! ",e); } try { sipStackPropertiesFile = new File(new URI(sipStackPropertiesFileLocation)); } catch (URISyntaxException e) { //if the uri contains space this will fail, so getting the path will work sipStackPropertiesFile = new File(url.getPath()); } FileInputStream sipStackPropertiesInputStream = null; try { sipStackPropertiesInputStream = new FileInputStream(sipStackPropertiesFile); sipStackProperties.load(sipStackPropertiesInputStream); } catch (Exception e) { logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFileLocation, e); } finally { if(sipStackPropertiesInputStream != null) { try { sipStackPropertiesInputStream.close(); } catch (IOException e) { logger.error("fail to close the following file " + sipStackPropertiesFile.getAbsolutePath(), e); } } } String debugLog = sipStackProperties.getProperty(DEBUG_LOG_STACK_PROP); if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) { sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + debugLog); } String serverLog = sipStackProperties.getProperty(SERVER_LOG_STACK_PROP); if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) { sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + serverLog); } // The whole MSS is built upon those assumptions, so those properties are not overrideable sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); isPropsLoaded = true; } else { logger.warn("no sip stack properties file defined "); } if(!isPropsLoaded) { logger.warn("loading default Mobicents Sip Servlets sip stack properties"); // Silently set default values sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32"); sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-debug.txt"); sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-messages.xml"); sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + getName()); sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64"); sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS", "1"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); } if(sipStackProperties.get(TCP_POST_PARSING_THREAD_POOL_SIZE) == null) { sipStackProperties.setProperty(TCP_POST_PARSING_THREAD_POOL_SIZE, "30"); } - if(sipStackProperties.get("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING") == null) { - sipStackProperties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false"); - } + sipStackProperties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false"); String serverHeaderValue = sipStackProperties.getProperty(SERVER_HEADER); if(serverHeaderValue != null) { List<String> serverHeaderList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(serverHeaderValue, ","); while(stringTokenizer.hasMoreTokens()) { serverHeaderList.add(stringTokenizer.nextToken()); } ServerHeader serverHeader = SipFactories.headerFactory.createServerHeader(serverHeaderList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultServerHeader(serverHeader); } String userAgent = sipStackProperties.getProperty(USER_AGENT_HEADER); if(userAgent != null) { List<String> userAgentList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(userAgent, ","); while(stringTokenizer.hasMoreTokens()) { userAgentList.add(stringTokenizer.nextToken()); } UserAgentHeader userAgentHeader = SipFactories.headerFactory.createUserAgentHeader(userAgentList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultUserAgentHeader(userAgentHeader); } if(logger.isInfoEnabled()) { logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties); } // final String balancers = (String)getAttribute(BALANCERS); if(balancers != null) { if(sipStackProperties.get(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME, LoadBalancerHeartBeatingServiceImpl.class.getCanonicalName()); } if(sipStackProperties.get(LoadBalancerHeartBeatingService.BALANCERS) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.BALANCERS, balancers); } } sipStackProperties.put("org.mobicents.ha.javax.sip.REPLICATION_STRATEGY", "ConfirmedDialogNoApplicationData"); // Create SipStack object sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties); LoadBalancerHeartBeatingService loadBalancerHeartBeatingService = null; if(sipStack instanceof ClusteredSipStack) { loadBalancerHeartBeatingService = ((ClusteredSipStack) sipStack).getLoadBalancerHeartBeatingService(); if ((this.container != null) && (this.container instanceof Engine) && ((Engine)container).getJvmRoute() != null) { final String jvmRoute = ((Engine)container).getJvmRoute(); if(jvmRoute != null) { loadBalancerHeartBeatingService.setJvmRoute(jvmRoute); } } } if(sipApplicationDispatcher != null && loadBalancerHeartBeatingService != null && sipApplicationDispatcher instanceof LoadBalancerHeartBeatingListener) { loadBalancerHeartBeatingService.addLoadBalancerHeartBeatingListener((LoadBalancerHeartBeatingListener)sipApplicationDispatcher); } // for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups if(sipStack instanceof SipStackExt && addressResolverClass != null && addressResolverClass.trim().length() > 0) { if(logger.isDebugEnabled()) { logger.debug("Sip Stack " + sipStack.getStackName() +" will be using " + addressResolverClass + " as AddressResolver"); } try { // create parameters argument to identify constructor Class[] paramTypes = new Class[1]; paramTypes[0] = SipApplicationDispatcher.class; // get constructor of AddressResolver in order to instantiate Constructor addressResolverConstructor = Class.forName(addressResolverClass).getConstructor( paramTypes); // Wrap properties object in order to pass to constructor of AddressResolver Object[] conArgs = new Object[1]; conArgs[0] = sipApplicationDispatcher; // Creates a new instance of AddressResolver Class with the supplied sipApplicationDispatcher. AddressResolver addressResolver = (AddressResolver) addressResolverConstructor.newInstance(conArgs); ((SipStackExt) sipStack).setAddressResolver(addressResolver); } catch (Exception e) { logger.error("Couldn't set the AddressResolver " + addressResolverClass, e); throw e; } } else { if(logger.isInfoEnabled()) { logger.info("no AddressResolver will be used since none has been specified."); } } if(logger.isInfoEnabled()) { logger.info("SIP stack initialized"); } } catch (Exception ex) { throw new LifecycleException("A problem occured while initializing the SIP Stack", ex); } } @Override public void stop() throws LifecycleException { super.stop(); // Tomcat specific unloading case // Issue 1411 http://code.google.com/p/mobicents/issues/detail?id=1411 // Sip Connectors should be removed after removing all Sip Servlets to allow them to send BYE to terminate cleanly synchronized (connectors) { for (Connector connector : connectors) { ExtendedListeningPoint extendedListeningPoint = (ExtendedListeningPoint) connector.getProtocolHandler().getAttribute(ExtendedListeningPoint.class.getSimpleName()); if(extendedListeningPoint != null) { extendedListeningPoint.getSipProvider().removeSipListener(sipApplicationDispatcher); sipApplicationDispatcher.getSipNetworkInterfaceManager().removeExtendedListeningPoint(extendedListeningPoint); } } } if(!connectorsStartedExternally) { sipApplicationDispatcher.stop(); } } /** * Retrieve the sip application dispatcher class name * @return the sip application dispatcher class name */ public String getSipApplicationDispatcherClassName() { return sipApplicationDispatcherClassName; } /** * Set the sip application dispatcher class name * @param sipApplicationDispatcherClassName the sip application dispatcher class name to be set */ public void setSipApplicationDispatcherClassName(String sipApplicationDispatcherName) { this.sipApplicationDispatcherClassName = sipApplicationDispatcherName; } /** * @return the sipApplicationDispatcher */ public SipApplicationDispatcher getSipApplicationDispatcher() { return sipApplicationDispatcher; } /** * @param sipApplicationDispatcher the sipApplicationDispatcher to set */ public void setSipApplicationDispatcher( SipApplicationDispatcher sipApplicationDispatcher) { this.sipApplicationDispatcher = sipApplicationDispatcher; } // /** // * @return the sipApplicationRouterClassName // */ // public String getSipApplicationRouterClassName() { // return sipApplicationRouterClassName; // } // // /** // * @param sipApplicationRouterClassName the sipApplicationRouterClassName to set // */ // public void setSipApplicationRouterClassName( // String sipApplicationRouterClassName) { // this.sipApplicationRouterClassName = sipApplicationRouterClassName; // } /** * @return the darConfigurationFileLocation */ public String getDarConfigurationFileLocation() { return darConfigurationFileLocation; } /** * @param darConfigurationFileLocation the darConfigurationFileLocation to set */ public void setDarConfigurationFileLocation(String darConfigurationFileLocation) { this.darConfigurationFileLocation = darConfigurationFileLocation; } /** * Message queue size. If the number of pending requests exceeds this number they are rejected. * * @return */ public int getSipMessageQueueSize() { return sipMessageQueueSize; } /** * Message queue size. If the number of pending requests exceeds this number they are rejected. * * @return */ public void setSipMessageQueueSize(int sipMessageQueueSize) { this.sipMessageQueueSize = sipMessageQueueSize; } /** * ConcurrencyControl control mode is SipSession, AppSession or None * Specifies the isolation level of concurrently executing requests. * * @return */ public String getConcurrencyControlMode() { return concurrencyControlMode; } /** * ConcurrencyControl control mode is SipSession, AppSession or None * Specifies the isolation level of concurrently executing requests. * * @return */ public void setConcurrencyControlMode(String concurrencyControlMode) { this.concurrencyControlMode = concurrencyControlMode; } /** * @param memoryThreshold the memoryThreshold to set */ public void setMemoryThreshold(int memoryThreshold) { this.memoryThreshold = memoryThreshold; } /** * @return the memoryThreshold */ public int getMemoryThreshold() { return memoryThreshold; } /** * @param skipStatistics the skipStatistics to set */ public void setGatherStatistics(boolean skipStatistics) { this.gatherStatistics = skipStatistics; if(logger.isInfoEnabled()) { logger.info("Gathering Statistics set to " + skipStatistics); } } /** * @return the skipStatistics */ public boolean isGatherStatistics() { return gatherStatistics; } /** * PRESENT TO ACCOMODATE JOPR. NEED TO FILE A BUG ON THIS * @return the skipStatistics */ public boolean getGatherStatistics() { return gatherStatistics; } /** * @param backToNormalPercentageOfMemoryUsed the backToNormalPercentageOfMemoryUsed to set */ public void setBackToNormalMemoryThreshold( int backToNormalMemoryThreshold) { this.backToNormalMemoryThreshold = backToNormalMemoryThreshold; } /** * @return the backToNormalPercentageOfMemoryUsed */ public int getBackToNormalMemoryThreshold() { return backToNormalMemoryThreshold; } /** * @param backToNormalQueueSize the backToNormalQueueSize to set */ public void setBackToNormalSipMessageQueueSize(int backToNormalSipMessageQueueSize) { this.backToNormalSipMessageQueueSize = backToNormalSipMessageQueueSize; } /** * @return the backToNormalQueueSize */ public int getBackToNormalSipMessageQueueSize() { return backToNormalSipMessageQueueSize; } /** * @param congestionControlPolicy the congestionControlPolicy to set */ public void setCongestionControlPolicy(String congestionControlPolicy) { this.congestionControlPolicy = congestionControlPolicy; } /** * @return the congestionControlPolicy */ public String getCongestionControlPolicy() { return congestionControlPolicy; } /** * @param congestionControlCheckingInterval the congestionControlCheckingInterval to set */ public void setCongestionControlCheckingInterval( long congestionControlCheckingInterval) { this.congestionControlCheckingInterval = congestionControlCheckingInterval; } /** * @return the congestionControlCheckingInterval */ public long getCongestionControlCheckingInterval() { return congestionControlCheckingInterval; } public String getAdditionalParameterableHeaders() { return additionalParameterableHeaders; } public void setAdditionalParameterableHeaders( String additionalParameterableHeaders) { this.additionalParameterableHeaders = additionalParameterableHeaders; String[] headers = additionalParameterableHeaders.split(","); for(String header : headers) { if(header != null && header.length()>0) { JainSipUtils.PARAMETERABLE_HEADER_NAMES.add(header); } } } /** * @return the bypassResponseExecutor */ public boolean isBypassResponseExecutor() { return bypassResponseExecutor; } /** * @param bypassResponseExecutor the bypassResponseExecutor to set */ public void setBypassResponseExecutor(boolean bypassResponseExecutor) { this.bypassResponseExecutor = bypassResponseExecutor; } /** * @return the bypassRequestExecutor */ public boolean isBypassRequestExecutor() { return bypassRequestExecutor; } /** * @param bypassRequestExecutor the bypassRequestExecutor to set */ public void setBypassRequestExecutor(boolean bypassRequestExecutor) { this.bypassRequestExecutor = bypassRequestExecutor; } /** * @param usePrettyEncoding the usePrettyEncoding to set */ public void setUsePrettyEncoding(boolean usePrettyEncoding) { this.usePrettyEncoding = usePrettyEncoding; } /** * @return the usePrettyEncoding */ public boolean isUsePrettyEncoding() { return usePrettyEncoding; } /** * @param sipPathName the sipPathName to set */ public void setSipPathName(String sipPathName) { this.sipPathName = sipPathName; } /** * @return the sipPathName */ public String getSipPathName() { return sipPathName; } /** * @param baseTimerInterval the baseTimerInterval to set */ public void setBaseTimerInterval(int baseTimerInterval) { this.baseTimerInterval = baseTimerInterval; } /** * @return the baseTimerInterval */ public int getBaseTimerInterval() { return baseTimerInterval; } public String getOutboundProxy() { return outboundProxy; } public void setOutboundProxy(String outboundProxy) { this.outboundProxy = outboundProxy; } public int getDispatcherThreadPoolSize() { return dispatcherThreadPoolSize; } public void setDispatcherThreadPoolSize(int dispatcherThreadPoolSize) { this.dispatcherThreadPoolSize = dispatcherThreadPoolSize; } /** * @deprecated * @param balancers the balancers to set */ public void setBalancers(String balancers) { this.balancers = balancers; } public boolean addSipConnector(SipConnector sipConnector) throws Exception { if(sipConnector == null) { throw new IllegalArgumentException("The sip connector passed is null"); } Connector connectorToAdd = findSipConnector(sipConnector.getIpAddress(), sipConnector.getPort(), sipConnector.getTransport()); if(connectorToAdd == null) { Connector connector = new Connector( SipProtocolHandler.class.getName()); SipProtocolHandler sipProtocolHandler = (SipProtocolHandler) connector .getProtocolHandler(); sipProtocolHandler.setSipConnector(sipConnector); sipProtocolHandler.setSipStack(sipStack); connector.setService(this); connector.setContainer(container); connector.init(); addConnector(connector); ExtendedListeningPoint extendedListeningPoint = (ExtendedListeningPoint) sipProtocolHandler.getAttribute(ExtendedListeningPoint.class.getSimpleName()); if(extendedListeningPoint != null) { try { extendedListeningPoint.getSipProvider().addSipListener(sipApplicationDispatcher); sipApplicationDispatcher.getSipNetworkInterfaceManager().addExtendedListeningPoint(extendedListeningPoint); } catch (TooManyListenersException e) { logger.error("Connector.initialize", e); removeConnector(connector); return false; } } if(!sipProtocolHandler.isStarted()) { if(logger.isDebugEnabled()) { logger.debug("Sip Connector couldn't be started, removing it automatically"); } removeConnector(connector); } return sipProtocolHandler.isStarted(); } return false; } public boolean removeSipConnector(String ipAddress, int port, String transport) throws Exception { Connector connectorToRemove = findSipConnector(ipAddress, port, transport); if(connectorToRemove != null) { removeConnector(connectorToRemove); return true; } return false; } /** * Find a sip Connector by it's ip address, port and transport * @param ipAddress ip address of the connector to find * @param port port of the connector to find * @param transport transport of the connector to find * @return the found sip connector or null if noting found */ private Connector findSipConnector(String ipAddress, int port, String transport) { Connector connectorToRemove = null; for (Connector connector : connectors) { final ProtocolHandler protocolHandler = connector.getProtocolHandler(); if(protocolHandler instanceof SipProtocolHandler) { final SipProtocolHandler sipProtocolHandler = (SipProtocolHandler) protocolHandler; if(sipProtocolHandler.getIpAddress().equals(ipAddress) && sipProtocolHandler.getPort() == port && sipProtocolHandler.getSignalingTransport().equals(transport)) { // connector.destroy(); connectorToRemove = connector; break; } } } return connectorToRemove; } public SipConnector findSipConnector(String transport) { List<SipConnector> sipConnectors = new ArrayList<SipConnector>(); for (Connector connector : connectors) { final ProtocolHandler protocolHandler = connector.getProtocolHandler(); if(protocolHandler instanceof SipProtocolHandler) { SipConnector sc = (((SipProtocolHandler)protocolHandler).getSipConnector()); if(sc.getTransport().equalsIgnoreCase(transport)) return sc; } } return null; } public SipConnector[] findSipConnectors() { List<SipConnector> sipConnectors = new ArrayList<SipConnector>(); for (Connector connector : connectors) { final ProtocolHandler protocolHandler = connector.getProtocolHandler(); if(protocolHandler instanceof SipProtocolHandler) { sipConnectors.add(((SipProtocolHandler)protocolHandler).getSipConnector()); } } return sipConnectors.toArray(new SipConnector[sipConnectors.size()]); } /** * This method simply makes the HTTP and SSL ports avaialble everywhere in the JVM in order jsip ha to read them for * balancer description purposes. There is no other good way to communicate the properies to jsip ha without adding * more dependencies. */ public void initializeSystemPortProperties() { for (Connector connector : connectors) { if(connector.getProtocol().contains("HTTP")) { if(connector.getSecure()) { System.setProperty("org.mobicents.properties.sslPort", Integer.toString(connector.getPort())); } else { System.setProperty("org.mobicents.properties.httpPort", Integer.toString(connector.getPort())); } } } } protected ObjectName createSipConnectorObjectName(Connector connector, String domain, String type) throws MalformedObjectNameException { String encodedAddr = null; if (connector.getProperty("address") != null) { encodedAddr = URLEncoder.encode(connector.getProperty("address").toString()); } String addSuffix = (connector.getProperty("address") == null) ? "" : ",address=" + encodedAddr; ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port=" + connector.getPort() + ",transport=" + connector.getProperty("transport") + addSuffix); return _oname; } /** * @param t2Interval the t2Interval to set */ public void setT2Interval(int t2Interval) { this.t2Interval = t2Interval; } /** * @return the t2Interval */ public int getT2Interval() { return t2Interval; } /** * @param t4Interval the t4Interval to set */ public void setT4Interval(int t4Interval) { this.t4Interval = t4Interval; } /** * @return the t4Interval */ public int getT4Interval() { return t4Interval; } /** * @param timerDInterval the timerDInterval to set */ public void setTimerDInterval(int timerDInterval) { this.timerDInterval = timerDInterval; } /** * @return the timerDInterval */ public int getTimerDInterval() { return timerDInterval; } /** * @param sipStackPropertiesFile the sipStackPropertiesFile to set */ public void setSipStackPropertiesFile(String sipStackPropertiesFile) { sipStackPropertiesFileLocation = sipStackPropertiesFile; } /** * @return the sipStackProperties */ public Properties getSipStackProperties() { return sipStackProperties; } /** * @param sipStackProperties the sipStackProperties to set */ public void setSipStackProperties(Properties sipStackProperties) { this.sipStackProperties = sipStackProperties; } /** * @return the sipStackPropertiesFile */ public String getSipStackPropertiesFile() { return sipStackPropertiesFileLocation; } /** * @param dnsAddressResolverClass the dnsAddressResolverClass to set */ public void setAddressResolverClass(String dnsAddressResolverClass) { this.addressResolverClass = dnsAddressResolverClass; } /** * @return the dnsAddressResolverClass */ public String getAddressResolverClass() { return addressResolverClass; } /** * Whether we check for pending requests and return 491 response if there are any * * @return the flag value */ public boolean isDialogPendingRequestChecking() { return dialogPendingRequestChecking; } /** * * Whether we check for pending requests and return 491 response if there are any * * @param dialogPendingRequestChecking */ public void setDialogPendingRequestChecking(boolean dialogPendingRequestChecking) { this.dialogPendingRequestChecking = dialogPendingRequestChecking; } }
true
true
protected void initSipStack() throws LifecycleException { try { if(logger.isDebugEnabled()) { logger.debug("Initializing SIP stack"); } // This simply puts HTTP and SSL port numbers in JVM properties menat to be read by jsip ha when sending heart beats with Node description. StaticServiceHolder.sipStandardService.initializeSystemPortProperties(); String catalinaHome = System.getProperty("catalina.home"); if (catalinaHome == null) { catalinaHome = System.getProperty("catalina.base"); } if(catalinaHome == null) { catalinaHome = "."; } if(sipStackPropertiesFileLocation != null && !sipStackPropertiesFileLocation.startsWith("file:///")) { sipStackPropertiesFileLocation = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFileLocation; } boolean isPropsLoaded = false; if(sipStackProperties == null) { sipStackProperties = new Properties(); } else { isPropsLoaded = true; } if (logger.isDebugEnabled()) { logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFileLocation); } if(sipStackPropertiesFileLocation != null) { //hack to get around space char in path see http://weblogs.java.net/blog/kohsuke/archive/2007/04/how_to_convert.html, // we create a URL since it's permissive enough File sipStackPropertiesFile = null; URL url = null; try { url = new URL(sipStackPropertiesFileLocation); } catch (MalformedURLException e) { logger.fatal("Cannot find the sip stack properties file ! ",e); throw new IllegalArgumentException("The Default Application Router file Location : "+sipStackPropertiesFileLocation+" is not valid ! ",e); } try { sipStackPropertiesFile = new File(new URI(sipStackPropertiesFileLocation)); } catch (URISyntaxException e) { //if the uri contains space this will fail, so getting the path will work sipStackPropertiesFile = new File(url.getPath()); } FileInputStream sipStackPropertiesInputStream = null; try { sipStackPropertiesInputStream = new FileInputStream(sipStackPropertiesFile); sipStackProperties.load(sipStackPropertiesInputStream); } catch (Exception e) { logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFileLocation, e); } finally { if(sipStackPropertiesInputStream != null) { try { sipStackPropertiesInputStream.close(); } catch (IOException e) { logger.error("fail to close the following file " + sipStackPropertiesFile.getAbsolutePath(), e); } } } String debugLog = sipStackProperties.getProperty(DEBUG_LOG_STACK_PROP); if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) { sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + debugLog); } String serverLog = sipStackProperties.getProperty(SERVER_LOG_STACK_PROP); if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) { sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + serverLog); } // The whole MSS is built upon those assumptions, so those properties are not overrideable sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); isPropsLoaded = true; } else { logger.warn("no sip stack properties file defined "); } if(!isPropsLoaded) { logger.warn("loading default Mobicents Sip Servlets sip stack properties"); // Silently set default values sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32"); sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-debug.txt"); sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-messages.xml"); sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + getName()); sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64"); sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS", "1"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); } if(sipStackProperties.get(TCP_POST_PARSING_THREAD_POOL_SIZE) == null) { sipStackProperties.setProperty(TCP_POST_PARSING_THREAD_POOL_SIZE, "30"); } if(sipStackProperties.get("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING") == null) { sipStackProperties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false"); } String serverHeaderValue = sipStackProperties.getProperty(SERVER_HEADER); if(serverHeaderValue != null) { List<String> serverHeaderList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(serverHeaderValue, ","); while(stringTokenizer.hasMoreTokens()) { serverHeaderList.add(stringTokenizer.nextToken()); } ServerHeader serverHeader = SipFactories.headerFactory.createServerHeader(serverHeaderList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultServerHeader(serverHeader); } String userAgent = sipStackProperties.getProperty(USER_AGENT_HEADER); if(userAgent != null) { List<String> userAgentList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(userAgent, ","); while(stringTokenizer.hasMoreTokens()) { userAgentList.add(stringTokenizer.nextToken()); } UserAgentHeader userAgentHeader = SipFactories.headerFactory.createUserAgentHeader(userAgentList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultUserAgentHeader(userAgentHeader); } if(logger.isInfoEnabled()) { logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties); } // final String balancers = (String)getAttribute(BALANCERS); if(balancers != null) { if(sipStackProperties.get(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME, LoadBalancerHeartBeatingServiceImpl.class.getCanonicalName()); } if(sipStackProperties.get(LoadBalancerHeartBeatingService.BALANCERS) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.BALANCERS, balancers); } } sipStackProperties.put("org.mobicents.ha.javax.sip.REPLICATION_STRATEGY", "ConfirmedDialogNoApplicationData"); // Create SipStack object sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties); LoadBalancerHeartBeatingService loadBalancerHeartBeatingService = null; if(sipStack instanceof ClusteredSipStack) { loadBalancerHeartBeatingService = ((ClusteredSipStack) sipStack).getLoadBalancerHeartBeatingService(); if ((this.container != null) && (this.container instanceof Engine) && ((Engine)container).getJvmRoute() != null) { final String jvmRoute = ((Engine)container).getJvmRoute(); if(jvmRoute != null) { loadBalancerHeartBeatingService.setJvmRoute(jvmRoute); } } } if(sipApplicationDispatcher != null && loadBalancerHeartBeatingService != null && sipApplicationDispatcher instanceof LoadBalancerHeartBeatingListener) { loadBalancerHeartBeatingService.addLoadBalancerHeartBeatingListener((LoadBalancerHeartBeatingListener)sipApplicationDispatcher); } // for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups if(sipStack instanceof SipStackExt && addressResolverClass != null && addressResolverClass.trim().length() > 0) { if(logger.isDebugEnabled()) { logger.debug("Sip Stack " + sipStack.getStackName() +" will be using " + addressResolverClass + " as AddressResolver"); } try { // create parameters argument to identify constructor Class[] paramTypes = new Class[1]; paramTypes[0] = SipApplicationDispatcher.class; // get constructor of AddressResolver in order to instantiate Constructor addressResolverConstructor = Class.forName(addressResolverClass).getConstructor( paramTypes); // Wrap properties object in order to pass to constructor of AddressResolver Object[] conArgs = new Object[1]; conArgs[0] = sipApplicationDispatcher; // Creates a new instance of AddressResolver Class with the supplied sipApplicationDispatcher. AddressResolver addressResolver = (AddressResolver) addressResolverConstructor.newInstance(conArgs); ((SipStackExt) sipStack).setAddressResolver(addressResolver); } catch (Exception e) { logger.error("Couldn't set the AddressResolver " + addressResolverClass, e); throw e; } } else { if(logger.isInfoEnabled()) { logger.info("no AddressResolver will be used since none has been specified."); } } if(logger.isInfoEnabled()) { logger.info("SIP stack initialized"); } } catch (Exception ex) { throw new LifecycleException("A problem occured while initializing the SIP Stack", ex); } }
protected void initSipStack() throws LifecycleException { try { if(logger.isDebugEnabled()) { logger.debug("Initializing SIP stack"); } // This simply puts HTTP and SSL port numbers in JVM properties menat to be read by jsip ha when sending heart beats with Node description. StaticServiceHolder.sipStandardService.initializeSystemPortProperties(); String catalinaHome = System.getProperty("catalina.home"); if (catalinaHome == null) { catalinaHome = System.getProperty("catalina.base"); } if(catalinaHome == null) { catalinaHome = "."; } if(sipStackPropertiesFileLocation != null && !sipStackPropertiesFileLocation.startsWith("file:///")) { sipStackPropertiesFileLocation = "file:///" + catalinaHome.replace(File.separatorChar, '/') + "/" + sipStackPropertiesFileLocation; } boolean isPropsLoaded = false; if(sipStackProperties == null) { sipStackProperties = new Properties(); } else { isPropsLoaded = true; } if (logger.isDebugEnabled()) { logger.debug("Loading SIP stack properties from following file : " + sipStackPropertiesFileLocation); } if(sipStackPropertiesFileLocation != null) { //hack to get around space char in path see http://weblogs.java.net/blog/kohsuke/archive/2007/04/how_to_convert.html, // we create a URL since it's permissive enough File sipStackPropertiesFile = null; URL url = null; try { url = new URL(sipStackPropertiesFileLocation); } catch (MalformedURLException e) { logger.fatal("Cannot find the sip stack properties file ! ",e); throw new IllegalArgumentException("The Default Application Router file Location : "+sipStackPropertiesFileLocation+" is not valid ! ",e); } try { sipStackPropertiesFile = new File(new URI(sipStackPropertiesFileLocation)); } catch (URISyntaxException e) { //if the uri contains space this will fail, so getting the path will work sipStackPropertiesFile = new File(url.getPath()); } FileInputStream sipStackPropertiesInputStream = null; try { sipStackPropertiesInputStream = new FileInputStream(sipStackPropertiesFile); sipStackProperties.load(sipStackPropertiesInputStream); } catch (Exception e) { logger.warn("Could not find or problem when loading the sip stack properties file : " + sipStackPropertiesFileLocation, e); } finally { if(sipStackPropertiesInputStream != null) { try { sipStackPropertiesInputStream.close(); } catch (IOException e) { logger.error("fail to close the following file " + sipStackPropertiesFile.getAbsolutePath(), e); } } } String debugLog = sipStackProperties.getProperty(DEBUG_LOG_STACK_PROP); if(debugLog != null && debugLog.length() > 0 && !debugLog.startsWith("file:///")) { sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + debugLog); } String serverLog = sipStackProperties.getProperty(SERVER_LOG_STACK_PROP); if(serverLog != null && serverLog.length() > 0 && !serverLog.startsWith("file:///")) { sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + serverLog); } // The whole MSS is built upon those assumptions, so those properties are not overrideable sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); isPropsLoaded = true; } else { logger.warn("no sip stack properties file defined "); } if(!isPropsLoaded) { logger.warn("loading default Mobicents Sip Servlets sip stack properties"); // Silently set default values sipStackProperties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32"); sipStackProperties.setProperty(DEBUG_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-debug.txt"); sipStackProperties.setProperty(SERVER_LOG_STACK_PROP, catalinaHome + "/" + "mss-jsip-" + getName() +"-messages.xml"); sipStackProperties.setProperty("javax.sip.STACK_NAME", "mss-" + getName()); sipStackProperties.setProperty(AUTOMATIC_DIALOG_SUPPORT_STACK_PROP, "off"); sipStackProperties.setProperty("gov.nist.javax.sip.DELIVER_UNSOLICITED_NOTIFY", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.THREAD_POOL_SIZE", "64"); sipStackProperties.setProperty("gov.nist.javax.sip.REENTRANT_LISTENER", "true"); sipStackProperties.setProperty("gov.nist.javax.sip.MAX_FORK_TIME_SECONDS", "1"); sipStackProperties.setProperty(LOOSE_DIALOG_VALIDATION, "true"); sipStackProperties.setProperty(PASS_INVITE_NON_2XX_ACK_TO_LISTENER, "true"); } if(sipStackProperties.get(TCP_POST_PARSING_THREAD_POOL_SIZE) == null) { sipStackProperties.setProperty(TCP_POST_PARSING_THREAD_POOL_SIZE, "30"); } sipStackProperties.setProperty("gov.nist.javax.sip.AUTOMATIC_DIALOG_ERROR_HANDLING", "false"); String serverHeaderValue = sipStackProperties.getProperty(SERVER_HEADER); if(serverHeaderValue != null) { List<String> serverHeaderList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(serverHeaderValue, ","); while(stringTokenizer.hasMoreTokens()) { serverHeaderList.add(stringTokenizer.nextToken()); } ServerHeader serverHeader = SipFactories.headerFactory.createServerHeader(serverHeaderList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultServerHeader(serverHeader); } String userAgent = sipStackProperties.getProperty(USER_AGENT_HEADER); if(userAgent != null) { List<String> userAgentList = new ArrayList<String>(); StringTokenizer stringTokenizer = new StringTokenizer(userAgent, ","); while(stringTokenizer.hasMoreTokens()) { userAgentList.add(stringTokenizer.nextToken()); } UserAgentHeader userAgentHeader = SipFactories.headerFactory.createUserAgentHeader(userAgentList); ((MessageFactoryExt)SipFactories.messageFactory).setDefaultUserAgentHeader(userAgentHeader); } if(logger.isInfoEnabled()) { logger.info("Mobicents Sip Servlets sip stack properties : " + sipStackProperties); } // final String balancers = (String)getAttribute(BALANCERS); if(balancers != null) { if(sipStackProperties.get(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.LB_HB_SERVICE_CLASS_NAME, LoadBalancerHeartBeatingServiceImpl.class.getCanonicalName()); } if(sipStackProperties.get(LoadBalancerHeartBeatingService.BALANCERS) == null) { sipStackProperties.put(LoadBalancerHeartBeatingService.BALANCERS, balancers); } } sipStackProperties.put("org.mobicents.ha.javax.sip.REPLICATION_STRATEGY", "ConfirmedDialogNoApplicationData"); // Create SipStack object sipStack = SipFactories.sipFactory.createSipStack(sipStackProperties); LoadBalancerHeartBeatingService loadBalancerHeartBeatingService = null; if(sipStack instanceof ClusteredSipStack) { loadBalancerHeartBeatingService = ((ClusteredSipStack) sipStack).getLoadBalancerHeartBeatingService(); if ((this.container != null) && (this.container instanceof Engine) && ((Engine)container).getJvmRoute() != null) { final String jvmRoute = ((Engine)container).getJvmRoute(); if(jvmRoute != null) { loadBalancerHeartBeatingService.setJvmRoute(jvmRoute); } } } if(sipApplicationDispatcher != null && loadBalancerHeartBeatingService != null && sipApplicationDispatcher instanceof LoadBalancerHeartBeatingListener) { loadBalancerHeartBeatingService.addLoadBalancerHeartBeatingListener((LoadBalancerHeartBeatingListener)sipApplicationDispatcher); } // for nist sip stack set the DNS Address resolver allowing to make DNS SRV lookups if(sipStack instanceof SipStackExt && addressResolverClass != null && addressResolverClass.trim().length() > 0) { if(logger.isDebugEnabled()) { logger.debug("Sip Stack " + sipStack.getStackName() +" will be using " + addressResolverClass + " as AddressResolver"); } try { // create parameters argument to identify constructor Class[] paramTypes = new Class[1]; paramTypes[0] = SipApplicationDispatcher.class; // get constructor of AddressResolver in order to instantiate Constructor addressResolverConstructor = Class.forName(addressResolverClass).getConstructor( paramTypes); // Wrap properties object in order to pass to constructor of AddressResolver Object[] conArgs = new Object[1]; conArgs[0] = sipApplicationDispatcher; // Creates a new instance of AddressResolver Class with the supplied sipApplicationDispatcher. AddressResolver addressResolver = (AddressResolver) addressResolverConstructor.newInstance(conArgs); ((SipStackExt) sipStack).setAddressResolver(addressResolver); } catch (Exception e) { logger.error("Couldn't set the AddressResolver " + addressResolverClass, e); throw e; } } else { if(logger.isInfoEnabled()) { logger.info("no AddressResolver will be used since none has been specified."); } } if(logger.isInfoEnabled()) { logger.info("SIP stack initialized"); } } catch (Exception ex) { throw new LifecycleException("A problem occured while initializing the SIP Stack", ex); } }
diff --git a/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java b/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java index 153d2989b..3151cc22d 100644 --- a/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java +++ b/RecentActivity/src/org/sleuthkit/autopsy/recentactivity/Chrome.java @@ -1,458 +1,482 @@ /* * * Autopsy Forensic Browser * * Copyright 2012 Basis Technology Corp. * * Copyright 2012 42six Solutions. * Contact: aebadirad <at> 42six <dot> com * Project Contact/Architect: carrier <at> sleuthkit <dot> org * * 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.sleuthkit.autopsy.recentactivity; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.sleuthkit.autopsy.ingest.IngestServices; import org.sleuthkit.datamodel.FsContent; import org.sleuthkit.autopsy.datamodel.ContentUtils; import java.util.logging.Level; import org.sleuthkit.autopsy.coreutils.Logger; import java.util.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.SQLException; import org.sleuthkit.autopsy.casemodule.services.FileManager; import org.sleuthkit.autopsy.coreutils.EscapeUtil; import org.sleuthkit.autopsy.ingest.IngestImageWorkerController; import org.sleuthkit.autopsy.ingest.IngestModuleImage; import org.sleuthkit.autopsy.ingest.IngestModuleInit; import org.sleuthkit.autopsy.ingest.ModuleDataEvent; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE; import org.sleuthkit.datamodel.BlackboardAttribute; import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE; import org.sleuthkit.datamodel.Image; import org.sleuthkit.datamodel.TskCoreException; /** * Chrome recent activity extraction */ public class Chrome extends Extract implements IngestModuleImage { private static final String chquery = "SELECT urls.url, urls.title, urls.visit_count, urls.typed_count, " + "last_visit_time, urls.hidden, visits.visit_time, (SELECT urls.url FROM urls WHERE urls.id=visits.url) as from_visit, visits.transition FROM urls, visits WHERE urls.id = visits.url"; private static final String chcookiequery = "select name, value, host_key, expires_utc,last_access_utc, creation_utc from cookies"; private static final String chbookmarkquery = "SELECT starred.title, urls.url, starred.date_added, starred.date_modified, urls.typed_count,urls._last_visit_time FROM starred INNER JOIN urls ON urls.id = starred.url_id"; private static final String chdownloadquery = "select full_path, url, start_time, received_bytes from downloads"; private static final String chloginquery = "select origin_url, username_value, signon_realm from logins"; private final Logger logger = Logger.getLogger(this.getClass().getName()); public int ChromeCount = 0; final public static String MODULE_VERSION = "1.0"; private String args; private IngestServices services; //hide public constructor to prevent from instantiation by ingest module loader Chrome() { moduleName = "Chrome"; } @Override public String getVersion() { return MODULE_VERSION; } @Override public String getArguments() { return args; } @Override public void setArguments(String args) { this.args = args; } @Override public void process(Image image, IngestImageWorkerController controller) { this.getHistory(image, controller); this.getBookmark(image, controller); this.getCookie(image, controller); this.getLogin(image, controller); this.getDownload(image, controller); } private void getHistory(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> historyFiles = null; try { historyFiles = fileManager.findFiles(image, "History", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (historyFiles != null && !historyFiles.isEmpty()) { while (j < historyFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + historyFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(historyFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + historyFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome web history artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + historyFiles.get(j).getName()); } File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } List<HashMap<String, Object>> tempList = this.dbConnect(temps, chquery); logger.log(Level.INFO, moduleName + "- Now getting history from " + temps + " with " + tempList.size() + "artifacts identified."); for (HashMap<String, Object> result : tempList) { Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? result.get("url").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? EscapeUtil.decodeURL(result.get("url").toString()) : ""))); //TODO Revisit usage of deprecated constructor per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_visit_time").toString())) / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_visit_time").toString())) / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID(), "Recent Activity", ((result.get("from_visit").toString() != null) ? result.get("from_visit").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("title").toString() != null) ? result.get("title").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", (Util.extractDomain((result.get("url").toString() != null) ? result.get("url").toString() : "")))); this.addArtifact(ARTIFACT_TYPE.TSK_WEB_HISTORY, historyFiles.get(j), bbattributes); } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome web history artifacts."); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY)); } } private void getBookmark(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> bookmarkFiles = null; try { bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) { while (j < bookmarkFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(bookmarkFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFiles.get(j).getName()); } logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps); File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } try { - final JsonParser parser = new JsonParser(); + final JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(temps)); JsonObject jElement = jsonElement.getAsJsonObject(); JsonObject jRoot = jElement.get("roots").getAsJsonObject(); JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject(); JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children"); for (JsonElement result : jBookmarkArray) { try { JsonObject address = result.getAsJsonObject(); - String url = address.get("url").getAsString(); - String name = address.get("name").getAsString(); - Long date = address.get("date_added").getAsLong(); + if (address == null) { + continue; + } + JsonElement urlEl = address.get("url"); + String url = null; + if (urlEl != null) { + url = urlEl.getAsString(); + } + else { + url = ""; + } + String name = null; + JsonElement nameEl = address.get("name"); + if (nameEl != null) { + name = nameEl.getAsString(); + } + else { + name = ""; + } + Long date = null; + JsonElement dateEl = address.get("date_added"); + if (dateEl != null) { + date = dateEl.getAsLong(); + } + else { + date = Long.valueOf(0); + } String domain = Util.extractDomain(url); BlackboardArtifact bbart = bookmarkFiles.get(j).newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK); Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain)); bbart.addAttributes(bbattributes); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex); errors++; } } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts."); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK)); } } //COOKIES section // This gets the cookie info private void getCookie(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> cookiesFiles = null; try { cookiesFiles = fileManager.findFiles(image, "Cookies", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (cookiesFiles != null && !cookiesFiles.isEmpty()) { while (j < cookiesFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + cookiesFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(cookiesFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + cookiesFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome cookie artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + cookiesFiles.get(j).getName()); } File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } List<HashMap<String, Object>> tempList = this.dbConnect(temps, chcookiequery); logger.log(Level.INFO, moduleName + "- Now getting cookies from " + temps + " with " + tempList.size() + "artifacts identified."); for (HashMap<String, Object> result : tempList) { Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", "Title", ((result.get("name").toString() != null) ? result.get("name").toString() : ""))); //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_access_utc").toString())) / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("name").toString() != null) ? result.get("name").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_access_utc").toString())) / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), "Recent Activity", ((result.get("value").toString() != null) ? result.get("value").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("host_key").toString() != null) ? result.get("host_key").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("host_key").toString() != null) ? EscapeUtil.decodeURL(result.get("host_key").toString()) : ""))); String domain = result.get("host_key").toString(); domain = domain.replaceFirst("^\\.+(?!$)", ""); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain)); this.addArtifact(ARTIFACT_TYPE.TSK_WEB_COOKIE, cookiesFiles.get(j), bbattributes); } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome cookie artifacts."); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_COOKIE)); } } //Downloads section // This gets the downloads info private void getDownload(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> historyFiles = null; try { historyFiles = fileManager.findFiles(image, "History", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (historyFiles != null && !historyFiles.isEmpty()) { while (j < historyFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + historyFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(historyFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + historyFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome download artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + historyFiles.get(j).getName()); } File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } List<HashMap<String, Object>> tempList = this.dbConnect(temps, chdownloadquery); logger.log(Level.INFO, moduleName + "- Now getting downloads from " + temps + " with " + tempList.size() + "artifacts identified."); for (HashMap<String, Object> result : tempList) { Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PATH.getTypeID(), "Recent Activity", (result.get("full_path").toString()))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PATH_ID.getTypeID(), "Recent Activity", Util.findID(image, (result.get("full_path").toString())))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? result.get("url").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("url").toString() != null) ? EscapeUtil.decodeURL(result.get("url").toString()) : ""))); Long time = (Long.valueOf(result.get("start_time").toString())); String Tempdate = time.toString(); time = Long.valueOf(Tempdate) / 10000000; //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", time)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", time)); String domain = Util.extractDomain((result.get("url").toString() != null) ? result.get("url").toString() : ""); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); this.addArtifact(ARTIFACT_TYPE.TSK_WEB_DOWNLOAD, historyFiles.get(j), bbattributes); } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome download artifacts."); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_DOWNLOAD)); } } //Login/Password section // This gets the user info private void getLogin(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> signonFiles = null; try { signonFiles = fileManager.findFiles(image, "signons.sqlite", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (signonFiles != null && !signonFiles.isEmpty()) { while (j < signonFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + signonFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(signonFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + signonFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome login artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + signonFiles.get(j).getName()); } File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } List<HashMap<String, Object>> tempList = this.dbConnect(temps, chloginquery); logger.log(Level.INFO, moduleName + "- Now getting login information from " + temps + " with " + tempList.size() + "artifacts identified."); for (HashMap<String, Object> result : tempList) { Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", ((result.get("origin_url").toString() != null) ? result.get("origin_url").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", ((result.get("origin_url").toString() != null) ? EscapeUtil.decodeURL(result.get("origin_url").toString()) : ""))); //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", ((Long.valueOf(result.get("last_visit_time").toString())) / 1000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Recent Activity", ((Long.valueOf(result.get("last_visit_time").toString())) / 1000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_REFERRER.getTypeID(), "Recent Activity", ((result.get("from_visit").toString() != null) ? result.get("from_visit").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", ((result.get("title").toString() != null) ? result.get("title").toString() : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", (Util.extractDomain((result.get("origin_url").toString() != null) ? result.get("url").toString() : "")))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_USERNAME.getTypeID(), "Recent Activity", ((result.get("username_value").toString() != null) ? result.get("username_value").toString().replaceAll("'", "''") : ""))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", result.get("signon_realm").toString())); this.addArtifact(ARTIFACT_TYPE.TSK_WEB_HISTORY, signonFiles.get(j), bbattributes); } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome login artifacts."); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_HISTORY)); } } @Override public void init(IngestModuleInit initContext) { services = IngestServices.getDefault(); } @Override public void complete() { logger.info("Chrome Extract has completed"); } @Override public void stop() { logger.info("Attmped to stop chrome extract, but operation is not supported; skipping..."); } @Override public String getDescription() { return "Extracts activity from the Google Chrome browser."; } @Override public ModuleType getType() { return ModuleType.Image; } @Override public boolean hasSimpleConfiguration() { return false; } @Override public boolean hasAdvancedConfiguration() { return false; } @Override public javax.swing.JPanel getSimpleConfiguration() { return null; } @Override public javax.swing.JPanel getAdvancedConfiguration() { return null; } @Override public void saveAdvancedConfiguration() { } @Override public void saveSimpleConfiguration() { } @Override public boolean hasBackgroundJobsRunning() { return false; } }
false
true
private void getBookmark(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> bookmarkFiles = null; try { bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) { while (j < bookmarkFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(bookmarkFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFiles.get(j).getName()); } logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps); File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } try { final JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(temps)); JsonObject jElement = jsonElement.getAsJsonObject(); JsonObject jRoot = jElement.get("roots").getAsJsonObject(); JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject(); JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children"); for (JsonElement result : jBookmarkArray) { try { JsonObject address = result.getAsJsonObject(); String url = address.get("url").getAsString(); String name = address.get("name").getAsString(); Long date = address.get("date_added").getAsLong(); String domain = Util.extractDomain(url); BlackboardArtifact bbart = bookmarkFiles.get(j).newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK); Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain)); bbart.addAttributes(bbattributes); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex); errors++; } } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts."); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK)); } }
private void getBookmark(Image image, IngestImageWorkerController controller) { FileManager fileManager = currentCase.getServices().getFileManager(); List<FsContent> bookmarkFiles = null; try { bookmarkFiles = fileManager.findFiles(image, "Bookmarks", "Chrome"); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error when trying to get Chrome history files.", ex); } int j = 0; if (bookmarkFiles != null && !bookmarkFiles.isEmpty()) { while (j < bookmarkFiles.size()) { String temps = currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db"; int errors = 0; try { ContentUtils.writeToFile(bookmarkFiles.get(j), new File(currentCase.getTempDirectory() + File.separator + bookmarkFiles.get(j).getName().toString() + j + ".db")); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing temp sqlite db for Chrome bookmark artifacts.{0}", ex); this.addErrorMessage(this.getName() + ": Error while trying to analyze file:" + bookmarkFiles.get(j).getName()); } logger.log(Level.INFO, moduleName + "- Now getting Bookmarks from " + temps); File dbFile = new File(temps); if (controller.isCancelled()) { dbFile.delete(); break; } try { final JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(new FileReader(temps)); JsonObject jElement = jsonElement.getAsJsonObject(); JsonObject jRoot = jElement.get("roots").getAsJsonObject(); JsonObject jBookmark = jRoot.get("bookmark_bar").getAsJsonObject(); JsonArray jBookmarkArray = jBookmark.getAsJsonArray("children"); for (JsonElement result : jBookmarkArray) { try { JsonObject address = result.getAsJsonObject(); if (address == null) { continue; } JsonElement urlEl = address.get("url"); String url = null; if (urlEl != null) { url = urlEl.getAsString(); } else { url = ""; } String name = null; JsonElement nameEl = address.get("name"); if (nameEl != null) { name = nameEl.getAsString(); } else { name = ""; } Long date = null; JsonElement dateEl = address.get("date_added"); if (dateEl != null) { date = dateEl.getAsLong(); } else { date = Long.valueOf(0); } String domain = Util.extractDomain(url); BlackboardArtifact bbart = bookmarkFiles.get(j).newArtifact(ARTIFACT_TYPE.TSK_WEB_BOOKMARK); Collection<BlackboardAttribute> bbattributes = new ArrayList<BlackboardAttribute>(); //TODO Revisit usage of deprecated constructor as per TSK-583 //bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_LAST_ACCESSED.getTypeID(), "Recent Activity", "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DATETIME_ACCESSED.getTypeID(), "Last Visited", (date / 10000000))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL.getTypeID(), "Recent Activity", url)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL_DECODED.getTypeID(), "Recent Activity", EscapeUtil.decodeURL(url))); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_NAME.getTypeID(), "Recent Activity", name)); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PROG_NAME.getTypeID(), "Recent Activity", "Chrome")); bbattributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_DOMAIN.getTypeID(), "Recent Activity", domain)); bbart.addAttributes(bbattributes); } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Error while trying to insert Chrom bookmark artifact{0}", ex); errors++; } } if (errors > 0) { this.addErrorMessage(this.getName() + ": Error parsing " + errors + " Chrome bookmark artifacts."); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, "Error while trying to read into the Bookmarks for Chrome." + ex); } j++; dbFile.delete(); } services.fireModuleDataEvent(new ModuleDataEvent("Recent Activity", BlackboardArtifact.ARTIFACT_TYPE.TSK_WEB_BOOKMARK)); } }
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/rest/PlacemarkRestService.java b/GAE/src/org/waterforpeople/mapping/app/web/rest/PlacemarkRestService.java index e759b75b0..ffa1e1731 100644 --- a/GAE/src/org/waterforpeople/mapping/app/web/rest/PlacemarkRestService.java +++ b/GAE/src/org/waterforpeople/mapping/app/web/rest/PlacemarkRestService.java @@ -1,119 +1,119 @@ /* * Copyright (C) 2012 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo FLOW. * * Akvo FLOW is free software: you can redistribute it and modify it under the terms of * the GNU Affero General Public License (AGPL) as published by the Free Software Foundation, * either version 3 of the License or any later version. * * Akvo FLOW 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 included below for more details. * * The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>. */ package org.waterforpeople.mapping.app.web.rest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.waterforpeople.mapping.app.web.rest.dto.PlacemarkDto; import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType; import com.gallatinsystems.framework.gwt.dto.client.BaseDto; import com.gallatinsystems.surveyal.dao.SurveyedLocaleDao; import com.gallatinsystems.surveyal.domain.SurveyedLocale; @Controller @RequestMapping("/placemarks") public class PlacemarkRestService { private static final Logger log = Logger .getLogger(PlacemarkRestService.class.getName()); @Inject SurveyedLocaleDao localeDao; @RequestMapping(method = RequestMethod.GET, value = "") @ResponseBody - public Map<String, List<? extends BaseDto>> listPlaceMarks( + public Map<String, List<PlacemarkDto>> listPlaceMarks( @RequestParam(value = "country", defaultValue = "") String country, @RequestParam(value = "id", defaultValue = "") String surveyedLocaleId) { - final Map<String, List<? extends BaseDto>> response = new HashMap<String, List<? extends BaseDto>>(); + final Map<String, List<PlacemarkDto>> response = new HashMap<String, List<PlacemarkDto>>(); final List<PlacemarkDto> result = new ArrayList<PlacemarkDto>(); final List<SurveyedLocale> slList = new ArrayList<SurveyedLocale>(); final boolean needDetails = !StringUtils.isEmpty(surveyedLocaleId) && StringUtils.isEmpty(country); if (StringUtils.isEmpty(country) && StringUtils.isEmpty(surveyedLocaleId)) { final String msg = "You must pass a parameter [country] or [id]"; log.log(Level.SEVERE, msg); throw new HttpMessageNotReadableException(msg); } if (!StringUtils.isEmpty(country)) { slList.addAll(localeDao.listBySubLevel(country, null, null, null, null, null, null)); } else if (!StringUtils.isEmpty(surveyedLocaleId)) { slList.add(localeDao.getById(Long.valueOf(surveyedLocaleId))); } if (slList.size() > 0) { for (SurveyedLocale ap : slList) { result.add(marshallDomainToDto(ap, needDetails)); } } response.put("placemarks", result); return response; } private PlacemarkDto marshallDomainToDto(SurveyedLocale sl, boolean needDetails) { final PlacemarkDto dto = new PlacemarkDto(); final String markType = StringUtils.isEmpty(sl.getLocaleType()) ? AccessPointType.WATER_POINT .toString() : sl.getLocaleType().toUpperCase(); dto.setMarkType(markType); dto.setLatitude(sl.getLatitude()); dto.setLongitude(sl.getLongitude()); dto.setCollectionDate(sl.getLastUpdateDateTime()); dto.setKeyId(sl.getKey().getId()); // if (needDetails) { // List<SurveyalValueDto> details = new ArrayList<SurveyalValueDto>(); // for (SurveyalValue sv : sl.getSurveyalValues()) { // SurveyalValueDto svDto = new SurveyalValueDto(); // DtoMarshaller.copyToDto(sv, svDto); // // if (StringUtils.isEmpty(sv.getMetricName())) { // svDto.setQuestionText(sv.getQuestionText()); // svDto.setStringValue(sv.getStringValue()); // } else { // svDto.setMetricName(sv.getMetricName()); // svDto.setStringValue(sv.getStringValue()); // } // details.add(svDto); // } // dto.setDetails(details); // } return dto; } }
false
true
public Map<String, List<? extends BaseDto>> listPlaceMarks( @RequestParam(value = "country", defaultValue = "") String country, @RequestParam(value = "id", defaultValue = "") String surveyedLocaleId) { final Map<String, List<? extends BaseDto>> response = new HashMap<String, List<? extends BaseDto>>(); final List<PlacemarkDto> result = new ArrayList<PlacemarkDto>(); final List<SurveyedLocale> slList = new ArrayList<SurveyedLocale>(); final boolean needDetails = !StringUtils.isEmpty(surveyedLocaleId) && StringUtils.isEmpty(country); if (StringUtils.isEmpty(country) && StringUtils.isEmpty(surveyedLocaleId)) { final String msg = "You must pass a parameter [country] or [id]"; log.log(Level.SEVERE, msg); throw new HttpMessageNotReadableException(msg); } if (!StringUtils.isEmpty(country)) { slList.addAll(localeDao.listBySubLevel(country, null, null, null, null, null, null)); } else if (!StringUtils.isEmpty(surveyedLocaleId)) { slList.add(localeDao.getById(Long.valueOf(surveyedLocaleId))); } if (slList.size() > 0) { for (SurveyedLocale ap : slList) { result.add(marshallDomainToDto(ap, needDetails)); } } response.put("placemarks", result); return response; }
public Map<String, List<PlacemarkDto>> listPlaceMarks( @RequestParam(value = "country", defaultValue = "") String country, @RequestParam(value = "id", defaultValue = "") String surveyedLocaleId) { final Map<String, List<PlacemarkDto>> response = new HashMap<String, List<PlacemarkDto>>(); final List<PlacemarkDto> result = new ArrayList<PlacemarkDto>(); final List<SurveyedLocale> slList = new ArrayList<SurveyedLocale>(); final boolean needDetails = !StringUtils.isEmpty(surveyedLocaleId) && StringUtils.isEmpty(country); if (StringUtils.isEmpty(country) && StringUtils.isEmpty(surveyedLocaleId)) { final String msg = "You must pass a parameter [country] or [id]"; log.log(Level.SEVERE, msg); throw new HttpMessageNotReadableException(msg); } if (!StringUtils.isEmpty(country)) { slList.addAll(localeDao.listBySubLevel(country, null, null, null, null, null, null)); } else if (!StringUtils.isEmpty(surveyedLocaleId)) { slList.add(localeDao.getById(Long.valueOf(surveyedLocaleId))); } if (slList.size() > 0) { for (SurveyedLocale ap : slList) { result.add(marshallDomainToDto(ap, needDetails)); } } response.put("placemarks", result); return response; }
diff --git a/src/main/java/com/gramercysoftware/hibernate/SQLiteDialect.java b/src/main/java/com/gramercysoftware/hibernate/SQLiteDialect.java index 8571efc..2d1b812 100644 --- a/src/main/java/com/gramercysoftware/hibernate/SQLiteDialect.java +++ b/src/main/java/com/gramercysoftware/hibernate/SQLiteDialect.java @@ -1,151 +1,151 @@ /* * Hibernate Dialect for SQLite * Copyright (C) 2011 David Harcombe * * 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.gramercysoftware.hibernate; import java.sql.Types; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.type.StandardBasicTypes; public class SQLiteDialect extends Dialect { public SQLiteDialect() { registerColumnType(Types.BIT, "integer"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.DECIMAL, "decimal"); registerColumnType(Types.CHAR, "char"); registerColumnType(Types.VARCHAR, "varchar"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.BINARY, "blob"); registerColumnType(Types.VARBINARY, "blob"); registerColumnType(Types.LONGVARBINARY, "blob"); - // registerColumnType(Types.NULL, "null"); + registerColumnType(Types.NULL, "null"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.BOOLEAN, "integer"); registerFunction("concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", "")); registerFunction("mod", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 % ?2")); registerFunction("substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); registerFunction("substring", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); } public boolean supportsIdentityColumns() { return true; } public boolean hasDataTypeInIdentityColumn() { return false; } public String getIdentityColumnString() { return "integer"; } public String getIdentitySelectString() { return "select last_insert_rowid()"; } public boolean supportsLimit() { return true; } protected String getLimitString(String query, boolean hasOffset) { return new StringBuffer(query.length() + 20).append(query).append(hasOffset ? " limit ? offset ?" : " limit ?").toString(); } public boolean supportsTemporaryTables() { return true; } public String getCreateTemporaryTableString() { return "create temporary table if not exists"; } public boolean dropTemporaryTableAfterUse() { return false; } public boolean supportsCurrentTimestampSelection() { return true; } public boolean isCurrentTimestampSelectStringCallable() { return false; } public String getCurrentTimestampSelectString() { return "select current_timestamp"; } public boolean supportsUnionAll() { return true; } public boolean hasAlterTable() { return false; } public boolean dropConstraints() { return false; } public String getAddColumnString() { return "add column"; } public String getForUpdateString() { return ""; } public boolean supportsOuterJoinForUpdate() { return false; } public String getDropForeignKeyString() { throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect"); } public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) { throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect"); } public String getAddPrimaryKeyConstraintString(String constraintName) { throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect"); } public boolean supportsIfExistsBeforeTableName() { return true; } public boolean supportsCascadeDelete() { return false; } }
true
true
public SQLiteDialect() { registerColumnType(Types.BIT, "integer"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.DECIMAL, "decimal"); registerColumnType(Types.CHAR, "char"); registerColumnType(Types.VARCHAR, "varchar"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.BINARY, "blob"); registerColumnType(Types.VARBINARY, "blob"); registerColumnType(Types.LONGVARBINARY, "blob"); // registerColumnType(Types.NULL, "null"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.BOOLEAN, "integer"); registerFunction("concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", "")); registerFunction("mod", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 % ?2")); registerFunction("substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); registerFunction("substring", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); }
public SQLiteDialect() { registerColumnType(Types.BIT, "integer"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.DECIMAL, "decimal"); registerColumnType(Types.CHAR, "char"); registerColumnType(Types.VARCHAR, "varchar"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.BINARY, "blob"); registerColumnType(Types.VARBINARY, "blob"); registerColumnType(Types.LONGVARBINARY, "blob"); registerColumnType(Types.NULL, "null"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.BOOLEAN, "integer"); registerFunction("concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", "")); registerFunction("mod", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1 % ?2")); registerFunction("substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); registerFunction("substring", new StandardSQLFunction("substr", StandardBasicTypes.STRING)); }
diff --git a/src/main/java/com/bibounde/vprotovis/gwt/client/spider/VSpiderChartComponent.java b/src/main/java/com/bibounde/vprotovis/gwt/client/spider/VSpiderChartComponent.java index b780a37..18c5ebe 100644 --- a/src/main/java/com/bibounde/vprotovis/gwt/client/spider/VSpiderChartComponent.java +++ b/src/main/java/com/bibounde/vprotovis/gwt/client/spider/VSpiderChartComponent.java @@ -1,457 +1,457 @@ package com.bibounde.vprotovis.gwt.client.spider; import java.util.logging.Logger; import com.bibounde.vprotovis.gwt.client.Tooltip; import com.bibounde.vprotovis.gwt.client.TooltipOptions; import com.bibounde.vprotovis.gwt.client.UIDLUtil; import com.bibounde.vprotovis.gwt.client.VAbstractChartComponent; import com.bibounde.vprotovis.gwt.client.TooltipComposite.ArrowStyle; public class VSpiderChartComponent extends VAbstractChartComponent { public static final String UIDL_DATA_SERIES_COUNT = "vprotovis.data.series.count"; public static final String UIDL_DATA_SERIES_NAMES = "vprotovis.data.series.names"; public static final String UIDL_DATA_SERIE_VALUE = "vprotovis.data.serie.value."; public static final String UIDL_DATA_SERIE_TOOLTIP_VALUES = "vprotovis.data.serie.tooltip.values."; public static final String UIDL_DATA_AXIS_VALUES = "vprotovis.data.axis.values"; public static final String UIDL_DATA_AXIS_COUNT = "vprotovis.data.axis.count"; public static final String UIDL_DATA_AXIS_LABEL_VALUES = "vprotovis.data.axis.label.values"; public static final String UIDL_DATA_AXIS_LABEL_RANGE = "vprotovis.data.axis.label.range"; public static final String UIDL_DATA_MAX_VALUE = "vprotovis.data.max.value"; public static final String UIDL_OPTIONS_BOTTOM = "vprotovis.options.bottom"; public static final String UIDL_OPTIONS_LEFT = "vprotovis.options.left"; public static final String UIDL_OPTIONS_RULE_WIDTH = "vprotovis.options.rule.width"; public static final String UIDL_OPTIONS_AREA_ENABLED = "vprotovis.options.area.enabled"; public static final String UIDL_OPTIONS_AREA_OPACITY = "vprotovis.options.area.opacity"; public static final String UIDL_OPTIONS_AXIS_ENABLED = "vprotovis.options.axis.enabled"; public static final String UIDL_OPTIONS_AXIS_CAPTION_ENABLED = "vprotovis.options.axis.caption.enabled"; public static final String UIDL_OPTIONS_AXIS_LABEL_ENABLED = "vprotovis.options.axis.label.enabled"; public static final String UIDL_OPTIONS_AXIS_GRID_ENABLED = "vprotovis.options.axis.grid.enabled"; public static final String UIDL_OPTIONS_AXIS_STEP = "vprotovis.options.axis.step"; public static final String UIDL_OPTIONS_AXIS_OFFSET = "vprotovis.options.axis.offset"; public static final String UIDL_OPTIONS_LINE_WIDTH = "vprotovis.options.line.width"; /** Set the CSS class name to allow styling. */ public static final String CLASSNAME = "v-vprotovis-spiderchart"; private Logger LOGGER = Logger.getLogger(VSpiderChartComponent.class.getName()); private Tooltip currentTooltip; /** * @see com.bibounde.vprotovis.gwt.client.VAbstractChartComponent#getClassName() */ @Override public String getClassName() { return CLASSNAME; } public native void render()/*-{ var vspiderchart = this; function theta(angle) { return Math.PI * ((angle + 90)/180); } function createRule(angle, labelText) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(2)); axis.left(function() { return centerLeft + (this.index * Math.cos(theta(angle)) * ruleWidth); }); axis.bottom(function() { return centerBottom + (this.index * Math.sin(theta(angle)) * ruleWidth); }); axis.lineWidth(1); axis.strokeStyle(axisColor); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisCaptionEnabled()()) { var label = axis.anchor("center").add($wnd.pv.Label); label.visible(function() { return this.index > 0; }); label.text(labelText); label.textMargin(2); if (angle > 0 && angle < 180) { label.textAlign("right"); } else if (angle > 180) { label.textAlign("left"); } else { label.textAlign("center"); } if ((angle >= 0 && angle <= 45) || (angle >= 315)) { label.textBaseline("bottom"); } else if ((angle > 45 && angle <= 135) || (angle >= 225 && angle < 315)) { label.textBaseline("middle"); } else { label.textBaseline("top"); } } } function createGrid(count, step) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(count)); axis.left(function() { return centerLeft + Math.cos(theta(this.index * angle)) * step; }); axis.bottom(function() { return centerBottom + Math.sin(theta(this.index * angle)) * step; }); axis.lineWidth(1); axis.strokeStyle(axisColor); } function createTicks(range, labels, step) { var rule = vis.add($wnd.pv.Rule).data(range); rule.width(5); rule.left(centerLeft - 2); rule.bottom(function(d) { return centerBottom + (step * d); }); rule.strokeStyle(axisColor); var label = rule.anchor("center").add($wnd.pv.Label); label.text(function() { return labels[this.index]; }); label.textAlign("right"); label.textMargin(5); label.textStyle(axisColor); } function getTooltipInfo(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return coords; } } return new Array(-1, -1, -1); } function enabledTooltipContains(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return true; } } return false; } function createDataLine(serieIndex, data, color) { var line = vis.add($wnd.pv.Line).data(data); line.left( function(d) { var left = centerLeft + Math.cos(theta(this.index * angle)) * (dataStep * d); leftValues[serieIndex][this.index] = left; return left; }); line.bottom(function(d) { var bottom = centerBottom + Math.sin(theta(this.index * angle)) * (dataStep * d); bottomValues[serieIndex][this.index] = bottom; return bottom; }); line.strokeStyle(color); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAreaEnabled()()) { line.fillStyle(color.rgb().alpha(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAreaOpacity()())); } line.lineWidth(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLineWidth()()); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { enableTooltip(line, serieIndex, data, color); } } function enableTooltip(line, serieIndex, data, color) { line.event("point", function(){ var val = data[this.index]; //Retrieves coords for top tooltip var coords = getTooltipInfo(this.index, val); if (this.index < columns.length) { vis.valueIndex(coords[1]); vis.serieIndex(coords[0]); var left = leftValues[vis.serieIndex()][vis.valueIndex()]; var top = chartHeight - bottomValues[vis.serieIndex()][vis.valueIndex()]; var text = tooltips[vis.serieIndex()][vis.valueIndex()]; vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::showTooltip(IILjava/lang/String;)(left, top, text); } else { vis.valueIndex(-1); vis.serieIndex(-1); } return this.parent; }); line.event("unpoint", function(){ vis.valueIndex(-1); vis.serieIndex(-1); vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::hideTooltip()(); return this.parent; }); var dot = vis.add($wnd.pv.Dot); dot.visible(function() { return vis.valueIndex() >= 0; }); dot.left(function() { return leftValues[vis.serieIndex()][vis.valueIndex()]; }); dot.bottom(function() { return bottomValues[vis.serieIndex()][vis.valueIndex()]; }); dot.fillStyle(function() { return $wnd.pv.color(colors.range()[vis.serieIndex()]).brighter(0.8).rgb(); }); dot.strokeStyle(function() {return colors.range()[vis.serieIndex()];}); dot.radius(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRadiusWidth()()); } function createLegend() { var legengTop = marginTop + (chartHeight - marginBottom - marginTop - (serieNames.length * 18)) / 2; //Use bar instead of DOT because msie-shim does not support it var legend = vis.add($wnd.pv.Bar).data(serieNames); legend.top(function(){ return legengTop + (this.index * 18); }); legend.width(11).height(11).left(chartWidth - marginRight - legendAreaWidth + legendInsetLeft); legend.fillStyle(colors.by($wnd.pv.index)); legend.anchor("left").add($wnd.pv.Label).textBaseline("middle").textMargin(16).textStyle(legendColor); } var data = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getData()()); var colors = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getColors()()); var axisColor = $wnd.pv.color("#969696"); var legendColor = $wnd.pv.color("#464646"); var columns = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisNames()()); var serieNames = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getSerieNames()()); var ruleWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRuleWidth()(); var centerBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterBottom()(); var centerLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterLeft()(); var angle = 360 / columns.length; var maxValue = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMaxValue()(); var axisOffset = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisOffset()(); var dataStep = (ruleWidth - axisOffset)/maxValue; var marginLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginLeft()(); var marginRight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginRight()(); var marginBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginBottom()(); var marginTop = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginTop()(); var chartWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartWidth()(); var chartHeight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartHeight()(); var vis = new $wnd.pv.Panel().canvas(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getDivId()()); vis.width(chartWidth); vis.height(chartHeight); if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisEnabled()()) { //Rule creation for (i=0; i< columns.length; i++) { createRule(i * angle, columns[i]); } var axisStep = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisStep()(); - var gridStep = (ruleWidth - axisOffset) / (axisStep * maxValue); + var gridStep = (ruleWidth - axisOffset) / maxValue; if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisGridEnabled()()) { //Create grid - for (i=1; i<= maxValue; i++) { + for (i=axisStep; i<= maxValue; i=i+axisStep) { createGrid(columns.length + 1, i * gridStep); } } if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisLabelEnabled()()) { //Create ticks var range = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisRange()()); var labels = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisLabels()()); createTicks(range, labels, gridStep); } } //Tooltip initialisation if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { vis.def("valueIndex", -1).def("serieIndex", -1); vis.event("mousemove", $wnd.pv.Behavior.point(10)); vis.events("all"); var tooltips = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getTooltips()()); //Display only one tooltip for same value. Only tooltip for top line is displayed var enabledTooltips = new Array(); for (i=data.length - 1; i>=0; i--) { for(j=0;j<data[i].length;j++) { if (!enabledTooltipContains(j, data[i][j])) { enabledTooltips.push(new Array(i, j, data[i][j])); } } } } //Init coord arrays for tooltip var leftValues = new Array(); var bottomValues = new Array(); for (i=0;i<=data.length;i++){ leftValues.push(new Array()); bottomValues.push(new Array()); } //Display data for (i=0; i<data.length; i++) { createDataLine(i, data[i], colors.range()[i]); } //Legend management if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isLegendEnabled()()) { var legendAreaWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendAreaWidth()(); var legendInsetLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendInsetLeft()(); createLegend(); } vis.render(); }-*/; public void showTooltip(int x, int y, String tooltipText) { this.hideTooltip(); this.currentTooltip = new Tooltip(); this.currentTooltip.setText(tooltipText); //Tooltip location calculation this.currentTooltip.show(); TooltipOptions options = this.getTooltipOptions(this.currentTooltip.getOffsetWidth(), this.currentTooltip.getOffsetHeight(), x, y); this.currentTooltip.setArrowStyle(options.arrowStyle); this.currentTooltip.setPopupPosition(options.left, options.top); } public void hideTooltip() { if (this.currentTooltip != null) { this.currentTooltip.hide(); this.currentTooltip = null; } } public String getData() { int serieCount = this.currentUIDL.getIntVariable(UIDL_DATA_SERIES_COUNT); StringBuilder ret = new StringBuilder("["); for (int i = 0; i < serieCount; i++) { if (i > 0) { ret.append(","); } String[] values = this.currentUIDL.getStringArrayVariable(UIDL_DATA_SERIE_VALUE + i); ret.append(UIDLUtil.getJSArray(values, false)); } ret.append("]"); return ret.toString(); } public String getTooltips() { int serieCount = this.currentUIDL.getIntVariable(UIDL_DATA_SERIES_COUNT); StringBuilder ret = new StringBuilder("["); for (int i = 0; i < serieCount; i++) { if (i > 0) { ret.append(","); } String[] values = this.currentUIDL.getStringArrayVariable(UIDL_DATA_SERIE_TOOLTIP_VALUES + i); ret.append(UIDLUtil.getJSArray(values, true)); } ret.append("]"); return ret.toString(); } public String getAxisNames() { return UIDLUtil.getJSArray(this.currentUIDL.getStringArrayVariable(UIDL_DATA_AXIS_VALUES), true); } public String getSerieNames() { return UIDLUtil.getJSArray(this.currentUIDL.getStringArrayVariable(UIDL_DATA_SERIES_NAMES), true); } public double getRuleWidth() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_RULE_WIDTH); } public double getCenterBottom() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_BOTTOM); } public double getCenterLeft() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_LEFT); } public boolean isAxisEnabled() { return this.currentUIDL.getBooleanVariable(UIDL_OPTIONS_AXIS_ENABLED); } public double getAxisOffset() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_AXIS_OFFSET); } public double getAxisStep() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_AXIS_STEP); } public double getMaxValue() { return this.currentUIDL.getDoubleVariable(UIDL_DATA_MAX_VALUE); } public boolean isAxisGridEnabled() { return this.currentUIDL.getBooleanVariable(UIDL_OPTIONS_AXIS_GRID_ENABLED); } public boolean isAxisLabelEnabled() { return this.currentUIDL.getBooleanVariable(UIDL_OPTIONS_AXIS_LABEL_ENABLED); } public boolean isAxisCaptionEnabled() { return this.currentUIDL.getBooleanVariable(UIDL_OPTIONS_AXIS_CAPTION_ENABLED); } public int getLineWidth() { return this.currentUIDL.getIntVariable(UIDL_OPTIONS_LINE_WIDTH); } public boolean isAreaEnabled() { return this.currentUIDL.getBooleanVariable(UIDL_OPTIONS_AREA_ENABLED); } public double getAreaOpacity() { return this.currentUIDL.getDoubleVariable(UIDL_OPTIONS_AREA_OPACITY); } public String getAxisLabels() { return UIDLUtil.getJSArray(this.currentUIDL.getStringArrayVariable(UIDL_DATA_AXIS_LABEL_VALUES), true); } public String getAxisRange() { return UIDLUtil.getJSArray(this.currentUIDL.getStringArrayVariable(UIDL_DATA_AXIS_LABEL_RANGE), false); } public int getRadiusWidth() { return this.getLineWidth() + 2; } private TooltipOptions getTooltipOptions(int tooltipWidth, int tooltipHeight, int x, int y) { int left = this.getElement().getAbsoluteLeft() + x; int top = this.getElement().getAbsoluteTop() + y; int tooltipArrowOffset = 10; int tooltipMarginOffset = 5; TooltipOptions ret = new TooltipOptions(); ret.arrowStyle = ArrowStyle.BOTTOM_LEFT; ret.left = left - tooltipArrowOffset; ret.top = top - tooltipHeight - tooltipArrowOffset - this.getRadiusWidth() - 2; return ret; } }
false
true
public native void render()/*-{ var vspiderchart = this; function theta(angle) { return Math.PI * ((angle + 90)/180); } function createRule(angle, labelText) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(2)); axis.left(function() { return centerLeft + (this.index * Math.cos(theta(angle)) * ruleWidth); }); axis.bottom(function() { return centerBottom + (this.index * Math.sin(theta(angle)) * ruleWidth); }); axis.lineWidth(1); axis.strokeStyle(axisColor); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisCaptionEnabled()()) { var label = axis.anchor("center").add($wnd.pv.Label); label.visible(function() { return this.index > 0; }); label.text(labelText); label.textMargin(2); if (angle > 0 && angle < 180) { label.textAlign("right"); } else if (angle > 180) { label.textAlign("left"); } else { label.textAlign("center"); } if ((angle >= 0 && angle <= 45) || (angle >= 315)) { label.textBaseline("bottom"); } else if ((angle > 45 && angle <= 135) || (angle >= 225 && angle < 315)) { label.textBaseline("middle"); } else { label.textBaseline("top"); } } } function createGrid(count, step) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(count)); axis.left(function() { return centerLeft + Math.cos(theta(this.index * angle)) * step; }); axis.bottom(function() { return centerBottom + Math.sin(theta(this.index * angle)) * step; }); axis.lineWidth(1); axis.strokeStyle(axisColor); } function createTicks(range, labels, step) { var rule = vis.add($wnd.pv.Rule).data(range); rule.width(5); rule.left(centerLeft - 2); rule.bottom(function(d) { return centerBottom + (step * d); }); rule.strokeStyle(axisColor); var label = rule.anchor("center").add($wnd.pv.Label); label.text(function() { return labels[this.index]; }); label.textAlign("right"); label.textMargin(5); label.textStyle(axisColor); } function getTooltipInfo(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return coords; } } return new Array(-1, -1, -1); } function enabledTooltipContains(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return true; } } return false; } function createDataLine(serieIndex, data, color) { var line = vis.add($wnd.pv.Line).data(data); line.left( function(d) { var left = centerLeft + Math.cos(theta(this.index * angle)) * (dataStep * d); leftValues[serieIndex][this.index] = left; return left; }); line.bottom(function(d) { var bottom = centerBottom + Math.sin(theta(this.index * angle)) * (dataStep * d); bottomValues[serieIndex][this.index] = bottom; return bottom; }); line.strokeStyle(color); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAreaEnabled()()) { line.fillStyle(color.rgb().alpha(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAreaOpacity()())); } line.lineWidth(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLineWidth()()); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { enableTooltip(line, serieIndex, data, color); } } function enableTooltip(line, serieIndex, data, color) { line.event("point", function(){ var val = data[this.index]; //Retrieves coords for top tooltip var coords = getTooltipInfo(this.index, val); if (this.index < columns.length) { vis.valueIndex(coords[1]); vis.serieIndex(coords[0]); var left = leftValues[vis.serieIndex()][vis.valueIndex()]; var top = chartHeight - bottomValues[vis.serieIndex()][vis.valueIndex()]; var text = tooltips[vis.serieIndex()][vis.valueIndex()]; vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::showTooltip(IILjava/lang/String;)(left, top, text); } else { vis.valueIndex(-1); vis.serieIndex(-1); } return this.parent; }); line.event("unpoint", function(){ vis.valueIndex(-1); vis.serieIndex(-1); vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::hideTooltip()(); return this.parent; }); var dot = vis.add($wnd.pv.Dot); dot.visible(function() { return vis.valueIndex() >= 0; }); dot.left(function() { return leftValues[vis.serieIndex()][vis.valueIndex()]; }); dot.bottom(function() { return bottomValues[vis.serieIndex()][vis.valueIndex()]; }); dot.fillStyle(function() { return $wnd.pv.color(colors.range()[vis.serieIndex()]).brighter(0.8).rgb(); }); dot.strokeStyle(function() {return colors.range()[vis.serieIndex()];}); dot.radius(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRadiusWidth()()); } function createLegend() { var legengTop = marginTop + (chartHeight - marginBottom - marginTop - (serieNames.length * 18)) / 2; //Use bar instead of DOT because msie-shim does not support it var legend = vis.add($wnd.pv.Bar).data(serieNames); legend.top(function(){ return legengTop + (this.index * 18); }); legend.width(11).height(11).left(chartWidth - marginRight - legendAreaWidth + legendInsetLeft); legend.fillStyle(colors.by($wnd.pv.index)); legend.anchor("left").add($wnd.pv.Label).textBaseline("middle").textMargin(16).textStyle(legendColor); } var data = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getData()()); var colors = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getColors()()); var axisColor = $wnd.pv.color("#969696"); var legendColor = $wnd.pv.color("#464646"); var columns = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisNames()()); var serieNames = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getSerieNames()()); var ruleWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRuleWidth()(); var centerBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterBottom()(); var centerLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterLeft()(); var angle = 360 / columns.length; var maxValue = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMaxValue()(); var axisOffset = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisOffset()(); var dataStep = (ruleWidth - axisOffset)/maxValue; var marginLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginLeft()(); var marginRight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginRight()(); var marginBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginBottom()(); var marginTop = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginTop()(); var chartWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartWidth()(); var chartHeight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartHeight()(); var vis = new $wnd.pv.Panel().canvas(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getDivId()()); vis.width(chartWidth); vis.height(chartHeight); if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisEnabled()()) { //Rule creation for (i=0; i< columns.length; i++) { createRule(i * angle, columns[i]); } var axisStep = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisStep()(); var gridStep = (ruleWidth - axisOffset) / (axisStep * maxValue); if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisGridEnabled()()) { //Create grid for (i=1; i<= maxValue; i++) { createGrid(columns.length + 1, i * gridStep); } } if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisLabelEnabled()()) { //Create ticks var range = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisRange()()); var labels = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisLabels()()); createTicks(range, labels, gridStep); } } //Tooltip initialisation if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { vis.def("valueIndex", -1).def("serieIndex", -1); vis.event("mousemove", $wnd.pv.Behavior.point(10)); vis.events("all"); var tooltips = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getTooltips()()); //Display only one tooltip for same value. Only tooltip for top line is displayed var enabledTooltips = new Array(); for (i=data.length - 1; i>=0; i--) { for(j=0;j<data[i].length;j++) { if (!enabledTooltipContains(j, data[i][j])) { enabledTooltips.push(new Array(i, j, data[i][j])); } } } } //Init coord arrays for tooltip var leftValues = new Array(); var bottomValues = new Array(); for (i=0;i<=data.length;i++){ leftValues.push(new Array()); bottomValues.push(new Array()); } //Display data for (i=0; i<data.length; i++) { createDataLine(i, data[i], colors.range()[i]); } //Legend management if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isLegendEnabled()()) { var legendAreaWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendAreaWidth()(); var legendInsetLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendInsetLeft()(); createLegend(); } vis.render(); }-*/;
public native void render()/*-{ var vspiderchart = this; function theta(angle) { return Math.PI * ((angle + 90)/180); } function createRule(angle, labelText) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(2)); axis.left(function() { return centerLeft + (this.index * Math.cos(theta(angle)) * ruleWidth); }); axis.bottom(function() { return centerBottom + (this.index * Math.sin(theta(angle)) * ruleWidth); }); axis.lineWidth(1); axis.strokeStyle(axisColor); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisCaptionEnabled()()) { var label = axis.anchor("center").add($wnd.pv.Label); label.visible(function() { return this.index > 0; }); label.text(labelText); label.textMargin(2); if (angle > 0 && angle < 180) { label.textAlign("right"); } else if (angle > 180) { label.textAlign("left"); } else { label.textAlign("center"); } if ((angle >= 0 && angle <= 45) || (angle >= 315)) { label.textBaseline("bottom"); } else if ((angle > 45 && angle <= 135) || (angle >= 225 && angle < 315)) { label.textBaseline("middle"); } else { label.textBaseline("top"); } } } function createGrid(count, step) { var axis = vis.add($wnd.pv.Line).data($wnd.pv.range(count)); axis.left(function() { return centerLeft + Math.cos(theta(this.index * angle)) * step; }); axis.bottom(function() { return centerBottom + Math.sin(theta(this.index * angle)) * step; }); axis.lineWidth(1); axis.strokeStyle(axisColor); } function createTicks(range, labels, step) { var rule = vis.add($wnd.pv.Rule).data(range); rule.width(5); rule.left(centerLeft - 2); rule.bottom(function(d) { return centerBottom + (step * d); }); rule.strokeStyle(axisColor); var label = rule.anchor("center").add($wnd.pv.Label); label.text(function() { return labels[this.index]; }); label.textAlign("right"); label.textMargin(5); label.textStyle(axisColor); } function getTooltipInfo(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return coords; } } return new Array(-1, -1, -1); } function enabledTooltipContains(valueIndex, value) { for(var i=0;i<enabledTooltips.length;i++) { var coords = enabledTooltips[i]; if (coords[1] == valueIndex && coords[2] == value) { return true; } } return false; } function createDataLine(serieIndex, data, color) { var line = vis.add($wnd.pv.Line).data(data); line.left( function(d) { var left = centerLeft + Math.cos(theta(this.index * angle)) * (dataStep * d); leftValues[serieIndex][this.index] = left; return left; }); line.bottom(function(d) { var bottom = centerBottom + Math.sin(theta(this.index * angle)) * (dataStep * d); bottomValues[serieIndex][this.index] = bottom; return bottom; }); line.strokeStyle(color); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAreaEnabled()()) { line.fillStyle(color.rgb().alpha(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAreaOpacity()())); } line.lineWidth(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLineWidth()()); if (vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { enableTooltip(line, serieIndex, data, color); } } function enableTooltip(line, serieIndex, data, color) { line.event("point", function(){ var val = data[this.index]; //Retrieves coords for top tooltip var coords = getTooltipInfo(this.index, val); if (this.index < columns.length) { vis.valueIndex(coords[1]); vis.serieIndex(coords[0]); var left = leftValues[vis.serieIndex()][vis.valueIndex()]; var top = chartHeight - bottomValues[vis.serieIndex()][vis.valueIndex()]; var text = tooltips[vis.serieIndex()][vis.valueIndex()]; vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::showTooltip(IILjava/lang/String;)(left, top, text); } else { vis.valueIndex(-1); vis.serieIndex(-1); } return this.parent; }); line.event("unpoint", function(){ vis.valueIndex(-1); vis.serieIndex(-1); vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::hideTooltip()(); return this.parent; }); var dot = vis.add($wnd.pv.Dot); dot.visible(function() { return vis.valueIndex() >= 0; }); dot.left(function() { return leftValues[vis.serieIndex()][vis.valueIndex()]; }); dot.bottom(function() { return bottomValues[vis.serieIndex()][vis.valueIndex()]; }); dot.fillStyle(function() { return $wnd.pv.color(colors.range()[vis.serieIndex()]).brighter(0.8).rgb(); }); dot.strokeStyle(function() {return colors.range()[vis.serieIndex()];}); dot.radius(vspiderchart.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRadiusWidth()()); } function createLegend() { var legengTop = marginTop + (chartHeight - marginBottom - marginTop - (serieNames.length * 18)) / 2; //Use bar instead of DOT because msie-shim does not support it var legend = vis.add($wnd.pv.Bar).data(serieNames); legend.top(function(){ return legengTop + (this.index * 18); }); legend.width(11).height(11).left(chartWidth - marginRight - legendAreaWidth + legendInsetLeft); legend.fillStyle(colors.by($wnd.pv.index)); legend.anchor("left").add($wnd.pv.Label).textBaseline("middle").textMargin(16).textStyle(legendColor); } var data = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getData()()); var colors = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getColors()()); var axisColor = $wnd.pv.color("#969696"); var legendColor = $wnd.pv.color("#464646"); var columns = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisNames()()); var serieNames = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getSerieNames()()); var ruleWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getRuleWidth()(); var centerBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterBottom()(); var centerLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getCenterLeft()(); var angle = 360 / columns.length; var maxValue = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMaxValue()(); var axisOffset = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisOffset()(); var dataStep = (ruleWidth - axisOffset)/maxValue; var marginLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginLeft()(); var marginRight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginRight()(); var marginBottom = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginBottom()(); var marginTop = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getMarginTop()(); var chartWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartWidth()(); var chartHeight = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getChartHeight()(); var vis = new $wnd.pv.Panel().canvas(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getDivId()()); vis.width(chartWidth); vis.height(chartHeight); if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisEnabled()()) { //Rule creation for (i=0; i< columns.length; i++) { createRule(i * angle, columns[i]); } var axisStep = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisStep()(); var gridStep = (ruleWidth - axisOffset) / maxValue; if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisGridEnabled()()) { //Create grid for (i=axisStep; i<= maxValue; i=i+axisStep) { createGrid(columns.length + 1, i * gridStep); } } if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isAxisLabelEnabled()()) { //Create ticks var range = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisRange()()); var labels = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getAxisLabels()()); createTicks(range, labels, gridStep); } } //Tooltip initialisation if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isTooltipEnabled()()) { vis.def("valueIndex", -1).def("serieIndex", -1); vis.event("mousemove", $wnd.pv.Behavior.point(10)); vis.events("all"); var tooltips = eval(this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getTooltips()()); //Display only one tooltip for same value. Only tooltip for top line is displayed var enabledTooltips = new Array(); for (i=data.length - 1; i>=0; i--) { for(j=0;j<data[i].length;j++) { if (!enabledTooltipContains(j, data[i][j])) { enabledTooltips.push(new Array(i, j, data[i][j])); } } } } //Init coord arrays for tooltip var leftValues = new Array(); var bottomValues = new Array(); for (i=0;i<=data.length;i++){ leftValues.push(new Array()); bottomValues.push(new Array()); } //Display data for (i=0; i<data.length; i++) { createDataLine(i, data[i], colors.range()[i]); } //Legend management if (this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::isLegendEnabled()()) { var legendAreaWidth = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendAreaWidth()(); var legendInsetLeft = this.@com.bibounde.vprotovis.gwt.client.spider.VSpiderChartComponent::getLegendInsetLeft()(); createLegend(); } vis.render(); }-*/;
diff --git a/loci/formats/FilePattern.java b/loci/formats/FilePattern.java index f692229ce..266c25a0c 100644 --- a/loci/formats/FilePattern.java +++ b/loci/formats/FilePattern.java @@ -1,735 +1,738 @@ // // FilePattern.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats; import java.io.File; import java.math.BigInteger; import java.util.Arrays; import java.util.Vector; /** * FilePattern is a collection of methods for handling file patterns, a way of * succinctly representing a collection of files meant to be part of the same * data series. * * Examples: * <ul> * <li>C:\data\BillM\sdub&lt;1-12&gt;.pic</li> * <li>C:\data\Kevin\80&lt;01-59&gt;0&lt;2-3&gt;.pic</li> * <li>/data/Josiah/cell-Z&lt;0-39&gt;.C&lt;0-1&gt;.tiff</li> * </ul> * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/FilePattern.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/FilePattern.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu */ public class FilePattern { // -- Fields -- /** The file pattern string. */ private String pattern; /** The validity of the file pattern. */ private boolean valid; /** Error message generated during file pattern construction. */ private String msg; /** Indices into the pattern indicating the start of a numerical block. */ private int[] startIndex; /** Indices into the pattern indicating the end of a numerical block. */ private int[] endIndex; /** First number of each numerical block. */ private BigInteger[] begin; /** Last number of each numerical block. */ private BigInteger[] end; /** Step size of each numerical block. */ private BigInteger[] step; /** Total numbers withins each numerical block. */ private int[] count; /** Whether each numerical block is fixed width. */ private boolean[] fixed; /** The number of leading zeroes for each numerical block. */ private int[] zeroes; /** File listing for this file pattern. */ private String[] files; // -- Constructors -- /** Creates a pattern object using the given file as a template. */ public FilePattern(Location file) { this(FilePattern.findPattern(file)); } /** * Creates a pattern object using the given * filename and directory path as a template. */ public FilePattern(String name, String dir) { this(FilePattern.findPattern(name, dir)); } /** Creates a pattern object for files with the given pattern string. */ public FilePattern(String pattern) { this.pattern = pattern; valid = false; if (pattern == null) { msg = "Null pattern string."; return; } // locate numerical blocks int len = pattern.length(); Vector lt = new Vector(len); Vector gt = new Vector(len); int left = -1; while (true) { left = pattern.indexOf("<", left + 1); if (left < 0) break; lt.add(new Integer(left)); } int right = -1; while (true) { right = pattern.indexOf(">", right + 1); if (right < 0) break; gt.add(new Integer(right)); } // assemble numerical block indices int num = lt.size(); if (num != gt.size()) { msg = "Mismatched numerical block markers."; return; } startIndex = new int[num]; endIndex = new int[num]; for (int i=0; i<num; i++) { int val = ((Integer) lt.elementAt(i)).intValue(); if (i > 0 && val < endIndex[i - 1]) { msg = "Bad numerical block marker order."; return; } startIndex[i] = val; val = ((Integer) gt.elementAt(i)).intValue(); if (val <= startIndex[i]) { msg = "Bad numerical block marker order."; return; } endIndex[i] = val + 1; } // parse numerical blocks begin = new BigInteger[num]; end = new BigInteger[num]; step = new BigInteger[num]; count = new int[num]; fixed = new boolean[num]; zeroes = new int[num]; for (int i=0; i<num; i++) { String block = pattern.substring(startIndex[i], endIndex[i]); int dash = block.indexOf("-"); String b, e, s; if (dash < 0) { // no range; assume entire block is a single number (e.g., <15>) b = e = block.substring(1, block.length() - 1); s = "1"; } else { int colon = block.indexOf(":"); b = block.substring(1, dash); if (colon < 0) { e = block.substring(dash + 1, block.length() - 1); s = "1"; } else { e = block.substring(dash + 1, colon); s = block.substring(colon + 1, block.length() - 1); } } try { begin[i] = new BigInteger(b); end[i] = new BigInteger(e); if (begin[i].compareTo(end[i]) > 0) { msg = "Begin value cannot be greater than ending value."; return; } step[i] = new BigInteger(s); if (step[i].compareTo(BigInteger.ONE) < 0) { msg = "Step value must be at least one."; return; } count[i] = end[i].subtract(begin[i]).divide(step[i]).intValue() + 1; fixed[i] = b.length() == e.length(); int z = 0; for (z=0; z<e.length(); z++) { if (e.charAt(z) != '0') break; } zeroes[i] = z; } catch (NumberFormatException exc) { msg = "Invalid numerical range values."; return; } } // build file listing Vector v = new Vector(); buildFiles("", num, v); files = new String[v.size()]; v.copyInto(files); valid = true; } // -- FilePattern API methods -- /** Gets the file pattern string. */ public String getPattern() { return pattern; } /** Gets whether the file pattern string is valid. */ public boolean isValid() { return valid; } /** Gets the file pattern error message, if any. */ public String getErrorMessage() { return msg; } /** Gets the first number of each numerical block. */ public BigInteger[] getFirst() { return begin; } /** Gets the last number of each numerical block. */ public BigInteger[] getLast() { return end; } /** Gets the step increment of each numerical block. */ public BigInteger[] getStep() { return step; } /** Gets the total count of each numerical block. */ public int[] getCount() { return count; } /** Gets a listing of all files matching the given file pattern. */ public String[] getFiles() { return files; } /** Gets the specified numerical block. */ public String getBlock(int i) { if (i < 0 || i >= startIndex.length) return null; return pattern.substring(startIndex[i], endIndex[i]); } /** Gets each numerical block. */ public String[] getBlocks() { String[] s = new String[startIndex.length]; for (int i=0; i<s.length; i++) s[i] = getBlock(i); return s; } /** Gets the pattern's text string before any numerical ranges. */ public String getPrefix() { int s = pattern.lastIndexOf(File.separator) + 1; int e; if (startIndex.length > 0) e = startIndex[0]; else { int dot = pattern.lastIndexOf("."); e = dot < s ? pattern.length() : dot; } return s <= e ? pattern.substring(s, e) : ""; } /** Gets the pattern's text string after all numerical ranges. */ public String getSuffix() { return endIndex.length > 0 ? pattern.substring(endIndex[endIndex.length - 1]) : pattern; } /** Gets the pattern's text string before the given numerical block. */ public String getPrefix(int i) { if (i < 0 || i >= startIndex.length) return null; int s = i > 0 ? endIndex[i - 1] : (pattern.lastIndexOf(File.separator) + 1); int e = startIndex[i]; return s <= e ? pattern.substring(s, e) : null; } /** Gets the pattern's text string before each numerical block. */ public String[] getPrefixes() { String[] s = new String[startIndex.length]; for (int i=0; i<s.length; i++) s[i] = getPrefix(i); return s; } // -- Utility methods -- /** * Identifies the group pattern from a given file within that group. * @param file The file to use as a template for the match. */ public static String findPattern(Location file) { return findPattern(file.getName(), file.getAbsoluteFile().getParent()); } /** * Identifies the group pattern from a given file within that group. * @param file The file to use as a template for the match. */ public static String findPattern(File file) { return findPattern(file.getName(), file.getAbsoluteFile().getParent()); } /** * Identifies the group pattern from a given file within that group. * @param name The filename to use as a template for the match. * @param dir The directory in which to search for matching files. */ public static String findPattern(String name, String dir) { if (dir == null) dir = ""; // current directory else if (!dir.equals("") && !dir.endsWith(File.separator)) { dir += File.separator; } Location dirFile = new Location(dir.equals("") ? "." : dir); // list files in the given directory Location[] f = dirFile.listFiles(); if (f == null) return null; String[] nameList = new String[f.length]; for (int i=0; i<nameList.length; i++) nameList[i] = f[i].getName(); return findPattern(name, dir, nameList); } /** * Identifies the group pattern from a given file within that group. * @param name The filename to use as a template for the match. * @param dir The directory prefix to use for matching files. * @param nameList The names through which to search for matching files. */ public static String findPattern(String name, String dir, String[] nameList) { if (dir == null) dir = ""; // current directory else if (!dir.equals("") && !dir.endsWith(File.separator)) { dir += File.separator; } // compile list of numerical blocks int len = name.length(); int bound = (len + 1) / 2; int[] indexList = new int[bound]; int[] endList = new int[bound]; int q = 0; boolean num = false; int ndx = -1, e = 0; for (int i=0; i<len; i++) { char c = name.charAt(i); if (c >= '0' && c <= '9') { if (num) e++; else { num = true; ndx = i; e = ndx + 1; } } else if (num) { num = false; indexList[q] = ndx; endList[q] = e; q++; } } if (num) { indexList[q] = ndx; endList[q] = e; q++; } // analyze each block, building pattern as we go StringBuffer sb = new StringBuffer(dir); for (int i=0; i<q; i++) { int last = i > 0 ? endList[i - 1] : 0; sb.append(name.substring(last, indexList[i])); String pre = name.substring(0, indexList[i]); String post = name.substring(endList[i]); NumberFilter filter = new NumberFilter(pre, post); String[] list = matchFiles(nameList, filter); if (list == null || list.length == 0) return null; if (list.length == 1) { // false alarm; this number block is constant sb.append(name.substring(indexList[i], endList[i])); continue; } boolean fix = true; for (int j=0; j<list.length; j++) { if (list[j].length() != len) { fix = false; break; } } if (fix) { // tricky; this fixed-width block could represent multiple numberings int width = endList[i] - indexList[i]; // check each character for duplicates boolean[] same = new boolean[width]; for (int j=0; j<width; j++) { same[j] = true; int jx = indexList[i] + j; char c = name.charAt(jx); for (int k=0; k<list.length; k++) { if (list[k].charAt(jx) != c) { same[j] = false; break; } } } // break down each sub-block int j = 0; while (j < width) { int jx = indexList[i] + j; if (same[j]) { sb.append(name.charAt(jx)); j++; } else { while (j < width && !same[j]) j++; String p = findPattern(name, nameList, jx, indexList[i] + j, ""); char c = indexList[i] > 0 ? name.charAt(indexList[i] - 1) : '.'; // check if this block represents the series axis if (p == null && c != 'S' && c != 's' && c != 'E' && c != 'e') { // unable to find an appropriate breakdown of numerical blocks return null; } else if (p == null) { sb.append(name.charAt(endList[i] - 1)); } else sb.append(p); } } } else { // assume variable-width block represents only one numbering BigInteger[] numbers = new BigInteger[list.length]; for (int j=0; j<list.length; j++) { numbers[j] = filter.getNumber(list[j]); } Arrays.sort(numbers); String bounds = getBounds(numbers, false); if (bounds == null) return null; sb.append(bounds); } } sb.append(q > 0 ? name.substring(endList[q - 1]) : name); String pat = sb.toString(); // NB: Due to variations in axis length, the file pattern detected can // depend on the file name given as the basis of detection. // // To work around this problem, we redetect the pattern using the first // file in the pattern if it differs from the current base file name. // // For details, see Trac ticket #19: // https://skyking.microscopy.wisc.edu/trac/java/ticket/19 String first = pat.substring(dir.length()); first = first.replaceAll("<([0-9]+)-[0-9]+(:[0-9]+)?>", "$1"); - if (!name.equals(first)) return findPattern(first, dir, nameList); + if (!name.equals(first)) { + String pattern = findPattern(first, dir, nameList); + if (pattern != null) return pattern; + } return pat; } // -- Utility helper methods -- /** Recursive method for parsing a fixed-width numerical block. */ private static String findPattern(String name, String[] nameList, int ndx, int end, String p) { if (ndx == end) return p; for (int i=end-ndx; i>=1; i--) { NumberFilter filter = new NumberFilter( name.substring(0, ndx), name.substring(ndx + i)); String[] list = matchFiles(nameList, filter); BigInteger[] numbers = new BigInteger[list.length]; for (int j=0; j<list.length; j++) { numbers[j] = new BigInteger(list[j].substring(ndx, ndx + i)); } Arrays.sort(numbers); String bounds = getBounds(numbers, true); if (bounds == null) continue; String pat = findPattern(name, nameList, ndx + i, end, p + bounds); if (pat != null) return pat; } // no combination worked; this parse path is infeasible return null; } /** * Gets a string containing start, end and step values * for a sorted list of numbers. */ private static String getBounds(BigInteger[] numbers, boolean fixed) { if (numbers.length < 2) return null; BigInteger b = numbers[0]; BigInteger e = numbers[numbers.length - 1]; BigInteger s = numbers[1].subtract(b); if (s.equals(BigInteger.ZERO)) { // step size must be positive return null; } for (int i=2; i<numbers.length; i++) { if (!numbers[i].subtract(numbers[i - 1]).equals(s)) { // step size is not constant return null; } } String sb = b.toString(); String se = e.toString(); StringBuffer bounds = new StringBuffer("<"); if (fixed) { int zeroes = se.length() - sb.length(); for (int i=0; i<zeroes; i++) bounds.append("0"); } bounds.append(sb); bounds.append("-"); bounds.append(se); if (!s.equals(BigInteger.ONE)) { bounds.append(":"); bounds.append(s); } bounds.append(">"); return bounds.toString(); } /** Filters the given list of filenames according to the specified filter. */ private static String[] matchFiles(String[] inFiles, NumberFilter filter) { Vector v = new Vector(); for (int i=0; i<inFiles.length; i++) { if (filter.accept(inFiles[i])) v.add(inFiles[i]); } String[] s = new String[v.size()]; v.copyInto(s); return s; } // -- Helper methods -- /** Recursive method for building filenames for the file listing. */ private void buildFiles(String prefix, int ndx, Vector fileList) { // compute bounds for constant (non-block) pattern fragment int num = startIndex.length; int n1 = ndx == 0 ? 0 : endIndex[ndx - 1]; int n2 = ndx == num ? pattern.length() : startIndex[ndx]; String pre = pattern.substring(n1, n2); if (ndx == 0) fileList.add(pre + prefix); else { // for (int i=begin[ndx]; i<end[ndx]; i+=step[ndx]) BigInteger bi = begin[--ndx]; while (bi.compareTo(end[ndx]) <= 0) { String s = bi.toString(); int z = zeroes[ndx]; if (fixed[ndx]) z += end[ndx].toString().length() - s.length(); for (int j=0; j<z; j++) s = "0" + s; buildFiles(s + pre + prefix, ndx, fileList); bi = bi.add(step[ndx]); } } } // -- Main method -- /** Method for testing file pattern logic. */ public static void main(String[] args) { String pat = null; if (args.length > 0) { // test file pattern detection based on the given file on disk Location file = new Location(args[0]); LogTools.println("File = " + file.getAbsoluteFile()); pat = findPattern(file); } else { // test file pattern detection from a virtual file list String[] nameList = new String[2 * 4 * 3 * 12 + 1]; nameList[0] = "outlier.ext"; int count = 1; for (int i=1; i<=2; i++) { for (int j=1; j<=4; j++) { for (int k=0; k<=2; k++) { for (int l=1; l<=12; l++) { String sl = (l < 10 ? "0" : "") + l; nameList[count++] = "hypothetical" + sl + k + j + "c" + i + ".ext"; } } } } pat = findPattern(nameList[1], null, nameList); } if (pat == null) LogTools.println("No pattern found."); else { LogTools.println("Pattern = " + pat); FilePattern fp = new FilePattern(pat); if (fp.isValid()) { LogTools.println("Pattern is valid."); LogTools.println("Files:"); String[] ids = fp.getFiles(); for (int i=0; i<ids.length; i++) { LogTools.println(" #" + i + ": " + ids[i]); } } else LogTools.println("Pattern is invalid: " + fp.getErrorMessage()); } } } // -- Notes -- // Some patterns observed: // // TAABA1.PIC TAABA2.PIC TAABA3.PIC ... TAABA45.PIC // // 0m.tiff 3m.tiff 6m.tiff ... 36m.tiff // // cell-Z0.C0.tiff cell-Z1.C0.tiff cell-Z2.C0.tiff ... cell-Z39.C0.tiff // cell-Z0.C1.tiff cell-Z1.C1.tiff cell-Z2.C1.tiff ... cell-Z39.C1.tiff // // CRG401.PIC // // TST00101.PIC TST00201.PIC TST00301.PIC // TST00102.PIC TST00202.PIC TST00302.PIC // // 800102.pic 800202.pic 800302.pic ... 805902.pic // 800103.pic 800203.pic 800303.pic ... 805903.pic // // nd400102.pic nd400202.pic nd400302.pic ... nd406002.pic // nd400103.pic nd400203.pic nd400303.pic ... nd406003.pic // // WTERZ2_Series13_z000_ch00.tif ... WTERZ2_Series13_z018_ch00.tif // // -------------------------------------------------------------------------- // // The file pattern notation defined here encompasses all patterns above. // // TAABA<1-45>.PIC // <0-36:3>m.tiff // cell-Z<0-39>.C<0-1>.tiff // CRG401.PIC // TST00<1-3>0<1-2>.PIC // 80<01-59>0<2-3>.pic // nd40<01-60>0<2-3>.pic // WTERZ2_Series13_z0<00-18>_ch00.tif // // In general: <B-E:S> where B is the start number, E is the end number, and S // is the step increment. If zero padding has been used, the start number B // will have leading zeroes to indicate that. If the step increment is one, it // can be omitted. // // -------------------------------------------------------------------------- // // If file groups not limited to numbering need to be handled, we can extend // the notation as follows: // // A pattern such as: // // ABCR.PIC ABCG.PIC ABCB.PIC // // Could be represented as: // // ABC<R|G|B>.PIC // // If such cases come up, they will need to be identified heuristically and // incorporated into the detection algorithm. // // -------------------------------------------------------------------------- // // Here is a sketch of the algorithm for determining the pattern from a given // file within a particular group: // // 01 - Detect number blocks within the file name, marking them with stars. // For example: // // xyz800303b.pic -> xyz<>b.pic // // Where <> represents a numerical block with unknown properties. // // 02 - Get a file listing for all files matching the given pattern. In the // example above, we'd get: // // xyz800102b.pic, xyz800202b.pic, ..., xyz805902b.pic, // xyz800103b.pic, xyz800203b.pic, ..., xyz805903b.pic // // 03 - There are two possibilities: "fixed width" and "variable width." // // Variable width: Not all filenames are the same length in characters. // Assume the block only covers a single number. Extract that number // from each filename, sort them and analyze as described below. // // Fixed width: All filenames are the same length in characters. The // block could represent more than one number. // // First, for each character, determine if that character varies between // filenames. If not, lock it down, splitting the block as necessary // into fixed-width blocks. When finished, the above example looks like: // // xyz80<2>0<1>b.pic // // Where <N> represents a numerical block of width N. // // For each remaining block, extract the numbers from each matching // filename, sort the lists, and analyze as described below. // // 04 - In either case, analyze each list of numbers. The first on the list // is B. The last one is E. And S is the second one minus B. But check // the list to make sure no numbers are missing for that step size. // // NOTE: The fixed width algorithm above is insufficient for patterns like // "0101.pic" through "2531.pic," where no fixed constant pads the two // numerical counts. An additional step is required, as follows: // // 05 - For each fixed-width block, recursively divide it into pieces, and // analyze the numerical scheme according to those pieces. For example, // in the problem case given above, we'd have: // // <4>.pic // // Recursively, we'd analyze: // // <4>.pic // <3><R1>.pic // <2><R2>.pic // <1><R3>.pic // // The <Rx> blocks represent recursive calls to analyze the remainder of // the width. // // The function decides if a given combination of widths is valid by // determining if each individual width is valid. An individual width // is valid if the computed B, S and E properly cover the numerical set. // // If no combination of widths is found to be valid, the file numbering // is screwy. Print an error message.
true
true
public static String findPattern(String name, String dir, String[] nameList) { if (dir == null) dir = ""; // current directory else if (!dir.equals("") && !dir.endsWith(File.separator)) { dir += File.separator; } // compile list of numerical blocks int len = name.length(); int bound = (len + 1) / 2; int[] indexList = new int[bound]; int[] endList = new int[bound]; int q = 0; boolean num = false; int ndx = -1, e = 0; for (int i=0; i<len; i++) { char c = name.charAt(i); if (c >= '0' && c <= '9') { if (num) e++; else { num = true; ndx = i; e = ndx + 1; } } else if (num) { num = false; indexList[q] = ndx; endList[q] = e; q++; } } if (num) { indexList[q] = ndx; endList[q] = e; q++; } // analyze each block, building pattern as we go StringBuffer sb = new StringBuffer(dir); for (int i=0; i<q; i++) { int last = i > 0 ? endList[i - 1] : 0; sb.append(name.substring(last, indexList[i])); String pre = name.substring(0, indexList[i]); String post = name.substring(endList[i]); NumberFilter filter = new NumberFilter(pre, post); String[] list = matchFiles(nameList, filter); if (list == null || list.length == 0) return null; if (list.length == 1) { // false alarm; this number block is constant sb.append(name.substring(indexList[i], endList[i])); continue; } boolean fix = true; for (int j=0; j<list.length; j++) { if (list[j].length() != len) { fix = false; break; } } if (fix) { // tricky; this fixed-width block could represent multiple numberings int width = endList[i] - indexList[i]; // check each character for duplicates boolean[] same = new boolean[width]; for (int j=0; j<width; j++) { same[j] = true; int jx = indexList[i] + j; char c = name.charAt(jx); for (int k=0; k<list.length; k++) { if (list[k].charAt(jx) != c) { same[j] = false; break; } } } // break down each sub-block int j = 0; while (j < width) { int jx = indexList[i] + j; if (same[j]) { sb.append(name.charAt(jx)); j++; } else { while (j < width && !same[j]) j++; String p = findPattern(name, nameList, jx, indexList[i] + j, ""); char c = indexList[i] > 0 ? name.charAt(indexList[i] - 1) : '.'; // check if this block represents the series axis if (p == null && c != 'S' && c != 's' && c != 'E' && c != 'e') { // unable to find an appropriate breakdown of numerical blocks return null; } else if (p == null) { sb.append(name.charAt(endList[i] - 1)); } else sb.append(p); } } } else { // assume variable-width block represents only one numbering BigInteger[] numbers = new BigInteger[list.length]; for (int j=0; j<list.length; j++) { numbers[j] = filter.getNumber(list[j]); } Arrays.sort(numbers); String bounds = getBounds(numbers, false); if (bounds == null) return null; sb.append(bounds); } } sb.append(q > 0 ? name.substring(endList[q - 1]) : name); String pat = sb.toString(); // NB: Due to variations in axis length, the file pattern detected can // depend on the file name given as the basis of detection. // // To work around this problem, we redetect the pattern using the first // file in the pattern if it differs from the current base file name. // // For details, see Trac ticket #19: // https://skyking.microscopy.wisc.edu/trac/java/ticket/19 String first = pat.substring(dir.length()); first = first.replaceAll("<([0-9]+)-[0-9]+(:[0-9]+)?>", "$1"); if (!name.equals(first)) return findPattern(first, dir, nameList); return pat; }
public static String findPattern(String name, String dir, String[] nameList) { if (dir == null) dir = ""; // current directory else if (!dir.equals("") && !dir.endsWith(File.separator)) { dir += File.separator; } // compile list of numerical blocks int len = name.length(); int bound = (len + 1) / 2; int[] indexList = new int[bound]; int[] endList = new int[bound]; int q = 0; boolean num = false; int ndx = -1, e = 0; for (int i=0; i<len; i++) { char c = name.charAt(i); if (c >= '0' && c <= '9') { if (num) e++; else { num = true; ndx = i; e = ndx + 1; } } else if (num) { num = false; indexList[q] = ndx; endList[q] = e; q++; } } if (num) { indexList[q] = ndx; endList[q] = e; q++; } // analyze each block, building pattern as we go StringBuffer sb = new StringBuffer(dir); for (int i=0; i<q; i++) { int last = i > 0 ? endList[i - 1] : 0; sb.append(name.substring(last, indexList[i])); String pre = name.substring(0, indexList[i]); String post = name.substring(endList[i]); NumberFilter filter = new NumberFilter(pre, post); String[] list = matchFiles(nameList, filter); if (list == null || list.length == 0) return null; if (list.length == 1) { // false alarm; this number block is constant sb.append(name.substring(indexList[i], endList[i])); continue; } boolean fix = true; for (int j=0; j<list.length; j++) { if (list[j].length() != len) { fix = false; break; } } if (fix) { // tricky; this fixed-width block could represent multiple numberings int width = endList[i] - indexList[i]; // check each character for duplicates boolean[] same = new boolean[width]; for (int j=0; j<width; j++) { same[j] = true; int jx = indexList[i] + j; char c = name.charAt(jx); for (int k=0; k<list.length; k++) { if (list[k].charAt(jx) != c) { same[j] = false; break; } } } // break down each sub-block int j = 0; while (j < width) { int jx = indexList[i] + j; if (same[j]) { sb.append(name.charAt(jx)); j++; } else { while (j < width && !same[j]) j++; String p = findPattern(name, nameList, jx, indexList[i] + j, ""); char c = indexList[i] > 0 ? name.charAt(indexList[i] - 1) : '.'; // check if this block represents the series axis if (p == null && c != 'S' && c != 's' && c != 'E' && c != 'e') { // unable to find an appropriate breakdown of numerical blocks return null; } else if (p == null) { sb.append(name.charAt(endList[i] - 1)); } else sb.append(p); } } } else { // assume variable-width block represents only one numbering BigInteger[] numbers = new BigInteger[list.length]; for (int j=0; j<list.length; j++) { numbers[j] = filter.getNumber(list[j]); } Arrays.sort(numbers); String bounds = getBounds(numbers, false); if (bounds == null) return null; sb.append(bounds); } } sb.append(q > 0 ? name.substring(endList[q - 1]) : name); String pat = sb.toString(); // NB: Due to variations in axis length, the file pattern detected can // depend on the file name given as the basis of detection. // // To work around this problem, we redetect the pattern using the first // file in the pattern if it differs from the current base file name. // // For details, see Trac ticket #19: // https://skyking.microscopy.wisc.edu/trac/java/ticket/19 String first = pat.substring(dir.length()); first = first.replaceAll("<([0-9]+)-[0-9]+(:[0-9]+)?>", "$1"); if (!name.equals(first)) { String pattern = findPattern(first, dir, nameList); if (pattern != null) return pattern; } return pat; }
diff --git a/src/main/java/cse/buffalo/edu/algorithms/search/BST.java b/src/main/java/cse/buffalo/edu/algorithms/search/BST.java index 8fa6193..1e41926 100644 --- a/src/main/java/cse/buffalo/edu/algorithms/search/BST.java +++ b/src/main/java/cse/buffalo/edu/algorithms/search/BST.java @@ -1,246 +1,246 @@ package cse.buffalo.edu.algorithms.search; import cse.buffalo.edu.algorithms.stdlib.StdIn; import cse.buffalo.edu.algorithms.stdlib.StdOut; import cse.buffalo.edu.algorithms.datastructure.queue.Queue; import java.util.NoSuchElementException; public class BST<Key extends Comparable<Key>, Value> { private Node root; private class Node { private Key key; private Value value; private Node left, right; private int N; public Node(Key key, Value value) { this.key = key; this.value = value; this.N = 1; } } // This is a very concise, but tricky code. public void put(Key key, Value value) { root = put(root, key, value); } private Node put(Node x, Key key, Value value) { if (x == null) return new Node(key, value); int cmp = key.compareTo(x.key); if (cmp == 0) x.value = value; else if (cmp < 0) x.left = put(x.left, key, value); else x.right = put(x.right, key, value); x.N = 1 + size(x.left) + size(x.right); return x; } // Why we use recusive in put() but not get() // because this operation often falls within the // inner loop in typical applications. public Value get(Key key) { Node tmp = root; while (tmp != null) { int cmp = key.compareTo(tmp.key); if (cmp == 0) return tmp.value; else if (cmp < 0) tmp = tmp.left; else tmp = tmp.right; } return null; } public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); } // Need a little time to understand this. private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = 1 + size(x.left) + size(x.right); // Trciky part. If x != null, return x itself. return x; } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = 1 + size(x.left) + size(x.right); return x; } public void delete(Key key) { if (!contains(key)) { System.err.println("Symbol table does not contian " + key); return; } root = delete(root, key); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); // Search for the key. - if (cmp < 0) delete(x.left, key); - else if (cmp > 0) delete(x.right, key); + if (cmp < 0) x.left = delete(x.left, key); + else if (cmp > 0) x.right = delete(x.right, key); else { // Case 1: no right child. // You can do the same thing when there is no left child // but because no left child can be handle by the case 2, // you don't need to do it here if (x.right == null) return x.left; Node t = x; // Replace this node with the min node of the right subtree. x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = 1 + size(x.left) + size(x.right); return x; } public Key min() { if (isEmpty()) return null; return min(root).key; } private Node min(Node x) { if (x.left == null) return x; else return min(x.left); } public Key max() { if (isEmpty()) return null; return max(root).key; } private Node max(Node x) { if (x.right == null) return x; else return max(x.right); } public Value floor(Key key) { return floor(root, key).value; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; else if (cmp < 0) return floor(x.left, key); else { // Find the smallest one in the right section. Node t = floor(x.right, key); if (t != null) return t; else return x; } } public Value ceiling(Key key) { return ceiling(root, key).value; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; else if (cmp > 0) return ceiling(x.right, key); else { Node t = floor(x.left, key); if (t != null) return t; else return x; } } // Number of elements smaller than the key. // It is also a little bit tricky. public int rank(Key key) { return rank(root, key); } private int rank(Node x, Key key) { // Stop condition for the recursion. if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp == 0) return size(x.left); else if (cmp < 0) return rank(x.left, key); else return 1 + size(x.left) + rank(x.right, key); } // Key of given rank. public Key select(int k) { if (k < 0) return null; if (k >= size()) return null; Node x = select(root, k); return x.key; } private Node select(Node x, int k) { if (x == null) return null; int t = size(x.left); if (t == k) return x; else if (t < k) return select(x.left, k); // The following is the tricky part. else return select(x.right, k-t-1); } public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; else return x.N; } public boolean isEmpty() { return size() == 0; } public boolean contains(Key key) { return get(key) != null; } public Iterable<Key> keys() { Queue<Key> q = new Queue<Key>(); inorder(root, q); return q; } // Ascending order. A concise and important part. private void inorder(Node x, Queue<Key> q) { if (x == null) return; inorder(x.left, q); q.enqueue(x.key); inorder(x.right, q); } public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) { StdOut.println(s + " " + st.get(s)); } } }
true
true
private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); // Search for the key. if (cmp < 0) delete(x.left, key); else if (cmp > 0) delete(x.right, key); else { // Case 1: no right child. // You can do the same thing when there is no left child // but because no left child can be handle by the case 2, // you don't need to do it here if (x.right == null) return x.left; Node t = x; // Replace this node with the min node of the right subtree. x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = 1 + size(x.left) + size(x.right); return x; }
private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); // Search for the key. if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { // Case 1: no right child. // You can do the same thing when there is no left child // but because no left child can be handle by the case 2, // you don't need to do it here if (x.right == null) return x.left; Node t = x; // Replace this node with the min node of the right subtree. x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = 1 + size(x.left) + size(x.right); return x; }
diff --git a/src/org/apache/xerces/impl/xs/XMLSchemaLoader.java b/src/org/apache/xerces/impl/xs/XMLSchemaLoader.java index 46e27832..8d3034ce 100644 --- a/src/org/apache/xerces/impl/xs/XMLSchemaLoader.java +++ b/src/org/apache/xerces/impl/xs/XMLSchemaLoader.java @@ -1,1328 +1,1331 @@ /* * 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.xerces.impl.xs; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Hashtable; import java.util.Locale; import java.util.StringTokenizer; import java.util.Vector; import java.util.WeakHashMap; import org.apache.xerces.dom.DOMErrorImpl; import org.apache.xerces.dom.DOMMessageFormatter; import org.apache.xerces.dom.DOMStringListImpl; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.CMNodeFactory; import org.apache.xerces.impl.xs.traversers.XSDHandler; import org.apache.xerces.util.DOMEntityResolverWrapper; import org.apache.xerces.util.DOMErrorHandlerWrapper; import org.apache.xerces.util.DefaultErrorHandler; import org.apache.xerces.util.ParserConfigurationSettings; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XMLGrammarLoader; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.grammars.XSGrammar; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLErrorHandler; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.LSInputList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSLoader; import org.apache.xerces.xs.XSModel; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMError; import org.w3c.dom.DOMErrorHandler; import org.w3c.dom.DOMException; import org.w3c.dom.DOMStringList; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.InputSource; /** * This class implements xni.grammars.XMLGrammarLoader. * It also serves as implementation of xs.XSLoader interface and DOMConfiguration interface. * * This class is designed to interact either with a proxy for a user application * which wants to preparse schemas, or with our own Schema validator. * It is hoped that none of these "external" classes will therefore need to communicate directly * with XSDHandler in future. * <p>This class only knows how to make XSDHandler do its thing. * The caller must ensure that all its properties (schemaLocation, JAXPSchemaSource * etc.) have been properly set. * * @xerces.internal * * @author Neil Graham, IBM * @version $Id$ */ public class XMLSchemaLoader implements XMLGrammarLoader, XMLComponent, // XML Component API XSLoader, DOMConfiguration { // Feature identifiers: /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: continue after fatal error. */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; /** Feature identifier: allow java encodings to be recognized when parsing schema docs. */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: standard uri conformant feature. */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Feature identifier: validate annotations. */ protected static final String VALIDATE_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE; /** Feature: disallow doctype*/ protected static final String DISALLOW_DOCTYPE = Constants.XERCES_FEATURE_PREFIX + Constants.DISALLOW_DOCTYPE_DECL_FEATURE; /** Feature: generate synthetic annotations */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; protected static final String AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; protected static final String PARSER_SETTINGS = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; // recognized features: private static final String[] RECOGNIZED_FEATURES = { SCHEMA_FULL_CHECKING, AUGMENT_PSVI, CONTINUE_AFTER_FATAL_ERROR, ALLOW_JAVA_ENCODINGS, STANDARD_URI_CONFORMANT_FEATURE, DISALLOW_DOCTYPE, GENERATE_SYNTHETIC_ANNOTATIONS, VALIDATE_ANNOTATIONS, HONOUR_ALL_SCHEMALOCATIONS }; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: error handler. */ protected static final String ERROR_HANDLER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; protected static final String SECURITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; // recognized properties private static final String [] RECOGNIZED_PROPERTIES = { ENTITY_MANAGER, SYMBOL_TABLE, ERROR_REPORTER, ERROR_HANDLER, ENTITY_RESOLVER, XMLGRAMMAR_POOL, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE, SECURITY_MANAGER }; // Data // features and properties private ParserConfigurationSettings fLoaderConfig = new ParserConfigurationSettings(); private XMLErrorReporter fErrorReporter = new XMLErrorReporter (); private XMLEntityManager fEntityManager = null; private XMLEntityResolver fUserEntityResolver = null; private XMLGrammarPool fGrammarPool = null; private String fExternalSchemas = null; private String fExternalNoNSSchema = null; // JAXP property: schema source private Object fJAXPSource = null; // is Schema Full Checking enabled private boolean fIsCheckedFully = false; // boolean that tells whether we've tested the JAXP property. private boolean fJAXPProcessed = false; // if features/properties has not been changed, the value of this attribute is "false" private boolean fSettingsChanged = true; // xml schema parsing private XSDHandler fSchemaHandler; private XSGrammarBucket fGrammarBucket; private XSDeclarationPool fDeclPool = null; private SubstitutionGroupHandler fSubGroupHandler; private CMBuilder fCMBuilder; private XSDDescription fXSDDescription = new XSDDescription(); private WeakHashMap fJAXPCache; private Locale fLocale = Locale.getDefault(); // XSLoader attributes private DOMStringList fRecognizedParameters = null; /** DOM L3 error handler */ private DOMErrorHandlerWrapper fErrorHandler = null; /** DOM L3 resource resolver */ private DOMEntityResolverWrapper fResourceResolver = null; // default constructor. Create objects we absolutely need: public XMLSchemaLoader() { this( new SymbolTable(), null, new XMLEntityManager(), null, null, null); } public XMLSchemaLoader(SymbolTable symbolTable) { this( symbolTable, null, new XMLEntityManager(), null, null, null); } /** * This constractor is used by the XMLSchemaValidator. Additional properties, i.e. XMLEntityManager, * will be passed during reset(XMLComponentManager). * @param errorReporter * @param grammarBucket * @param sHandler * @param builder */ XMLSchemaLoader(XMLErrorReporter errorReporter, XSGrammarBucket grammarBucket, SubstitutionGroupHandler sHandler, CMBuilder builder) { this(null, errorReporter, null, grammarBucket, sHandler, builder); } XMLSchemaLoader(SymbolTable symbolTable, XMLErrorReporter errorReporter, XMLEntityManager entityResolver, XSGrammarBucket grammarBucket, SubstitutionGroupHandler sHandler, CMBuilder builder) { // store properties and features in configuration fLoaderConfig.addRecognizedFeatures(RECOGNIZED_FEATURES); fLoaderConfig.addRecognizedProperties(RECOGNIZED_PROPERTIES); if (symbolTable != null){ fLoaderConfig.setProperty(SYMBOL_TABLE, symbolTable); } if(errorReporter == null) { errorReporter = new XMLErrorReporter (); errorReporter.setLocale(fLocale); errorReporter.setProperty(ERROR_HANDLER, new DefaultErrorHandler()); } fErrorReporter = errorReporter; // make sure error reporter knows about schemas... if(fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter()); } fLoaderConfig.setProperty(ERROR_REPORTER, fErrorReporter); fEntityManager = entityResolver; // entity manager is null if XMLSchemaValidator creates the loader if (fEntityManager != null){ fLoaderConfig.setProperty(ENTITY_MANAGER, fEntityManager); } // by default augment PSVI (i.e. don't use declaration pool) fLoaderConfig.setFeature(AUGMENT_PSVI, true); if(grammarBucket == null ) { grammarBucket = new XSGrammarBucket(); } fGrammarBucket = grammarBucket; if(sHandler == null) { sHandler = new SubstitutionGroupHandler(fGrammarBucket); } fSubGroupHandler = sHandler; //get an instance of the CMNodeFactory */ CMNodeFactory nodeFactory = new CMNodeFactory() ; if(builder == null) { builder = new CMBuilder(nodeFactory); } fCMBuilder = builder; fSchemaHandler = new XSDHandler(fGrammarBucket); fDeclPool = new XSDeclarationPool(); fJAXPCache = new WeakHashMap(); fSettingsChanged = true; } /** * Returns a list of feature identifiers that are recognized by * this XMLGrammarLoader. This method may return null if no features * are recognized. */ public String[] getRecognizedFeatures() { return (String[])(RECOGNIZED_FEATURES.clone()); } // getRecognizedFeatures(): String[] /** * Returns the state of a feature. * * @param featureId The feature identifier. * * @throws XMLConfigurationException Thrown on configuration error. */ public boolean getFeature(String featureId) throws XMLConfigurationException { return fLoaderConfig.getFeature(featureId); } // getFeature (String): boolean /** * Sets the state of a feature. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws XMLConfigurationException Thrown when a feature is not * recognized or cannot be set. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { fSettingsChanged = true; if(featureId.equals(CONTINUE_AFTER_FATAL_ERROR)) { fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, state); } else if(featureId.equals(GENERATE_SYNTHETIC_ANNOTATIONS)) { fSchemaHandler.setGenerateSyntheticAnnotations(state); } fLoaderConfig.setFeature(featureId, state); } // setFeature(String, boolean) /** * Returns a list of property identifiers that are recognized by * this XMLGrammarLoader. This method may return null if no properties * are recognized. */ public String[] getRecognizedProperties() { return (String[])(RECOGNIZED_PROPERTIES.clone()); } // getRecognizedProperties(): String[] /** * Returns the state of a property. * * @param propertyId The property identifier. * * @throws XMLConfigurationException Thrown on configuration error. */ public Object getProperty(String propertyId) throws XMLConfigurationException { return fLoaderConfig.getProperty(propertyId); } // getProperty(String): Object /** * Sets the state of a property. * * @param propertyId The property identifier. * @param state The state of the property. * * @throws XMLConfigurationException Thrown when a property is not * recognized or cannot be set. */ public void setProperty(String propertyId, Object state) throws XMLConfigurationException { fSettingsChanged = true; fLoaderConfig.setProperty(propertyId, state); if(propertyId.equals( JAXP_SCHEMA_SOURCE)) { fJAXPSource = state; fJAXPProcessed = false; } else if(propertyId.equals( XMLGRAMMAR_POOL)) { fGrammarPool = (XMLGrammarPool)state; } else if (propertyId.equals(SCHEMA_LOCATION)){ fExternalSchemas = (String)state; } else if (propertyId.equals(SCHEMA_NONS_LOCATION)){ fExternalNoNSSchema = (String) state; } else if (propertyId.equals(ENTITY_RESOLVER)){ fEntityManager.setProperty(ENTITY_RESOLVER, state); } else if (propertyId.equals(ERROR_REPORTER)){ fErrorReporter = (XMLErrorReporter)state; if (fErrorReporter.getMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN) == null) { fErrorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter()); } } } // setProperty(String, Object) /** * Set the locale to use for messages. * * @param locale The locale object to use for localization of messages. * * @exception XNIException Thrown if the parser does not support the * specified locale. */ public void setLocale(Locale locale) { fLocale = locale; fErrorReporter.setLocale(locale); } // setLocale(Locale) /** Return the Locale the XMLGrammarLoader is using. */ public Locale getLocale() { return fLocale; } // getLocale(): Locale /** * Sets the error handler. * * @param errorHandler The error handler. */ public void setErrorHandler(XMLErrorHandler errorHandler) { fErrorReporter.setProperty(ERROR_HANDLER, errorHandler); } // setErrorHandler(XMLErrorHandler) /** Returns the registered error handler. */ public XMLErrorHandler getErrorHandler() { return fErrorReporter.getErrorHandler(); } // getErrorHandler(): XMLErrorHandler /** * Sets the entity resolver. * * @param entityResolver The new entity resolver. */ public void setEntityResolver(XMLEntityResolver entityResolver) { fUserEntityResolver = entityResolver; fLoaderConfig.setProperty(ENTITY_RESOLVER, entityResolver); fEntityManager.setProperty(ENTITY_RESOLVER, entityResolver); } // setEntityResolver(XMLEntityResolver) /** Returns the registered entity resolver. */ public XMLEntityResolver getEntityResolver() { return fUserEntityResolver; } // getEntityResolver(): XMLEntityResolver /** * Returns a Grammar object by parsing the contents of the * entities pointed to by sources. * * @param source the locations of the entity which forms * the staring point of the grammars to be constructed * @throws IOException when a problem is encounted reading the entity * @throws XNIException when a condition arises (such as a FatalError) that requires parsing * of the entity be terminated */ public void loadGrammar(XMLInputSource source[]) throws IOException, XNIException { int numSource = source.length; for (int i = 0; i < numSource; ++i) { loadGrammar(source[i]); } } /** * Returns a Grammar object by parsing the contents of the * entity pointed to by source. * * @param source the location of the entity which forms * the starting point of the grammar to be constructed. * @throws IOException When a problem is encountered reading the entity * XNIException When a condition arises (such as a FatalError) that requires parsing * of the entity be terminated. */ public Grammar loadGrammar(XMLInputSource source) throws IOException, XNIException { // REVISIT: this method should have a namespace parameter specified by // user. In this case we can easily detect if a schema asked to be loaded // is already in the local cache. reset(fLoaderConfig); fSettingsChanged = false; XSDDescription desc = new XSDDescription(); desc.fContextType = XSDDescription.CONTEXT_PREPARSE; desc.setBaseSystemId(source.getBaseSystemId()); desc.setLiteralSystemId( source.getSystemId()); // none of the other fields make sense for preparsing Hashtable locationPairs = new Hashtable(); // Process external schema location properties. // We don't call tokenizeSchemaLocationStr here, because we also want // to check whether the values are valid URI. processExternalHints(fExternalSchemas, fExternalNoNSSchema, locationPairs, fErrorReporter); SchemaGrammar grammar = loadSchema(desc, source, locationPairs); if(grammar != null && fGrammarPool != null) { fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, fGrammarBucket.getGrammars()); // NOTE: we only need to verify full checking in case the schema was not provided via JAXP // since full checking already verified for all JAXP schemas if(fIsCheckedFully && fJAXPCache.get(grammar) != grammar) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } } return grammar; } // loadGrammar(XMLInputSource): Grammar /** * This method is called either from XMLGrammarLoader.loadGrammar or from XMLSchemaValidator. * Note: in either case, the EntityManager (or EntityResolvers) are not going to be invoked * to resolve the location of the schema in XSDDescription * @param desc * @param source * @param locationPairs * @return An XML Schema grammar * @throws IOException * @throws XNIException */ SchemaGrammar loadSchema(XSDDescription desc, XMLInputSource source, Hashtable locationPairs) throws IOException, XNIException { // this should only be done once per invocation of this object; // unless application alters JAXPSource in the mean time. if(!fJAXPProcessed) { processJAXPSchemaSource(locationPairs); } SchemaGrammar grammar = fSchemaHandler.parseSchema(source, desc, locationPairs); return grammar; } // loadSchema(XSDDescription, XMLInputSource): SchemaGrammar /** * This method tries to resolve location of the given schema. * The loader stores the namespace/location pairs in a hashtable (use "" as the * namespace of absent namespace). When resolving an entity, loader first tries * to find in the hashtable whether there is a value for that namespace, * if so, pass that location value to the user-defined entity resolver. * * @param desc * @param locationPairs * @param entityResolver * @return the XMLInputSource * @throws IOException */ public static XMLInputSource resolveDocument(XSDDescription desc, Hashtable locationPairs, XMLEntityResolver entityResolver) throws IOException { String loc = null; // we consider the schema location properties for import if (desc.getContextType() == XSDDescription.CONTEXT_IMPORT || desc.fromInstance()) { // use empty string as the key for absent namespace String namespace = desc.getTargetNamespace(); String ns = namespace == null ? XMLSymbols.EMPTY_STRING : namespace; // get the location hint for that namespace LocationArray tempLA = (LocationArray)locationPairs.get(ns); if(tempLA != null) loc = tempLA.getFirstLocation(); } // if it's not import, or if the target namespace is not set // in the schema location properties, use location hint if (loc == null) { String[] hints = desc.getLocationHints(); if (hints != null && hints.length > 0) loc = hints[0]; } String expandedLoc = XMLEntityManager.expandSystemId(loc, desc.getBaseSystemId(), false); desc.setLiteralSystemId(loc); desc.setExpandedSystemId(expandedLoc); return entityResolver.resolveEntity(desc); } // add external schema locations to the location pairs public static void processExternalHints(String sl, String nsl, Hashtable locations, XMLErrorReporter er) { if (sl != null) { try { // get the attribute decl for xsi:schemaLocation // because external schema location property has the same syntax // as xsi:schemaLocation XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); // validation the string value to get the list of URI's attrDecl.fType.validate(sl, null, null); if (!tokenizeSchemaLocationStr(sl, locations)) { // report warning (odd number of items) er.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[]{sl}, XMLErrorReporter.SEVERITY_WARNING); } } catch (InvalidDatatypeValueException ex) { // report warning (not list of URI's) er.reportError(XSMessageFormatter.SCHEMA_DOMAIN, ex.getKey(), ex.getArgs(), XMLErrorReporter.SEVERITY_WARNING); } } if (nsl != null) { try { // similarly for no ns schema location property XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); attrDecl.fType.validate(nsl, null, null); LocationArray la = ((LocationArray)locations.get(XMLSymbols.EMPTY_STRING)); if(la == null) { la = new LocationArray(); locations.put(XMLSymbols.EMPTY_STRING, la); } la.addLocation(nsl); } catch (InvalidDatatypeValueException ex) { // report warning (not a URI) er.reportError(XSMessageFormatter.SCHEMA_DOMAIN, ex.getKey(), ex.getArgs(), XMLErrorReporter.SEVERITY_WARNING); } } } // this method takes a SchemaLocation string. // If an error is encountered, false is returned; // otherwise, true is returned. In either case, locations // is augmented to include as many tokens as possible. // @param schemaStr The schemaLocation string to tokenize // @param locations Hashtable mapping namespaces to LocationArray objects holding lists of locaitons // @return true if no problems; false if string could not be tokenized public static boolean tokenizeSchemaLocationStr(String schemaStr, Hashtable locations) { if (schemaStr!= null) { StringTokenizer t = new StringTokenizer(schemaStr, " \n\t\r"); String namespace, location; while (t.hasMoreTokens()) { namespace = t.nextToken (); if (!t.hasMoreTokens()) { return false; // error! } location = t.nextToken(); LocationArray la = ((LocationArray)locations.get(namespace)); if(la == null) { la = new LocationArray(); locations.put(namespace, la); } la.addLocation(location); } } return true; } // tokenizeSchemaLocation(String, Hashtable): boolean /** * Translate the various JAXP SchemaSource property types to XNI * XMLInputSource. Valid types are: String, org.xml.sax.InputSource, * InputStream, File, or Object[] of any of previous types. * REVISIT: the JAXP 1.2 spec is less than clear as to whether this property * should be available to imported schemas. I have assumed * that it should. - NG * Note: all JAXP schema files will be checked for full-schema validity if the feature was set up * */ private void processJAXPSchemaSource(Hashtable locationPairs) throws IOException { fJAXPProcessed = true; if (fJAXPSource == null) { return; } Class componentType = fJAXPSource.getClass().getComponentType(); XMLInputSource xis = null; String sid = null; if (componentType == null) { // Not an array if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); if (g != null) { fGrammarBucket.putGrammar(g); return; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(fJAXPSource); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } SchemaGrammar g = loadSchema(fXSDDescription, xis, locationPairs); // it is possible that we won't be able to resolve JAXP schema-source location if (g != null) { if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { fJAXPCache.put(fJAXPSource, g); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } } fGrammarBucket.putGrammar(g); } return; } else if ( (componentType != Object.class) && (componentType != String.class) && (componentType != File.class) && (componentType != InputStream.class) && - (componentType != InputSource.class) + (componentType != InputSource.class) && + !File.class.isAssignableFrom(componentType) && + !InputStream.class.isAssignableFrom(componentType) && + !InputSource.class.isAssignableFrom(componentType) ) { // Not an Object[], String[], File[], InputStream[], InputSource[] throw new XMLConfigurationException( XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+ "\" property cannot have an array of type {"+componentType.getName()+ "}. Possible types of the array supported are Object, String, File, "+ "InputStream, InputSource."); } // JAXP spec. allow []s of type String, File, InputStream, // InputSource also, apart from [] of type Object. Object[] objArr = (Object[]) fJAXPSource; // make local vector for storing target namespaces of schemasources specified in object arrays. ArrayList jaxpSchemaSourceNamespaces = new ArrayList(); for (int i = 0; i < objArr.length; i++) { if(objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); if (g != null) { fGrammarBucket.putGrammar(g); continue; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(objArr[i]); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } String targetNamespace = null ; // load schema SchemaGrammar grammar = fSchemaHandler.parseSchema(xis,fXSDDescription, locationPairs); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } if (grammar != null) { targetNamespace = grammar.getTargetNamespace(); if (jaxpSchemaSourceNamespaces.contains(targetNamespace)) { //when an array of objects is passed it is illegal to have two schemas that share same namespace. throw new java.lang.IllegalArgumentException( " When using array of Objects as the value of SCHEMA_SOURCE property , " + "no two Schemas should share the same targetNamespace. " ); } else { jaxpSchemaSourceNamespaces.add(targetNamespace) ; } if (objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { fJAXPCache.put(objArr[i], grammar); } fGrammarBucket.putGrammar(grammar); } else { //REVISIT: What should be the acutal behavior if grammar can't be loaded as specified in schema source? } } }//processJAXPSchemaSource private XMLInputSource xsdToXMLInputSource( Object val) { if (val instanceof String) { // String value is treated as a URI that is passed through the // EntityResolver String loc = (String) val; fXSDDescription.reset(); fXSDDescription.setValues(null, loc, null, null); XMLInputSource xis = null; try { xis = fEntityManager.resolveEntity(fXSDDescription); } catch (IOException ex) { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[] { loc }, XMLErrorReporter.SEVERITY_ERROR); } if (xis == null) { // REVISIT: can this happen? // Treat value as a URI and pass in as systemId return new XMLInputSource(null, loc, null); } return xis; } else if (val instanceof InputSource) { return saxToXMLInputSource((InputSource) val); } else if (val instanceof InputStream) { return new XMLInputSource(null, null, null, (InputStream) val, null); } else if (val instanceof File) { File file = (File) val; InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException ex) { fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[] { file.toString() }, XMLErrorReporter.SEVERITY_ERROR); } return new XMLInputSource(null, null, null, is, null); } throw new XMLConfigurationException( XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+ "\" property cannot have a value of type {"+val.getClass().getName()+ "}. Possible types of the value supported are String, File, InputStream, "+ "InputSource OR an array of these types."); } //Convert a SAX InputSource to an equivalent XNI XMLInputSource private static XMLInputSource saxToXMLInputSource(InputSource sis) { String publicId = sis.getPublicId(); String systemId = sis.getSystemId(); Reader charStream = sis.getCharacterStream(); if (charStream != null) { return new XMLInputSource(publicId, systemId, null, charStream, null); } InputStream byteStream = sis.getByteStream(); if (byteStream != null) { return new XMLInputSource(publicId, systemId, null, byteStream, sis.getEncoding()); } return new XMLInputSource(publicId, systemId, null); } static class LocationArray{ int length ; String [] locations = new String[2]; public void resize(int oldLength , int newLength){ String [] temp = new String[newLength] ; System.arraycopy(locations, 0, temp, 0, Math.min(oldLength, newLength)); locations = temp ; length = Math.min(oldLength, newLength); } public void addLocation(String location){ if(length >= locations.length ){ resize(length, Math.max(1, length*2)); } locations[length++] = location; }//setLocation() public String [] getLocationArray(){ if(length < locations.length ){ resize(locations.length, length); } return locations; }//getLocationArray() public String getFirstLocation(){ return length > 0 ? locations[0] : null; } public int getLength(){ return length ; } } //locationArray /* (non-Javadoc) * @see org.apache.xerces.xni.parser.XMLComponent#getFeatureDefault(java.lang.String) */ public Boolean getFeatureDefault(String featureId) { if (featureId.equals(AUGMENT_PSVI)){ return Boolean.TRUE; } return null; } /* (non-Javadoc) * @see org.apache.xerces.xni.parser.XMLComponent#getPropertyDefault(java.lang.String) */ public Object getPropertyDefault(String propertyId) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) * @see org.apache.xerces.xni.parser.XMLComponent#reset(org.apache.xerces.xni.parser.XMLComponentManager) */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { fGrammarBucket.reset(); fSubGroupHandler.reset(); boolean parser_settings; try { parser_settings = componentManager.getFeature(PARSER_SETTINGS); } catch (XMLConfigurationException e){ parser_settings = true; } if (!parser_settings || !fSettingsChanged) { // need to reprocess JAXP schema sources fJAXPProcessed = false; // reinitialize grammar bucket initGrammarBucket(); return; } // get registered entity manager to be able to resolve JAXP schema-source property: // Note: in case XMLSchemaValidator has created the loader, // the entity manager property is null fEntityManager = (XMLEntityManager)componentManager.getProperty(ENTITY_MANAGER); // get the error reporter fErrorReporter = (XMLErrorReporter)componentManager.getProperty(ERROR_REPORTER); boolean psvi = true; try { psvi = componentManager.getFeature(AUGMENT_PSVI); } catch (XMLConfigurationException e) { psvi = false; } if (!psvi) { fDeclPool.reset(); fCMBuilder.setDeclPool(fDeclPool); fSchemaHandler.setDeclPool(fDeclPool); } else { fCMBuilder.setDeclPool(null); fSchemaHandler.setDeclPool(null); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNSSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNSSchema = null; } // get JAXP sources if available try { fJAXPSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); fJAXPProcessed = false; } catch (XMLConfigurationException e) { fJAXPSource = null; fJAXPProcessed = false; } // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e) { fGrammarPool = null; } initGrammarBucket(); // get continue-after-fatal-error feature try { boolean fatalError = componentManager.getFeature(CONTINUE_AFTER_FATAL_ERROR); fErrorReporter.setFeature(CONTINUE_AFTER_FATAL_ERROR, fatalError); } catch (XMLConfigurationException e) { } // set full validation to false try { fIsCheckedFully = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e){ fIsCheckedFully = false; } // get generate-synthetic-annotations feature try { fSchemaHandler.setGenerateSyntheticAnnotations(componentManager.getFeature(GENERATE_SYNTHETIC_ANNOTATIONS)); } catch (XMLConfigurationException e) { fSchemaHandler.setGenerateSyntheticAnnotations(false); } fSchemaHandler.reset(componentManager); } private void initGrammarBucket(){ if(fGrammarPool != null) { Grammar [] initialGrammars = fGrammarPool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA); for (int i = 0; i < initialGrammars.length; i++) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar((SchemaGrammar)(initialGrammars[i]), true)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fErrorReporter.reportError(XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); } } } } /* (non-Javadoc) * @see org.apache.xerces.xs.XSLoader#getConfig() */ public DOMConfiguration getConfig() { return this; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSLoader#load(org.w3c.dom.ls.LSInput) */ public XSModel load(LSInput is) { try { Grammar g = loadGrammar(dom2xmlInputSource(is)); return ((XSGrammar) g).toXSModel(); } catch (Exception e) { reportDOMFatalError(e); return null; } } /* (non-Javadoc) * @see org.apache.xerces.xs.XSLoader#loadInputList(org.apache.xerces.xs.DOMInputList) */ public XSModel loadInputList(LSInputList is) { int length = is.getLength(); if (length == 0) { return null; } SchemaGrammar[] gs = new SchemaGrammar[length]; for (int i = 0; i < length; i++) { try { gs[i] = (SchemaGrammar) loadGrammar(dom2xmlInputSource(is.item(i))); } catch (Exception e) { reportDOMFatalError(e); return null; } } return new XSModelImpl(gs); } /* (non-Javadoc) * @see org.apache.xerces.xs.XSLoader#loadURI(java.lang.String) */ public XSModel loadURI(String uri) { try { Grammar g = loadGrammar(new XMLInputSource(null, uri, null)); return ((XSGrammar)g).toXSModel(); } catch (Exception e){ reportDOMFatalError(e); return null; } } /* (non-Javadoc) * @see org.apache.xerces.xs.XSLoader#loadURIList(org.apache.xerces.xs.StringList) */ public XSModel loadURIList(StringList uriList) { int length = uriList.getLength(); if (length == 0) { return null; } SchemaGrammar[] gs = new SchemaGrammar[length]; for (int i = 0; i < length; i++) { try { gs[i] = (SchemaGrammar) loadGrammar(new XMLInputSource(null, uriList.item(i), null)); } catch (Exception e) { reportDOMFatalError(e); return null; } } return new XSModelImpl(gs); } void reportDOMFatalError(Exception e) { if (fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl(); error.fException = e; error.fMessage = e.getMessage(); error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler().handleError(error); } } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#canSetParameter(java.lang.String, java.lang.Object) */ public boolean canSetParameter(String name, Object value) { if(value instanceof Boolean){ if (name.equals(Constants.DOM_VALIDATE) || name.equals(SCHEMA_FULL_CHECKING) || name.equals(VALIDATE_ANNOTATIONS) || name.equals(CONTINUE_AFTER_FATAL_ERROR) || name.equals(ALLOW_JAVA_ENCODINGS) || name.equals(STANDARD_URI_CONFORMANT_FEATURE) || name.equals(GENERATE_SYNTHETIC_ANNOTATIONS) || name.equals(HONOUR_ALL_SCHEMALOCATIONS)) { return true; } return false; } if (name.equals(Constants.DOM_ERROR_HANDLER) || name.equals(Constants.DOM_RESOURCE_RESOLVER) || name.equals(SYMBOL_TABLE) || name.equals(ERROR_REPORTER) || name.equals(ERROR_HANDLER) || name.equals(ENTITY_RESOLVER) || name.equals(XMLGRAMMAR_POOL) || name.equals(SCHEMA_LOCATION) || name.equals(SCHEMA_NONS_LOCATION) || name.equals(JAXP_SCHEMA_SOURCE)) { return true; } return false; } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameter(java.lang.String) */ public Object getParameter(String name) throws DOMException { if (name.equals(Constants.DOM_ERROR_HANDLER)){ return (fErrorHandler != null) ? fErrorHandler.getErrorHandler() : null; } else if (name.equals(Constants.DOM_RESOURCE_RESOLVER)) { return (fResourceResolver != null) ? fResourceResolver.getEntityResolver() : null; } try { boolean feature = getFeature(name); return (feature) ? Boolean.TRUE : Boolean.FALSE; } catch (Exception e) { Object property; try { property = getProperty(name); return property; } catch (Exception ex) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } } } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameterNames() */ public DOMStringList getParameterNames() { if (fRecognizedParameters == null){ Vector v = new Vector(); v.add(Constants.DOM_VALIDATE); v.add(Constants.DOM_ERROR_HANDLER); v.add(Constants.DOM_RESOURCE_RESOLVER); v.add(SYMBOL_TABLE); v.add(ERROR_REPORTER); v.add(ERROR_HANDLER); v.add(ENTITY_RESOLVER); v.add(XMLGRAMMAR_POOL); v.add(SCHEMA_LOCATION); v.add(SCHEMA_NONS_LOCATION); v.add(JAXP_SCHEMA_SOURCE); v.add(SCHEMA_FULL_CHECKING); v.add(CONTINUE_AFTER_FATAL_ERROR); v.add(ALLOW_JAVA_ENCODINGS); v.add(STANDARD_URI_CONFORMANT_FEATURE); v.add(VALIDATE_ANNOTATIONS); v.add(GENERATE_SYNTHETIC_ANNOTATIONS); v.add(HONOUR_ALL_SCHEMALOCATIONS); fRecognizedParameters = new DOMStringListImpl(v); } return fRecognizedParameters; } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#setParameter(java.lang.String, java.lang.Object) */ public void setParameter(String name, Object value) throws DOMException { if (value instanceof Boolean) { boolean state = ((Boolean) value).booleanValue(); if (name.equals("validate") && state) { return; } try { setFeature(name, state); } catch (Exception e) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } return; } if (name.equals(Constants.DOM_ERROR_HANDLER)) { if (value instanceof DOMErrorHandler) { try { fErrorHandler = new DOMErrorHandlerWrapper((DOMErrorHandler) value); setErrorHandler(fErrorHandler); } catch (XMLConfigurationException e) { } } else { // REVISIT: type mismatch String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } return; } if (name.equals(Constants.DOM_RESOURCE_RESOLVER)) { if (value instanceof LSResourceResolver) { try { fResourceResolver = new DOMEntityResolverWrapper((LSResourceResolver) value); setEntityResolver(fResourceResolver); } catch (XMLConfigurationException e) {} } else { // REVISIT: type mismatch String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } return; } try { setProperty(name, value); } catch (Exception ex) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "FEATURE_NOT_SUPPORTED", new Object[] { name }); throw new DOMException(DOMException.NOT_SUPPORTED_ERR, msg); } } XMLInputSource dom2xmlInputSource(LSInput is) { // need to wrap the LSInput with an XMLInputSource XMLInputSource xis = null; /** * An LSParser looks at inputs specified in LSInput in * the following order: characterStream, byteStream, * stringData, systemId, publicId. For consistency * have the same behaviour for XSLoader. */ // check whether there is a Reader // according to DOM, we need to treat such reader as "UTF-16". if (is.getCharacterStream() != null) { xis = new XMLInputSource(is.getPublicId(), is.getSystemId(), is.getBaseURI(), is.getCharacterStream(), "UTF-16"); } // check whether there is an InputStream else if (is.getByteStream() != null) { xis = new XMLInputSource(is.getPublicId(), is.getSystemId(), is.getBaseURI(), is.getByteStream(), is.getEncoding()); } // if there is a string data, use a StringReader // according to DOM, we need to treat such data as "UTF-16". else if (is.getStringData() != null && is.getStringData().length() != 0) { xis = new XMLInputSource(is.getPublicId(), is.getSystemId(), is.getBaseURI(), new StringReader(is.getStringData()), "UTF-16"); } // otherwise, just use the public/system/base Ids else { xis = new XMLInputSource(is.getPublicId(), is.getSystemId(), is.getBaseURI()); } return xis; } } // XMLGrammarLoader
true
true
private void processJAXPSchemaSource(Hashtable locationPairs) throws IOException { fJAXPProcessed = true; if (fJAXPSource == null) { return; } Class componentType = fJAXPSource.getClass().getComponentType(); XMLInputSource xis = null; String sid = null; if (componentType == null) { // Not an array if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); if (g != null) { fGrammarBucket.putGrammar(g); return; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(fJAXPSource); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } SchemaGrammar g = loadSchema(fXSDDescription, xis, locationPairs); // it is possible that we won't be able to resolve JAXP schema-source location if (g != null) { if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { fJAXPCache.put(fJAXPSource, g); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } } fGrammarBucket.putGrammar(g); } return; } else if ( (componentType != Object.class) && (componentType != String.class) && (componentType != File.class) && (componentType != InputStream.class) && (componentType != InputSource.class) ) { // Not an Object[], String[], File[], InputStream[], InputSource[] throw new XMLConfigurationException( XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+ "\" property cannot have an array of type {"+componentType.getName()+ "}. Possible types of the array supported are Object, String, File, "+ "InputStream, InputSource."); } // JAXP spec. allow []s of type String, File, InputStream, // InputSource also, apart from [] of type Object. Object[] objArr = (Object[]) fJAXPSource; // make local vector for storing target namespaces of schemasources specified in object arrays. ArrayList jaxpSchemaSourceNamespaces = new ArrayList(); for (int i = 0; i < objArr.length; i++) { if(objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); if (g != null) { fGrammarBucket.putGrammar(g); continue; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(objArr[i]); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } String targetNamespace = null ; // load schema SchemaGrammar grammar = fSchemaHandler.parseSchema(xis,fXSDDescription, locationPairs); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } if (grammar != null) { targetNamespace = grammar.getTargetNamespace(); if (jaxpSchemaSourceNamespaces.contains(targetNamespace)) { //when an array of objects is passed it is illegal to have two schemas that share same namespace. throw new java.lang.IllegalArgumentException( " When using array of Objects as the value of SCHEMA_SOURCE property , " + "no two Schemas should share the same targetNamespace. " ); } else { jaxpSchemaSourceNamespaces.add(targetNamespace) ; } if (objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { fJAXPCache.put(objArr[i], grammar); } fGrammarBucket.putGrammar(grammar); } else { //REVISIT: What should be the acutal behavior if grammar can't be loaded as specified in schema source? } } }//processJAXPSchemaSource
private void processJAXPSchemaSource(Hashtable locationPairs) throws IOException { fJAXPProcessed = true; if (fJAXPSource == null) { return; } Class componentType = fJAXPSource.getClass().getComponentType(); XMLInputSource xis = null; String sid = null; if (componentType == null) { // Not an array if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); if (g != null) { fGrammarBucket.putGrammar(g); return; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(fJAXPSource); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } SchemaGrammar g = loadSchema(fXSDDescription, xis, locationPairs); // it is possible that we won't be able to resolve JAXP schema-source location if (g != null) { if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { fJAXPCache.put(fJAXPSource, g); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } } fGrammarBucket.putGrammar(g); } return; } else if ( (componentType != Object.class) && (componentType != String.class) && (componentType != File.class) && (componentType != InputStream.class) && (componentType != InputSource.class) && !File.class.isAssignableFrom(componentType) && !InputStream.class.isAssignableFrom(componentType) && !InputSource.class.isAssignableFrom(componentType) ) { // Not an Object[], String[], File[], InputStream[], InputSource[] throw new XMLConfigurationException( XMLConfigurationException.NOT_SUPPORTED, "\""+JAXP_SCHEMA_SOURCE+ "\" property cannot have an array of type {"+componentType.getName()+ "}. Possible types of the array supported are Object, String, File, "+ "InputStream, InputSource."); } // JAXP spec. allow []s of type String, File, InputStream, // InputSource also, apart from [] of type Object. Object[] objArr = (Object[]) fJAXPSource; // make local vector for storing target namespaces of schemasources specified in object arrays. ArrayList jaxpSchemaSourceNamespaces = new ArrayList(); for (int i = 0; i < objArr.length; i++) { if(objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); if (g != null) { fGrammarBucket.putGrammar(g); continue; } } fXSDDescription.reset(); xis = xsdToXMLInputSource(objArr[i]); sid = xis.getSystemId(); fXSDDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; if (sid != null) { fXSDDescription.setBaseSystemId(xis.getBaseSystemId()); fXSDDescription.setLiteralSystemId(sid); fXSDDescription.setExpandedSystemId(sid); fXSDDescription.fLocationHints = new String[]{sid}; } String targetNamespace = null ; // load schema SchemaGrammar grammar = fSchemaHandler.parseSchema(xis,fXSDDescription, locationPairs); if (fIsCheckedFully) { XSConstraints.fullSchemaChecking(fGrammarBucket, fSubGroupHandler, fCMBuilder, fErrorReporter); } if (grammar != null) { targetNamespace = grammar.getTargetNamespace(); if (jaxpSchemaSourceNamespaces.contains(targetNamespace)) { //when an array of objects is passed it is illegal to have two schemas that share same namespace. throw new java.lang.IllegalArgumentException( " When using array of Objects as the value of SCHEMA_SOURCE property , " + "no two Schemas should share the same targetNamespace. " ); } else { jaxpSchemaSourceNamespaces.add(targetNamespace) ; } if (objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { fJAXPCache.put(objArr[i], grammar); } fGrammarBucket.putGrammar(grammar); } else { //REVISIT: What should be the acutal behavior if grammar can't be loaded as specified in schema source? } } }//processJAXPSchemaSource
diff --git a/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIQuickFixTest.java b/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIQuickFixTest.java index 41e88a281..05c5927ec 100644 --- a/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIQuickFixTest.java +++ b/cdi/tests/org.jboss.tools.cdi.ui.test/src/org/jboss/tools/cdi/ui/test/marker/CDIQuickFixTest.java @@ -1,20 +1,20 @@ package org.jboss.tools.cdi.ui.test.marker; import org.eclipse.core.runtime.CoreException; import org.jboss.tools.cdi.core.test.tck.TCKTest; import org.jboss.tools.cdi.internal.core.validation.CDIValidationErrorManager; import org.jboss.tools.common.base.test.QuickFixTestUtil; import org.jboss.tools.common.ui.marker.ConfigureProblemSeverityMarkerResolution; public class CDIQuickFixTest extends TCKTest { QuickFixTestUtil util = new QuickFixTestUtil(); public void testConfigureProblemSeverity() throws CoreException { util.checkPrpposal(tckProject, "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.java", - "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.new", + "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.qfxresult", CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_FIELD_IN_SESSION_BEAN_ID, ConfigureProblemSeverityMarkerResolution.class); } }
true
true
public void testConfigureProblemSeverity() throws CoreException { util.checkPrpposal(tckProject, "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.java", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.new", CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_FIELD_IN_SESSION_BEAN_ID, ConfigureProblemSeverityMarkerResolution.class); }
public void testConfigureProblemSeverity() throws CoreException { util.checkPrpposal(tckProject, "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.java", "JavaSource/org/jboss/jsr299/tck/tests/jbt/quickfixes/NonStaticProducerBroken.qfxresult", CDIValidationErrorManager.MESSAGE_ID_ATTRIBUTE_NAME, CDIValidationErrorManager.ILLEGAL_PRODUCER_FIELD_IN_SESSION_BEAN_ID, ConfigureProblemSeverityMarkerResolution.class); }
diff --git a/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/validation/EnvironmentValidationService.java b/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/validation/EnvironmentValidationService.java index 30ba56b7..69e89833 100644 --- a/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/validation/EnvironmentValidationService.java +++ b/easysoa-registry/easysoa-registry-core/src/main/java/org/easysoa/validation/EnvironmentValidationService.java @@ -1,222 +1,224 @@ /** * EasySOA Registry * Copyright 2011 Open Wide * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact : easysoa-dev@googlegroups.com */ package org.easysoa.validation; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.easysoa.services.DocumentService; import org.easysoa.services.PublicationService; import org.easysoa.services.ServiceValidationService; import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.CoreInstance; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.impl.blob.StringBlob; import org.nuxeo.ecm.core.api.repository.Repository; import org.nuxeo.ecm.core.api.repository.RepositoryManager; import org.nuxeo.runtime.api.Framework; import org.nuxeo.runtime.transaction.TransactionHelper; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; /** * * @author mkalam-alami * */ public class EnvironmentValidationService { private static final String TEMPLATES_FOLDER = "./nxserver/nuxeo.war/templates"; private static final String VALIDATION_REPORT_TEMPLATE = "validationReport.ftl"; private static Log log = LogFactory.getLog(EnvironmentValidationService.class); private static Configuration freemarkerCfg = null; private ServiceValidationService serviceValidationService; private PublicationService publicationService; private DocumentService docService; private CoreSession session = null; static { try { freemarkerCfg = new Configuration(); freemarkerCfg.setDirectoryForTemplateLoading(new File(TEMPLATES_FOLDER)); freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper()); } catch (IOException e) { log.error("Failed to initialize templating configuration, no validation reports will be produced: " + e.getMessage()); } } public EnvironmentValidationService() throws Exception { serviceValidationService = Framework.getService(ServiceValidationService.class); publicationService = Framework.getService(PublicationService.class); docService = Framework.getService(DocumentService.class); } public String run(String runName, String environmentName) throws ClientException { synchronized(log) { String validationReportHtml = null; boolean wasActiveTx = false; try { // Init RepositoryManager mgr = Framework.getService(RepositoryManager.class); Repository repository = mgr.getDefaultRepository(); wasActiveTx = TransactionHelper.isTransactionActive(); if (wasActiveTx) { TransactionHelper.commitOrRollbackTransaction(); } TransactionHelper.startTransaction(); session = repository.open(); String tmpWorkspaceName = "tmp" + + System.currentTimeMillis(); // Fork existing environment DocumentModel environmentModel = docService.findEnvironment(session, environmentName); if (environmentModel != null) { DocumentModel tmpWorkspaceModel = null; ValidationResultList validationResults = null; - //try { + try { // Run discovery replay ExchangeReplayController exchangeReplayController = serviceValidationService.getExchangeReplayController(); if (exchangeReplayController != null) { // Create temporary environment tmpWorkspaceModel = publicationService.forkEnvironment(session, environmentModel, tmpWorkspaceName); exchangeReplayController.replayRecord(runName, environmentName); // Validate temporary environment validationResults = serviceValidationService.validateServices(session, tmpWorkspaceModel); } else { log.error("Cannot run scheduled validation: No exchange replay controller available"); } - /*} + } catch (Exception e) { log.error("Failed to run scheduled validation", e); throw e; } finally { if (tmpWorkspaceModel != null) { // Remove temporary environment session.removeDocument(tmpWorkspaceModel.getRef()); } - }*/ + } if (freemarkerCfg != null && validationResults != null) { // Create report Template tpl = freemarkerCfg.getTemplate(VALIDATION_REPORT_TEMPLATE); List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); for (ValidationResult validationResult : validationResults) { List<Map<String, Object>> validatorsResults = new ArrayList<Map<String, Object>>(); for (ValidatorResult validatorResult : validationResult) { Map<String, Object> paramsOneValidator = new HashMap<String, Object>(); paramsOneValidator.put("validationSuccess", validatorResult.isValidated() ? "passed" : "failed"); paramsOneValidator.put("validatorName", validatorResult.getValidatorName()); paramsOneValidator.put("validationLog", validatorResult.getValidationLog()); validatorsResults.add(paramsOneValidator); } Map<String, Object> paramsOneResult = new HashMap<String, Object>(); paramsOneResult.put("validatorsResults", validatorsResults); paramsOneResult.put("validationSuccess", validationResult.isValidationPassed() ? "passed" : "failed"); paramsOneResult.put("serviceName", validationResult.getServiceName()); results.add(paramsOneResult); } Map<String, Object> params = new HashMap<String, Object>(); List<String> validatorsNames = new ArrayList<String>(); - for (ValidatorResult validatorResult : validationResults.get(0)) { - validatorsNames.add(validatorResult.getValidatorName()); + if (!validationResults.isEmpty()) { + for (ValidatorResult validatorResult : validationResults.get(0)) { + validatorsNames.add(validatorResult.getValidatorName()); + } } params.put("results", results); params.put("validatorsNames", validatorsNames); params.put("validationSuccess", validationResults.isEveryValidationPassed() ? "passed" : "failed"); params.put("date", new Date()); params.put("runName", runName); params.put("environmentName", environmentName); StringWriter writer = new StringWriter(); tpl.process(params, writer); writer.flush(); validationReportHtml = writer.getBuffer().toString(); // Save report | TODO if too much files, remove the older ones DocumentModel workspaceModel = docService.findWorkspace(session, environmentName); @SuppressWarnings("unchecked") List<Map<String, Object>> files = (List<Map<String, Object>>) workspaceModel.getProperty("files", "files"); Map<String, Object> newFile = new HashMap<String, Object>(); newFile.put("filename", "Validation report - " + new Date(System.currentTimeMillis()).toString() + ".html"); newFile.put("file", new StringBlob(validationReportHtml)); files.add(newFile); workspaceModel.setProperty("files", "files", files); session.saveDocument(workspaceModel); } } else { log.error("Failed to run scheduled validation: environment '" + environmentName + "' doesn't exist. Did you publish it?"); } } catch (Exception e) { log.error("Failed to run scheduled validation", e); } finally { TransactionHelper.commitOrRollbackTransaction(); if (session != null) { CoreInstance.getInstance().close(session); } if (wasActiveTx) { TransactionHelper.startTransaction(); } } return validationReportHtml; } } }
false
true
public String run(String runName, String environmentName) throws ClientException { synchronized(log) { String validationReportHtml = null; boolean wasActiveTx = false; try { // Init RepositoryManager mgr = Framework.getService(RepositoryManager.class); Repository repository = mgr.getDefaultRepository(); wasActiveTx = TransactionHelper.isTransactionActive(); if (wasActiveTx) { TransactionHelper.commitOrRollbackTransaction(); } TransactionHelper.startTransaction(); session = repository.open(); String tmpWorkspaceName = "tmp" + + System.currentTimeMillis(); // Fork existing environment DocumentModel environmentModel = docService.findEnvironment(session, environmentName); if (environmentModel != null) { DocumentModel tmpWorkspaceModel = null; ValidationResultList validationResults = null; //try { // Run discovery replay ExchangeReplayController exchangeReplayController = serviceValidationService.getExchangeReplayController(); if (exchangeReplayController != null) { // Create temporary environment tmpWorkspaceModel = publicationService.forkEnvironment(session, environmentModel, tmpWorkspaceName); exchangeReplayController.replayRecord(runName, environmentName); // Validate temporary environment validationResults = serviceValidationService.validateServices(session, tmpWorkspaceModel); } else { log.error("Cannot run scheduled validation: No exchange replay controller available"); } /*} catch (Exception e) { log.error("Failed to run scheduled validation", e); throw e; } finally { if (tmpWorkspaceModel != null) { // Remove temporary environment session.removeDocument(tmpWorkspaceModel.getRef()); } }*/ if (freemarkerCfg != null && validationResults != null) { // Create report Template tpl = freemarkerCfg.getTemplate(VALIDATION_REPORT_TEMPLATE); List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); for (ValidationResult validationResult : validationResults) { List<Map<String, Object>> validatorsResults = new ArrayList<Map<String, Object>>(); for (ValidatorResult validatorResult : validationResult) { Map<String, Object> paramsOneValidator = new HashMap<String, Object>(); paramsOneValidator.put("validationSuccess", validatorResult.isValidated() ? "passed" : "failed"); paramsOneValidator.put("validatorName", validatorResult.getValidatorName()); paramsOneValidator.put("validationLog", validatorResult.getValidationLog()); validatorsResults.add(paramsOneValidator); } Map<String, Object> paramsOneResult = new HashMap<String, Object>(); paramsOneResult.put("validatorsResults", validatorsResults); paramsOneResult.put("validationSuccess", validationResult.isValidationPassed() ? "passed" : "failed"); paramsOneResult.put("serviceName", validationResult.getServiceName()); results.add(paramsOneResult); } Map<String, Object> params = new HashMap<String, Object>(); List<String> validatorsNames = new ArrayList<String>(); for (ValidatorResult validatorResult : validationResults.get(0)) { validatorsNames.add(validatorResult.getValidatorName()); } params.put("results", results); params.put("validatorsNames", validatorsNames); params.put("validationSuccess", validationResults.isEveryValidationPassed() ? "passed" : "failed"); params.put("date", new Date()); params.put("runName", runName); params.put("environmentName", environmentName); StringWriter writer = new StringWriter(); tpl.process(params, writer); writer.flush(); validationReportHtml = writer.getBuffer().toString(); // Save report | TODO if too much files, remove the older ones DocumentModel workspaceModel = docService.findWorkspace(session, environmentName); @SuppressWarnings("unchecked") List<Map<String, Object>> files = (List<Map<String, Object>>) workspaceModel.getProperty("files", "files"); Map<String, Object> newFile = new HashMap<String, Object>(); newFile.put("filename", "Validation report - " + new Date(System.currentTimeMillis()).toString() + ".html"); newFile.put("file", new StringBlob(validationReportHtml)); files.add(newFile); workspaceModel.setProperty("files", "files", files); session.saveDocument(workspaceModel); } } else { log.error("Failed to run scheduled validation: environment '" + environmentName + "' doesn't exist. Did you publish it?"); } } catch (Exception e) { log.error("Failed to run scheduled validation", e); } finally { TransactionHelper.commitOrRollbackTransaction(); if (session != null) { CoreInstance.getInstance().close(session); } if (wasActiveTx) { TransactionHelper.startTransaction(); } } return validationReportHtml; } }
public String run(String runName, String environmentName) throws ClientException { synchronized(log) { String validationReportHtml = null; boolean wasActiveTx = false; try { // Init RepositoryManager mgr = Framework.getService(RepositoryManager.class); Repository repository = mgr.getDefaultRepository(); wasActiveTx = TransactionHelper.isTransactionActive(); if (wasActiveTx) { TransactionHelper.commitOrRollbackTransaction(); } TransactionHelper.startTransaction(); session = repository.open(); String tmpWorkspaceName = "tmp" + + System.currentTimeMillis(); // Fork existing environment DocumentModel environmentModel = docService.findEnvironment(session, environmentName); if (environmentModel != null) { DocumentModel tmpWorkspaceModel = null; ValidationResultList validationResults = null; try { // Run discovery replay ExchangeReplayController exchangeReplayController = serviceValidationService.getExchangeReplayController(); if (exchangeReplayController != null) { // Create temporary environment tmpWorkspaceModel = publicationService.forkEnvironment(session, environmentModel, tmpWorkspaceName); exchangeReplayController.replayRecord(runName, environmentName); // Validate temporary environment validationResults = serviceValidationService.validateServices(session, tmpWorkspaceModel); } else { log.error("Cannot run scheduled validation: No exchange replay controller available"); } } catch (Exception e) { log.error("Failed to run scheduled validation", e); throw e; } finally { if (tmpWorkspaceModel != null) { // Remove temporary environment session.removeDocument(tmpWorkspaceModel.getRef()); } } if (freemarkerCfg != null && validationResults != null) { // Create report Template tpl = freemarkerCfg.getTemplate(VALIDATION_REPORT_TEMPLATE); List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); for (ValidationResult validationResult : validationResults) { List<Map<String, Object>> validatorsResults = new ArrayList<Map<String, Object>>(); for (ValidatorResult validatorResult : validationResult) { Map<String, Object> paramsOneValidator = new HashMap<String, Object>(); paramsOneValidator.put("validationSuccess", validatorResult.isValidated() ? "passed" : "failed"); paramsOneValidator.put("validatorName", validatorResult.getValidatorName()); paramsOneValidator.put("validationLog", validatorResult.getValidationLog()); validatorsResults.add(paramsOneValidator); } Map<String, Object> paramsOneResult = new HashMap<String, Object>(); paramsOneResult.put("validatorsResults", validatorsResults); paramsOneResult.put("validationSuccess", validationResult.isValidationPassed() ? "passed" : "failed"); paramsOneResult.put("serviceName", validationResult.getServiceName()); results.add(paramsOneResult); } Map<String, Object> params = new HashMap<String, Object>(); List<String> validatorsNames = new ArrayList<String>(); if (!validationResults.isEmpty()) { for (ValidatorResult validatorResult : validationResults.get(0)) { validatorsNames.add(validatorResult.getValidatorName()); } } params.put("results", results); params.put("validatorsNames", validatorsNames); params.put("validationSuccess", validationResults.isEveryValidationPassed() ? "passed" : "failed"); params.put("date", new Date()); params.put("runName", runName); params.put("environmentName", environmentName); StringWriter writer = new StringWriter(); tpl.process(params, writer); writer.flush(); validationReportHtml = writer.getBuffer().toString(); // Save report | TODO if too much files, remove the older ones DocumentModel workspaceModel = docService.findWorkspace(session, environmentName); @SuppressWarnings("unchecked") List<Map<String, Object>> files = (List<Map<String, Object>>) workspaceModel.getProperty("files", "files"); Map<String, Object> newFile = new HashMap<String, Object>(); newFile.put("filename", "Validation report - " + new Date(System.currentTimeMillis()).toString() + ".html"); newFile.put("file", new StringBlob(validationReportHtml)); files.add(newFile); workspaceModel.setProperty("files", "files", files); session.saveDocument(workspaceModel); } } else { log.error("Failed to run scheduled validation: environment '" + environmentName + "' doesn't exist. Did you publish it?"); } } catch (Exception e) { log.error("Failed to run scheduled validation", e); } finally { TransactionHelper.commitOrRollbackTransaction(); if (session != null) { CoreInstance.getInstance().close(session); } if (wasActiveTx) { TransactionHelper.startTransaction(); } } return validationReportHtml; } }
diff --git a/Bytecode/BlindPassenger.java b/Bytecode/BlindPassenger.java index 9fe3a89..0274754 100644 --- a/Bytecode/BlindPassenger.java +++ b/Bytecode/BlindPassenger.java @@ -1,50 +1,50 @@ import java.io.*; public class BlindPassenger { public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int t,n; //System.out.println(line); - t = Integer.parseInt(line); + t = Integer.parseInt(line.trim()); for(int i=0;i<t;++i) { line = br.readLine(); - n = Integer.parseInt(line); --n; + n = Integer.parseInt(line.trim()); --n; if(n == 0) { System.out.println("poor conductor"); } else { char direction='l',seat_posn='l'; int row_no = 0, relative_seat_no = 0; row_no = (int) Math.ceil(n/5.0); relative_seat_no = n % 5; if(row_no % 2 == 0) { //even row, need to reverse the relative seat no relative_seat_no = 6 - relative_seat_no; } if(relative_seat_no < 3) { direction = 'L'; if(relative_seat_no == 1) seat_posn = 'W'; else seat_posn = 'A'; } else { direction = 'R'; if(relative_seat_no == 3) seat_posn = 'A'; else if(relative_seat_no == 4) seat_posn = 'M'; else seat_posn = 'W'; } System.out.println(row_no + " " + seat_posn + " " + direction); } } } }
false
true
public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int t,n; //System.out.println(line); t = Integer.parseInt(line); for(int i=0;i<t;++i) { line = br.readLine(); n = Integer.parseInt(line); --n; if(n == 0) { System.out.println("poor conductor"); } else { char direction='l',seat_posn='l'; int row_no = 0, relative_seat_no = 0; row_no = (int) Math.ceil(n/5.0); relative_seat_no = n % 5; if(row_no % 2 == 0) { //even row, need to reverse the relative seat no relative_seat_no = 6 - relative_seat_no; } if(relative_seat_no < 3) { direction = 'L'; if(relative_seat_no == 1) seat_posn = 'W'; else seat_posn = 'A'; } else { direction = 'R'; if(relative_seat_no == 3) seat_posn = 'A'; else if(relative_seat_no == 4) seat_posn = 'M'; else seat_posn = 'W'; } System.out.println(row_no + " " + seat_posn + " " + direction); } } }
public static void main(String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int t,n; //System.out.println(line); t = Integer.parseInt(line.trim()); for(int i=0;i<t;++i) { line = br.readLine(); n = Integer.parseInt(line.trim()); --n; if(n == 0) { System.out.println("poor conductor"); } else { char direction='l',seat_posn='l'; int row_no = 0, relative_seat_no = 0; row_no = (int) Math.ceil(n/5.0); relative_seat_no = n % 5; if(row_no % 2 == 0) { //even row, need to reverse the relative seat no relative_seat_no = 6 - relative_seat_no; } if(relative_seat_no < 3) { direction = 'L'; if(relative_seat_no == 1) seat_posn = 'W'; else seat_posn = 'A'; } else { direction = 'R'; if(relative_seat_no == 3) seat_posn = 'A'; else if(relative_seat_no == 4) seat_posn = 'M'; else seat_posn = 'W'; } System.out.println(row_no + " " + seat_posn + " " + direction); } } }
diff --git a/src/main/java/com/yahoo/ycsb/Client.java b/src/main/java/com/yahoo/ycsb/Client.java index a3134a2..0ad6f04 100644 --- a/src/main/java/com/yahoo/ycsb/Client.java +++ b/src/main/java/com/yahoo/ycsb/Client.java @@ -1,884 +1,884 @@ /** * Copyright (c) 2010 Yahoo! Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.yahoo.ycsb; import java.io.*; import java.text.DecimalFormat; import java.util.*; import com.yahoo.ycsb.db.MagicKey; import com.yahoo.ycsb.measurements.Measurements; import com.yahoo.ycsb.measurements.exporter.MeasurementsExporter; import com.yahoo.ycsb.measurements.exporter.TextMeasurementsExporter; import com.yahoo.ycsb.workloads.CoreWorkload; import org.apache.log4j.xml.DOMConfigurator; import javax.xml.parsers.FactoryConfigurationError; //import org.apache.log4j.BasicConfigurator; /** * A thread to periodically show the status of the experiment, to reassure you that progress is being made. * * @author cooperb * */ class StatusThread extends Thread { Vector<Thread> _threads; String _label; boolean _standardstatus; /** * The interval for reporting status. */ public static final long sleeptime=10000; public StatusThread(Vector<Thread> threads, String label, boolean standardstatus) { _threads=threads; _label=label; _standardstatus=standardstatus; } /** * Run and periodically report status. */ public void run() { long st=System.currentTimeMillis(); long lasten=st; long lasttotalops=0; boolean alldone; do { alldone=true; int totalops=0; //terminate this thread when all the worker threads are done for (Thread t : _threads) { if (t.getState()!=Thread.State.TERMINATED) { alldone=false; } ClientThread ct=(ClientThread)t; totalops+=ct.getOpsDone(); } long en=System.currentTimeMillis(); long interval=en-st; //double throughput=1000.0*((double)totalops)/((double)interval); double curthroughput=1000.0*(((double)(totalops-lasttotalops))/((double)(en-lasten))); lasttotalops=totalops; lasten=en; DecimalFormat d = new DecimalFormat("#.##"); if (totalops==0) { System.err.println(_label+" "+(interval/1000)+" sec: "+totalops+" operations; "+Measurements.getMeasurements().getSummary()); } else { System.err.println(_label+" "+(interval/1000)+" sec: "+totalops+" operations; "+d.format(curthroughput)+" current ops/sec; "+Measurements.getMeasurements().getSummary()); } if (_standardstatus) { if (totalops==0) { System.out.println(_label+" "+(interval/1000)+" sec: "+totalops+" operations; "+Measurements.getMeasurements().getSummary()); } else { System.out.println(_label+" "+(interval/1000)+" sec: "+totalops+" operations; "+d.format(curthroughput)+" current ops/sec; "+Measurements.getMeasurements().getSummary()); } } try { sleep(sleeptime); } catch (InterruptedException e) { //do nothing } } while (!alldone); } } /** * A thread for executing transactions or data inserts to the database. * * @author cooperb * */ class ClientThread extends Thread { static Random random=new Random(); DB _db; boolean _dotransactions; Workload _workload; int _opcount; int _mulreadcount; double _target; int _opsdone; int _threadid; int _nodecount; int _threadcount; Object _workloadstate; Properties _props; /** * Constructor. * * @param db the DB implementation to use * @param dotransactions true to do transactions, false to insert data * @param workload the workload to use * @param threadid the id of this thread * @param threadcount the total number of threads * @param props the properties defining the experiment * @param opcount the number of operations (transactions or inserts) to do * @param targetperthreadperms target number of operations per thread per ms */ public ClientThread(DB db, boolean dotransactions, Workload workload, int threadid, int nodecount, int threadcount, Properties props, int opcount, double targetperthreadperms, int mulreadcount) { //TODO: consider removing threadcount and threadid _db=db; _dotransactions=dotransactions; _workload=workload; _opcount=opcount; _opsdone=0; _target=targetperthreadperms; _threadid=threadid; _nodecount=nodecount; _threadcount=threadcount; _props=props; _mulreadcount = mulreadcount; //System.out.println("Interval = "+interval); } public int getOpsDone() { return _opsdone; } public void run() { CoreWorkload.MUL_READ_COUNT = this._mulreadcount; try { _db.init(); System.out.println(_threadid+". Waiting: loading phase..."); Thread.sleep(60000); if(_dotransactions){ _db.waitLoad(); System.out.println(_threadid+". Starting execution phase..."); Thread.sleep(30000); } } catch (DBException e) { e.printStackTrace(); e.printStackTrace(System.out); return; } catch (InterruptedException e1){ e1.printStackTrace(); e1.printStackTrace(System.out); System.out.println("Thread interrupted"); } try { _workloadstate=_workload.initThread(_props,_threadid,_threadcount); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); return; } //spread the thread operations out so they don't all hit the DB at the same time try { //GH issue 4 - throws exception if _target>1 because random.nextInt argument must be >0 //and the sleep() doesn't make sense for granularities < 1 ms anyway if ( (_target>0) && (_target<=1.0) ) { sleep(random.nextInt((int)(1.0/_target))); } } catch (InterruptedException e) { // do nothing. } try { if (_dotransactions) { long st=System.currentTimeMillis(); while (((_opcount == 0) || (_opsdone < _opcount)) && !_workload.isStopRequested()) { if (!_workload.doTransaction(_db,_workloadstate)) { continue;//Sebastiano } _opsdone++; //throttle the operations if (_target>0) { //this is more accurate than other throttling approaches we have tried, //like sleeping for (1/target throughput)-operation latency, //because it smooths timing inaccuracies (from sleep() taking an int, //current time in millis) over many operations while (System.currentTimeMillis()-st<((double)_opsdone)/_target) { try { sleep(1); } catch (InterruptedException e) { // do nothing. } } } } } else { long st=System.currentTimeMillis(); while (((_opcount == 0) || (_opsdone < _opcount)) && !_workload.isStopRequested()) { if (!_workload.doInsert(_db,_workloadstate)) { break; } _opsdone++; //throttle the operations if (_target>0) { //this is more accurate than other throttling approaches we have tried, //like sleeping for (1/target throughput)-operation latency, //because it smooths timing inaccuracies (from sleep() taking an int, //current time in millis) over many operations while (System.currentTimeMillis()-st<((double)_opsdone)/_target) { try { sleep(1); } catch (InterruptedException e) { // do nothing. } } } } } } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { if(!_dotransactions){ _db.endLoad(); _db.cleanup(); } } catch (DBException e) { e.printStackTrace(); e.printStackTrace(System.out); return; } } } /** * Main class for executing YCSB. */ public class Client { public static final String OPERATION_COUNT_PROPERTY="operationcount"; public static final String MULTIPLE_READ_COUNT_PROPERTY="multiplereadcount"; public static final String RECORD_COUNT_PROPERTY="recordcount"; public static final String WORKLOAD_PROPERTY="workload"; /** * Indicates how many inserts to do, if less than recordcount. Useful for partitioning * the load among multiple servers, if the client is the bottleneck. Additionally, workloads * should support the "insertstart" property, which tells them which record to start at. */ public static final String INSERT_COUNT_PROPERTY="insertcount"; /** * The maximum amount of time (in seconds) for which the benchmark will be run. */ public static final String MAX_EXECUTION_TIME = "maxexecutiontime"; public static void usageMessage() { System.out.println("Usage: java com.yahoo.ycsb.Client [options]"); System.out.println("Options:"); System.out.println(" -threads n: execute using n threads (default: 1) - can also be specified as the \n" + " \"threadcount\" property using -p"); System.out.println(" -target n: attempt to do n operations per second (default: unlimited) - can also\n" + " be specified as the \"target\" property using -p"); System.out.println(" -load: run the loading phase of the workload"); System.out.println(" -t: run the transactions phase of the workload (default)"); System.out.println(" -db dbname: specify the name of the DB to use (default: com.yahoo.ycsb.BasicDB) - \n" + " can also be specified as the \"db\" property using -p"); System.out.println(" -P propertyfile: load properties from the given file. Multiple files can"); System.out.println(" be specified, and will be processed in the order specified"); System.out.println(" -p name=value: specify a property to be passed to the DB and workloads;"); System.out.println(" multiple properties can be specified, and override any"); System.out.println(" values in the propertyfile"); System.out.println(" -s: show status during run (default: no status)"); System.out.println(" -l label: use label for status (e.g. to label one experiment out of a whole batch)"); System.out.println(""); System.out.println("Required properties:"); System.out.println(" "+WORKLOAD_PROPERTY+": the name of the workload class to use (e.g. com.yahoo.ycsb.workloads.CoreWorkload)"); System.out.println(""); System.out.println("To run the transaction phase from multiple servers, start a separate client on each."); System.out.println("To run the load phase from multiple servers, start a separate client on each; additionally,"); System.out.println("use the \"insertcount\" and \"insertstart\" properties to divide up the records to be inserted"); } public static boolean checkRequiredProperties(Properties props) { if (props.getProperty(WORKLOAD_PROPERTY)==null) { System.out.println("Missing property: "+WORKLOAD_PROPERTY); return false; } return true; } /** * Exports the measurements to either sysout or a file using the exporter * loaded from conf. * @throws IOException Either failed to write to output stream or failed to close it. */ private static void exportMeasurements(Properties props, int opcount, long runtime) throws IOException { MeasurementsExporter exporter = null; try { // if no destination file is provided the results will be written to stdout OutputStream out; String exportFile = props.getProperty("exportfile"); if (exportFile == null) { out = System.out; } else { out = new FileOutputStream(exportFile); } // if no exporter is provided the default text one will be used String exporterStr = props.getProperty("exporter", "com.yahoo.ycsb.measurements.exporter.TextMeasurementsExporter"); try { exporter = (MeasurementsExporter) Class.forName(exporterStr).getConstructor(OutputStream.class).newInstance(out); } catch (Exception e) { System.err.println("Could not find exporter " + exporterStr + ", will use default text reporter."); e.printStackTrace(); exporter = new TextMeasurementsExporter(out); } exporter.write("OVERALL", "RunTime(ms)", runtime); double throughput = 1000.0 * ((double) opcount) / ((double) runtime); exporter.write("OVERALL", "Throughput(ops/sec)", throughput); Measurements.getMeasurements().exportMeasurements(exporter); } finally { if (exporter != null) { exporter.close(); } } } public static int NODE_INDEX; @SuppressWarnings("unchecked") public static void main(String[] args) { String dbname; Properties props=new Properties(); Properties fileprops=new Properties(); boolean dotransactions=true; int threadcount=1; int nodecount=1; int target=0; boolean status=false; String label=""; //parse arguments int argindex=0; if (args.length==0) { usageMessage(); System.exit(0); } try { DOMConfigurator.configure("log4j.xml"); } catch (FactoryConfigurationError e) { e.printStackTrace(); System.exit(-1); } while (args[argindex].startsWith("-")) { if (args[argindex].compareTo("-threads")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int tcount=Integer.parseInt(args[argindex]); props.setProperty("threadcount", tcount+""); argindex++; } else if (args[argindex].compareTo("-nodes")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int nodes=Integer.parseInt(args[argindex]); props.setProperty("nodecount", nodes+""); argindex++; } else if (args[argindex].compareTo("-target")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int ttarget=Integer.parseInt(args[argindex]); props.setProperty("target", ttarget+""); argindex++; } else if (args[argindex].compareTo("-load")==0) { dotransactions=false; argindex++; } else if (args[argindex].compareTo("-t")==0) { dotransactions=true; argindex++; } else if (args[argindex].compareTo("-s")==0) { status=true; argindex++; } else if (args[argindex].compareTo("-db")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } props.setProperty("db",args[argindex]); argindex++; } else if (args[argindex].compareTo("-l")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } label=args[argindex]; argindex++; } else if (args[argindex].compareTo("-P")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } String propfile=args[argindex]; argindex++; Properties myfileprops=new Properties(); try { myfileprops.load(new FileInputStream(propfile)); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=myfileprops.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,myfileprops.getProperty(prop)); } } else if (args[argindex].compareTo("-p")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int eq=args[argindex].indexOf('='); if (eq<0) { usageMessage(); System.exit(0); } String name=args[argindex].substring(0,eq); String value=args[argindex].substring(eq+1); props.put(name,value); //System.out.println("["+name+"]=["+value+"]"); argindex++; } else { System.out.println("Unknown option "+args[argindex]); usageMessage(); System.exit(0); } if (argindex>=args.length) { break; } } if (argindex!=args.length) { usageMessage(); System.exit(0); } //set up logging //BasicConfigurator.configure(); //overwrite file properties with properties from the command line //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=props.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,props.getProperty(prop)); } props=fileprops; if (!checkRequiredProperties(props)) { System.exit(0); } long maxExecutionTime = Integer.parseInt(props.getProperty(MAX_EXECUTION_TIME, "0")); //get number of threads, target and db threadcount=Integer.parseInt(props.getProperty("threadcount","1")); nodecount=Integer.parseInt(props.getProperty("nodecount","1")); dbname=props.getProperty("db","com.yahoo.ycsb.BasicDB"); target=Integer.parseInt(props.getProperty("target","0")); MagicKey.CLIENTS = nodecount; MagicKey.NUMBER = Integer.parseInt(props.getProperty(Client.RECORD_COUNT_PROPERTY)); //compute the target throughput double targetperthreadperms=-1; if (target>0) { double targetperthread=((double)target)/((double)threadcount); targetperthreadperms=targetperthread/1000.0; } System.out.println("YCSB Client 0.1"); System.out.print("Command line:"); for (int i=0; i<args.length; i++) { System.out.print(" "+args[i]); } System.out.println(); System.err.println("Loading workload..."); //show a warning message that creating the workload is taking a while //but only do so if it is taking longer than 2 seconds //(showing the message right away if the setup wasn't taking very long was confusing people) Thread warningthread=new Thread() { public void run() { try { sleep(2000); } catch (InterruptedException e) { return; } System.err.println(" (might take a few minutes for large data sets)"); } }; warningthread.start(); //set up measurements Measurements.setProperties(props); //load the workload ClassLoader classLoader = Client.class.getClassLoader(); Workload workload=null; try { Class workloadclass = classLoader.loadClass(props.getProperty(WORKLOAD_PROPERTY)); workload=(Workload)workloadclass.newInstance(); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { workload.init(props); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } warningthread.interrupt(); //run the workload System.err.println("Starting test."); int opcount; - int mulreadcount; + int mulreadcount = 20; if (dotransactions) { opcount=Integer.parseInt(props.getProperty(OPERATION_COUNT_PROPERTY,"0")); mulreadcount=Integer.parseInt(props.getProperty(MULTIPLE_READ_COUNT_PROPERTY,"0")); System.out.println("OPCOUNT: "+opcount + " MULREADCOUNT: " + mulreadcount); } else { if (props.containsKey(INSERT_COUNT_PROPERTY)) { opcount=Integer.parseInt(props.getProperty(INSERT_COUNT_PROPERTY,"0")); } else { opcount=Integer.parseInt(props.getProperty(RECORD_COUNT_PROPERTY,"0")); } } Vector<Thread> threads=new Vector<Thread>(); for (int threadid=0; threadid<threadcount; threadid++) { DB db=null; try { db=DBFactory.newDB(dbname,props); } catch (UnknownDBException e) { System.out.println("Unknown DB "+dbname); System.exit(0); } Thread t=new ClientThread(db,dotransactions,workload,threadid,nodecount,threadcount,props,opcount/threadcount,targetperthreadperms,mulreadcount); threads.add(t); //t.start(); } StatusThread statusthread=null; if (status) { boolean standardstatus=false; if (props.getProperty("measurementtype","").compareTo("timeseries")==0) { standardstatus=true; } statusthread=new StatusThread(threads,label,standardstatus); statusthread.start(); } long st=System.currentTimeMillis(); for (Thread t : threads) { t.start(); } Thread terminator = null; if (maxExecutionTime > 0) { terminator = new TerminatorThread(maxExecutionTime, threads, workload); terminator.start(); } int opsDone = 0; for (Thread t : threads) { try { t.join(); opsDone += ((ClientThread)t).getOpsDone(); } catch (InterruptedException e) { } } long en=System.currentTimeMillis(); if(dotransactions){ System.out.println("END_TRANSACTIONS"); } if (terminator != null && !terminator.isInterrupted()) { terminator.interrupt(); } if (status) { statusthread.interrupt(); } try { workload.cleanup(); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { exportMeasurements(props, opsDone, en - st); } catch (IOException e) { System.err.println("Could not export measurements, error: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } System.exit(0); } }
true
true
public static void main(String[] args) { String dbname; Properties props=new Properties(); Properties fileprops=new Properties(); boolean dotransactions=true; int threadcount=1; int nodecount=1; int target=0; boolean status=false; String label=""; //parse arguments int argindex=0; if (args.length==0) { usageMessage(); System.exit(0); } try { DOMConfigurator.configure("log4j.xml"); } catch (FactoryConfigurationError e) { e.printStackTrace(); System.exit(-1); } while (args[argindex].startsWith("-")) { if (args[argindex].compareTo("-threads")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int tcount=Integer.parseInt(args[argindex]); props.setProperty("threadcount", tcount+""); argindex++; } else if (args[argindex].compareTo("-nodes")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int nodes=Integer.parseInt(args[argindex]); props.setProperty("nodecount", nodes+""); argindex++; } else if (args[argindex].compareTo("-target")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int ttarget=Integer.parseInt(args[argindex]); props.setProperty("target", ttarget+""); argindex++; } else if (args[argindex].compareTo("-load")==0) { dotransactions=false; argindex++; } else if (args[argindex].compareTo("-t")==0) { dotransactions=true; argindex++; } else if (args[argindex].compareTo("-s")==0) { status=true; argindex++; } else if (args[argindex].compareTo("-db")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } props.setProperty("db",args[argindex]); argindex++; } else if (args[argindex].compareTo("-l")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } label=args[argindex]; argindex++; } else if (args[argindex].compareTo("-P")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } String propfile=args[argindex]; argindex++; Properties myfileprops=new Properties(); try { myfileprops.load(new FileInputStream(propfile)); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=myfileprops.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,myfileprops.getProperty(prop)); } } else if (args[argindex].compareTo("-p")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int eq=args[argindex].indexOf('='); if (eq<0) { usageMessage(); System.exit(0); } String name=args[argindex].substring(0,eq); String value=args[argindex].substring(eq+1); props.put(name,value); //System.out.println("["+name+"]=["+value+"]"); argindex++; } else { System.out.println("Unknown option "+args[argindex]); usageMessage(); System.exit(0); } if (argindex>=args.length) { break; } } if (argindex!=args.length) { usageMessage(); System.exit(0); } //set up logging //BasicConfigurator.configure(); //overwrite file properties with properties from the command line //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=props.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,props.getProperty(prop)); } props=fileprops; if (!checkRequiredProperties(props)) { System.exit(0); } long maxExecutionTime = Integer.parseInt(props.getProperty(MAX_EXECUTION_TIME, "0")); //get number of threads, target and db threadcount=Integer.parseInt(props.getProperty("threadcount","1")); nodecount=Integer.parseInt(props.getProperty("nodecount","1")); dbname=props.getProperty("db","com.yahoo.ycsb.BasicDB"); target=Integer.parseInt(props.getProperty("target","0")); MagicKey.CLIENTS = nodecount; MagicKey.NUMBER = Integer.parseInt(props.getProperty(Client.RECORD_COUNT_PROPERTY)); //compute the target throughput double targetperthreadperms=-1; if (target>0) { double targetperthread=((double)target)/((double)threadcount); targetperthreadperms=targetperthread/1000.0; } System.out.println("YCSB Client 0.1"); System.out.print("Command line:"); for (int i=0; i<args.length; i++) { System.out.print(" "+args[i]); } System.out.println(); System.err.println("Loading workload..."); //show a warning message that creating the workload is taking a while //but only do so if it is taking longer than 2 seconds //(showing the message right away if the setup wasn't taking very long was confusing people) Thread warningthread=new Thread() { public void run() { try { sleep(2000); } catch (InterruptedException e) { return; } System.err.println(" (might take a few minutes for large data sets)"); } }; warningthread.start(); //set up measurements Measurements.setProperties(props); //load the workload ClassLoader classLoader = Client.class.getClassLoader(); Workload workload=null; try { Class workloadclass = classLoader.loadClass(props.getProperty(WORKLOAD_PROPERTY)); workload=(Workload)workloadclass.newInstance(); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { workload.init(props); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } warningthread.interrupt(); //run the workload System.err.println("Starting test."); int opcount; int mulreadcount; if (dotransactions) { opcount=Integer.parseInt(props.getProperty(OPERATION_COUNT_PROPERTY,"0")); mulreadcount=Integer.parseInt(props.getProperty(MULTIPLE_READ_COUNT_PROPERTY,"0")); System.out.println("OPCOUNT: "+opcount + " MULREADCOUNT: " + mulreadcount); } else { if (props.containsKey(INSERT_COUNT_PROPERTY)) { opcount=Integer.parseInt(props.getProperty(INSERT_COUNT_PROPERTY,"0")); } else { opcount=Integer.parseInt(props.getProperty(RECORD_COUNT_PROPERTY,"0")); } } Vector<Thread> threads=new Vector<Thread>(); for (int threadid=0; threadid<threadcount; threadid++) { DB db=null; try { db=DBFactory.newDB(dbname,props); } catch (UnknownDBException e) { System.out.println("Unknown DB "+dbname); System.exit(0); } Thread t=new ClientThread(db,dotransactions,workload,threadid,nodecount,threadcount,props,opcount/threadcount,targetperthreadperms,mulreadcount); threads.add(t); //t.start(); } StatusThread statusthread=null; if (status) { boolean standardstatus=false; if (props.getProperty("measurementtype","").compareTo("timeseries")==0) { standardstatus=true; } statusthread=new StatusThread(threads,label,standardstatus); statusthread.start(); } long st=System.currentTimeMillis(); for (Thread t : threads) { t.start(); } Thread terminator = null; if (maxExecutionTime > 0) { terminator = new TerminatorThread(maxExecutionTime, threads, workload); terminator.start(); } int opsDone = 0; for (Thread t : threads) { try { t.join(); opsDone += ((ClientThread)t).getOpsDone(); } catch (InterruptedException e) { } } long en=System.currentTimeMillis(); if(dotransactions){ System.out.println("END_TRANSACTIONS"); } if (terminator != null && !terminator.isInterrupted()) { terminator.interrupt(); } if (status) { statusthread.interrupt(); } try { workload.cleanup(); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { exportMeasurements(props, opsDone, en - st); } catch (IOException e) { System.err.println("Could not export measurements, error: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } System.exit(0); }
public static void main(String[] args) { String dbname; Properties props=new Properties(); Properties fileprops=new Properties(); boolean dotransactions=true; int threadcount=1; int nodecount=1; int target=0; boolean status=false; String label=""; //parse arguments int argindex=0; if (args.length==0) { usageMessage(); System.exit(0); } try { DOMConfigurator.configure("log4j.xml"); } catch (FactoryConfigurationError e) { e.printStackTrace(); System.exit(-1); } while (args[argindex].startsWith("-")) { if (args[argindex].compareTo("-threads")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int tcount=Integer.parseInt(args[argindex]); props.setProperty("threadcount", tcount+""); argindex++; } else if (args[argindex].compareTo("-nodes")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int nodes=Integer.parseInt(args[argindex]); props.setProperty("nodecount", nodes+""); argindex++; } else if (args[argindex].compareTo("-target")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int ttarget=Integer.parseInt(args[argindex]); props.setProperty("target", ttarget+""); argindex++; } else if (args[argindex].compareTo("-load")==0) { dotransactions=false; argindex++; } else if (args[argindex].compareTo("-t")==0) { dotransactions=true; argindex++; } else if (args[argindex].compareTo("-s")==0) { status=true; argindex++; } else if (args[argindex].compareTo("-db")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } props.setProperty("db",args[argindex]); argindex++; } else if (args[argindex].compareTo("-l")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } label=args[argindex]; argindex++; } else if (args[argindex].compareTo("-P")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } String propfile=args[argindex]; argindex++; Properties myfileprops=new Properties(); try { myfileprops.load(new FileInputStream(propfile)); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=myfileprops.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,myfileprops.getProperty(prop)); } } else if (args[argindex].compareTo("-p")==0) { argindex++; if (argindex>=args.length) { usageMessage(); System.exit(0); } int eq=args[argindex].indexOf('='); if (eq<0) { usageMessage(); System.exit(0); } String name=args[argindex].substring(0,eq); String value=args[argindex].substring(eq+1); props.put(name,value); //System.out.println("["+name+"]=["+value+"]"); argindex++; } else { System.out.println("Unknown option "+args[argindex]); usageMessage(); System.exit(0); } if (argindex>=args.length) { break; } } if (argindex!=args.length) { usageMessage(); System.exit(0); } //set up logging //BasicConfigurator.configure(); //overwrite file properties with properties from the command line //Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e=props.propertyNames(); e.hasMoreElements(); ) { String prop=(String)e.nextElement(); fileprops.setProperty(prop,props.getProperty(prop)); } props=fileprops; if (!checkRequiredProperties(props)) { System.exit(0); } long maxExecutionTime = Integer.parseInt(props.getProperty(MAX_EXECUTION_TIME, "0")); //get number of threads, target and db threadcount=Integer.parseInt(props.getProperty("threadcount","1")); nodecount=Integer.parseInt(props.getProperty("nodecount","1")); dbname=props.getProperty("db","com.yahoo.ycsb.BasicDB"); target=Integer.parseInt(props.getProperty("target","0")); MagicKey.CLIENTS = nodecount; MagicKey.NUMBER = Integer.parseInt(props.getProperty(Client.RECORD_COUNT_PROPERTY)); //compute the target throughput double targetperthreadperms=-1; if (target>0) { double targetperthread=((double)target)/((double)threadcount); targetperthreadperms=targetperthread/1000.0; } System.out.println("YCSB Client 0.1"); System.out.print("Command line:"); for (int i=0; i<args.length; i++) { System.out.print(" "+args[i]); } System.out.println(); System.err.println("Loading workload..."); //show a warning message that creating the workload is taking a while //but only do so if it is taking longer than 2 seconds //(showing the message right away if the setup wasn't taking very long was confusing people) Thread warningthread=new Thread() { public void run() { try { sleep(2000); } catch (InterruptedException e) { return; } System.err.println(" (might take a few minutes for large data sets)"); } }; warningthread.start(); //set up measurements Measurements.setProperties(props); //load the workload ClassLoader classLoader = Client.class.getClassLoader(); Workload workload=null; try { Class workloadclass = classLoader.loadClass(props.getProperty(WORKLOAD_PROPERTY)); workload=(Workload)workloadclass.newInstance(); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { workload.init(props); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } warningthread.interrupt(); //run the workload System.err.println("Starting test."); int opcount; int mulreadcount = 20; if (dotransactions) { opcount=Integer.parseInt(props.getProperty(OPERATION_COUNT_PROPERTY,"0")); mulreadcount=Integer.parseInt(props.getProperty(MULTIPLE_READ_COUNT_PROPERTY,"0")); System.out.println("OPCOUNT: "+opcount + " MULREADCOUNT: " + mulreadcount); } else { if (props.containsKey(INSERT_COUNT_PROPERTY)) { opcount=Integer.parseInt(props.getProperty(INSERT_COUNT_PROPERTY,"0")); } else { opcount=Integer.parseInt(props.getProperty(RECORD_COUNT_PROPERTY,"0")); } } Vector<Thread> threads=new Vector<Thread>(); for (int threadid=0; threadid<threadcount; threadid++) { DB db=null; try { db=DBFactory.newDB(dbname,props); } catch (UnknownDBException e) { System.out.println("Unknown DB "+dbname); System.exit(0); } Thread t=new ClientThread(db,dotransactions,workload,threadid,nodecount,threadcount,props,opcount/threadcount,targetperthreadperms,mulreadcount); threads.add(t); //t.start(); } StatusThread statusthread=null; if (status) { boolean standardstatus=false; if (props.getProperty("measurementtype","").compareTo("timeseries")==0) { standardstatus=true; } statusthread=new StatusThread(threads,label,standardstatus); statusthread.start(); } long st=System.currentTimeMillis(); for (Thread t : threads) { t.start(); } Thread terminator = null; if (maxExecutionTime > 0) { terminator = new TerminatorThread(maxExecutionTime, threads, workload); terminator.start(); } int opsDone = 0; for (Thread t : threads) { try { t.join(); opsDone += ((ClientThread)t).getOpsDone(); } catch (InterruptedException e) { } } long en=System.currentTimeMillis(); if(dotransactions){ System.out.println("END_TRANSACTIONS"); } if (terminator != null && !terminator.isInterrupted()) { terminator.interrupt(); } if (status) { statusthread.interrupt(); } try { workload.cleanup(); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { exportMeasurements(props, opsDone, en - st); } catch (IOException e) { System.err.println("Could not export measurements, error: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } System.exit(0); }
diff --git a/Smite/src/me/comp/Smite/Smite.java b/Smite/src/me/comp/Smite/Smite.java index f842971..8fb2263 100644 --- a/Smite/src/me/comp/Smite/Smite.java +++ b/Smite/src/me/comp/Smite/Smite.java @@ -1,53 +1,53 @@ package me.comp.Smite; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; public class Smite extends JavaPlugin { public static Smite plugin; public final Logger logger = Logger.getLogger("Minecraft"); public void onDisable() { PluginDescriptionFile pdffile = this.getDescription(); this.logger.info(pdffile.getName() + "is now disabled."); } public void onEnable() { PluginDescriptionFile pdffile = this.getDescription(); this.logger.info(pdffile.getName() + "is now enabled."); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = (Player) sender; World world = player.getWorld(); if(commandLabel.equalsIgnoreCase("smite")) { if(args.length == 0) { - Block targetblock = player.getTargetBlock(null, 20); + Block targetblock = player.getTargetBlock(null, 50); Location location = targetblock.getLocation(); world.strikeLightning(location); - world.createExplosion(location, 50); + world.createExplosion(location, 20); } else if (args.length == 1) { if(player.getServer().getPlayer(args[0]) != null) { Player targetplayer = player.getServer().getPlayer(args[0]); Location location = targetplayer.getLocation(); world.strikeLightning(location); player.sendMessage(ChatColor.GRAY + "Smiting Player " + targetplayer.getDisplayName()); } else { player.sendMessage(ChatColor.RED + "Error: The player is offline. "); } } else if (args.length > 1) { player.sendMessage(ChatColor.RED + "Error: Too Many Arguments!"); } } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = (Player) sender; World world = player.getWorld(); if(commandLabel.equalsIgnoreCase("smite")) { if(args.length == 0) { Block targetblock = player.getTargetBlock(null, 20); Location location = targetblock.getLocation(); world.strikeLightning(location); world.createExplosion(location, 50); } else if (args.length == 1) { if(player.getServer().getPlayer(args[0]) != null) { Player targetplayer = player.getServer().getPlayer(args[0]); Location location = targetplayer.getLocation(); world.strikeLightning(location); player.sendMessage(ChatColor.GRAY + "Smiting Player " + targetplayer.getDisplayName()); } else { player.sendMessage(ChatColor.RED + "Error: The player is offline. "); } } else if (args.length > 1) { player.sendMessage(ChatColor.RED + "Error: Too Many Arguments!"); } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { Player player = (Player) sender; World world = player.getWorld(); if(commandLabel.equalsIgnoreCase("smite")) { if(args.length == 0) { Block targetblock = player.getTargetBlock(null, 50); Location location = targetblock.getLocation(); world.strikeLightning(location); world.createExplosion(location, 20); } else if (args.length == 1) { if(player.getServer().getPlayer(args[0]) != null) { Player targetplayer = player.getServer().getPlayer(args[0]); Location location = targetplayer.getLocation(); world.strikeLightning(location); player.sendMessage(ChatColor.GRAY + "Smiting Player " + targetplayer.getDisplayName()); } else { player.sendMessage(ChatColor.RED + "Error: The player is offline. "); } } else if (args.length > 1) { player.sendMessage(ChatColor.RED + "Error: Too Many Arguments!"); } } return false; }
diff --git a/src/main/java/com/laytonsmith/core/functions/EntityManagement.java b/src/main/java/com/laytonsmith/core/functions/EntityManagement.java index 38c45893..2343e72b 100644 --- a/src/main/java/com/laytonsmith/core/functions/EntityManagement.java +++ b/src/main/java/com/laytonsmith/core/functions/EntityManagement.java @@ -1,1183 +1,1183 @@ package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.StringUtils; import com.laytonsmith.abstraction.*; import com.laytonsmith.abstraction.blocks.MCBlockFace; import com.laytonsmith.abstraction.enums.MCEntityEffect; import com.laytonsmith.abstraction.enums.MCEntityType; import com.laytonsmith.abstraction.enums.MCEquipmentSlot; import com.laytonsmith.abstraction.enums.MCProjectileType; import com.laytonsmith.annotations.api; import com.laytonsmith.core.CHLog; import com.laytonsmith.core.CHVersion; import com.laytonsmith.core.LogLevel; import com.laytonsmith.core.ObjectGenerator; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.ParseTree; import com.laytonsmith.core.Static; import com.laytonsmith.core.constructs.*; import com.laytonsmith.core.environments.CommandHelperEnvironment; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.functions.Exceptions.ExceptionType; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author jb_aero */ public class EntityManagement { public static String docs(){ return "This class of functions allow entities to be managed."; } public static abstract class EntityFunction extends AbstractFunction { public boolean isRestricted() { return true; } public Boolean runAsync() { return false; } public CHVersion since() { return CHVersion.V3_3_1; } } public static abstract class EntityGetterFunction extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException}; } public Integer[] numArgs() { return new Integer[]{1}; } } public static abstract class EntitySetterFunction extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.CastException, ExceptionType.BadEntityException}; } public Integer[] numArgs() { return new Integer[]{2}; } } @api public static class all_entities extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.InvalidWorldException, ExceptionType.FormatException, ExceptionType.CastException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { CArray ret = new CArray(t); if (args.length == 0) { for (MCWorld w : Static.getServer().getWorlds()) { for (MCEntity e : w.getEntities()) { ret.push(new CInt(e.getEntityId(), t)); } } } else { MCWorld w; MCChunk c; if (args.length == 3) { w = Static.getServer().getWorld(args[0].val()); try { int x = Static.getInt32(args[1], t); int z = Static.getInt32(args[2], t); c = w.getChunkAt(x, z); } catch (ConfigRuntimeException cre) { CArray l = CArray.GetAssociativeArray(t); l.set("x", args[1], t); l.set("z", args[2], t); c = w.getChunkAt(ObjectGenerator.GetGenerator().location(l, w, t)); } for (MCEntity e : c.getEntities()) { ret.push(new CInt(e.getEntityId(), t)); } } else { if (args[0] instanceof CArray) { c = ObjectGenerator.GetGenerator().location(args[0], null, t).getChunk(); for (MCEntity e : c.getEntities()) { ret.push(new CInt(e.getEntityId(), t)); } } else { w = Static.getServer().getWorld(args[0].val()); for (MCEntity e : w.getEntities()) { ret.push(new CInt(e.getEntityId(), t)); } } } } return ret; } public String getName() { return "all_entities"; } public Integer[] numArgs() { return new Integer[]{0, 1, 3}; } public String docs() { return "array {[world, [x, z]] | [locationArray]} Returns an array of IDs for all entities in the given" + " scope. With no args, this will return all entities loaded on the entire server. If the first" + " argument is given and is a location, only entities in the chunk containin that location will" + " be returned, or if it is a world only entities in that world will be returned. If all three" + " arguments are given, only entities in the chunk with those coords will be returned. This can" + " take chunk coords (ints) or location coords (doubles)."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Getting all entities in a world", "msg(all_entities(pworld()))", "Sends you an array of all entities in your world."), new ExampleScript("Getting entities in a chunk", "msg(all_entities(pworld(), 5, -3))", "Sends you an array of all entities in chunk (5,-3)."), new ExampleScript("Getting entities in your chunk", "msg(all_entities(ploc()))", "Sends you an array of all entities in the chunk you are in.") }; } } @api public static class entity_loc extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity e = Static.getEntity(Static.getInt32(args[0], t), t); return ObjectGenerator.GetGenerator().location(e.getLocation()); } public String getName() { return "entity_loc"; } public String docs() { return "locationArray {entityID} Returns the location array for this entity, if it exists." + " This array will be compatible with any function that expects a location."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Sample output", "entity_loc(5048)", "{0: -3451.96, 1: 65.0, 2: 718.521, 3: world, 4: -170.9, 5: 35.5, pitch: 35.5," + " world: world, x: -3451.96, y: 65.0, yaw: -170.9, z: 718.521}") }; } } @api public static class set_entity_loc extends EntitySetterFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.BadEntityException, ExceptionType.FormatException, ExceptionType.CastException, ExceptionType.InvalidWorldException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity e = Static.getEntity(Static.getInt32(args[0], t), t); MCLocation l; if (args[1] instanceof CArray) { l = ObjectGenerator.GetGenerator().location((CArray) args[1], e.getWorld(), t); } else { throw new Exceptions.FormatException("An array was expected but recieved " + args[1], t); } return new CBoolean(e.teleport(l), t); } public String getName() { return "set_entity_loc"; } public String docs() { return "boolean {entityID, locationArray} Teleports the entity to the given location and returns whether" + " the action was successful. Note this can set both location and direction."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Teleporting an entity to you", "set_entity_loc(386, ploc())", "The entity will teleport to the block you are standing on."), new ExampleScript("Teleporting an entity to another", "set_entity_loc(201, entity_location(10653))", "The entity will teleport to the other and face the same direction, if they both exist."), new ExampleScript("Setting location with a normal array", "set_entity_loc(465, array(214, 64, 1812, 'world', -170, 10))", "This set location and direction."), new ExampleScript("Setting location with an associative array", "set_entity_loc(852, array(x: 214, y: 64, z: 1812, world: 'world', yaw: -170, pitch: 10))", "This also sets location and direction") }; } } @api public static class entity_velocity extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity e = Static.getEntity(Static.getInt32(args[0], t), t); CArray va = ObjectGenerator.GetGenerator().velocity(e.getVelocity(), t); return va; } public String getName() { return "entity_velocity"; } public String docs() { return "array {entityID} Returns an associative array indicating the x/y/z components of this entity's velocity." + " As a convenience, the magnitude is also included."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("A stationary entity", "msg(entity_velocity(235))", "{magnitude: 0.0, x: 0.0, y: 0.0, z: 0.0}") }; } } @api public static class set_entity_velocity extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity e = Static.getEntity(Static.getInt32(args[0], t), t); e.setVelocity(ObjectGenerator.GetGenerator().velocity(args[1], t)); return new CVoid(t); } public String getName() { return "set_entity_velocity"; } public String docs() { return "void {entityID, array} Sets the velocity of this entity according to the supplied xyz array. All 3" + " values default to 0, so an empty array will simply stop the entity's motion. Both normal and" + " associative arrays are accepted."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Setting a bounce with a normal array", "set_entity_velocity(235, array(0, 0.5, 0))", "The entity just hopped, unless it was an item frame or painting."), new ExampleScript("Setting a bounce with an associative array", "set_entity_velocity(235, array(y: 0.5))", "The entity just hopped, unless it was an item frame or painting.") }; } } @api public static class entity_remove extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity((int) Static.getInt(args[0], t), t); if (ent == null) { return new CVoid(t); } else if (ent instanceof MCHumanEntity) { throw new ConfigRuntimeException("Cannot remove human entity (" + ent.getEntityId() + ")!", ExceptionType.BadEntityException, t); } else { ent.remove(); return new CVoid(t); } } public String getName() { return "entity_remove"; } public String docs() { return "void {entityID} Removes the specified entity from the world, without any drops or animations. " + "Note: you can't remove players. As a safety measure for working with NPC plugins, it will " + "not work on anything human, even if it is not a player."; } } @api public static class entity_type extends EntityGetterFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent; int id = Static.getInt32(args[0], t); try { ent = Static.getEntity(id, t); } catch (ConfigRuntimeException cre) { return new CNull(t); } return new CString(ent.getType().name(), t); } public String getName() { return "entity_type"; } public String docs() { return "mixed {entityID} Returns the EntityType of the entity with the specified ID." + " Returns null if the entity does not exist."; } } @api public static class get_entity_age extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCEntity ent = Static.getEntity(id, t); if (ent == null) { return new CNull(t); } else { return new CInt(ent.getTicksLived(), t); } } public String getName() { return "get_entity_age"; } public String docs() { return "int {entityID} Returns the entity age as an integer, represented by server ticks."; } } @api public static class set_entity_age extends EntitySetterFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException, ExceptionType.RangeException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); int age = Static.getInt32(args[1], t); if (age < 1) { throw new ConfigRuntimeException("Entity age can't be less than 1 server tick.", ExceptionType.RangeException, t); } MCEntity ent = Static.getEntity(id, t); if (ent == null) { return new CNull(t); } else { ent.setTicksLived(age); return new CVoid(t); } } public String getName() { return "set_entity_age"; } public String docs() { return "void {entityID, int} Sets the age of the entity to the specified int, represented by server ticks."; } } @api public static class get_mob_age extends EntityGetterFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UnageableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); MCLivingEntity ent = Static.getLivingEntity(id, t); if (ent == null) { return new CNull(t); } else if (ent instanceof MCAgeable) { MCAgeable mob = ((MCAgeable) ent); return new CInt(mob.getAge(), t); } else { throw new ConfigRuntimeException("The specified entity does not age", ExceptionType.UnageableMobException, t); } } public String getName() { return "get_mob_age"; } public String docs() { return "int {entityID} Returns the mob's age as an integer. Zero represents the point of adulthood. Throws an" + " UnageableMobException if the mob is not a type that ages"; } } @api public static class set_mob_age extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.UnageableMobException, ExceptionType.CastException, ExceptionType.BadEntityException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { int id = Static.getInt32(args[0], t); int age = Static.getInt32(args[1], t); boolean lock = false; if (args.length == 3) { lock = (boolean) Static.getBoolean(args[2]); } MCLivingEntity ent = Static.getLivingEntity(id, t); if (ent == null) { return new CNull(t); } else if (ent instanceof MCAgeable) { MCAgeable mob = ((MCAgeable) ent); mob.setAge(age); mob.setAgeLock(lock); return new CVoid(t); } else { throw new ConfigRuntimeException("The specified entity does not age", ExceptionType.UnageableMobException, t); } } public String getName() { return "set_mob_age"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public String docs() { return "void {entityID, int[, lockAge]} sets the age of the mob to the specified int, and locks it at that age" + " if lockAge is true, but by default it will not. Throws a UnageableMobException if the mob does" + " not age naturally."; } } @api public static class get_mob_effects extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity mob = Static.getLivingEntity(Static.getInt32(args[0], t), t); return ObjectGenerator.GetGenerator().potions(mob.getEffects(), t); } public String getName() { return "get_mob_effects"; } public String docs() { return "array {entityID} Returns an array of potion arrays showing" + " the effects on this mob."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{new ExampleScript("Basic use", "msg(get_mob_effects(259))", "{{ambient: false, id: 1, seconds: 30, strength: 1}}")}; } } @api public static class set_mob_effect extends EntityFunction { public String getName() { return "set_mob_effect"; } public Integer[] numArgs() { return new Integer[]{3, 4, 5}; } public String docs() { return "boolean {entityId, potionID, strength, [seconds], [ambient]} Effect is 1-19. Seconds defaults to 30." + " If the potionID is out of range, a RangeException is thrown, because out of range potion effects" + " cause the client to crash, fairly hardcore. See http://www.minecraftwiki.net/wiki/Potion_effects" + " for a complete list of potions that can be added. To remove an effect, set the seconds to 0." + " Strength is the number of levels to add to the base power (effect level 1). Ambient takes a boolean" + " of whether the particles should be less noticeable. The function returns true if the effect was" + " added or removed as desired, and false if it wasn't (however, this currently only will happen if" + " an effect is attempted to be removed, yet isn't already on the mob)."; } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.BadEntityException, ExceptionType.RangeException}; } public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCLivingEntity mob = Static.getLivingEntity(Static.getInt32(args[0], t), t); int effect = Static.getInt32(args[1], t); int strength = Static.getInt32(args[2], t); int seconds = 30; boolean ambient = false; if (args.length >= 4) { seconds = Static.getInt32(args[3], t); } if (args.length == 5) { ambient = Static.getBoolean(args[4]); } if (seconds == 0) { return new CBoolean(mob.removeEffect(effect), t); } else { mob.addEffect(effect, strength, seconds, ambient, t); return new CBoolean(true, t); } } } @api(environments={CommandHelperEnvironment.class}) public static class shoot_projectile extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.BadEntityException, ExceptionType.FormatException, ExceptionType.PlayerOfflineException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCCommandSender cmdsr = environment.getEnv(CommandHelperEnvironment.class).GetCommandSender(); MCLivingEntity ent = null; int id; MCProjectileType toShoot = MCProjectileType.FIREBALL; if (args.length >= 1) { try { id = Static.GetPlayer(args[0], t).getEntityId(); } catch (ConfigRuntimeException notPlayer) { try { id = Static.getInt32(args[0], t); } catch (ConfigRuntimeException notEntIDEither) { throw new ConfigRuntimeException("Could not find an entity matching " + args[0] + "!", ExceptionType.BadEntityException, t); } } } else { if (cmdsr instanceof MCPlayer) { id = ((MCLivingEntity) cmdsr).getEntityId(); Static.AssertPlayerNonNull((MCPlayer) cmdsr, t); } else { throw new ConfigRuntimeException("A player was expected!", ExceptionType.PlayerOfflineException, t); } } if (args.length == 2) { try { toShoot = MCProjectileType.valueOf(args[1].toString().toUpperCase()); } catch (IllegalArgumentException badEnum) { throw new ConfigRuntimeException(args[1] + " is not a valid Projectile", ExceptionType.FormatException, t); } } ent = Static.getLivingEntity(id, t); return new CInt(ent.launchProjectile(toShoot).getEntityId(), t); } public String getName() { return "shoot_projectile"; } public Integer[] numArgs() { return new Integer[]{0, 1, 2}; } public String docs() { return "int {[player[, projectile]] | [entityID[, projectile]]} shoots a projectile from the entity or player" + " specified, or the current player if no arguments are passed. If no projectile is specified," + " it defaults to a fireball. Returns the EntityID of the projectile. Valid projectiles: " + StringUtils.Join(MCProjectileType.values(), ", ", ", or ", " or "); } } @api(environments = {CommandHelperEnvironment.class}) public static class entities_in_radius extends EntityFunction { public String getName() { return "entities_in_radius"; } public Integer[] numArgs() { return new Integer[]{2, 3}; } public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCLocation loc; int dist; List<String> types = new ArrayList<String>(); if (!(args[0] instanceof CArray)) { throw new ConfigRuntimeException("Expecting an array at parameter 1 of entities_in_radius", ExceptionType.BadEntityException, t); } loc = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t); dist = Static.getInt32(args[1], t); if (args.length == 3) { if (args[2] instanceof CArray) { CArray ta = (CArray) args[2]; for (int i = 0; i < ta.size(); i++) { types.add(ta.get(i, t).val()); } } else { types.add(args[2].val()); } types = prepareTypes(t, types); } // The idea and code comes from skore87 (http://forums.bukkit.org/members/skore87.105075/) // http://forums.bukkit.org/threads/getnearbyentities-of-a-location.101499/#post-1341141 int chunkRadius = dist < 16 ? 1 : (dist - (dist % 16)) / 16; CArray entities = new CArray(t); for (int chX = 0 - chunkRadius; chX <= chunkRadius; chX++) { for (int chZ = 0 - chunkRadius; chZ <= chunkRadius; chZ++) { for (MCEntity e : loc.getChunk().getEntities()) { - if (e.getWorld() != loc.getWorld()) { + if (!e.getWorld().equals(loc.getWorld())) { continue; } if (e.getLocation().distance(loc) <= dist && e.getLocation().getBlock() != loc.getBlock()) { if (types.isEmpty() || types.contains(e.getType().name())) { entities.push(new CInt(e.getEntityId(), t)); } } } } } return entities; } private List<String> prepareTypes(Target t, List<String> types) { List<String> newTypes = new ArrayList<String>(); MCEntityType entityType = null; for (String type : types) { try { entityType = MCEntityType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { throw new ConfigRuntimeException(String.format("Wrong entity type: %s", type), ExceptionType.BadEntityException, t); } newTypes.add(entityType.name()); } return newTypes; } public String docs() { return "array {location array, distance, [type] | location array, distance, [arrayTypes]} Returns an array of" + " all entities within the given radius. Set type argument to filter entities to a specific type. You" + " can pass an array of types. Valid types (case doesn't matter): " + StringUtils.Join(MCEntityType.values(), ", ", ", or ", " or "); } public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.BadEntityException, ExceptionType.FormatException}; } } //@api public static class get_mob_target extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); if (le.getTarget(t) == null) { return new CNull(t); } else { return new CInt(le.getTarget(t).getEntityId(), t); } } public String getName() { return "get_mob_target"; } public String docs() { return "entityID {entityID} Gets the mob's target if it has one, and returns the target's entityID." + " If there is no target, null is returned instead."; } } //@api public static class set_mob_target extends EntitySetterFunction { @Override public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.BadEntityException, ExceptionType.CastException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); MCLivingEntity target = null; if (!(args[1] instanceof CNull)) { target = Static.getLivingEntity(Static.getInt32(args[1], t), t); } le.setTarget(target, t); return new CVoid(t); } public String getName() { return "set_mob_target"; } public String docs() { return "void {entityID, entityID} The first ID is the entity who is targetting, the second is the target." + " It can also be set to null to clear the current target."; } } @api public static class get_mob_equipment extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); Map<MCEquipmentSlot, MCItemStack> eq = le.getEquipment().getAllEquipment(); CArray ret = CArray.GetAssociativeArray(t); for (MCEquipmentSlot key : eq.keySet()) { ret.set(key.name().toLowerCase(), ObjectGenerator.GetGenerator().item(eq.get(key), t), t); } return ret; } public String getName() { return "get_mob_equipment"; } public String docs() { return "equipmentArray {entityID} Returns an associative array showing the equipment this entity is wearing."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Getting a mob's equipment", "get_mob_equipment(276)", "{boots: null," + " chestplate: null, helmet: {data: 0, enchants: {} meta: null, type: 91}, leggings: null," + " weapon: {data: 5, enchants: {} meta: {display: Excalibur, lore: null}, type: 276}}") }; } } @api public static class set_mob_equipment extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntityEquipment ee = Static.getLivingEntity(Static.getInt32(args[0], t), t).getEquipment(); Map<MCEquipmentSlot, MCItemStack> eq = ee.getAllEquipment(); if (args[1] instanceof CNull) { ee.clearEquipment(); return new CVoid(t); } else if (args[1] instanceof CArray) { CArray ea = (CArray) args[1]; for (String key : ea.keySet()) { try { eq.put(MCEquipmentSlot.valueOf(key.toUpperCase()), ObjectGenerator.GetGenerator().item(ea.get(key, t), t)); } catch (IllegalArgumentException iae) { throw new Exceptions.FormatException("Not an equipment slot: " + key, t); } } } else { throw new Exceptions.FormatException("Expected argument 2 to be an array", t); } ee.setAllEquipment(eq); return new CVoid(t); } public String getName() { return "set_mob_equipment"; } public String docs() { return "void {entityID, array} Takes an associative array with keys representing equipment slots and values" + " of itemArrays, the same used by set_pinv. The equipment slots are: " + StringUtils.Join(MCEquipmentSlot.values(), ", ", ", or ", " or "); } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "set_mob_equipment(spawn_mob('SKELETON')[0], array(WEAPON: array(type: 261)))", "Gives a bow to a skeleton") }; } } @api public static class get_max_health extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); return new CInt(le.getMaxHealth(), t); } public String getName() { return "get_max_health"; } public String docs() { return "int {entityID} Returns the maximum health of this living entity."; } } @api public static class set_max_health extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); le.setMaxHealth(Static.getInt32(args[1], t)); return new CVoid(t); } public String getName() { return "set_max_health"; } public String docs() { return "void {entityID, int} Sets the max health of this living entity." + " this is persistent for players, and will not reset even" + " after server restarts."; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{new ExampleScript("Basic use", "set_max_health(256, 10)", "The entity will now only have 5 hearts max.")}; } } @api public static class entity_onfire extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity(Static.getInt32(args[0], t), t); return new CInt(Static.ticksToMs(ent.getFireTicks())/1000, t); } public String getName() { return "entity_onfire"; } public String docs() { return "int {entityID} Returns the number of seconds until this entity" + " stops being on fire, 0 if it already isn't."; } } @api public static class set_entity_onfire extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity(Static.getInt32(args[0], t), t); int setTicks = (int) Static.msToTicks(Static.getInt(args[1], t)*1000); if (setTicks < 0) { throw new Exceptions.FormatException("Seconds cannot be less than 0", t); } ent.setFireTicks(setTicks); return new CVoid(t); } public String getName() { return "set_entity_onfire"; } public String docs() { return "void {entityID, seconds} Sets the entity on fire for the" + " given number of seconds. Throws a FormatException" + " if seconds is less than 0."; } } @api public static class play_entity_effect extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity(Static.getInt32(args[0], t), t); MCEntityEffect mee; try { mee = MCEntityEffect.valueOf(args[1].val().toUpperCase()); } catch (IllegalArgumentException iae) { throw new Exceptions.FormatException("Unknown effect at arg 2.", t); } ent.playEffect(mee); return new CVoid(t); } public String getName() { return "play_entity_effect"; } public String docs() { return "void {entityID, effect} Plays the given visual effect on the" + " entity. Non-applicable effects simply won't happen. Note:" + " the death effect makes the mob invisible to players and" + " immune to melee attacks. When used on players, they are" + " shown the respawn menu, but because they are not actually" + " dead, they can only log out. Possible effects are: " + StringUtils.Join(MCEntityEffect.values(), ", ", ", or ", " or "); } } @api public static class get_mob_name extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); return new CString(le.getCustomName(), t); } public String getName() { return "get_mob_name"; } public String docs() { return "string {entityID} Returns the name of the given mob."; } } @api public static class set_mob_name extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity le = Static.getLivingEntity(Static.getInt32(args[0], t), t); le.setCustomName(args[1].val()); return new CVoid(t); } public String getName() { return "set_mob_name"; } public String docs() { return "void {entityID, name} Sets the name of the given mob. This" + " automatically truncates if it is more than 64 characters."; } } @api(environments = {CommandHelperEnvironment.class}) public static class spawn_entity extends EntityFunction { public ExceptionType[] thrown() { return new ExceptionType[]{ExceptionType.CastException, ExceptionType.FormatException, ExceptionType.BadEntityException, ExceptionType.InvalidWorldException, ExceptionType.PlayerOfflineException}; } public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCCommandSender cs = environment.getEnv(CommandHelperEnvironment.class).GetCommandSender(); int qty = 1; CArray ret = new CArray(t); MCEntityType entType; MCLocation l; MCEntity ent; if (args.length == 3) { l = ObjectGenerator.GetGenerator().location(args[2], null, t); } else { if (cs instanceof MCPlayer) { l = ((MCPlayer) cs).getLocation(); } else if (cs instanceof MCBlockCommandSender){ l = ((MCBlockCommandSender) cs).getBlock().getRelative(MCBlockFace.UP).getLocation(); } else { throw new ConfigRuntimeException("A physical commandsender must exist or location must be explicit.", ExceptionType.PlayerOfflineException, t); } } if (args.length >= 2) { qty = Static.getInt32(args[1], t); } try { entType = MCEntityType.valueOf(args[0].val().toUpperCase()); if (!entType.isSpawnable()) { throw new Exceptions.FormatException("Unspawnable entitytype: " + args[0].val(), t); } } catch (IllegalArgumentException iae) { throw new Exceptions.FormatException("Unknown entitytype: " + args[0].val(), t); } for (int i = 0; i < qty; i++) { switch (entType) { case DROPPED_ITEM: CArray c = new CArray(t); c.set("type", new CInt(1, t), t); c.set("qty", new CInt(qty, t), t); MCItemStack is = ObjectGenerator.GetGenerator().item(c, t); ent = l.getWorld().dropItem(l, is); qty = 0; break; case FALLING_BLOCK: ent = l.getWorld().spawnFallingBlock(l, 12, (byte) 0); break; default: ent = l.getWorld().spawn(l, entType); } ret.push(new CInt(ent.getEntityId(), t)); } return ret; } public String getName() { return "spawn_entity"; } public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } public String docs() { List<String> spawnable = new ArrayList<String>(); for (MCEntityType type : MCEntityType.values()) { if (type.isSpawnable()) { spawnable.add(type.name()); } } return "array {entityType, [qty], [location]} Spawns the specified number of entities of the given type" + " at the given location. Returns an array of entityIDs of what is spawned. Qty defaults to 1" + " and location defaults to the location of the commandsender, if it is a block or player." + " If the commandsender is console, location must be supplied. ---- Entitytype can be one of " + StringUtils.Join(spawnable, ", ", " or ", ", or ") + ". Falling_blocks will be sand by default, and dropped_items will be stone," + " as these entities already have their own functions for spawning."; } } @api public static class set_entity_rider extends EntitySetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity horse, rider; boolean success; if (args[0] instanceof CNull) { horse = null; } else { horse = Static.getEntity(Static.getInt32(args[0], t), t); } if (args[1] instanceof CNull) { rider = null; } else { rider = Static.getEntity(Static.getInt32(args[1], t), t); } if ((horse == null && rider == null) || horse == rider) { throw new Exceptions.FormatException("Horse and rider cannot be the same entity", t); } else if (horse == null) { success = rider.leaveVehicle(); } else if (rider == null) { success = horse.eject(); } else { success = horse.setPassenger(rider); } return new CBoolean(success, t); } public String getName() { return "set_entity_rider"; } public String docs() { return "boolean {horse, rider} Sets the way two entities are stacked. Horse and rider are entity ids." + " If rider is null, horse will eject its current rider, if it has one. If horse is null," + " rider will leave whatever it is riding. If horse and rider are both valid entities," + " rider will ride horse. The function returns the success of whatever operation is done." + " If horse and rider are both null, or otherwise the same, a FormatException is thrown."; } } @api public static class get_entity_rider extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity(Static.getInt32(args[0], t), t); if (ent.getPassenger() instanceof MCEntity) { return new CInt(ent.getPassenger().getEntityId(), t); } return null; } public String getName() { return "get_entity_rider"; } public String docs() { return "mixed {entityID} Returns the ID of the given entity's rider, or null if it doesn't have one."; } } @api public static class get_entity_vehicle extends EntityGetterFunction { public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCEntity ent = Static.getEntity(Static.getInt32(args[0], t), t); if (ent.isInsideVehicle()) { return new CInt(ent.getVehicle().getEntityId(), t); } return new CNull(t); } public String getName() { return "get_entity_vehicle"; } public String docs() { return "mixed {entityID} Returns the ID of the given entity's vehicle, or null if it doesn't have one."; } } }
true
true
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCLocation loc; int dist; List<String> types = new ArrayList<String>(); if (!(args[0] instanceof CArray)) { throw new ConfigRuntimeException("Expecting an array at parameter 1 of entities_in_radius", ExceptionType.BadEntityException, t); } loc = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t); dist = Static.getInt32(args[1], t); if (args.length == 3) { if (args[2] instanceof CArray) { CArray ta = (CArray) args[2]; for (int i = 0; i < ta.size(); i++) { types.add(ta.get(i, t).val()); } } else { types.add(args[2].val()); } types = prepareTypes(t, types); } // The idea and code comes from skore87 (http://forums.bukkit.org/members/skore87.105075/) // http://forums.bukkit.org/threads/getnearbyentities-of-a-location.101499/#post-1341141 int chunkRadius = dist < 16 ? 1 : (dist - (dist % 16)) / 16; CArray entities = new CArray(t); for (int chX = 0 - chunkRadius; chX <= chunkRadius; chX++) { for (int chZ = 0 - chunkRadius; chZ <= chunkRadius; chZ++) { for (MCEntity e : loc.getChunk().getEntities()) { if (e.getWorld() != loc.getWorld()) { continue; } if (e.getLocation().distance(loc) <= dist && e.getLocation().getBlock() != loc.getBlock()) { if (types.isEmpty() || types.contains(e.getType().name())) { entities.push(new CInt(e.getEntityId(), t)); } } } } } return entities; }
public Construct exec(Target t, Environment env, Construct... args) throws ConfigRuntimeException { MCPlayer p = env.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCLocation loc; int dist; List<String> types = new ArrayList<String>(); if (!(args[0] instanceof CArray)) { throw new ConfigRuntimeException("Expecting an array at parameter 1 of entities_in_radius", ExceptionType.BadEntityException, t); } loc = ObjectGenerator.GetGenerator().location(args[0], p != null ? p.getWorld() : null, t); dist = Static.getInt32(args[1], t); if (args.length == 3) { if (args[2] instanceof CArray) { CArray ta = (CArray) args[2]; for (int i = 0; i < ta.size(); i++) { types.add(ta.get(i, t).val()); } } else { types.add(args[2].val()); } types = prepareTypes(t, types); } // The idea and code comes from skore87 (http://forums.bukkit.org/members/skore87.105075/) // http://forums.bukkit.org/threads/getnearbyentities-of-a-location.101499/#post-1341141 int chunkRadius = dist < 16 ? 1 : (dist - (dist % 16)) / 16; CArray entities = new CArray(t); for (int chX = 0 - chunkRadius; chX <= chunkRadius; chX++) { for (int chZ = 0 - chunkRadius; chZ <= chunkRadius; chZ++) { for (MCEntity e : loc.getChunk().getEntities()) { if (!e.getWorld().equals(loc.getWorld())) { continue; } if (e.getLocation().distance(loc) <= dist && e.getLocation().getBlock() != loc.getBlock()) { if (types.isEmpty() || types.contains(e.getType().name())) { entities.push(new CInt(e.getEntityId(), t)); } } } } } return entities; }
diff --git a/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/merrimac/clad/AbstractListComposite.java b/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/merrimac/clad/AbstractListComposite.java index c7aa8050..fc6c213f 100644 --- a/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/merrimac/clad/AbstractListComposite.java +++ b/org.eclipse.bpmn2.modeler.core/src/org/eclipse/bpmn2/modeler/core/merrimac/clad/AbstractListComposite.java @@ -1,813 +1,813 @@ /******************************************************************************* * Copyright (c) 2011, 2012 Red Hat, Inc. * All rights reserved. * This program is 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: * Red Hat, Inc. - initial API and implementation * * @author Bob Brodt ******************************************************************************/ package org.eclipse.bpmn2.modeler.core.merrimac.clad; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.eclipse.bpmn2.modeler.core.Activator; import org.eclipse.bpmn2.modeler.core.merrimac.IConstants; import org.eclipse.bpmn2.modeler.core.merrimac.providers.TableCursor; import org.eclipse.bpmn2.modeler.core.utils.ModelUtil; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.BasicFeatureMap; import org.eclipse.emf.ecore.util.FeatureMap; import org.eclipse.emf.ecore.util.FeatureMap.Entry; import org.eclipse.emf.edit.provider.INotifyChangedListener; import org.eclipse.emf.transaction.RecordingCommand; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.IExpansionListener; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.plugin.AbstractUIPlugin; /** * @author Bob Brodt * */ public abstract class AbstractListComposite extends ListAndDetailCompositeBase implements INotifyChangedListener { public static final int HIDE_TITLE = 1 << 18; // Hide section title - useful if this is the only thing in the PropertySheetTab public static final int ADD_BUTTON = 1 << 19; // show "Add" button public static final int REMOVE_BUTTON = 1 << 20; // show "Remove" button public static final int MOVE_BUTTONS = 1 << 21; // show "Up" and "Down" buttons public static final int EDIT_BUTTON = 1 << 23; // show "Edit..." button public static final int SHOW_DETAILS = 1 << 24; // create a "Details" section public static final int DELETE_BUTTON = 1 << 25; // show "Delete" button - this uses EcoreUtil.delete() to kill the EObject public static final int COMPACT_STYLE = ( ADD_BUTTON|REMOVE_BUTTON|MOVE_BUTTONS|SHOW_DETAILS); public static final int DEFAULT_STYLE = ( ADD_BUTTON|REMOVE_BUTTON|MOVE_BUTTONS|EDIT_BUTTON|SHOW_DETAILS); public static final int DELETE_STYLE = ( ADD_BUTTON|DELETE_BUTTON|MOVE_BUTTONS|EDIT_BUTTON|SHOW_DETAILS); public static final int READ_ONLY_STYLE = ( ADD_BUTTON|REMOVE_BUTTON|MOVE_BUTTONS); public static final int CUSTOM_STYLES_MASK = ( HIDE_TITLE|ADD_BUTTON|REMOVE_BUTTON|MOVE_BUTTONS|EDIT_BUTTON|SHOW_DETAILS); public static final int CUSTOM_BUTTONS_MASK = ( ADD_BUTTON|REMOVE_BUTTON|MOVE_BUTTONS|EDIT_BUTTON); protected EStructuralFeature feature; // widgets SashForm sashForm; protected Section tableSection; protected ToolBarManager tableToolBarManager; protected Section detailSection; protected ToolBarManager detailToolBarManager; protected Table table; protected TableViewer tableViewer; protected AbstractDetailComposite detailComposite; boolean removeIsDelete = false; Action addAction; Action removeAction; Action upAction; Action downAction; Action editAction; protected ListCompositeColumnProvider columnProvider; protected ListCompositeContentProvider contentProvider; public AbstractListComposite(AbstractBpmn2PropertySection section) { this(section,DEFAULT_STYLE); } public AbstractListComposite(AbstractBpmn2PropertySection section, int style) { super(section.getSectionRoot(), style & ~CUSTOM_STYLES_MASK); this.style = style; } public AbstractListComposite(final Composite parent, int style) { super(parent, style & ~CUSTOM_STYLES_MASK); this.style = style; } abstract public void setListItemClass(EClass clazz); abstract public EClass getListItemClass(EObject object, EStructuralFeature feature); public EClass getListItemClass() { EClass eclass = getListItemClass(businessObject, feature); if (eclass==null) eclass = (EClass) feature.getEType(); return eclass; } public EClass getDefaultListItemClass(EObject object, EStructuralFeature feature) { EClass lic = getListItemClass(object,feature); if (lic!=null) return lic; lic = (EClass) feature.getEType(); EClass oc = object.eClass(); if (oc.isInstance(lic)) return oc; return lic; } /** * Create a default ColumnTableProvider if none was set in setTableProvider(); * @param object * @param feature * @return */ public ListCompositeColumnProvider getColumnProvider(EObject object, EStructuralFeature feature) { if (columnProvider==null) { final EList<EObject> list = (EList<EObject>)object.eGet(feature); final EClass listItemClass = getDefaultListItemClass(object, feature); boolean canModify; if (style==READ_ONLY_STYLE) canModify = false; else canModify = ((style & SHOW_DETAILS)==0 && (style & EDIT_BUTTON)==0) || ((style & SHOW_DETAILS)!=0 && (style & EDIT_BUTTON)!=0); columnProvider = new ListCompositeColumnProvider(this, canModify); // default is to include property name as the first column EStructuralFeature nameAttribute = listItemClass.getEStructuralFeature("name"); if (nameAttribute!=null) columnProvider.add(object, listItemClass, nameAttribute); for (EAttribute a1 : listItemClass.getEAllAttributes()) { if ("anyAttribute".equals(a1.getName())) { List<EStructuralFeature> anyAttributes = new ArrayList<EStructuralFeature>(); // are there any actual "anyAttribute" instances we can look at // to get the feature names and types from? // TODO: enhance the table to dynamically allow creation of new // columns which will be added to the "anyAttributes" for (EObject instance : list) { if (listItemClass.isInstance(instance)) { Object o = instance.eGet(a1); if (o instanceof BasicFeatureMap) { BasicFeatureMap map = (BasicFeatureMap)o; for (Entry entry : map) { EStructuralFeature f1 = entry.getEStructuralFeature(); if (f1 instanceof EAttribute && !anyAttributes.contains(f1)) { columnProvider.add(object, listItemClass, f1); anyAttributes.add(f1); } } } } } } else if (FeatureMap.Entry.class.equals(a1.getEType().getInstanceClass())) { // TODO: how do we handle these? if (a1 instanceof EAttribute) columnProvider.add(object, listItemClass, a1); } else { if (a1!=nameAttribute) columnProvider.add(object, listItemClass, a1); } } if (columnProvider.getColumns().size()==0) { feature = listItemClass.getEStructuralFeature("id"); columnProvider.addRaw(object, feature); } } return columnProvider; } public ListCompositeColumnProvider getColumnProvider() { return columnProvider; } /** * Override this to create your own Details section. This composite will be displayed * in a twistie section whenever the user selects an item from the table. The section * is automatically hidden when the table is collapsed. * * @param parent * @param eClass * @return */ abstract public AbstractDetailComposite createDetailComposite(Composite parent, Class eClass); public ListCompositeContentProvider getContentProvider(EObject object, EStructuralFeature feature, EList<EObject>list) { if (contentProvider==null) contentProvider = new ListCompositeContentProvider(this, object, feature, list); return contentProvider; } /** * Add a new list item. * @param object * @param feature * @return the new item to be added to the list, or null if item creation failed */ abstract protected EObject addListItem(EObject object, EStructuralFeature feature); /** * Edit the currently selected list item. * @param object * @param feature * @return the selected item if edit was successful, null if not */ abstract protected EObject editListItem(EObject object, EStructuralFeature feature); /** * Remove a list item (does not delete it from the model.) * @param object * @param feature * @param item * @return the item that follows the one removed, or null if the removed item was at the bottom of the list */ abstract protected Object removeListItem(EObject object, EStructuralFeature feature, int index); /** * Remove an item from the list and delete it from model. * @param object * @param feature * @param index * @return the item that follows the one deleted, or null if the deleted item was at the bottom of the list */ abstract protected Object deleteListItem(EObject object, EStructuralFeature feature, int index); /** * Move the currently selected item up in the list. * @param object * @param feature * @param index * @return the selected item if it was moved, null if the item is already at the top of the list. */ abstract protected Object moveListItemUp(EObject object, EStructuralFeature feature, int index); /** * Move the currently selected item down in the list. * @param object * @param feature * @param index * @return the selected item if it was moved, null if the item is already at the bottom of the list. */ abstract protected Object moveListItemDown(EObject object, EStructuralFeature feature, int index); protected int[] buildIndexMap(EObject object, EStructuralFeature feature) { EList<EObject> list = (EList<EObject>)object.eGet(feature); EClass listItemClass = getListItemClass(object,feature); int[] map = null; if (listItemClass!=null) { int[] tempMap = new int[list.size()]; int index = 0; int realIndex = 0; for (EObject o : list) { EClass ec = o.eClass(); if (ec == listItemClass) { tempMap[index] = realIndex; ++index; } ++realIndex; } map = new int[index]; for (int i=0; i<index; ++i) map[i] = tempMap[i]; } else { map = new int[list.size()]; for (int i=0; i<map.length; ++i) map[i] = i; } return map; } public void setTitle(String title) { if (tableSection!=null) tableSection.setText(title); } public void bindList(final EObject theobject, final EStructuralFeature thefeature) { if (!(theobject.eGet(thefeature) instanceof EList<?>)) { return; } // Class<?> clazz = thefeature.getEType().getInstanceClass(); // if (!EObject.class.isAssignableFrom(clazz)) { // return; // } setBusinessObject(theobject); this.feature = thefeature; final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); final EClass listItemClass = getDefaultListItemClass(businessObject,feature); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(listItemClass); } else { label = ModelUtil.getLabel(listItemClass); } final String prefName = "list."+listItemClass.getName()+".expanded"; //////////////////////////////////////////////////////////// // Collect columns to be displayed and build column provider //////////////////////////////////////////////////////////// if (createColumnProvider(businessObject, feature) <= 0) { dispose(); return; } //////////////////////////////////////////////////////////// // SashForm contains the table section and a possible // details section //////////////////////////////////////////////////////////// if ((style & HIDE_TITLE)==0 || (style & SHOW_DETAILS)!=0) { // display title in the table section and/or show a details section // SHOW_DETAILS forces drawing of a section title sashForm = new SashForm(this, SWT.NONE); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); tableSection = createListSection(sashForm,label); if ((style & SHOW_DETAILS)!=0) { detailSection = createDetailSection(sashForm, label); detailSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState()) { detailSection.setVisible(false); if (editAction!=null) editAction.setChecked(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { redrawPage(); } }); tableSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState() && detailSection!=null) { detailSection.setVisible(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { preferenceStore.setValue(prefName, e.getState()); redrawPage(); } }); sashForm.setWeights(new int[] { 50, 50 }); } else sashForm.setWeights(new int[] { 100 }); } else { tableSection = createListSection(sashForm,label); } //////////////////////////////////////////////////////////// // Create table viewer and cell editors //////////////////////////////////////////////////////////// tableViewer = new TableViewer(table); columnProvider.createTableLayout(table); columnProvider.setTableViewer(tableViewer); tableViewer.setLabelProvider(columnProvider); tableViewer.setCellModifier(columnProvider); tableViewer.setContentProvider(getContentProvider(businessObject,feature,list)); tableViewer.setColumnProperties(columnProvider.getColumnProperties()); tableViewer.setCellEditors(columnProvider.createCellEditors(table)); //////////////////////////////////////////////////////////// // Create handlers //////////////////////////////////////////////////////////// if ((style & SHOW_DETAILS)!=0) { // && (style & EDIT_BUTTON)==0) { tableViewer.addDoubleClickListener( new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { showDetails(true); } }); } tableViewer.addPostSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { boolean enable = !event.getSelection().isEmpty(); if ((style & SHOW_DETAILS)!=0) { if (detailSection!=null && detailSection.isVisible()) showDetails(true); // else if ((style & EDIT_BUTTON)==0) // showDetails(true); } if (removeAction!=null) removeAction.setEnabled(enable); if (editAction!=null) editAction.setEnabled(enable); if (upAction!=null && downAction!=null) { int i = table.getSelectionIndex(); if (i>0) upAction.setEnabled(true); else upAction.setEnabled(false); if (i>=0 && i<table.getItemCount()-1) downAction.setEnabled(true); else downAction.setEnabled(false); } } }); tableViewer.setInput(list); // a TableCursor allows navigation of the table with keys TableCursor.create(table, tableViewer); redrawPage(); boolean expanded = preferenceStore.getBoolean(prefName); if (expanded && tableSection!=null) tableSection.setExpanded(true); } private void showDetails(boolean enable) { if (detailSection!=null) { if (enable) { IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection(); if (selection.getFirstElement() instanceof EObject) { EObject o = (EObject)selection.getFirstElement(); if (detailComposite!=null) detailComposite.dispose(); detailComposite = createDetailComposite(detailSection, o.eClass().getInstanceClass()); detailSection.setClient(detailComposite); toolkit.adapt(detailComposite); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(o); } else { label = ModelUtil.getLabel(o); } detailSection.setText(label+" Details"); ((AbstractDetailComposite)detailComposite).setBusinessObject(o); enable = !detailComposite.isEmpty(); detailSection.setExpanded(enable); if (!enable && editAction!=null) editAction.setEnabled(enable); } } detailSection.setVisible(enable); detailSection.setExpanded(enable); if (editAction!=null) editAction.setChecked(enable); sashForm.setWeights(new int[] { 50, 50 }); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); redrawPage(); } } /** * @param theobject * @param thefeature * @return */ protected int createColumnProvider(EObject theobject, EStructuralFeature thefeature) { if (columnProvider==null) { EClass listItemClass = getDefaultListItemClass(theobject,thefeature); columnProvider = getColumnProvider(theobject, thefeature); // remove disabled columns List<TableColumn> removed = new ArrayList<TableColumn>(); for (TableColumn tc : (List<TableColumn>)columnProvider.getColumns()) { if (tc.feature!=null) { if (!"id".equals(tc.feature.getName())) { if (!isModelObjectEnabled(listItemClass, tc.feature)) { removed.add(tc); } } } } if (removed.size()>0) { for (TableColumn tc : removed) columnProvider.remove(tc); } } return columnProvider.getColumns().size(); } private Section createListSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.COMPACT | ExpandableComposite.TITLE_BAR); section.setText(label+" List"); Composite tableComposite = toolkit.createComposite(section, SWT.NONE); section.setClient(tableComposite); tableComposite.setLayout(new GridLayout(1, false)); table = toolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.V_SCROLL); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1); gridData.widthHint = 100; gridData.heightHint = 100; table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); tableToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = tableToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/add.png"); if ((style & ADD_BUTTON)!=0) { addAction = new Action("Add", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = addListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); showDetails(true); } } }); } }; tableToolBarManager.add(addAction); } if ((style & DELETE_BUTTON)!=0 || (style & REMOVE_BUTTON)!=0) { if ((style & DELETE_BUTTON)!=0) { removeIsDelete = true; id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/delete.png"); } else { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/remove.png"); } removeAction = new Action(removeIsDelete ? "Delete" : "Remove", id) { @Override public void run() { super.run(); showDetails(false); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { - int i = table.getSelectionIndex(); + final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); + int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item; if (removeIsDelete) item = deleteListItem(businessObject,feature,i); else item = removeListItem(businessObject,feature,i); - final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); if (item!=null) { if (i>=list.size()) i = list.size() - 1; if (i>=0) tableViewer.setSelection(new StructuredSelection(item)); } Display.getDefault().asyncExec( new Runnable() { @Override public void run() { showDetails(false); } }); } }); } }; tableToolBarManager.add(removeAction); removeAction.setEnabled(false); } if ((style & MOVE_BUTTONS)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/up.png"); upAction = new Action("Move Up", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { - int i = table.getSelectionIndex(); + final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); + int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item = moveListItemUp(businessObject,feature,i); - final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(upAction); upAction.setEnabled(false); id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/down.png"); downAction = new Action("Move Down", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { - int i = table.getSelectionIndex(); + final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); + int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item = moveListItemDown(businessObject,feature,i); - final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(downAction); downAction.setEnabled(false); } if ((style & EDIT_BUTTON)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/edit.png"); editAction = new Action("Edit", id) { @Override public void run() { super.run(); if ((style & SHOW_DETAILS)!=0) { if (!editAction.isChecked()) { showDetails(true); } else { showDetails(false); } } else { editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = editListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); } } }); } } }; tableToolBarManager.add(editAction); editAction.setEnabled(false); } tableToolBarManager.update(true); section.setTextClient(toolbar); // hook a resource change listener to this Table Control table.setData(IConstants.NOTIFY_CHANGE_LISTENER_KEY,this); return section; } protected Section createDetailSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); section.setText(label+" Details"); section.setVisible(false); detailToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = detailToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/close.png"); detailToolBarManager.add( new Action("Close", id) { @Override public void run() { super.run(); showDetails(false); } }); detailToolBarManager.update(true); section.setTextClient(toolbar); return section; } @SuppressWarnings("unchecked") @Override public void notifyChanged(Notification notification) { EList<EObject> table = (EList<EObject>)businessObject.eGet(feature); Object n = notification.getNotifier(); if (table.contains(n)) { tableViewer.setInput(table); return; // quick exit before the exhaustive search that follows } if (n instanceof EObject) { HashSet<Object> visited = new HashSet<Object>(); if (refreshIfNeededRecursive((EObject)n, table, visited)) return; } } @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(EObject value, EList<EObject> table, HashSet<Object> visited) { for (EStructuralFeature f : value.eClass().getEAllStructuralFeatures()) { try { Object v = value.eGet(f); if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (!((List)v).isEmpty()) if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeeded((EObject)v, table)) return true; } } } catch (Exception e) { // some getters may throw exceptions - ignore those } } return refreshIfNeeded(value, table); } static int count = 0; @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(List list, EList<EObject> table, HashSet<Object> visited) { for (Object v : list) { if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeededRecursive((EObject)v, table, visited)) return true; } } } return false; } private boolean refreshIfNeeded(EObject value, EList<EObject> table) { if (table.contains(value)) { tableViewer.setInput(table); return true; } return false; } public void setVisible (boolean visible) { super.setVisible(visible); Object data = getLayoutData(); if (data instanceof GridData) { ((GridData)data).exclude = !visible; } } }
false
true
public void bindList(final EObject theobject, final EStructuralFeature thefeature) { if (!(theobject.eGet(thefeature) instanceof EList<?>)) { return; } // Class<?> clazz = thefeature.getEType().getInstanceClass(); // if (!EObject.class.isAssignableFrom(clazz)) { // return; // } setBusinessObject(theobject); this.feature = thefeature; final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); final EClass listItemClass = getDefaultListItemClass(businessObject,feature); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(listItemClass); } else { label = ModelUtil.getLabel(listItemClass); } final String prefName = "list."+listItemClass.getName()+".expanded"; //////////////////////////////////////////////////////////// // Collect columns to be displayed and build column provider //////////////////////////////////////////////////////////// if (createColumnProvider(businessObject, feature) <= 0) { dispose(); return; } //////////////////////////////////////////////////////////// // SashForm contains the table section and a possible // details section //////////////////////////////////////////////////////////// if ((style & HIDE_TITLE)==0 || (style & SHOW_DETAILS)!=0) { // display title in the table section and/or show a details section // SHOW_DETAILS forces drawing of a section title sashForm = new SashForm(this, SWT.NONE); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); tableSection = createListSection(sashForm,label); if ((style & SHOW_DETAILS)!=0) { detailSection = createDetailSection(sashForm, label); detailSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState()) { detailSection.setVisible(false); if (editAction!=null) editAction.setChecked(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { redrawPage(); } }); tableSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState() && detailSection!=null) { detailSection.setVisible(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { preferenceStore.setValue(prefName, e.getState()); redrawPage(); } }); sashForm.setWeights(new int[] { 50, 50 }); } else sashForm.setWeights(new int[] { 100 }); } else { tableSection = createListSection(sashForm,label); } //////////////////////////////////////////////////////////// // Create table viewer and cell editors //////////////////////////////////////////////////////////// tableViewer = new TableViewer(table); columnProvider.createTableLayout(table); columnProvider.setTableViewer(tableViewer); tableViewer.setLabelProvider(columnProvider); tableViewer.setCellModifier(columnProvider); tableViewer.setContentProvider(getContentProvider(businessObject,feature,list)); tableViewer.setColumnProperties(columnProvider.getColumnProperties()); tableViewer.setCellEditors(columnProvider.createCellEditors(table)); //////////////////////////////////////////////////////////// // Create handlers //////////////////////////////////////////////////////////// if ((style & SHOW_DETAILS)!=0) { // && (style & EDIT_BUTTON)==0) { tableViewer.addDoubleClickListener( new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { showDetails(true); } }); } tableViewer.addPostSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { boolean enable = !event.getSelection().isEmpty(); if ((style & SHOW_DETAILS)!=0) { if (detailSection!=null && detailSection.isVisible()) showDetails(true); // else if ((style & EDIT_BUTTON)==0) // showDetails(true); } if (removeAction!=null) removeAction.setEnabled(enable); if (editAction!=null) editAction.setEnabled(enable); if (upAction!=null && downAction!=null) { int i = table.getSelectionIndex(); if (i>0) upAction.setEnabled(true); else upAction.setEnabled(false); if (i>=0 && i<table.getItemCount()-1) downAction.setEnabled(true); else downAction.setEnabled(false); } } }); tableViewer.setInput(list); // a TableCursor allows navigation of the table with keys TableCursor.create(table, tableViewer); redrawPage(); boolean expanded = preferenceStore.getBoolean(prefName); if (expanded && tableSection!=null) tableSection.setExpanded(true); } private void showDetails(boolean enable) { if (detailSection!=null) { if (enable) { IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection(); if (selection.getFirstElement() instanceof EObject) { EObject o = (EObject)selection.getFirstElement(); if (detailComposite!=null) detailComposite.dispose(); detailComposite = createDetailComposite(detailSection, o.eClass().getInstanceClass()); detailSection.setClient(detailComposite); toolkit.adapt(detailComposite); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(o); } else { label = ModelUtil.getLabel(o); } detailSection.setText(label+" Details"); ((AbstractDetailComposite)detailComposite).setBusinessObject(o); enable = !detailComposite.isEmpty(); detailSection.setExpanded(enable); if (!enable && editAction!=null) editAction.setEnabled(enable); } } detailSection.setVisible(enable); detailSection.setExpanded(enable); if (editAction!=null) editAction.setChecked(enable); sashForm.setWeights(new int[] { 50, 50 }); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); redrawPage(); } } /** * @param theobject * @param thefeature * @return */ protected int createColumnProvider(EObject theobject, EStructuralFeature thefeature) { if (columnProvider==null) { EClass listItemClass = getDefaultListItemClass(theobject,thefeature); columnProvider = getColumnProvider(theobject, thefeature); // remove disabled columns List<TableColumn> removed = new ArrayList<TableColumn>(); for (TableColumn tc : (List<TableColumn>)columnProvider.getColumns()) { if (tc.feature!=null) { if (!"id".equals(tc.feature.getName())) { if (!isModelObjectEnabled(listItemClass, tc.feature)) { removed.add(tc); } } } } if (removed.size()>0) { for (TableColumn tc : removed) columnProvider.remove(tc); } } return columnProvider.getColumns().size(); } private Section createListSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.COMPACT | ExpandableComposite.TITLE_BAR); section.setText(label+" List"); Composite tableComposite = toolkit.createComposite(section, SWT.NONE); section.setClient(tableComposite); tableComposite.setLayout(new GridLayout(1, false)); table = toolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.V_SCROLL); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1); gridData.widthHint = 100; gridData.heightHint = 100; table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); tableToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = tableToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/add.png"); if ((style & ADD_BUTTON)!=0) { addAction = new Action("Add", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = addListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); showDetails(true); } } }); } }; tableToolBarManager.add(addAction); } if ((style & DELETE_BUTTON)!=0 || (style & REMOVE_BUTTON)!=0) { if ((style & DELETE_BUTTON)!=0) { removeIsDelete = true; id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/delete.png"); } else { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/remove.png"); } removeAction = new Action(removeIsDelete ? "Delete" : "Remove", id) { @Override public void run() { super.run(); showDetails(false); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { int i = table.getSelectionIndex(); Object item; if (removeIsDelete) item = deleteListItem(businessObject,feature,i); else item = removeListItem(businessObject,feature,i); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); if (item!=null) { if (i>=list.size()) i = list.size() - 1; if (i>=0) tableViewer.setSelection(new StructuredSelection(item)); } Display.getDefault().asyncExec( new Runnable() { @Override public void run() { showDetails(false); } }); } }); } }; tableToolBarManager.add(removeAction); removeAction.setEnabled(false); } if ((style & MOVE_BUTTONS)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/up.png"); upAction = new Action("Move Up", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { int i = table.getSelectionIndex(); Object item = moveListItemUp(businessObject,feature,i); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(upAction); upAction.setEnabled(false); id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/down.png"); downAction = new Action("Move Down", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { int i = table.getSelectionIndex(); Object item = moveListItemDown(businessObject,feature,i); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(downAction); downAction.setEnabled(false); } if ((style & EDIT_BUTTON)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/edit.png"); editAction = new Action("Edit", id) { @Override public void run() { super.run(); if ((style & SHOW_DETAILS)!=0) { if (!editAction.isChecked()) { showDetails(true); } else { showDetails(false); } } else { editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = editListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); } } }); } } }; tableToolBarManager.add(editAction); editAction.setEnabled(false); } tableToolBarManager.update(true); section.setTextClient(toolbar); // hook a resource change listener to this Table Control table.setData(IConstants.NOTIFY_CHANGE_LISTENER_KEY,this); return section; } protected Section createDetailSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); section.setText(label+" Details"); section.setVisible(false); detailToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = detailToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/close.png"); detailToolBarManager.add( new Action("Close", id) { @Override public void run() { super.run(); showDetails(false); } }); detailToolBarManager.update(true); section.setTextClient(toolbar); return section; } @SuppressWarnings("unchecked") @Override public void notifyChanged(Notification notification) { EList<EObject> table = (EList<EObject>)businessObject.eGet(feature); Object n = notification.getNotifier(); if (table.contains(n)) { tableViewer.setInput(table); return; // quick exit before the exhaustive search that follows } if (n instanceof EObject) { HashSet<Object> visited = new HashSet<Object>(); if (refreshIfNeededRecursive((EObject)n, table, visited)) return; } } @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(EObject value, EList<EObject> table, HashSet<Object> visited) { for (EStructuralFeature f : value.eClass().getEAllStructuralFeatures()) { try { Object v = value.eGet(f); if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (!((List)v).isEmpty()) if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeeded((EObject)v, table)) return true; } } } catch (Exception e) { // some getters may throw exceptions - ignore those } } return refreshIfNeeded(value, table); } static int count = 0; @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(List list, EList<EObject> table, HashSet<Object> visited) { for (Object v : list) { if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeededRecursive((EObject)v, table, visited)) return true; } } } return false; } private boolean refreshIfNeeded(EObject value, EList<EObject> table) { if (table.contains(value)) { tableViewer.setInput(table); return true; } return false; } public void setVisible (boolean visible) { super.setVisible(visible); Object data = getLayoutData(); if (data instanceof GridData) { ((GridData)data).exclude = !visible; } } }
public void bindList(final EObject theobject, final EStructuralFeature thefeature) { if (!(theobject.eGet(thefeature) instanceof EList<?>)) { return; } // Class<?> clazz = thefeature.getEType().getInstanceClass(); // if (!EObject.class.isAssignableFrom(clazz)) { // return; // } setBusinessObject(theobject); this.feature = thefeature; final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); final EClass listItemClass = getDefaultListItemClass(businessObject,feature); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(listItemClass); } else { label = ModelUtil.getLabel(listItemClass); } final String prefName = "list."+listItemClass.getName()+".expanded"; //////////////////////////////////////////////////////////// // Collect columns to be displayed and build column provider //////////////////////////////////////////////////////////// if (createColumnProvider(businessObject, feature) <= 0) { dispose(); return; } //////////////////////////////////////////////////////////// // SashForm contains the table section and a possible // details section //////////////////////////////////////////////////////////// if ((style & HIDE_TITLE)==0 || (style & SHOW_DETAILS)!=0) { // display title in the table section and/or show a details section // SHOW_DETAILS forces drawing of a section title sashForm = new SashForm(this, SWT.NONE); sashForm.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1)); tableSection = createListSection(sashForm,label); if ((style & SHOW_DETAILS)!=0) { detailSection = createDetailSection(sashForm, label); detailSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState()) { detailSection.setVisible(false); if (editAction!=null) editAction.setChecked(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { redrawPage(); } }); tableSection.addExpansionListener(new IExpansionListener() { @Override public void expansionStateChanging(ExpansionEvent e) { if (!e.getState() && detailSection!=null) { detailSection.setVisible(false); } } @Override public void expansionStateChanged(ExpansionEvent e) { preferenceStore.setValue(prefName, e.getState()); redrawPage(); } }); sashForm.setWeights(new int[] { 50, 50 }); } else sashForm.setWeights(new int[] { 100 }); } else { tableSection = createListSection(sashForm,label); } //////////////////////////////////////////////////////////// // Create table viewer and cell editors //////////////////////////////////////////////////////////// tableViewer = new TableViewer(table); columnProvider.createTableLayout(table); columnProvider.setTableViewer(tableViewer); tableViewer.setLabelProvider(columnProvider); tableViewer.setCellModifier(columnProvider); tableViewer.setContentProvider(getContentProvider(businessObject,feature,list)); tableViewer.setColumnProperties(columnProvider.getColumnProperties()); tableViewer.setCellEditors(columnProvider.createCellEditors(table)); //////////////////////////////////////////////////////////// // Create handlers //////////////////////////////////////////////////////////// if ((style & SHOW_DETAILS)!=0) { // && (style & EDIT_BUTTON)==0) { tableViewer.addDoubleClickListener( new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { showDetails(true); } }); } tableViewer.addPostSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { boolean enable = !event.getSelection().isEmpty(); if ((style & SHOW_DETAILS)!=0) { if (detailSection!=null && detailSection.isVisible()) showDetails(true); // else if ((style & EDIT_BUTTON)==0) // showDetails(true); } if (removeAction!=null) removeAction.setEnabled(enable); if (editAction!=null) editAction.setEnabled(enable); if (upAction!=null && downAction!=null) { int i = table.getSelectionIndex(); if (i>0) upAction.setEnabled(true); else upAction.setEnabled(false); if (i>=0 && i<table.getItemCount()-1) downAction.setEnabled(true); else downAction.setEnabled(false); } } }); tableViewer.setInput(list); // a TableCursor allows navigation of the table with keys TableCursor.create(table, tableViewer); redrawPage(); boolean expanded = preferenceStore.getBoolean(prefName); if (expanded && tableSection!=null) tableSection.setExpanded(true); } private void showDetails(boolean enable) { if (detailSection!=null) { if (enable) { IStructuredSelection selection = (IStructuredSelection)tableViewer.getSelection(); if (selection.getFirstElement() instanceof EObject) { EObject o = (EObject)selection.getFirstElement(); if (detailComposite!=null) detailComposite.dispose(); detailComposite = createDetailComposite(detailSection, o.eClass().getInstanceClass()); detailSection.setClient(detailComposite); toolkit.adapt(detailComposite); Composite parent = this.getParent(); String label; if (parent instanceof AbstractDetailComposite) { label = ((AbstractDetailComposite)parent).getPropertiesProvider().getLabel(o); } else { label = ModelUtil.getLabel(o); } detailSection.setText(label+" Details"); ((AbstractDetailComposite)detailComposite).setBusinessObject(o); enable = !detailComposite.isEmpty(); detailSection.setExpanded(enable); if (!enable && editAction!=null) editAction.setEnabled(enable); } } detailSection.setVisible(enable); detailSection.setExpanded(enable); if (editAction!=null) editAction.setChecked(enable); sashForm.setWeights(new int[] { 50, 50 }); final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); redrawPage(); } } /** * @param theobject * @param thefeature * @return */ protected int createColumnProvider(EObject theobject, EStructuralFeature thefeature) { if (columnProvider==null) { EClass listItemClass = getDefaultListItemClass(theobject,thefeature); columnProvider = getColumnProvider(theobject, thefeature); // remove disabled columns List<TableColumn> removed = new ArrayList<TableColumn>(); for (TableColumn tc : (List<TableColumn>)columnProvider.getColumns()) { if (tc.feature!=null) { if (!"id".equals(tc.feature.getName())) { if (!isModelObjectEnabled(listItemClass, tc.feature)) { removed.add(tc); } } } } if (removed.size()>0) { for (TableColumn tc : removed) columnProvider.remove(tc); } } return columnProvider.getColumns().size(); } private Section createListSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.COMPACT | ExpandableComposite.TITLE_BAR); section.setText(label+" List"); Composite tableComposite = toolkit.createComposite(section, SWT.NONE); section.setClient(tableComposite); tableComposite.setLayout(new GridLayout(1, false)); table = toolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.V_SCROLL); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1); gridData.widthHint = 100; gridData.heightHint = 100; table.setLayoutData(gridData); table.setLinesVisible(true); table.setHeaderVisible(true); tableToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = tableToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/add.png"); if ((style & ADD_BUTTON)!=0) { addAction = new Action("Add", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = addListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); showDetails(true); } } }); } }; tableToolBarManager.add(addAction); } if ((style & DELETE_BUTTON)!=0 || (style & REMOVE_BUTTON)!=0) { if ((style & DELETE_BUTTON)!=0) { removeIsDelete = true; id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/delete.png"); } else { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/remove.png"); } removeAction = new Action(removeIsDelete ? "Delete" : "Remove", id) { @Override public void run() { super.run(); showDetails(false); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item; if (removeIsDelete) item = deleteListItem(businessObject,feature,i); else item = removeListItem(businessObject,feature,i); tableViewer.setInput(list); if (item!=null) { if (i>=list.size()) i = list.size() - 1; if (i>=0) tableViewer.setSelection(new StructuredSelection(item)); } Display.getDefault().asyncExec( new Runnable() { @Override public void run() { showDetails(false); } }); } }); } }; tableToolBarManager.add(removeAction); removeAction.setEnabled(false); } if ((style & MOVE_BUTTONS)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/up.png"); upAction = new Action("Move Up", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item = moveListItemUp(businessObject,feature,i); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(upAction); upAction.setEnabled(false); id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/down.png"); downAction = new Action("Move Down", id) { @Override public void run() { super.run(); editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); int i = list.indexOf(((IStructuredSelection)tableViewer.getSelection()).getFirstElement()); Object item = moveListItemDown(businessObject,feature,i); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(item)); } }); } }; tableToolBarManager.add(downAction); downAction.setEnabled(false); } if ((style & EDIT_BUTTON)!=0) { id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/edit.png"); editAction = new Action("Edit", id) { @Override public void run() { super.run(); if ((style & SHOW_DETAILS)!=0) { if (!editAction.isChecked()) { showDetails(true); } else { showDetails(false); } } else { editingDomain.getCommandStack().execute(new RecordingCommand(editingDomain) { @Override protected void doExecute() { EObject newItem = editListItem(businessObject,feature); if (newItem!=null) { final EList<EObject> list = (EList<EObject>)businessObject.eGet(feature); tableViewer.setInput(list); tableViewer.setSelection(new StructuredSelection(newItem)); } } }); } } }; tableToolBarManager.add(editAction); editAction.setEnabled(false); } tableToolBarManager.update(true); section.setTextClient(toolbar); // hook a resource change listener to this Table Control table.setData(IConstants.NOTIFY_CHANGE_LISTENER_KEY,this); return section; } protected Section createDetailSection(Composite parent, String label) { Section section = toolkit.createSection(parent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); section.setText(label+" Details"); section.setVisible(false); detailToolBarManager = new ToolBarManager(SWT.FLAT); ToolBar toolbar = detailToolBarManager.createControl(section); ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/20/close.png"); detailToolBarManager.add( new Action("Close", id) { @Override public void run() { super.run(); showDetails(false); } }); detailToolBarManager.update(true); section.setTextClient(toolbar); return section; } @SuppressWarnings("unchecked") @Override public void notifyChanged(Notification notification) { EList<EObject> table = (EList<EObject>)businessObject.eGet(feature); Object n = notification.getNotifier(); if (table.contains(n)) { tableViewer.setInput(table); return; // quick exit before the exhaustive search that follows } if (n instanceof EObject) { HashSet<Object> visited = new HashSet<Object>(); if (refreshIfNeededRecursive((EObject)n, table, visited)) return; } } @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(EObject value, EList<EObject> table, HashSet<Object> visited) { for (EStructuralFeature f : value.eClass().getEAllStructuralFeatures()) { try { Object v = value.eGet(f); if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (!((List)v).isEmpty()) if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeeded((EObject)v, table)) return true; } } } catch (Exception e) { // some getters may throw exceptions - ignore those } } return refreshIfNeeded(value, table); } static int count = 0; @SuppressWarnings("rawtypes") private boolean refreshIfNeededRecursive(List list, EList<EObject> table, HashSet<Object> visited) { for (Object v : list) { if (!visited.contains(v)) { visited.add(v); if (v instanceof List) { if (refreshIfNeededRecursive((List)v, table, visited)) return true; } else if (v instanceof EObject) { if (refreshIfNeededRecursive((EObject)v, table, visited)) return true; } } } return false; } private boolean refreshIfNeeded(EObject value, EList<EObject> table) { if (table.contains(value)) { tableViewer.setInput(table); return true; } return false; } public void setVisible (boolean visible) { super.setVisible(visible); Object data = getLayoutData(); if (data instanceof GridData) { ((GridData)data).exclude = !visible; } } }
diff --git a/src/main/java/com/licel/jcardsim/crypto/ByteContainer.java b/src/main/java/com/licel/jcardsim/crypto/ByteContainer.java index c661b08..5eee92a 100644 --- a/src/main/java/com/licel/jcardsim/crypto/ByteContainer.java +++ b/src/main/java/com/licel/jcardsim/crypto/ByteContainer.java @@ -1,169 +1,169 @@ /* * Copyright 2011 Licel LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.licel.jcardsim.crypto; import java.math.BigInteger; import javacard.framework.JCSystem; import javacard.framework.Util; import javacard.security.CryptoException; /** * This class contains byte array, initialization flag of this * array and memory type */ public final class ByteContainer { private byte[] data; private boolean isInitialized; private byte memoryType; /** * Construct <code>ByteContainer</code> * with memory type <code>JCSystem.MEMORY_TYPE_PERSISTENT</code> */ public ByteContainer() { this(JCSystem.MEMORY_TYPE_PERSISTENT); } /** * Construct <code>ByteContainer</code> * with defined memory type * @param memoryType memoryType from JCSystem.MEMORY_.. */ public ByteContainer(byte memoryType) { isInitialized = false; this.memoryType = memoryType; } /** * Construct <code>ByteContainer</code> * with memory type <code>JCSystem.MEMORY_TYPE_PERSISTENT</code> * and fills it by byte representation of <code>BigInteger</code> * @param bInteger <code>BigInteger</code> object */ public ByteContainer(BigInteger bInteger) { this(bInteger.toByteArray(), (short) 0, (short) bInteger.toByteArray().length); } /** * Construct <code>ByteContainer</code> * with memory type <code>JCSystem.MEMORY_TYPE_PERSISTENT</code> * and fills it by defined byte array * @param buff byte array * @param offset * @param length */ public ByteContainer(byte[] buff, short offset, short length) { setBytes(buff, offset, length); } /** * Fills <code>ByteContainer</code>by byte representation of <code>BigInteger</code> * @param bInteger */ public void setBigInteger(BigInteger bInteger) { setBytes(bInteger.toByteArray()); } /** * Fills <code>ByteContainer</code>by defined byte array * @param buff */ public void setBytes(byte[] buff) { setBytes(buff, (short) 0, (short) buff.length); } /** * Fills <code>ByteContainer</code>by defined byte array * @param buff * @param offset * @param length */ public void setBytes(byte[] buff, short offset, short length) { - if (data == null) { + if (data == null || data.length != length) { switch (memoryType) { case JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; case JCSystem.MEMORY_TYPE_TRANSIENT_RESET: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; default: data = new byte[length]; break; } } Util.arrayCopy(buff, offset, data, (short) 0, length); isInitialized = true; } /** * Return <code>BigInteger</code> representation of the <code>ByteContainer</code> * @return BigInteger */ public BigInteger getBigInteger() { if (!isInitialized) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } return new BigInteger(1, data); } /** * Return transient plain byte array representation of the <code>ByteContainer</code> * @param event type of transient byte array * @return plain byte array */ public byte[] getBytes(byte event) { if (!isInitialized) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } byte[] result = JCSystem.makeTransientByteArray((short) data.length, event); getBytes(result, (short) 0); return result; } /** * Copy byte array representation of the <code>ByteContainer</code> * @param dest destination byte array * @param offset * @return bytes copies */ public short getBytes(byte[] dest, short offset) { if (!isInitialized) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } if (dest.length - offset < data.length) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } Util.arrayCopy(data, (short) 0, dest, offset, (short) data.length); // https://code.google.com/p/jcardsim/issues/detail?id=14 return (short)data.length; } /** * Clear internal structure of the <code>ByteContainer</code> */ public void clear() { if (data != null) { Util.arrayFillNonAtomic(data, (short) 0, (short) data.length, (byte) 0); } isInitialized = false; } public boolean isInitialized() { return isInitialized; } }
true
true
public void setBytes(byte[] buff, short offset, short length) { if (data == null) { switch (memoryType) { case JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; case JCSystem.MEMORY_TYPE_TRANSIENT_RESET: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; default: data = new byte[length]; break; } } Util.arrayCopy(buff, offset, data, (short) 0, length); isInitialized = true; }
public void setBytes(byte[] buff, short offset, short length) { if (data == null || data.length != length) { switch (memoryType) { case JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; case JCSystem.MEMORY_TYPE_TRANSIENT_RESET: data = JCSystem.makeTransientByteArray(length, JCSystem.CLEAR_ON_DESELECT); break; default: data = new byte[length]; break; } } Util.arrayCopy(buff, offset, data, (short) 0, length); isInitialized = true; }
diff --git a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/BindingTableEditor.java b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/BindingTableEditor.java index 2d03f371..9e701e5b 100644 --- a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/BindingTableEditor.java +++ b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/BindingTableEditor.java @@ -1,355 +1,355 @@ /******************************************************************************* * Copyright (c) 2010 BestSolution.at 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: * Tom Schindl <tom.schindl@bestsolution.at> - initial API and implementation ******************************************************************************/ package org.eclipse.e4.tools.emf.ui.internal.common.component; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.eclipse.core.databinding.observable.list.IObservableList; import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.property.list.IListProperty; import org.eclipse.e4.tools.emf.ui.common.EStackLayout; import org.eclipse.e4.tools.emf.ui.common.Util; import org.eclipse.e4.tools.emf.ui.common.component.AbstractComponentEditor; import org.eclipse.e4.tools.emf.ui.internal.ResourceProvider; import org.eclipse.e4.tools.emf.ui.internal.common.ComponentLabelProvider; import org.eclipse.e4.tools.emf.ui.internal.common.component.dialogs.BindingContextSelectionDialog; import org.eclipse.e4.ui.model.application.commands.MBindingTable; import org.eclipse.e4.ui.model.application.commands.MCommandsFactory; import org.eclipse.e4.ui.model.application.commands.MKeyBinding; import org.eclipse.e4.ui.model.application.commands.impl.CommandsPackageImpl; import org.eclipse.e4.ui.model.application.impl.ApplicationPackageImpl; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.databinding.EMFDataBindingContext; import org.eclipse.emf.databinding.EMFProperties; import org.eclipse.emf.databinding.FeaturePath; import org.eclipse.emf.databinding.IEMFListProperty; import org.eclipse.emf.databinding.edit.EMFEditProperties; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.edit.command.AddCommand; import org.eclipse.emf.edit.command.MoveCommand; import org.eclipse.emf.edit.command.RemoveCommand; import org.eclipse.emf.edit.command.SetCommand; import org.eclipse.jface.action.Action; import org.eclipse.jface.databinding.swt.IWidgetValueProperty; import org.eclipse.jface.databinding.swt.WidgetProperties; import org.eclipse.jface.databinding.viewers.ObservableListContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; public class BindingTableEditor extends AbstractComponentEditor { private Composite composite; private EMFDataBindingContext context; private IListProperty BINDING_TABLE__BINDINGS = EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS); private EStackLayout stackLayout; private List<Action> actions = new ArrayList<Action>(); @Inject public BindingTableEditor() { super(); } @PostConstruct void init() { actions.add(new Action(Messages.BindingTableEditor_AddKeyBinding, createImageDescriptor(ResourceProvider.IMG_KeyBinding)) { @Override public void run() { handleAddKeyBinding(); } }); } @Override public Image getImage(Object element, Display display) { return createImage(ResourceProvider.IMG_BindingTable); } @Override public String getLabel(Object element) { return Messages.BindingTableEditor_Label; } @Override public String getDescription(Object element) { return Messages.BindingTableEditor_Description; } @Override public Composite doGetEditor(Composite parent, Object object) { if (composite == null) { context = new EMFDataBindingContext(); if (getEditor().isModelFragment()) { composite = new Composite(parent, SWT.NONE); stackLayout = new EStackLayout(); composite.setLayout(stackLayout); createForm(composite, context, getMaster(), false); createForm(composite, context, getMaster(), true); } else { composite = createForm(parent, context, getMaster(), false); } } if (getEditor().isModelFragment()) { Control topControl; if (Util.isImport((EObject) object)) { topControl = composite.getChildren()[1]; } else { topControl = composite.getChildren()[0]; } if (stackLayout.topControl != topControl) { stackLayout.topControl = topControl; composite.layout(true, true); } } getMaster().setValue(object); return composite; } private Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master, boolean isImport) { CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM); CTabItem item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabDefault); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify); if (getEditor().isShowXMIId() || getEditor().isLiveModel()) { ControlFactory.createXMIId(parent, this); } if (isImport) { ControlFactory.createFindImport(parent, Messages, this, context); folder.setSelection(0); return folder; } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.ModelTooling_Common_Id); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; t.setLayoutData(gd); context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID).observeDetail(getMaster())); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_ContextId); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); t.setEditable(false); - context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), FeaturePath.fromList(CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, CommandsPackageImpl.Literals.BINDING_CONTEXT__NAME)).observeDetail(getMaster())); + context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), FeaturePath.fromList(CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID)).observeDetail(getMaster())); final Button b = new Button(parent, SWT.PUSH | SWT.FLAT); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false)); b.setImage(createImage(ResourceProvider.IMG_Obj16_zoom)); b.setText(Messages.ModelTooling_Common_FindEllipsis); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BindingContextSelectionDialog dialog = new BindingContextSelectionDialog(b.getShell(), getEditor().getModelProvider(), Messages); if (dialog.open() == BindingContextSelectionDialog.OK) { Command cmd = SetCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, dialog.getSelectedContext()); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_Keybindings); l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false)); final TableViewer viewer = new TableViewer(parent); ObservableListContentProvider cp = new ObservableListContentProvider(); viewer.setContentProvider(cp); GridData gd = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(gd); viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages)); IEMFListProperty prop = EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS); viewer.setInput(prop.observeDetail(getMaster())); Composite buttonComp = new Composite(parent, SWT.NONE); buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false)); GridLayout gl = new GridLayout(); gl.marginLeft = 0; gl.marginRight = 0; gl.marginWidth = 0; gl.marginHeight = 0; buttonComp.setLayout(gl); Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Up); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) - 1; if (idx >= 0) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Down); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) + 1; if (idx < container.getBindings().size()) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_AddEllipsis); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleAddKeyBinding(); } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Remove); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { List<?> keybinding = ((IStructuredSelection) viewer.getSelection()).toList(); Command cmd = RemoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, keybinding); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabSupplementary); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); ControlFactory.createStringListWidget(parent, Messages, this, Messages.ModelTooling_ApplicationElement_Tags, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS, VERTICAL_LIST_WIDGET_INDENT); ControlFactory.createMapProperties(parent, Messages, this, Messages.ModelTooling_Contribution_PersistedState, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE, VERTICAL_LIST_WIDGET_INDENT); folder.setSelection(0); return folder; } @Override public IObservableList getChildList(Object element) { return BINDING_TABLE__BINDINGS.observe(element); } @Override public String getDetailLabel(Object element) { MBindingTable cmd = (MBindingTable) element; if (cmd.getBindingContext() != null && cmd.getBindingContext().getName() != null && cmd.getBindingContext().getName().trim().length() > 0) { return cmd.getBindingContext().getName(); } return null; } @Override public FeaturePath[] getLabelProperties() { return new FeaturePath[] { FeaturePath.fromList(CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, CommandsPackageImpl.Literals.BINDING_CONTEXT__NAME) }; } @Override public List<Action> getActions(Object element) { ArrayList<Action> l = new ArrayList<Action>(super.getActions(element)); l.addAll(actions); return l; } protected void handleAddKeyBinding() { MKeyBinding handler = MCommandsFactory.INSTANCE.createKeyBinding(); Command cmd = AddCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, handler); setElementId(handler); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); getEditor().setSelection(handler); } } }
true
true
private Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master, boolean isImport) { CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM); CTabItem item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabDefault); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify); if (getEditor().isShowXMIId() || getEditor().isLiveModel()) { ControlFactory.createXMIId(parent, this); } if (isImport) { ControlFactory.createFindImport(parent, Messages, this, context); folder.setSelection(0); return folder; } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.ModelTooling_Common_Id); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; t.setLayoutData(gd); context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID).observeDetail(getMaster())); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_ContextId); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); t.setEditable(false); context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), FeaturePath.fromList(CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, CommandsPackageImpl.Literals.BINDING_CONTEXT__NAME)).observeDetail(getMaster())); final Button b = new Button(parent, SWT.PUSH | SWT.FLAT); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false)); b.setImage(createImage(ResourceProvider.IMG_Obj16_zoom)); b.setText(Messages.ModelTooling_Common_FindEllipsis); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BindingContextSelectionDialog dialog = new BindingContextSelectionDialog(b.getShell(), getEditor().getModelProvider(), Messages); if (dialog.open() == BindingContextSelectionDialog.OK) { Command cmd = SetCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, dialog.getSelectedContext()); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_Keybindings); l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false)); final TableViewer viewer = new TableViewer(parent); ObservableListContentProvider cp = new ObservableListContentProvider(); viewer.setContentProvider(cp); GridData gd = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(gd); viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages)); IEMFListProperty prop = EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS); viewer.setInput(prop.observeDetail(getMaster())); Composite buttonComp = new Composite(parent, SWT.NONE); buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false)); GridLayout gl = new GridLayout(); gl.marginLeft = 0; gl.marginRight = 0; gl.marginWidth = 0; gl.marginHeight = 0; buttonComp.setLayout(gl); Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Up); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) - 1; if (idx >= 0) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Down); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) + 1; if (idx < container.getBindings().size()) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_AddEllipsis); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleAddKeyBinding(); } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Remove); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { List<?> keybinding = ((IStructuredSelection) viewer.getSelection()).toList(); Command cmd = RemoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, keybinding); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabSupplementary); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); ControlFactory.createStringListWidget(parent, Messages, this, Messages.ModelTooling_ApplicationElement_Tags, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS, VERTICAL_LIST_WIDGET_INDENT); ControlFactory.createMapProperties(parent, Messages, this, Messages.ModelTooling_Contribution_PersistedState, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE, VERTICAL_LIST_WIDGET_INDENT); folder.setSelection(0); return folder; }
private Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master, boolean isImport) { CTabFolder folder = new CTabFolder(parent, SWT.BOTTOM); CTabItem item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabDefault); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify); if (getEditor().isShowXMIId() || getEditor().isLiveModel()) { ControlFactory.createXMIId(parent, this); } if (isImport) { ControlFactory.createFindImport(parent, Messages, this, context); folder.setSelection(0); return folder; } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.ModelTooling_Common_Id); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; t.setLayoutData(gd); context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID).observeDetail(getMaster())); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_ContextId); l.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Text t = new Text(parent, SWT.BORDER); t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); t.setEditable(false); context.bindValue(textProp.observeDelayed(200, t), EMFEditProperties.value(getEditingDomain(), FeaturePath.fromList(CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__ELEMENT_ID)).observeDetail(getMaster())); final Button b = new Button(parent, SWT.PUSH | SWT.FLAT); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, false, false)); b.setImage(createImage(ResourceProvider.IMG_Obj16_zoom)); b.setText(Messages.ModelTooling_Common_FindEllipsis); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { BindingContextSelectionDialog dialog = new BindingContextSelectionDialog(b.getShell(), getEditor().getModelProvider(), Messages); if (dialog.open() == BindingContextSelectionDialog.OK) { Command cmd = SetCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDING_CONTEXT, dialog.getSelectedContext()); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } { Label l = new Label(parent, SWT.NONE); l.setText(Messages.BindingTableEditor_Keybindings); l.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false)); final TableViewer viewer = new TableViewer(parent); ObservableListContentProvider cp = new ObservableListContentProvider(); viewer.setContentProvider(cp); GridData gd = new GridData(GridData.FILL_BOTH); viewer.getControl().setLayoutData(gd); viewer.setLabelProvider(new ComponentLabelProvider(getEditor(), Messages)); IEMFListProperty prop = EMFProperties.list(CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS); viewer.setInput(prop.observeDetail(getMaster())); Composite buttonComp = new Composite(parent, SWT.NONE); buttonComp.setLayoutData(new GridData(GridData.FILL, GridData.END, false, false)); GridLayout gl = new GridLayout(); gl.marginLeft = 0; gl.marginRight = 0; gl.marginWidth = 0; gl.marginHeight = 0; buttonComp.setLayout(gl); Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Up); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_up)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) - 1; if (idx >= 0) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Down); b.setImage(createImage(ResourceProvider.IMG_Obj16_arrow_down)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { IStructuredSelection s = (IStructuredSelection) viewer.getSelection(); if (s.size() == 1) { Object obj = s.getFirstElement(); MBindingTable container = (MBindingTable) getMaster().getValue(); int idx = container.getBindings().indexOf(obj) + 1; if (idx < container.getBindings().size()) { Command cmd = MoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, obj, idx); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); viewer.setSelection(new StructuredSelection(obj)); } } } } } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_AddEllipsis); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_add)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleAddKeyBinding(); } }); b = new Button(buttonComp, SWT.PUSH | SWT.FLAT); b.setText(Messages.ModelTooling_Common_Remove); b.setImage(createImage(ResourceProvider.IMG_Obj16_table_delete)); b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); b.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (!viewer.getSelection().isEmpty()) { List<?> keybinding = ((IStructuredSelection) viewer.getSelection()).toList(); Command cmd = RemoveCommand.create(getEditingDomain(), getMaster().getValue(), CommandsPackageImpl.Literals.BINDING_TABLE__BINDINGS, keybinding); if (cmd.canExecute()) { getEditingDomain().getCommandStack().execute(cmd); } } } }); } item = new CTabItem(folder, SWT.NONE); item.setText(Messages.ModelTooling_Common_TabSupplementary); parent = createScrollableContainer(folder); item.setControl(parent.getParent()); ControlFactory.createStringListWidget(parent, Messages, this, Messages.ModelTooling_ApplicationElement_Tags, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__TAGS, VERTICAL_LIST_WIDGET_INDENT); ControlFactory.createMapProperties(parent, Messages, this, Messages.ModelTooling_Contribution_PersistedState, ApplicationPackageImpl.Literals.APPLICATION_ELEMENT__PERSISTED_STATE, VERTICAL_LIST_WIDGET_INDENT); folder.setSelection(0); return folder; }
diff --git a/src/de/xghostkillerx/cookme/CookMePlayerListener.java b/src/de/xghostkillerx/cookme/CookMePlayerListener.java index 52ef867..7665d67 100644 --- a/src/de/xghostkillerx/cookme/CookMePlayerListener.java +++ b/src/de/xghostkillerx/cookme/CookMePlayerListener.java @@ -1,180 +1,180 @@ package de.xghostkillerx.cookme; import net.minecraft.server.MobEffect; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.craftbukkit.entity.CraftLivingEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerListener; import org.bukkit.inventory.ItemStack; /** * CookMePlayerListener * Handles the players activities! * * Refer to the forum thread: * http://bit.ly/cookmebukkit * Refer to the dev.bukkit.org page: * http://bit.ly/cookmebukkitdev * * @author xGhOsTkiLLeRx * @thanks nisovin * */ public class CookMePlayerListener extends PlayerListener { public static CookMe plugin; public CookMePlayerListener(CookMe instance) { plugin = instance; } public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); // Check if player is affected if (!player.hasPermission("cookme.safe")) { // Check for raw food & right clicking if (((event.getMaterial() == Material.RAW_BEEF) || (event.getMaterial() == Material.RAW_CHICKEN) || (event.getMaterial() == Material.RAW_FISH) || (event.getMaterial() == Material.ROTTEN_FLESH) || (event.getMaterial() == Material.PORK)) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { // Check for food level if (player.getFoodLevel() != 20) { int randomNumber = (int)(Math.random()*25) +1; int randomEffect = (int)(Math.random()*110) +50, randomEffectStrength = (int)(Math.random()*16); // Player gets random damage, stack minus 1 if (plugin.config.getBoolean("effects.damage") == true) { if ((randomNumber == 1) || (randomNumber == 12)) { int randomDamage = (int) (Math.random()*9) +1; decreaseItem(player, event); player.damage(randomDamage); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You got some random damage! Eat some cooked food!"); } } } // Food bar turns green (poison) if (plugin.config.getBoolean("effects.hungervenom") == true) { if ((randomNumber == 2 ) || (randomNumber == 13)) { int randomHungerVenom = (int)(Math.random()*80) +20, randomHungerVenomStrength = (int)(Math.random()*16); decreaseItem(player, event); setMobEffect(player, 17, randomHungerVenom, randomHungerVenomStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your foodbar is a random time venomed! Eat some cooked food!"); } } } // Player dies, stack minus 1 if (plugin.config.getBoolean("effects.death") == true) { if (randomNumber == 4 ) { decreaseItem(player, event); player.setHealth(0); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "The raw food killed you :("); } } } // Random venom damage (including green hearts :) ) if (plugin.config.getBoolean("effects.venom") == true) { if ((randomNumber == 5) || (randomNumber == 14)) { decreaseItem(player, event); setMobEffect(player, 19, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time venomed! Eat some cooked food!"); } } } // Sets the food level down. Stack minus 1 if (plugin.config.getBoolean("effects.hungerdecrease") == true) { if ((randomNumber == 6) || (randomNumber == 15)) { int currentFoodLevel = player.getFoodLevel(), randomFoodLevel = (int)(Math.random()*currentFoodLevel); decreaseItem(player, event); player.setFoodLevel(randomFoodLevel); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your food level went down! Eat some cooked food!"); } } } // Confusion if (plugin.config.getBoolean("effects.confusion") == true) { if ((randomNumber == 7) || (randomNumber == 16)) { decreaseItem(player, event); setMobEffect(player, 9, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time confused! Eat some cooked food!"); } } } // Blindness if (plugin.config.getBoolean("effects.blindness") == true) { if ((randomNumber == 8) || (randomNumber == 17)) { decreaseItem(player, event); setMobEffect(player, 15, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time blind! Eat some cooked food!"); } } } // Weakness if (plugin.config.getBoolean("effects.weakness") == true) { if ((randomNumber == 9) || (randomNumber == 18)) { decreaseItem(player, event); setMobEffect(player, 18, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time weaked! Eat some cooked food!"); } } } - // Slwoness + // Slowness if (plugin.config.getBoolean("effects.slowness") == true) { if ((randomNumber == 10) || (randomNumber == 19)) { decreaseItem(player, event); setMobEffect(player, 2, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time slower! Eat some cooked food!"); } } } // Slowness for blocks if (plugin.config.getBoolean("effects.slowness_blocks") == true) { if ((randomNumber == 11) || (randomNumber == 20)) { decreaseItem(player, event); setMobEffect(player, 4, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You mine for a random time slower! Eat some cooked food!"); } } } } } } } /* Sets the specific mob effect! BIG THANKS @nisovin for his awesome code! * http://www.wiki.vg/Protocol#Effects * * int type = ID value * int duration = in ticks (20 ticks = 1 second) * int amplifier = how fast the effect is applied (0 to 15) * */ public void setMobEffect(LivingEntity entity, int type, int duration, int amplifier) { ((CraftLivingEntity)entity).getHandle().addEffect(new MobEffect(type, duration, amplifier)); } // Sets the raw food -1 @SuppressWarnings("deprecation") public void decreaseItem (Player player, PlayerInteractEvent event) { ItemStack afterEating = player.getItemInHand(); if (afterEating.getAmount() == 1) { player.setItemInHand(null); player.updateInventory(); event.setCancelled(true); } else { afterEating.setAmount(afterEating.getAmount() -1); player.setItemInHand(afterEating); player.updateInventory(); event.setCancelled(true); } } }
true
true
public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); // Check if player is affected if (!player.hasPermission("cookme.safe")) { // Check for raw food & right clicking if (((event.getMaterial() == Material.RAW_BEEF) || (event.getMaterial() == Material.RAW_CHICKEN) || (event.getMaterial() == Material.RAW_FISH) || (event.getMaterial() == Material.ROTTEN_FLESH) || (event.getMaterial() == Material.PORK)) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { // Check for food level if (player.getFoodLevel() != 20) { int randomNumber = (int)(Math.random()*25) +1; int randomEffect = (int)(Math.random()*110) +50, randomEffectStrength = (int)(Math.random()*16); // Player gets random damage, stack minus 1 if (plugin.config.getBoolean("effects.damage") == true) { if ((randomNumber == 1) || (randomNumber == 12)) { int randomDamage = (int) (Math.random()*9) +1; decreaseItem(player, event); player.damage(randomDamage); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You got some random damage! Eat some cooked food!"); } } } // Food bar turns green (poison) if (plugin.config.getBoolean("effects.hungervenom") == true) { if ((randomNumber == 2 ) || (randomNumber == 13)) { int randomHungerVenom = (int)(Math.random()*80) +20, randomHungerVenomStrength = (int)(Math.random()*16); decreaseItem(player, event); setMobEffect(player, 17, randomHungerVenom, randomHungerVenomStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your foodbar is a random time venomed! Eat some cooked food!"); } } } // Player dies, stack minus 1 if (plugin.config.getBoolean("effects.death") == true) { if (randomNumber == 4 ) { decreaseItem(player, event); player.setHealth(0); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "The raw food killed you :("); } } } // Random venom damage (including green hearts :) ) if (plugin.config.getBoolean("effects.venom") == true) { if ((randomNumber == 5) || (randomNumber == 14)) { decreaseItem(player, event); setMobEffect(player, 19, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time venomed! Eat some cooked food!"); } } } // Sets the food level down. Stack minus 1 if (plugin.config.getBoolean("effects.hungerdecrease") == true) { if ((randomNumber == 6) || (randomNumber == 15)) { int currentFoodLevel = player.getFoodLevel(), randomFoodLevel = (int)(Math.random()*currentFoodLevel); decreaseItem(player, event); player.setFoodLevel(randomFoodLevel); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your food level went down! Eat some cooked food!"); } } } // Confusion if (plugin.config.getBoolean("effects.confusion") == true) { if ((randomNumber == 7) || (randomNumber == 16)) { decreaseItem(player, event); setMobEffect(player, 9, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time confused! Eat some cooked food!"); } } } // Blindness if (plugin.config.getBoolean("effects.blindness") == true) { if ((randomNumber == 8) || (randomNumber == 17)) { decreaseItem(player, event); setMobEffect(player, 15, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time blind! Eat some cooked food!"); } } } // Weakness if (plugin.config.getBoolean("effects.weakness") == true) { if ((randomNumber == 9) || (randomNumber == 18)) { decreaseItem(player, event); setMobEffect(player, 18, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time weaked! Eat some cooked food!"); } } } // Slwoness if (plugin.config.getBoolean("effects.slowness") == true) { if ((randomNumber == 10) || (randomNumber == 19)) { decreaseItem(player, event); setMobEffect(player, 2, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time slower! Eat some cooked food!"); } } } // Slowness for blocks if (plugin.config.getBoolean("effects.slowness_blocks") == true) { if ((randomNumber == 11) || (randomNumber == 20)) { decreaseItem(player, event); setMobEffect(player, 4, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You mine for a random time slower! Eat some cooked food!"); } } } } } } }
public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); // Check if player is affected if (!player.hasPermission("cookme.safe")) { // Check for raw food & right clicking if (((event.getMaterial() == Material.RAW_BEEF) || (event.getMaterial() == Material.RAW_CHICKEN) || (event.getMaterial() == Material.RAW_FISH) || (event.getMaterial() == Material.ROTTEN_FLESH) || (event.getMaterial() == Material.PORK)) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { // Check for food level if (player.getFoodLevel() != 20) { int randomNumber = (int)(Math.random()*25) +1; int randomEffect = (int)(Math.random()*110) +50, randomEffectStrength = (int)(Math.random()*16); // Player gets random damage, stack minus 1 if (plugin.config.getBoolean("effects.damage") == true) { if ((randomNumber == 1) || (randomNumber == 12)) { int randomDamage = (int) (Math.random()*9) +1; decreaseItem(player, event); player.damage(randomDamage); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You got some random damage! Eat some cooked food!"); } } } // Food bar turns green (poison) if (plugin.config.getBoolean("effects.hungervenom") == true) { if ((randomNumber == 2 ) || (randomNumber == 13)) { int randomHungerVenom = (int)(Math.random()*80) +20, randomHungerVenomStrength = (int)(Math.random()*16); decreaseItem(player, event); setMobEffect(player, 17, randomHungerVenom, randomHungerVenomStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your foodbar is a random time venomed! Eat some cooked food!"); } } } // Player dies, stack minus 1 if (plugin.config.getBoolean("effects.death") == true) { if (randomNumber == 4 ) { decreaseItem(player, event); player.setHealth(0); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "The raw food killed you :("); } } } // Random venom damage (including green hearts :) ) if (plugin.config.getBoolean("effects.venom") == true) { if ((randomNumber == 5) || (randomNumber == 14)) { decreaseItem(player, event); setMobEffect(player, 19, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time venomed! Eat some cooked food!"); } } } // Sets the food level down. Stack minus 1 if (plugin.config.getBoolean("effects.hungerdecrease") == true) { if ((randomNumber == 6) || (randomNumber == 15)) { int currentFoodLevel = player.getFoodLevel(), randomFoodLevel = (int)(Math.random()*currentFoodLevel); decreaseItem(player, event); player.setFoodLevel(randomFoodLevel); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "Your food level went down! Eat some cooked food!"); } } } // Confusion if (plugin.config.getBoolean("effects.confusion") == true) { if ((randomNumber == 7) || (randomNumber == 16)) { decreaseItem(player, event); setMobEffect(player, 9, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time confused! Eat some cooked food!"); } } } // Blindness if (plugin.config.getBoolean("effects.blindness") == true) { if ((randomNumber == 8) || (randomNumber == 17)) { decreaseItem(player, event); setMobEffect(player, 15, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time blind! Eat some cooked food!"); } } } // Weakness if (plugin.config.getBoolean("effects.weakness") == true) { if ((randomNumber == 9) || (randomNumber == 18)) { decreaseItem(player, event); setMobEffect(player, 18, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time weaked! Eat some cooked food!"); } } } // Slowness if (plugin.config.getBoolean("effects.slowness") == true) { if ((randomNumber == 10) || (randomNumber == 19)) { decreaseItem(player, event); setMobEffect(player, 2, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You are for a random time slower! Eat some cooked food!"); } } } // Slowness for blocks if (plugin.config.getBoolean("effects.slowness_blocks") == true) { if ((randomNumber == 11) || (randomNumber == 20)) { decreaseItem(player, event); setMobEffect(player, 4, randomEffect, randomEffectStrength); if (plugin.config.getBoolean("configuration.messages") == true) { player.sendMessage(ChatColor.DARK_RED + "You mine for a random time slower! Eat some cooked food!"); } } } } } } }
diff --git a/src/net/mdcreator/tpplus/home/HomeExecutor.java b/src/net/mdcreator/tpplus/home/HomeExecutor.java index 4e69505..77694cd 100644 --- a/src/net/mdcreator/tpplus/home/HomeExecutor.java +++ b/src/net/mdcreator/tpplus/home/HomeExecutor.java @@ -1,175 +1,175 @@ package net.mdcreator.tpplus.home; import net.mdcreator.tpplus.Home; import net.mdcreator.tpplus.TPPlus; import org.bukkit.ChatColor; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; public class HomeExecutor implements CommandExecutor{ private TPPlus plugin; private String title = ChatColor.DARK_GRAY + "[" + ChatColor.BLUE + "TP+" + ChatColor.DARK_GRAY + "] " + ChatColor.GRAY; public HomeExecutor(TPPlus plugin){ this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player send; if(!(sender instanceof Player)){ sender.sendMessage(title + ChatColor.RED + "Player context is required!"); return true; } send = (Player) sender; // /home if(args.length==0){ if(plugin.homesManager.homes.containsKey(send.getName())){ Home home = plugin.homesManager.homes.get(send.getName()); Location loc = send.getLocation(); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); - send.teleport(home.pos); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); + send.teleport(home.pos); send.sendMessage(title + "Home, sweet home."); } else{ sender.sendMessage(title + ChatColor.RED + "You need a home!"); } return true; }else if(args.length==1){ // /home help if(args[0].equals("help")){ return false; } else // /home set if(args[0].equals("set")){ Location loc = send.getLocation(); plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set."); } else // /home open if(args[0].equals("open")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.add(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", true); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 111); send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home close if(args[0].equals("close")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.remove(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", false); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 40); send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home [player] { Player target = plugin.getServer().getPlayer(args[0]); String name; if(target==null){ if(plugin.homesManager.homes.containsKey(args[0])){ name = args[0]; } else{ send.sendMessage(title + ChatColor.RED + "That player does not exist!"); return true; } } name = target.getName(); if(!plugin.homesManager.homes.containsKey(name)){ send.sendMessage(title + ChatColor.RED + "That player does not have a home!"); }else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){ send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!"); } else{ Location loc = send.getLocation(); Home home = plugin.homesManager.homes.get(name); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); send.teleport(home.pos); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Welcome."); } } return true; } else if(args.length==2){ if(args[0].equals("set")&&args[1].equals("bed")){ Location loc = send.getBedSpawnLocation(); if(loc==null){ send.sendMessage(title + ChatColor.RED + "You need a bed!"); return true; } plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set to bed."); return true; } return false; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player send; if(!(sender instanceof Player)){ sender.sendMessage(title + ChatColor.RED + "Player context is required!"); return true; } send = (Player) sender; // /home if(args.length==0){ if(plugin.homesManager.homes.containsKey(send.getName())){ Home home = plugin.homesManager.homes.get(send.getName()); Location loc = send.getLocation(); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); send.teleport(home.pos); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home, sweet home."); } else{ sender.sendMessage(title + ChatColor.RED + "You need a home!"); } return true; }else if(args.length==1){ // /home help if(args[0].equals("help")){ return false; } else // /home set if(args[0].equals("set")){ Location loc = send.getLocation(); plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set."); } else // /home open if(args[0].equals("open")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.add(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", true); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 111); send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home close if(args[0].equals("close")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.remove(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", false); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 40); send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home [player] { Player target = plugin.getServer().getPlayer(args[0]); String name; if(target==null){ if(plugin.homesManager.homes.containsKey(args[0])){ name = args[0]; } else{ send.sendMessage(title + ChatColor.RED + "That player does not exist!"); return true; } } name = target.getName(); if(!plugin.homesManager.homes.containsKey(name)){ send.sendMessage(title + ChatColor.RED + "That player does not have a home!"); }else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){ send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!"); } else{ Location loc = send.getLocation(); Home home = plugin.homesManager.homes.get(name); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); send.teleport(home.pos); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Welcome."); } } return true; } else if(args.length==2){ if(args[0].equals("set")&&args[1].equals("bed")){ Location loc = send.getBedSpawnLocation(); if(loc==null){ send.sendMessage(title + ChatColor.RED + "You need a bed!"); return true; } plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set to bed."); return true; } return false; } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { Player send; if(!(sender instanceof Player)){ sender.sendMessage(title + ChatColor.RED + "Player context is required!"); return true; } send = (Player) sender; // /home if(args.length==0){ if(plugin.homesManager.homes.containsKey(send.getName())){ Home home = plugin.homesManager.homes.get(send.getName()); Location loc = send.getLocation(); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.teleport(home.pos); send.sendMessage(title + "Home, sweet home."); } else{ sender.sendMessage(title + ChatColor.RED + "You need a home!"); } return true; }else if(args.length==1){ // /home help if(args[0].equals("help")){ return false; } else // /home set if(args[0].equals("set")){ Location loc = send.getLocation(); plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set."); } else // /home open if(args[0].equals("open")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.add(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", true); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 111); send.sendMessage(title + "Your home is now " + ChatColor.DARK_GREEN + "open" + ChatColor.GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home close if(args[0].equals("close")){ if(plugin.homesManager.homes.containsKey(send.getName())){ plugin.homesManager.openHomes.remove(send.getName()); FileConfiguration config = plugin.homesYML; config.set(send.getName() + ".open", false); plugin.saveHomes(); Location home = plugin.homesManager.homes.get(send.getName()).pos; home.getWorld().playEffect(home, Effect.ENDER_SIGNAL, 1); home.getWorld().playEffect(home, Effect.MOBSPAWNER_FLAMES, 1); home.getWorld().playEffect(home, Effect.STEP_SOUND, 40); send.sendMessage(title + "Your home is now " + ChatColor.DARK_RED + "closed" + ChatColor.DARK_GRAY + " to guests."); } else{ send.sendMessage(title + ChatColor.RED + "You need a home!"); } } else // /home [player] { Player target = plugin.getServer().getPlayer(args[0]); String name; if(target==null){ if(plugin.homesManager.homes.containsKey(args[0])){ name = args[0]; } else{ send.sendMessage(title + ChatColor.RED + "That player does not exist!"); return true; } } name = target.getName(); if(!plugin.homesManager.homes.containsKey(name)){ send.sendMessage(title + ChatColor.RED + "That player does not have a home!"); }else if(!plugin.homesManager.openHomes.contains(name)&&!send.isOp()&&!send.getName().equals(target.getName())){ send.sendMessage(title + ChatColor.RED + "That player's home is " + ChatColor.DARK_RED + "closed" + ChatColor.RED + "!"); } else{ Location loc = send.getLocation(); Home home = plugin.homesManager.homes.get(name); send.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); send.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); send.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); loc = home.pos; loc.getWorld().loadChunk(loc.getWorld().getChunkAt(loc)); send.teleport(home.pos); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Welcome."); } } return true; } else if(args.length==2){ if(args[0].equals("set")&&args[1].equals("bed")){ Location loc = send.getBedSpawnLocation(); if(loc==null){ send.sendMessage(title + ChatColor.RED + "You need a bed!"); return true; } plugin.homesManager.homes.put(send.getName(), new Home(loc)); FileConfiguration config = plugin.homesYML; String name = send.getName(); boolean newHome; newHome = config.getString(send.getName()) == null; config.set(name + ".x", loc.getX()); config.set(name + ".y", loc.getY()); config.set(name + ".z", loc.getZ()); config.set(name + ".yaw", loc.getPitch()); config.set(name + ".pitch", loc.getYaw()); config.set(name + ".world", loc.getWorld().getName()); if(newHome) config.set(name + ".open", false); plugin.saveHomes(); loc.getWorld().playEffect(loc, Effect.ENDER_SIGNAL, 1); loc.getWorld().playEffect(loc, Effect.MOBSPAWNER_FLAMES, 1); loc.getWorld().playEffect(loc, Effect.STEP_SOUND, 51); send.sendMessage(title + "Home set to bed."); return true; } return false; } return false; }
diff --git a/src/main/java/hudson/remoting/Request.java b/src/main/java/hudson/remoting/Request.java index 76923cb4..b78d2972 100644 --- a/src/main/java/hudson/remoting/Request.java +++ b/src/main/java/hudson/remoting/Request.java @@ -1,352 +1,353 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * 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 hudson.remoting; import java.io.IOException; import java.io.Serializable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * Request/response pattern over {@link Channel}, the layer-1 service. * * <p> * This assumes that the receiving side has all the class definitions * available to de-serialize {@link Request}, just like {@link Command}. * * @author Kohsuke Kawaguchi * @see Response */ abstract class Request<RSP extends Serializable,EXC extends Throwable> extends Command { /** * Executed on a remote system to perform the task. * * @param channel * The local channel. From the view point of the JVM that * {@link #call(Channel) made the call}, this channel is * the remote channel. * @return * the return value will be sent back to the calling process. * @throws EXC * The exception will be forwarded to the calling process. * If no checked exception is supposed to be thrown, use {@link RuntimeException}. */ protected abstract RSP perform(Channel channel) throws EXC; /** * Uniquely identifies this request. * Used for correlation between request and response. */ private final int id; private volatile Response<RSP,EXC> response; /** * While executing the call this is set to the handle of the execution. */ protected volatile transient Future<?> future; /** * If this request performed some I/O back in the caller side during the remote call execution, set to last such * operation, so that we can block until its completion. */ /*package*/ volatile transient Future<?> lastIo; protected Request() { synchronized(Request.class) { id = nextId++; } } /** * Sends this request to a remote system, and blocks until we receives a response. * * @param channel * The channel from which the request will be sent. * @throws InterruptedException * If the thread is interrupted while it's waiting for the call to complete. * @throws IOException * If there's an error during the communication. * @throws RequestAbortedException * If the channel is terminated while the call is in progress. * @throws EXC * If the {@link #perform(Channel)} throws an exception. */ public final RSP call(Channel channel) throws EXC, InterruptedException, IOException { // Channel.send() locks channel, and there are other call sequences // ( like Channel.terminate()->Request.abort()->Request.onCompleted() ) // that locks channel -> request, so lock objects in the same order synchronized(channel) { synchronized(this) { response=null; channel.pendingCalls.put(id,this); channel.send(this); } } try { synchronized(this) { // set the thread name to represent the channel we are blocked on, // so that thread dump would give us more useful information. Thread t = Thread.currentThread(); final String name = t.getName(); try { // wait until the response arrives t.setName(name+" / waiting for "+channel); while(response==null && !channel.isInClosed()) // I don't know exactly when this can happen, as pendingCalls are cleaned up by Channel, // but in production I've observed that in rare occasion it can block forever, even after a channel // is gone. So be defensive against that. wait(30*1000); if (response==null) // channel is closed and we still don't have a response throw new RequestAbortedException(null); } finally { t.setName(name); } if (lastIo!=null) try { lastIo.get(); } catch (ExecutionException e) { // ignore the I/O error } Object exc = response.exception; if (exc!=null) { if(exc instanceof RequestAbortedException) { // add one more exception, so that stack trace shows both who's waiting for the completion // and where the connection outage was detected. exc = new RequestAbortedException((RequestAbortedException)exc); } throw (EXC)exc; // some versions of JDK fails to compile this line. If so, upgrade your JDK. } return response.returnValue; } } catch (InterruptedException e) { // if we are cancelled, abort the remote computation, too. // do this outside the "synchronized(this)" block to prevent locking Request and Channel in a wrong order. synchronized (channel) { // ... so that the close check and send won't be interrupted in the middle by a close if (!channel.isOutClosed()) channel.send(new Cancel(id)); // only send a cancel if we can, or else ChannelClosedException will mask the original cause } throw e; } } /** * Makes an invocation but immediately returns without waiting for the completion * (AKA asynchronous invocation.) * * @param channel * The channel from which the request will be sent. * @return * The {@link Future} object that can be used to wait for the completion. * @throws IOException * If there's an error during the communication. */ public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException { response=null; channel.pendingCalls.put(id,this); channel.send(this); return new hudson.remoting.Future<RSP>() { private volatile boolean cancelled; public boolean cancel(boolean mayInterruptIfRunning) { if (cancelled || isDone()) { return false; } cancelled = true; if (mayInterruptIfRunning) { try { channel.send(new Cancel(id)); } catch (IOException x) { return false; } } return true; } public boolean isCancelled() { return cancelled; } public boolean isDone() { return isCancelled() || response!=null; } public RSP get() throws InterruptedException, ExecutionException { synchronized(Request.this) { try { while(response==null) { if (isCancelled()) { throw new CancellationException(); } Request.this.wait(); // wait until the response arrives } } catch (InterruptedException e) { try { channel.send(new Cancel(id)); } catch (IOException e1) { // couldn't cancel. ignore. } throw e; } if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { synchronized(Request.this) { - if(response==null) { + long end = System.currentTimeMillis() + unit.toMillis(timeout); + while(response==null && System.currentTimeMillis()<end) { if (isCancelled()) { throw new CancellationException(); } - Request.this.wait(unit.toMillis(timeout)); // wait until the response arrives + Request.this.wait(end-System.currentTimeMillis()); // wait until the response arrives } if(response==null) throw new TimeoutException(); if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } }; } /** * Called by the {@link Response} when we received it. */ /*package*/ synchronized void onCompleted(Response<RSP,EXC> response) { this.response = response; notify(); } /** * Aborts the processing. The calling thread will receive an exception. */ /*package*/ void abort(IOException e) { onCompleted(new Response(id,new RequestAbortedException(e))); } /** * Schedules the execution of this request. */ protected final void execute(final Channel channel) { channel.executingCalls.put(id,this); future = channel.executor.submit(new Runnable() { public void run() { try { Command rsp; CURRENT.set(Request.this); try { RSP r = Request.this.perform(channel); // normal completion rsp = new Response<RSP,EXC>(id,r); } catch (Throwable t) { // error return rsp = new Response<RSP,Throwable>(id,t); } finally { CURRENT.set(null); } if(chainCause) rsp.createdAt.initCause(createdAt); synchronized (channel) {// expand the synchronization block of the send() method to a check if(!channel.isOutClosed()) channel.send(rsp); } } catch (IOException e) { // communication error. // this means the caller will block forever logger.log(Level.SEVERE, "Failed to send back a reply",e); } finally { channel.executingCalls.remove(id); } } }); } /** * Next request ID. */ private static int nextId=0; private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(Request.class.getName()); /** * Set to true to chain {@link Command#createdAt} to track request/response relationship. * This will substantially increase the network traffic, but useful for debugging. */ public static boolean chainCause = Boolean.getBoolean(Request.class.getName()+".chainCause"); /** * Set to the {@link Request} object during {@linkplain #perform(Channel) the execution of the call}. */ /*package*/ static ThreadLocal<Request> CURRENT = new ThreadLocal<Request>(); /*package*/ static int getCurrentRequestId() { Request r = CURRENT.get(); return r!=null ? r.id : 0; } /** * Interrupts the execution of the remote computation. */ private static final class Cancel extends Command { private final int id; Cancel(int id) { this.id = id; } protected void execute(Channel channel) { Request<?,?> r = channel.executingCalls.get(id); if(r==null) return; // already completed Future<?> f = r.future; if(f!=null) f.cancel(true); } } }
false
true
public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException { response=null; channel.pendingCalls.put(id,this); channel.send(this); return new hudson.remoting.Future<RSP>() { private volatile boolean cancelled; public boolean cancel(boolean mayInterruptIfRunning) { if (cancelled || isDone()) { return false; } cancelled = true; if (mayInterruptIfRunning) { try { channel.send(new Cancel(id)); } catch (IOException x) { return false; } } return true; } public boolean isCancelled() { return cancelled; } public boolean isDone() { return isCancelled() || response!=null; } public RSP get() throws InterruptedException, ExecutionException { synchronized(Request.this) { try { while(response==null) { if (isCancelled()) { throw new CancellationException(); } Request.this.wait(); // wait until the response arrives } } catch (InterruptedException e) { try { channel.send(new Cancel(id)); } catch (IOException e1) { // couldn't cancel. ignore. } throw e; } if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { synchronized(Request.this) { if(response==null) { if (isCancelled()) { throw new CancellationException(); } Request.this.wait(unit.toMillis(timeout)); // wait until the response arrives } if(response==null) throw new TimeoutException(); if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } }; }
public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException { response=null; channel.pendingCalls.put(id,this); channel.send(this); return new hudson.remoting.Future<RSP>() { private volatile boolean cancelled; public boolean cancel(boolean mayInterruptIfRunning) { if (cancelled || isDone()) { return false; } cancelled = true; if (mayInterruptIfRunning) { try { channel.send(new Cancel(id)); } catch (IOException x) { return false; } } return true; } public boolean isCancelled() { return cancelled; } public boolean isDone() { return isCancelled() || response!=null; } public RSP get() throws InterruptedException, ExecutionException { synchronized(Request.this) { try { while(response==null) { if (isCancelled()) { throw new CancellationException(); } Request.this.wait(); // wait until the response arrives } } catch (InterruptedException e) { try { channel.send(new Cancel(id)); } catch (IOException e1) { // couldn't cancel. ignore. } throw e; } if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { synchronized(Request.this) { long end = System.currentTimeMillis() + unit.toMillis(timeout); while(response==null && System.currentTimeMillis()<end) { if (isCancelled()) { throw new CancellationException(); } Request.this.wait(end-System.currentTimeMillis()); // wait until the response arrives } if(response==null) throw new TimeoutException(); if(response.exception!=null) throw new ExecutionException(response.exception); return response.returnValue; } } }; }
diff --git a/avr/bi/extensions/trisano/src/org/trisano/mondrian/GetPopulation.java b/avr/bi/extensions/trisano/src/org/trisano/mondrian/GetPopulation.java index 3fa4be62e..55803a148 100644 --- a/avr/bi/extensions/trisano/src/org/trisano/mondrian/GetPopulation.java +++ b/avr/bi/extensions/trisano/src/org/trisano/mondrian/GetPopulation.java @@ -1,272 +1,269 @@ package org.trisano.mondrian; import mondrian.olap.*; import mondrian.olap.type.*; import mondrian.spi.UserDefinedFunction; import org.apache.log4j.Logger; import java.sql.*; import java.util.*; public class GetPopulation implements UserDefinedFunction { private static final Logger logger = Logger.getLogger(GetPopulation.class); public GetPopulation() { } public String getName() { return "GetPopulation"; } public String getDescription() { return "Returns the population for the current context"; } public Syntax getSyntax() { return Syntax.Function; } public Type getReturnType(Type[] parameterTypes) { return new NumericType(); } public Type[] getParameterTypes() { return new Type[] { new NumericType() }; } public Object execute(Evaluator evaluator, UserDefinedFunction.Argument[] arguments) { java.sql.Connection conn = null; List<Map<String, String>> dimensions = new ArrayList<Map<String, String>>(); ResultSet rs; String column_names = new String(""); String table_name, query; Integer table_rank, population = 0; ArrayList<String> params = new ArrayList<String>(); Boolean doneOne = false; try { conn = evaluator.getQuery().getConnection().getDataSource().getConnection(); PreparedStatement st = conn.prepareStatement("SELECT dim_cols[?], mapping_func[?] FROM population.population_dimensions WHERE dim_name = ?"); // Get data on all necessary dimensions for (Dimension d : evaluator.getCube().getDimensions()) { Integer depth; logger.debug("checking dimension " + d.getName()); HashMap<String, String> dimhash = new HashMap<String, String>(); depth = evaluator.getContext(d).getLevel().getDepth(); st.setInt(1, depth); st.setInt(2, depth); st.setString(3, d.getName()); rs = st.executeQuery(); if (rs.next() && depth != 0) { // rs.next() is true only if it returned something, or in // other words, only when this dimension is important to // us. We also only care when depth is nonzero dimhash.put("name", d.getName()); dimhash.put("depth", depth.toString()); dimhash.put("value", evaluator.getContext(d).getName()); dimhash.put("column", rs.getString(1)); dimhash.put("mapper", rs.getString(2)); dimensions.add(dimhash); if (! column_names.equals("")) column_names += ", "; column_names += "'" + dimhash.get("column") + "'"; logger.info("Dimension " + d.getName() + " is useful, so keeping. Column: " + dimhash.get("column") + "\tMapper: " + dimhash.get("mapper")); logger.debug("column names list now == " + column_names); } } // Figure out what table to use // TODO: Note that there's some room for SQL injection problems here, if column names are stupid if (dimensions.size() != 0) { query = "SELECT table_name, table_rank FROM ( \n" + " SELECT \n" + " ppt.table_name, \n" + " COUNT(*), \n" + " ppt.table_rank \n" + " FROM \n" + " population.population_tables ppt \n" + " JOIN information_schema.columns isc \n" + " ON ( \n" + " isc.table_name = ppt.table_name AND \n" + " isc.table_schema = 'population' \n" + " ) \n" + " WHERE \n" + " isc.column_name IN (" + column_names + ") \n" + " GROUP BY \n" + " ppt.table_name, \n" + " ppt.table_rank \n" + " HAVING \n" + " COUNT(*) = ? \n" + ") f \n" + "ORDER BY table_rank ASC LIMIT 1;"; logger.debug("For finding table, using query : " + query); st = conn.prepareStatement(query); //st.setString(1, column_names); st.setInt(1, dimensions.size()); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find population table for dimensions: " + column_names); return null; } } else { logger.debug("No dimensions specified; using highest-ranking table"); st = conn.prepareStatement("SELECT table_name, table_rank FROM population.population_tables ORDER BY table_rank ASC LIMIT 1"); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find default population table"); - return 0; + return null; } if (table_name == null || table_name.equals("")) { logger.warn("Couldn't find default population table"); - return 0; + return null; } } logger.info("Pulling data from table " + table_name + " with rank " + table_rank.toString()); // Build query query = "SELECT COALESCE(SUM(population), 0) FROM population." + table_name; if (dimensions.size() > 0) { query += " WHERE"; for (Map<String, String> m : dimensions) { if (doneOne) query += " AND"; query += " " + m.get("column") + " = "; if (m.get("mapper") == null) query += "?"; else query += m.get("mapper") + "(?)"; params.add(m.get("value")); doneOne = true; } } logger.info("Using query : " + query); st = conn.prepareStatement(query); int i = 1; for (String s : params) { st.setString(i, s); i++; } rs = st.executeQuery(); rs.next(); population = rs.getInt(1); logger.debug("Population: " + population); } catch (SQLException s) { logger.error("JDBC Error", s); } try { if (conn != null) conn.close(); } catch (SQLException s) { logger.error("JDBC Error when disconnecting: ", s); } - if (population == 0) - return null; - else - return population; + return population; } /* public Object execute(Evaluator evaluator, UserDefinedFunction.Argument[] arguments) { // Find the current level for dimensions that we care about for // population statistics, and calculate the total population given // those dimensions. Right now those dimensions are: // * Disease // * Investigating Jurisdiction // // Eventually this should probably implement some method to: // 1) Not hard code which dimensions are meaningful // 2) Handle multi-level dimensions // 3) Handle dimensions where Mondrian's value for the dimension // differs from the population table's value // TODO: test all this ArrayList<String> vals = new ArrayList<String>(); Object arg = arguments[0].evaluateScalar(evaluator); double population = 0; java.sql.Connection conn = null; if (!(arg instanceof Number)) return null; try { PreparedStatement st; ResultSet rs; String where = "", query; int i; conn = evaluator.getQuery().getConnection().getDataSource().getConnection(); st = conn.prepareStatement("SELECT dim_cols[?], mapping_func[?] FROM population.population_dimensions WHERE dim_name = ?"); for (Dimension d : evaluator.getCube().getDimensions()) { String colname, colmapper; Integer depth; depth = evaluator.getContext(d).getLevel().getDepth(); if (depth != 0) { st.setInt(1, depth); st.setInt(2, depth); st.setString(3, d.getName()); rs = st.executeQuery(); if (rs.next()) { // rs.next() is true only if it returned something, or in // other words, only when this dimension is important to us colname = rs.getString(1); colmapper = rs.getString(2); logger.debug("Found a meaningful dimension: " + d.getName() + " with colname " + colname + ", depth " + depth + ", and mapping func " + colmapper); if (!where.equals("")) where += " AND "; where += colname + " = "; if (colmapper != null) where += colmapper + "(?)"; else where += "?"; vals.add(evaluator.getContext(d).getName()); } } } query = "SELECT sum(population) FROM population.population" + (!where.equals("") ? " WHERE " + where : ""); logger.debug("Issuing query \"" + query + "\""); st = conn.prepareStatement(query); i = 0; for (String s : vals) { i++; st.setString(i, s); } rs = st.executeQuery(); if (rs.next()) population = rs.getDouble(1); } catch (SQLException s) { logger.warn("JDBC Error: " + s); } try { if (conn != null) conn.close(); } catch (SQLException s) { logger.warn("JDBC Error when disconnecting: " + s); } if (population == 0) return null; else return population; } */ public String[] getReservedWords() { return null; } }
false
true
public Object execute(Evaluator evaluator, UserDefinedFunction.Argument[] arguments) { java.sql.Connection conn = null; List<Map<String, String>> dimensions = new ArrayList<Map<String, String>>(); ResultSet rs; String column_names = new String(""); String table_name, query; Integer table_rank, population = 0; ArrayList<String> params = new ArrayList<String>(); Boolean doneOne = false; try { conn = evaluator.getQuery().getConnection().getDataSource().getConnection(); PreparedStatement st = conn.prepareStatement("SELECT dim_cols[?], mapping_func[?] FROM population.population_dimensions WHERE dim_name = ?"); // Get data on all necessary dimensions for (Dimension d : evaluator.getCube().getDimensions()) { Integer depth; logger.debug("checking dimension " + d.getName()); HashMap<String, String> dimhash = new HashMap<String, String>(); depth = evaluator.getContext(d).getLevel().getDepth(); st.setInt(1, depth); st.setInt(2, depth); st.setString(3, d.getName()); rs = st.executeQuery(); if (rs.next() && depth != 0) { // rs.next() is true only if it returned something, or in // other words, only when this dimension is important to // us. We also only care when depth is nonzero dimhash.put("name", d.getName()); dimhash.put("depth", depth.toString()); dimhash.put("value", evaluator.getContext(d).getName()); dimhash.put("column", rs.getString(1)); dimhash.put("mapper", rs.getString(2)); dimensions.add(dimhash); if (! column_names.equals("")) column_names += ", "; column_names += "'" + dimhash.get("column") + "'"; logger.info("Dimension " + d.getName() + " is useful, so keeping. Column: " + dimhash.get("column") + "\tMapper: " + dimhash.get("mapper")); logger.debug("column names list now == " + column_names); } } // Figure out what table to use // TODO: Note that there's some room for SQL injection problems here, if column names are stupid if (dimensions.size() != 0) { query = "SELECT table_name, table_rank FROM ( \n" + " SELECT \n" + " ppt.table_name, \n" + " COUNT(*), \n" + " ppt.table_rank \n" + " FROM \n" + " population.population_tables ppt \n" + " JOIN information_schema.columns isc \n" + " ON ( \n" + " isc.table_name = ppt.table_name AND \n" + " isc.table_schema = 'population' \n" + " ) \n" + " WHERE \n" + " isc.column_name IN (" + column_names + ") \n" + " GROUP BY \n" + " ppt.table_name, \n" + " ppt.table_rank \n" + " HAVING \n" + " COUNT(*) = ? \n" + ") f \n" + "ORDER BY table_rank ASC LIMIT 1;"; logger.debug("For finding table, using query : " + query); st = conn.prepareStatement(query); //st.setString(1, column_names); st.setInt(1, dimensions.size()); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find population table for dimensions: " + column_names); return null; } } else { logger.debug("No dimensions specified; using highest-ranking table"); st = conn.prepareStatement("SELECT table_name, table_rank FROM population.population_tables ORDER BY table_rank ASC LIMIT 1"); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find default population table"); return 0; } if (table_name == null || table_name.equals("")) { logger.warn("Couldn't find default population table"); return 0; } } logger.info("Pulling data from table " + table_name + " with rank " + table_rank.toString()); // Build query query = "SELECT COALESCE(SUM(population), 0) FROM population." + table_name; if (dimensions.size() > 0) { query += " WHERE"; for (Map<String, String> m : dimensions) { if (doneOne) query += " AND"; query += " " + m.get("column") + " = "; if (m.get("mapper") == null) query += "?"; else query += m.get("mapper") + "(?)"; params.add(m.get("value")); doneOne = true; } } logger.info("Using query : " + query); st = conn.prepareStatement(query); int i = 1; for (String s : params) { st.setString(i, s); i++; } rs = st.executeQuery(); rs.next(); population = rs.getInt(1); logger.debug("Population: " + population); } catch (SQLException s) { logger.error("JDBC Error", s); } try { if (conn != null) conn.close(); } catch (SQLException s) { logger.error("JDBC Error when disconnecting: ", s); } if (population == 0) return null; else return population; }
public Object execute(Evaluator evaluator, UserDefinedFunction.Argument[] arguments) { java.sql.Connection conn = null; List<Map<String, String>> dimensions = new ArrayList<Map<String, String>>(); ResultSet rs; String column_names = new String(""); String table_name, query; Integer table_rank, population = 0; ArrayList<String> params = new ArrayList<String>(); Boolean doneOne = false; try { conn = evaluator.getQuery().getConnection().getDataSource().getConnection(); PreparedStatement st = conn.prepareStatement("SELECT dim_cols[?], mapping_func[?] FROM population.population_dimensions WHERE dim_name = ?"); // Get data on all necessary dimensions for (Dimension d : evaluator.getCube().getDimensions()) { Integer depth; logger.debug("checking dimension " + d.getName()); HashMap<String, String> dimhash = new HashMap<String, String>(); depth = evaluator.getContext(d).getLevel().getDepth(); st.setInt(1, depth); st.setInt(2, depth); st.setString(3, d.getName()); rs = st.executeQuery(); if (rs.next() && depth != 0) { // rs.next() is true only if it returned something, or in // other words, only when this dimension is important to // us. We also only care when depth is nonzero dimhash.put("name", d.getName()); dimhash.put("depth", depth.toString()); dimhash.put("value", evaluator.getContext(d).getName()); dimhash.put("column", rs.getString(1)); dimhash.put("mapper", rs.getString(2)); dimensions.add(dimhash); if (! column_names.equals("")) column_names += ", "; column_names += "'" + dimhash.get("column") + "'"; logger.info("Dimension " + d.getName() + " is useful, so keeping. Column: " + dimhash.get("column") + "\tMapper: " + dimhash.get("mapper")); logger.debug("column names list now == " + column_names); } } // Figure out what table to use // TODO: Note that there's some room for SQL injection problems here, if column names are stupid if (dimensions.size() != 0) { query = "SELECT table_name, table_rank FROM ( \n" + " SELECT \n" + " ppt.table_name, \n" + " COUNT(*), \n" + " ppt.table_rank \n" + " FROM \n" + " population.population_tables ppt \n" + " JOIN information_schema.columns isc \n" + " ON ( \n" + " isc.table_name = ppt.table_name AND \n" + " isc.table_schema = 'population' \n" + " ) \n" + " WHERE \n" + " isc.column_name IN (" + column_names + ") \n" + " GROUP BY \n" + " ppt.table_name, \n" + " ppt.table_rank \n" + " HAVING \n" + " COUNT(*) = ? \n" + ") f \n" + "ORDER BY table_rank ASC LIMIT 1;"; logger.debug("For finding table, using query : " + query); st = conn.prepareStatement(query); //st.setString(1, column_names); st.setInt(1, dimensions.size()); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find population table for dimensions: " + column_names); return null; } } else { logger.debug("No dimensions specified; using highest-ranking table"); st = conn.prepareStatement("SELECT table_name, table_rank FROM population.population_tables ORDER BY table_rank ASC LIMIT 1"); rs = st.executeQuery(); if (rs.next()) { table_name = rs.getString(1); table_rank = rs.getInt(2); } else { logger.warn("Couldn't find default population table"); return null; } if (table_name == null || table_name.equals("")) { logger.warn("Couldn't find default population table"); return null; } } logger.info("Pulling data from table " + table_name + " with rank " + table_rank.toString()); // Build query query = "SELECT COALESCE(SUM(population), 0) FROM population." + table_name; if (dimensions.size() > 0) { query += " WHERE"; for (Map<String, String> m : dimensions) { if (doneOne) query += " AND"; query += " " + m.get("column") + " = "; if (m.get("mapper") == null) query += "?"; else query += m.get("mapper") + "(?)"; params.add(m.get("value")); doneOne = true; } } logger.info("Using query : " + query); st = conn.prepareStatement(query); int i = 1; for (String s : params) { st.setString(i, s); i++; } rs = st.executeQuery(); rs.next(); population = rs.getInt(1); logger.debug("Population: " + population); } catch (SQLException s) { logger.error("JDBC Error", s); } try { if (conn != null) conn.close(); } catch (SQLException s) { logger.error("JDBC Error when disconnecting: ", s); } return population; }
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java b/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java index 232f20b2d..7de241872 100644 --- a/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java +++ b/modules/cpr/src/main/java/org/atmosphere/cpr/SessionSupport.java @@ -1,56 +1,55 @@ /* * Copyright 2013 Jeanfrancois Arcand * * 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.atmosphere.cpr; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class SessionSupport implements HttpSessionListener { private final Logger logger = LoggerFactory.getLogger(SessionSupport.class); public SessionSupport() { } @Override public void sessionCreated(HttpSessionEvent se) { logger.trace("Session created"); } @Override public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); - BroadcasterFactory factory = BroadcasterFactory.getDefault(); - if (factory != null) { - for (Broadcaster b : factory.lookupAll()) { + if (BroadcasterFactory.getDefault() != null) { + for (Broadcaster b : BroadcasterFactory.getDefault().lookupAll()) { for (AtmosphereResource r : b.getAtmosphereResources()) { if (r.session() != null && r.session().getId().equals(s.getId())) { AtmosphereResourceImpl.class.cast(r).session(null); } } } } } catch (Throwable t) { logger.warn("", t); } } }
true
true
public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); BroadcasterFactory factory = BroadcasterFactory.getDefault(); if (factory != null) { for (Broadcaster b : factory.lookupAll()) { for (AtmosphereResource r : b.getAtmosphereResources()) { if (r.session() != null && r.session().getId().equals(s.getId())) { AtmosphereResourceImpl.class.cast(r).session(null); } } } } } catch (Throwable t) { logger.warn("", t); } }
public void sessionDestroyed(HttpSessionEvent se) { logger.trace("Session destroyed"); try { HttpSession s = se.getSession(); if (BroadcasterFactory.getDefault() != null) { for (Broadcaster b : BroadcasterFactory.getDefault().lookupAll()) { for (AtmosphereResource r : b.getAtmosphereResources()) { if (r.session() != null && r.session().getId().equals(s.getId())) { AtmosphereResourceImpl.class.cast(r).session(null); } } } } } catch (Throwable t) { logger.warn("", t); } }