diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellVmResource.java b/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellVmResource.java index 1d9bfe45..a051f96f 100644 --- a/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellVmResource.java +++ b/powershell/jaxrs/src/main/java/com/redhat/rhevm/api/powershell/resource/PowerShellVmResource.java @@ -1,368 +1,368 @@ /* * Copyright © 2010 Red Hat, Inc. * * 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 com.redhat.rhevm.api.powershell.resource; import java.util.List; import java.util.concurrent.Executor; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.redhat.rhevm.api.model.Action; import com.redhat.rhevm.api.model.CpuTopology; import com.redhat.rhevm.api.model.Display; import com.redhat.rhevm.api.model.Link; import com.redhat.rhevm.api.model.Ticket; import com.redhat.rhevm.api.model.VM; import com.redhat.rhevm.api.model.VmType; import com.redhat.rhevm.api.resource.AssignedPermissionsResource; import com.redhat.rhevm.api.resource.AssignedTagsResource; import com.redhat.rhevm.api.resource.VmResource; import com.redhat.rhevm.api.common.resource.UriInfoProvider; import com.redhat.rhevm.api.common.util.JAXBHelper; import com.redhat.rhevm.api.common.util.LinkHelper; import com.redhat.rhevm.api.common.util.ReflectionHelper; import com.redhat.rhevm.api.powershell.model.PowerShellTicket; import com.redhat.rhevm.api.powershell.model.PowerShellVM; import com.redhat.rhevm.api.powershell.util.PowerShellCmd; import com.redhat.rhevm.api.powershell.util.PowerShellParser; import com.redhat.rhevm.api.powershell.util.PowerShellPool; import com.redhat.rhevm.api.powershell.util.PowerShellPoolMap; import com.redhat.rhevm.api.powershell.util.PowerShellUtils; import static com.redhat.rhevm.api.common.util.CompletenessAssertor.validateParameters; import static com.redhat.rhevm.api.powershell.resource.PowerShellVmsResource.PROCESS_VMS; public class PowerShellVmResource extends AbstractPowerShellActionableResource<VM> implements VmResource { public PowerShellVmResource(String id, Executor executor, UriInfoProvider uriProvider, PowerShellPoolMap shellPools, PowerShellParser parser) { super(id, executor, uriProvider, shellPools, parser); } public static List<PowerShellVM> runAndParse(PowerShellPool pool, PowerShellParser parser, String command) { return PowerShellVM.parse(parser, PowerShellCmd.runCommand(pool, command)); } public static PowerShellVM runAndParseSingle(PowerShellPool pool, PowerShellParser parser, String command) { List<PowerShellVM> vms = runAndParse(pool, parser, command); return !vms.isEmpty() ? vms.get(0) : null; } public PowerShellVM runAndParseSingle(String command) { return runAndParseSingle(getPool(), getParser(), command); } public static VM addLinks(UriInfo uriInfo, PowerShellVM vm) { VM ret = JAXBHelper.clone("vm", VM.class, vm); String [] deviceCollections = { "cdroms", "disks", "floppies", "nics", "snapshots", "tags" }; ret.getLinks().clear(); for (String collection : deviceCollections) { addSubCollection(uriInfo, ret, collection); } if (VmType.DESKTOP.equals(ret.getType())) { addSubCollection(uriInfo, ret, "users"); } return LinkHelper.addLinks(uriInfo, ret); } @Override public VM get() { return addLinks(getUriInfo(), runAndParseSingle("get-vm " + PowerShellUtils.escape(getId()) + PROCESS_VMS)); } @Override public VM update(VM vm) { validateUpdate(vm); StringBuilder buf = new StringBuilder(); buf.append("$v = get-vm " + PowerShellUtils.escape(getId()) + ";"); if (vm.getName() != null) { buf.append("$v.name = " + PowerShellUtils.escape(vm.getName()) + ";"); } if (vm.getDescription() != null) { buf.append("$v.description = " + PowerShellUtils.escape(vm.getDescription()) + ";"); } if (vm.getType() != null) { buf.append("$v.vmtype = " + ReflectionHelper.capitalize(vm.getType().toString().toLowerCase()) + ";"); } if (vm.isSetMemory()) { buf.append(" $v.memorysize = " + Math.round((double)vm.getMemory()/(1024*1024)) + ";"); } if (vm.getCpu() != null && vm.getCpu().getTopology() != null) { CpuTopology topology = vm.getCpu().getTopology(); if (topology.isSetSockets()) { buf.append(" $v.numofsockets = " + topology.getSockets() + ";"); } if (topology.isSetCores()) { buf.append(" $v.numofcpuspersocket = " + topology.getCores() + ";"); } } String bootSequence = PowerShellVM.buildBootSequence(vm.getOs()); if (bootSequence != null) { buf.append(" $v.defaultbootsequence = '" + bootSequence + "';"); } if (vm.isSetOs() && vm.getOs().isSetType()) { buf.append(" $v.operatingsystem = " + PowerShellUtils.escape(vm.getOs().getType()) + ";"); } if (vm.isSetStateless()) { buf.append(" $v.stateless = " + PowerShellUtils.encode(vm.isStateless()) + ";"); } if (vm.isSetHighlyAvailable()) { buf.append(" $v.highlyavailable = " + PowerShellUtils.encode(vm.getHighlyAvailable().isValue()) + ";"); if (vm.getHighlyAvailable().isSetPriority()) { buf.append(" $v.priority = " + Integer.toString(vm.getHighlyAvailable().getPriority()) + ";"); } } if (vm.isSetDisplay()) { Display display = vm.getDisplay(); if (display.isSetMonitors()) { buf.append(" $v.numofmonitors = " + display.getMonitors() + ";"); } if (display.isSetType()) { buf.append(" $v.displaytype = '" + PowerShellVM.asString(display.getType()) + "';"); } // REVISIT display port a read-only property => extend immutability // assertion to support "display.port" style syntax } buf.append("update-vm -vmobject $v"); return addLinks(getUriInfo(), runAndParseSingle(buf.toString() + PROCESS_VMS)); } protected String[] getStrictlyImmutable() { return addStrictlyImmutable("type"); } @Override public Response start(Action action) { StringBuilder buf = new StringBuilder(); buf.append("start-vm"); buf.append(" -vmid " + PowerShellUtils.escape(getId())); if (action.isSetPause() && action.isPause()) { buf.append(" -runandpause"); } if (action.isSetVm()) { VM vm = action.getVm(); if (vm.isSetDisplay()) { buf.append(" -displaytype '" + PowerShellVM.asString(vm.getDisplay().getType()) + "'"); } String bootSequence = PowerShellVM.buildBootSequence(vm.getOs()); if (bootSequence != null) { buf.append(" -bootdevice '" + bootSequence + "'"); } if (vm.isSetCdroms() && vm.getCdroms().isSetCdRoms()) { String file = vm.getCdroms().getCdRoms().get(0).getFile().getId(); if (file != null) { - buf.append(" -isofilename '" + PowerShellUtils.escape(file) + "'"); + buf.append(" -isofilename " + PowerShellUtils.escape(file)); } } if (vm.isSetFloppies() && vm.getFloppies().isSetFloppies()) { String file = vm.getFloppies().getFloppies().get(0).getFile().getId(); if (file != null) { - buf.append(" -floppypath '" + PowerShellUtils.escape(file) + "'"); + buf.append(" -floppypath " + PowerShellUtils.escape(file)); } } } return doAction(getUriInfo(), new CommandRunner(action, buf.toString(), getPool())); } @Override public Response stop(Action action) { return doAction(getUriInfo(), new CommandRunner(action, "stop-vm", "vm", getId(), getPool())); } @Override public Response shutdown(Action action) { return doAction(getUriInfo(), new CommandRunner(action, "shutdown-vm", "vm", getId(), getPool())); } @Override public Response suspend(Action action) { return doAction(getUriInfo(), new CommandRunner(action, "suspend-vm", "vm", getId(), getPool())); } @Override public Response detach(Action action) { return doAction(getUriInfo(), new CommandRunner(action, "detach-vm", "vm", getId(), getPool())); } @Override public Response migrate(Action action) { validateParameters(action, "host.id|name"); StringBuilder buf = new StringBuilder(); String hostArg; if (action.getHost().isSetId()) { hostArg = PowerShellUtils.escape(action.getHost().getId()); } else { buf.append("$h = select-host -searchtext "); buf.append(PowerShellUtils.escape("name=" + action.getHost().getName())); buf.append(";"); hostArg = "$h.hostid"; } buf.append("migrate-vm"); buf.append(" -vmid " + PowerShellUtils.escape(getId())); buf.append(" -desthostid " + hostArg); return doAction(getUriInfo(), new CommandRunner(action, buf.toString(), getPool())); } @Override public Response export(Action action) { validateParameters(action, "storageDomain.id|name"); StringBuilder buf = new StringBuilder(); String storageDomainArg; if (action.getStorageDomain().isSetId()) { storageDomainArg = PowerShellUtils.escape(action.getStorageDomain().getId()); } else { buf.append("$dest = select-storagedomain "); buf.append("| ? { $_.name -eq "); buf.append(PowerShellUtils.escape(action.getStorageDomain().getName())); buf.append(" }; "); storageDomainArg = "$dest.storagedomainid"; } buf.append("export-vm"); buf.append(" -vmid " + PowerShellUtils.escape(getId())); buf.append(" -storagedomainid " + storageDomainArg); if (!action.isSetExclusive() || !action.isExclusive()) { buf.append(" -forceoverride"); } if (!action.isSetDiscardSnapshots() || !action.isDiscardSnapshots()) { buf.append(" -copycollapse"); } return doAction(getUriInfo(), new CommandRunner(action, buf.toString(), getPool())); } @Override public Response ticket(Action action) { StringBuilder buf = new StringBuilder(); buf.append("set-vmticket"); buf.append(" -vmid " + PowerShellUtils.escape(getId())); if (action.isSetTicket()) { Ticket ticket = action.getTicket(); if (ticket.isSetValue()) { buf.append(" -ticket " + PowerShellUtils.escape(ticket.getValue())); } if (ticket.isSetExpiry()) { buf.append(" -validtime " + PowerShellUtils.escape(Long.toString(ticket.getExpiry()))); } } return doAction(getUriInfo(), new CommandRunner(action, buf.toString(), getPool()) { protected void handleOutput(String output) { action.setTicket(PowerShellTicket.parse(getParser(), output)); } }); } public class CdRomQuery extends PowerShellCdRomsResource.CdRomQuery { public CdRomQuery(String id) { super(id); } @Override protected String getCdIsoPath() { return runAndParseSingle("get-vm " + PowerShellUtils.escape(id)).getCdIsoPath(); } } public class FloppyQuery extends PowerShellFloppiesResource.FloppyQuery { public FloppyQuery(String id) { super(id); } @Override protected String getFloppyPath() { return runAndParseSingle("get-vm " + PowerShellUtils.escape(id)).getFloppyPath(); } } @Override public PowerShellCdRomsResource getCdRomsResource() { return new PowerShellCdRomsResource(getId(), shellPools, new CdRomQuery(getId()), getUriProvider()); } @Override public PowerShellDisksResource getDisksResource() { return new PowerShellDisksResource(getId(), shellPools, getParser(), "get-vm", getUriProvider()); } @Override public PowerShellFloppiesResource getFloppiesResource() { return new PowerShellFloppiesResource(getId(), shellPools, new FloppyQuery(getId()), getUriProvider()); } @Override public PowerShellNicsResource getNicsResource() { return new PowerShellNicsResource(getId(), shellPools, getParser(), "get-vm", getUriProvider()); } @Override public PowerShellSnapshotsResource getSnapshotsResource() { return new PowerShellSnapshotsResource(getId(), getExecutor(), shellPools, getParser(), getUriProvider()); } @Override public AssignedTagsResource getTagsResource() { return new PowerShellAssignedTagsResource(VM.class, getId(), shellPools, getParser(), getUriProvider()); } @Override public PowerShellAttachedUsersResource getUsersResource() { return new PowerShellAttachedUsersResource(getId(), getExecutor(), shellPools, getParser(), getUriProvider()); } @Override public AssignedPermissionsResource getPermissionsResource() { return null; } private static void addSubCollection(UriInfo uriInfo, VM vm, String collection) { Link link = new Link(); link.setRel(collection); link.setHref(LinkHelper.getUriBuilder(uriInfo, vm).path(collection).build().toString()); vm.getLinks().add(link); } }
false
false
null
null
diff --git a/src/processing/mode/experimental/ErrorCheckerService.java b/src/processing/mode/experimental/ErrorCheckerService.java index 5453fef..1203bda 100644 --- a/src/processing/mode/experimental/ErrorCheckerService.java +++ b/src/processing/mode/experimental/ErrorCheckerService.java @@ -1,1399 +1,1398 @@ package processing.mode.experimental; import static processing.mode.experimental.ExperimentalMode.log; import static processing.mode.experimental.ExperimentalMode.logE; import java.awt.EventQueue; import java.io.File; import java.io.FileFilter; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.table.DefaultTableModel; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.problem.DefaultProblem; import processing.app.Base; import processing.app.Editor; import processing.app.Library; import processing.app.SketchCode; import processing.core.PApplet; import processing.mode.java.preproc.PdePreprocessor; public class ErrorCheckerService implements Runnable{ private DebugEditor editor; /** * Error check happens every sleepTime milliseconds */ public static final int sleepTime = 1000; /** * The amazing eclipse ast parser */ private ASTParser parser; /** * Used to indirectly stop the Error Checker Thread */ public boolean stopThread = false; /** * If true, Error Checking is paused. Calls to checkCode() become useless. */ private boolean pauseThread = false; protected ErrorWindow errorWindow; /** * IProblem[] returned by parser stored in here */ private IProblem[] problems; /** * Class name of current sketch */ protected String className; /** * Source code of current sketch */ protected String sourceCode; /** * URLs of extra imports jar files stored here. */ protected URL[] classpath; /** * Stores all Problems in the sketch */ public ArrayList<Problem> problemsList; /** * How many lines are present till the initial class declaration? In static * mode, this would include imports, class declaration and setup * declaration. In nomral mode, this would include imports, class * declaration only. It's fate is decided inside preprocessCode() */ public int mainClassOffset; /** * Fixed p5 offsets for all sketches */ public int defaultImportsOffset; /** * Is the sketch running in static mode or active mode? */ public boolean staticMode = false; /** * Compilation Unit for current sketch */ protected CompilationUnit cu; /** * If true, compilation checker will be reloaded with updated classpath * items. */ private boolean loadCompClass = true; /** * Compiler Checker class. Note that methods for compilation checking are * called from the compilationChecker object, not from this */ protected Class<?> checkerClass; /** * Compilation Checker object. */ protected Object compilationChecker; /** * List of jar files to be present in compilation checker's classpath */ protected ArrayList<URL> classpathJars; /** * Timestamp - for measuring total overhead */ private long lastTimeStamp = System.currentTimeMillis(); /** * Used for displaying the rotating slash on the Problem Window title bar */ private String[] slashAnimation = { "|", "/", "--", "\\", "|", "/", "--", "\\" }; private int slashAnimationIndex = 0; /** * Used to detect if the current tab index has changed and thus repaint the * textarea. */ public int currentTab = 0, lastTab = 0; /** * Stores the current import statements in the program. Used to compare for * changed import statements and update classpath if needed. */ private ArrayList<ImportStatement> programImports; /** * List of imports when sketch was last checked. Used for checking for * changed imports */ protected ArrayList<ImportStatement> previousImports = new ArrayList<ImportStatement>(); /** * Teh Preprocessor */ protected XQPreprocessor xqpreproc; /** * Regexp for import statements. (Used from Processing source) */ final public String importRegexp = "(?:^|;)\\s*(import\\s+)((?:static\\s+)?\\S+)(\\s*;)"; /** * Regexp for function declarations. (Used from Processing source) */ final Pattern FUNCTION_DECL = Pattern .compile("(^|;)\\s*((public|private|protected|final|static)\\s+)*" + "(void|int|float|double|String|char|byte)" + "(\\s*\\[\\s*\\])?\\s+[a-zA-Z0-9]+\\s*\\(", Pattern.MULTILINE); protected ErrorMessageSimplifier errorMsgSimplifier; public ErrorCheckerService(DebugEditor debugEditor) { this.editor = debugEditor; initParser(); initializeErrorWindow(); xqpreproc = new XQPreprocessor(); PdePreprocessor pdePrepoc = new PdePreprocessor(null); defaultImportsOffset = pdePrepoc.getCoreImports().length + pdePrepoc.getDefaultImports().length + 1; astGenerator = new ASTGenerator(this); syntaxErrors = new AtomicBoolean(true); errorMsgSimplifier = new ErrorMessageSimplifier(); tempErrorLog = new TreeMap<String, IProblem>(); } /** * Initializes ASTParser */ private void initParser() { try { parser = ASTParser.newParser(AST.JLS4); } catch (Exception e) { System.err.println("Experimental Mode initialization failed. " + "Are you running the right version of Processing? "); pauseThread(); } catch (Error e) { System.err.println("Experimental Mode initialization failed. "); e.printStackTrace(); pauseThread(); } } /** * Initialiazes the Error Window */ public void initializeErrorWindow() { if (editor == null) { return; } if (errorWindow != null) { return; } final ErrorCheckerService thisService = this; final DebugEditor thisEditor = editor; EventQueue.invokeLater(new Runnable() { public void run() { try { errorWindow = new ErrorWindow(thisEditor, thisService); // errorWindow.setVisible(true); editor.toFront(); errorWindow.errorTable.setFocusable(false); editor.setSelection(0, 0); } catch (Exception e) { e.printStackTrace(); } } }); } public void run() { stopThread = false; checkCode(); if(!hasSyntaxErrors()) editor.showProblemListView(XQConsoleToggle.CONSOLE); while (!stopThread) { try { // Take a nap. Thread.sleep(sleepTime); } catch (Exception e) { log("Oops! [ErrorCheckerThreaded]: " + e); // e.printStackTrace(); } updatePaintedThingys(); updateEditorStatus(); if (pauseThread) continue; if(textModified.get() == 0) continue; // Check every x seconds checkCode(); checkForMissingImports(); } } private void checkForMissingImports() { for (Problem p : problemsList) { if(p.getMessage().endsWith(" cannot be resolved to a type"));{ int idx = p.getMessage().indexOf(" cannot be resolved to a type"); if(idx > 1){ String missingClass = p.getMessage().substring(0, idx); //log("Will suggest for type:" + missingClass); astGenerator.suggestImports(missingClass); } } } } protected ASTGenerator astGenerator; /** * This thing acts as an event queue counter of sort. * Since error checking happens on demand, anytime this counter * goes above 0, error check is triggered, and counter reset. * It's thread safe to avoid any mess. */ protected AtomicInteger textModified = new AtomicInteger(); /** * Triggers error check */ public void runManualErrorCheck() { textModified.incrementAndGet(); } private boolean checkCode() { //log("checkCode() " + textModified.get() ); log("checkCode() " + textModified.get()); lastTimeStamp = System.currentTimeMillis(); try { sourceCode = preprocessCode(editor.getSketch().getMainProgram()); syntaxCheck(); log(editor.getSketch().getName() + "1 MCO " + mainClassOffset); // No syntax errors, proceed for compilation check, Stage 2. astGenerator.buildAST(cu); if (problems.length == 0 && editor.compilationCheckEnabled) { //mainClassOffset++; // just a hack. sourceCode = xqpreproc.doYourThing(sourceCode, programImports); prepareCompilerClasspath(); // mainClassOffset = xqpreproc.mainClassOffset; // tiny, but // // significant // if (staticMode) { // mainClassOffset++; // Extra line for setup() decl. // } // log(sourceCode); // log("--------------------------"); compileCheck(); log(editor.getSketch().getName() + "2 MCO " + mainClassOffset); } updateErrorTable(); editor.updateErrorBar(problemsList); updateEditorStatus(); editor.getTextArea().repaint(); updatePaintedThingys(); int x = textModified.get(); //log("TM " + x); if (x >= 2) { textModified.set(2); x = 2; } if (x > 0) textModified.set(x - 1); else textModified.set(0); return true; } catch (Exception e) { log("Oops! [ErrorCheckerService.checkCode]: " + e); e.printStackTrace(); } return false; } private AtomicBoolean syntaxErrors; public boolean hasSyntaxErrors(){ return syntaxErrors.get(); } protected TreeMap<String, IProblem> tempErrorLog; private void syntaxCheck() { syntaxErrors.set(true); parser.setSource(sourceCode.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); @SuppressWarnings("unchecked") Map<String, String> options = JavaCore.getOptions(); JavaCore.setComplianceOptions(JavaCore.VERSION_1_6, options); options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_6); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); parser.setCompilerOptions(options); cu = (CompilationUnit) parser.createAST(null); // Store errors returned by the ast parser problems = cu.getProblems(); // log("Problem Count: " + problems.length); // Populate the probList problemsList = new ArrayList<Problem>(); for (int i = 0; i < problems.length; i++) { int a[] = calculateTabIndexAndLineNumber(problems[i]); Problem p = new Problem(problems[i], a[0], a[1] + 1); //TODO: ^Why do cheeky stuff? problemsList.add(p); // log(problems[i].getMessage()); // for (String j : problems[i].getArguments()) { // log("arg " + j); // } // log(p.toString()); } if (problems.length == 0) syntaxErrors.set(false); else syntaxErrors.set(true); astGenerator.loadJars(); } protected URLClassLoader classLoader; private void compileCheck() { // Currently (Sept, 2012) I'm using Java's reflection api to load the // CompilationChecker class(from CompilationChecker.jar) that houses the // Eclispe JDT compiler and call its getErrorsAsObj method to obtain // errors. This way, I'm able to add the paths of contributed libraries // to the classpath of CompilationChecker, dynamically. The eclipse compiler // needs all referenced libraries in the classpath. try { // NOTE TO SELF: If classpath contains null Strings // URLClassLoader gets angry. Drops NPE bombs. // If imports have changed, reload classes with new classpath. if (loadCompClass) { // if (classpathJars.size() > 0) // System.out // .println("Experimental Mode: Loading contributed libraries referenced by import statements."); // The folder SketchBook/modes/ExperimentalMode/mode - File f = new File(Base.getSketchbookModesFolder().getAbsolutePath() + File.separator + "ExperimentalMode" - + File.separator + "mode"); + File f = editor.getMode().getContentFile("mode"); if(!f.exists()) { System.err.println("Could not locate the files required for on-the-fly error checking. Bummer."); return; } FileFilter fileFilter = new FileFilter() { public boolean accept(File file) { return (file.getName().endsWith(".jar") && !file .getName().startsWith("ExperimentalMode")); } }; File[] jarFiles = f.listFiles(fileFilter); // log( "Jar files found? " + (jarFiles != null)); //for (File jarFile : jarFiles) { //classpathJars.add(jarFile.toURI().toURL()); //} classpath = new URL[classpathJars.size() + jarFiles.length]; int ii = 0; for (; ii < classpathJars.size(); ii++) { classpath[ii] = classpathJars.get(ii); } for (int i = 0; i < jarFiles.length; i++) { classpath[ii++] = jarFiles[i].toURI().toURL(); } // log("CP Len -- " + classpath.length); classLoader = new URLClassLoader(classpath); // log("1."); checkerClass = Class.forName("CompilationChecker", true, classLoader); // log("2."); compilationChecker = checkerClass.newInstance(); astGenerator.loadJars(); // Update jar files for completition list loadCompClass = false; } if (compilerSettings == null) { prepareCompilerSetting(); } Method getErrors = checkerClass.getMethod("getErrorsAsObjArr", new Class[] { String.class, String.class, Map.class }); Object[][] errorList = (Object[][]) getErrors .invoke(compilationChecker, className, sourceCode, compilerSettings); if (errorList == null) { return; } problems = new DefaultProblem[errorList.length]; for (int i = 0; i < errorList.length; i++) { // for (int j = 0; j < errorList[i].length; j++) // System.out.print(errorList[i][j] + ", "); problems[i] = new DefaultProblem((char[]) errorList[i][0], (String) errorList[i][1], ((Integer) errorList[i][2]).intValue(), (String[]) errorList[i][3], ((Integer) errorList[i][4]).intValue(), ((Integer) errorList[i][5]).intValue(), ((Integer) errorList[i][6]).intValue(), ((Integer) errorList[i][7]).intValue(), 0); // System.out // .println("ECS: " + problems[i].getMessage() + "," // + problems[i].isError() + "," // + problems[i].isWarning()); IProblem problem = problems[i]; // log(problem.getMessage()); // for (String j : problem.getArguments()) { // log("arg " + j); // } int a[] = calculateTabIndexAndLineNumber(problem); Problem p = new Problem(problem, a[0], a[1]); if ((Boolean) errorList[i][8]) { p.setType(Problem.ERROR); } if ((Boolean) errorList[i][9]) { p.setType(Problem.WARNING); } // If warnings are disabled, skip 'em if (p.isWarning() && !warningsEnabled) { continue; } problemsList.add(p); } } catch (ClassNotFoundException e) { System.err.println("Compiltation Checker files couldn't be found! " + e + " compileCheck() problem."); stopThread(); } catch (MalformedURLException e) { System.err.println("Compiltation Checker files couldn't be found! " + e + " compileCheck() problem."); stopThread(); } catch (Exception e) { System.err.println("compileCheck() problem." + e); e.printStackTrace(); stopThread(); } catch (NoClassDefFoundError e) { System.err .println(e + " compileCheck() problem. Somebody tried to mess with Experimental Mode files."); stopThread(); } // log("Compilecheck, Done."); } public URLClassLoader getSketchClassLoader() { return classLoader; } /** * Processes import statements to obtain classpaths of contributed * libraries. This would be needed for compilation check. Also, adds * stuff(jar files, class files, candy) from the code folder. And it looks * messed up. * */ private void prepareCompilerClasspath() { if (!loadCompClass) { return; } // log("1.."); classpathJars = new ArrayList<URL>(); String entry = ""; boolean codeFolderChecked = false; for (ImportStatement impstat : programImports) { String item = impstat.getImportName(); int dot = item.lastIndexOf('.'); entry = (dot == -1) ? item : item.substring(0, dot); entry = entry.substring(6).trim(); // log("Entry--" + entry); if (ignorableImport(entry)) { // log("Ignoring: " + entry); continue; } Library library = null; // Try to get the library classpath and add it to the list try { library = editor.getMode().getLibrary(entry); // log("lib->" + library.getClassPath() + "<-"); String libraryPath[] = PApplet.split(library.getClassPath() .substring(1).trim(), File.pathSeparatorChar); for (int i = 0; i < libraryPath.length; i++) { // log(entry + " ::" // + new File(libraryPath[i]).toURI().toURL()); classpathJars.add(new File(libraryPath[i]).toURI().toURL()); } // log("-- "); // classpath[count] = (new File(library.getClassPath() // .substring(1))).toURI().toURL(); // log(" found "); // log(library.getClassPath().substring(1)); } catch (Exception e) { if (library == null && !codeFolderChecked) { // log(1); // Look around in the code folder for jar files if (editor.getSketch().hasCodeFolder()) { File codeFolder = editor.getSketch().getCodeFolder(); // get a list of .jar files in the "code" folder // (class files in subfolders should also be picked up) String codeFolderClassPath = Base .contentsToClassPath(codeFolder); codeFolderChecked = true; if (codeFolderClassPath.equalsIgnoreCase("")) { System.err.println("Experimental Mode: Yikes! Can't find \"" + entry + "\" library! Line: " + impstat.getLineNumber() + " in tab: " + editor.getSketch().getCode(impstat.getTab()) .getPrettyName()); System.out .println("Please make sure that the library is present in <sketchbook " + "folder>/libraries folder or in the code folder of your sketch"); } String codeFolderPath[] = PApplet.split( codeFolderClassPath.substring(1).trim(), File.pathSeparatorChar); try { for (int i = 0; i < codeFolderPath.length; i++) { classpathJars.add(new File(codeFolderPath[i]) .toURI().toURL()); } } catch (Exception e2) { System.out .println("Yikes! codefolder, prepareImports(): " + e2); } } else { System.err.println("Experimental Mode: Yikes! Can't find \"" + entry + "\" library! Line: " + impstat.getLineNumber() + " in tab: " + editor.getSketch().getCode(impstat.getTab()) .getPrettyName()); System.out .println("Please make sure that the library is present in <sketchbook " + "folder>/libraries folder or in the code folder of your sketch"); } } else { System.err .println("Yikes! There was some problem in prepareImports(): " + e); System.err.println("I was processing: " + entry); // e.printStackTrace(); } } } } /** * Ignore processing packages, java.*.*. etc. * * @param packageName * @return boolean */ protected boolean ignorableImport(String packageName) { // packageName.startsWith("processing.") // || if (packageName.startsWith("java.") || packageName.startsWith("javax.")) { return true; } return false; } /** * Various option for JDT Compiler */ @SuppressWarnings("rawtypes") protected Map compilerSettings; /** * Enable/Disable warnings from being shown */ public boolean warningsEnabled = true; /** * Sets compiler options for JDT Compiler */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void prepareCompilerSetting() { compilerSettings = new HashMap(); compilerSettings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); compilerSettings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); compilerSettings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6); compilerSettings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE); compilerSettings.put(CompilerOptions.OPTION_ReportMissingSerialVersion, CompilerOptions.IGNORE); compilerSettings.put(CompilerOptions.OPTION_ReportRawTypeReference, CompilerOptions.IGNORE); compilerSettings.put( CompilerOptions.OPTION_ReportUncheckedTypeOperation, CompilerOptions.IGNORE); } /** * Updates the error table in the Error Window. */ synchronized public void updateErrorTable() { try { String[][] errorData = new String[problemsList.size()][3]; for (int i = 0; i < problemsList.size(); i++) { errorData[i][0] = problemsList.get(i).message; ////TODO: this is temporary //+ " : " + errorMsgSimplifier.getIDName(problemsList.get(i).getIProblem().getID()); errorData[i][1] = editor.getSketch() .getCode(problemsList.get(i).tabIndex).getPrettyName(); errorData[i][2] = problemsList.get(i).lineNumber + ""; //TODO: This is temporary if(tempErrorLog.size() < 200) tempErrorLog.put(problemsList.get(i).message,problemsList.get(i).getIProblem()); } if (errorWindow != null) { DefaultTableModel tm = new DefaultTableModel(errorData, XQErrorTable.columnNames); if (errorWindow.isVisible()) { errorWindow.updateTable(tm); } // Update error table in the editor editor.updateTable(tm); // A rotating slash animation on the title bar to show // that error checker thread is running slashAnimationIndex++; if (slashAnimationIndex == slashAnimation.length) { slashAnimationIndex = 0; } if (editor != null) { String info = slashAnimation[slashAnimationIndex] + " T:" + (System.currentTimeMillis() - lastTimeStamp) + "ms"; errorWindow.setTitle("Problems - " + editor.getSketch().getName() + " " + info); } } } catch (Exception e) { log("Exception at updateErrorTable() " + e); e.printStackTrace(); stopThread(); } } /** * Repaints the textarea if required */ public void updatePaintedThingys() { currentTab = editor.getSketch().getCodeIndex( editor.getSketch().getCurrentCode()); //log("Tab changed " + currentTab + " LT " + lastTab); if (currentTab != lastTab) { textModified.set(5); lastTab = currentTab; editor.getTextArea().repaint(); editor.statusEmpty(); return; } } protected int lastCaretLine = -1; /** * Updates editor status bar, depending on whether the caret is on an error * line or not */ public void updateEditorStatus() { // editor.statusNotice("Position: " + // editor.getTextArea().getCaretLine()); for (ErrorMarker emarker : editor.errorBar.errorPoints) { if (emarker.problem.lineNumber == editor.getTextArea() .getCaretLine() + 1) { if (emarker.type == ErrorMarker.Warning) { editor.statusNotice(emarker.problem.message); //+ " : " + errorMsgSimplifier.getIDName(emarker.problem.getIProblem().getID())); //TODO: this is temporary } else { editor.statusError(emarker.problem.message); //+ " : " + errorMsgSimplifier.getIDName(emarker.problem.getIProblem().getID())); } return; } } if (editor.ta.getCaretLine() != lastCaretLine) { editor.statusEmpty(); lastCaretLine = editor.ta.getCaretLine(); } } /** * Maps offset from java code to pde code. Returns a bunch of offsets as array * * @param line * - line number in java code * @param offset * - offset from the start of the 'line' * @return int[0] - tab number, int[1] - line number in the int[0] tab, int[2] * - line start offset, int[3] - offset from line start. int[2] and * int[3] are on TODO */ public int[] JavaToPdeOffsets(int line, int offset){ int codeIndex = 0; int x = line - mainClassOffset; if (x < 0) { // log("Negative line number " // + problem.getSourceLineNumber() + " , offset " // + mainClassOffset); x = line - 2; // Another -1 for 0 index if (x < programImports.size() && x >= 0) { ImportStatement is = programImports.get(x); // log(is.importName + ", " + is.tab + ", " // + is.lineNumber); return new int[] { is.getTab(), is.getLineNumber() }; } else { // Some seriously ugly stray error, just can't find the source // line! Simply return first line for first tab. return new int[] { 0, 1 }; } } try { for (SketchCode sc : editor.getSketch().getCode()) { if (sc.isExtension("pde")) { int len = 0; if (editor.getSketch().getCurrentCode().equals(sc)) { len = Base.countLines(sc.getDocument().getText(0, sc.getDocument().getLength())) + 1; } else { len = Base.countLines(sc.getProgram()) + 1; } // log("x,len, CI: " + x + "," + len + "," // + codeIndex); if (x >= len) { // We're in the last tab and the line count is greater // than the no. // of lines in the tab, if (codeIndex >= editor.getSketch().getCodeCount() - 1) { // log("Exceeds lc " + x + "," + len // + problem.toString()); // x = len x = editor.getSketch().getCode(codeIndex) .getLineCount(); // TODO: Obtain line having last non-white space // character in the code. break; } else { x -= len; codeIndex++; } } else { if (codeIndex >= editor.getSketch().getCodeCount()) { codeIndex = editor.getSketch().getCodeCount() - 1; } break; } } } } catch (Exception e) { System.err .println("Things got messed up in ErrorCheckerService.JavaToPdeOffset()"); } return new int[] { codeIndex, x }; } public String getPDECodeAtLine(int tab, int linenumber){ if(linenumber < 0) return null; editor.getSketch().setCurrentCode(tab); return editor.ta.getLineText(linenumber); } /** * Calculates the tab number and line number of the error in that particular * tab. Provides mapping between pure java and pde code. * * @param problem * - IProblem * @return int[0] - tab number, int[1] - line number */ public int[] calculateTabIndexAndLineNumber(IProblem problem) { // String[] lines = {};// = PApplet.split(sourceString, '\n'); int codeIndex = 0; int x = problem.getSourceLineNumber() - mainClassOffset; if (x < 0) { // log("Negative line number " // + problem.getSourceLineNumber() + " , offset " // + mainClassOffset); x = problem.getSourceLineNumber() - 2; // Another -1 for 0 index if (x < programImports.size() && x >= 0) { ImportStatement is = programImports.get(x); // log(is.importName + ", " + is.tab + ", " // + is.lineNumber); return new int[] { is.getTab(), is.getLineNumber() }; } else { // Some seriously ugly stray error, just can't find the source // line! Simply return first line for first tab. return new int[] { 0, 1 }; } } try { for (SketchCode sc : editor.getSketch().getCode()) { if (sc.isExtension("pde")) { int len = 0; if (editor.getSketch().getCurrentCode().equals(sc)) { len = Base.countLines(sc.getDocument().getText(0, sc.getDocument().getLength())) + 1; } else { len = Base.countLines(sc.getProgram()) + 1; } // log("x,len, CI: " + x + "," + len + "," // + codeIndex); if (x >= len) { // We're in the last tab and the line count is greater // than the no. // of lines in the tab, if (codeIndex >= editor.getSketch().getCodeCount() - 1) { // log("Exceeds lc " + x + "," + len // + problem.toString()); // x = len x = editor.getSketch().getCode(codeIndex) .getLineCount(); // TODO: Obtain line having last non-white space // character in the code. break; } else { x -= len; codeIndex++; } } else { if (codeIndex >= editor.getSketch().getCodeCount()) { codeIndex = editor.getSketch().getCodeCount() - 1; } break; } } } } catch (Exception e) { System.err .println("Things got messed up in ErrorCheckerService.calculateTabIndexAndLineNumber()"); } return new int[] { codeIndex, x }; } /** * Fetches code from the editor tabs and pre-processes it into parsable pure * java source. And there's a difference between parsable and compilable. * XQPrerocessor.java makes this code compilable. <br> * Handles: <li>Removal of import statements <li>Conversion of int(), * char(), etc to PApplet.parseInt(), etc. <li>Replacing '#' with 0xff for * color representation<li>Converts all 'color' datatypes to int * (experimental) <li>Appends class declaration statement after determining * the mode the sketch is in - ACTIVE or STATIC * * @return String - Pure java representation of PDE code. Note that this * code is not yet compile ready. */ private String preprocessCode(String pdeCode) { programImports = new ArrayList<ImportStatement>(); StringBuffer rawCode = new StringBuffer(); try { for (SketchCode sc : editor.getSketch().getCode()) { if (sc.isExtension("pde")) { try { if (editor.getSketch().getCurrentCode().equals(sc)) { rawCode.append(scrapImportStatements(sc.getDocument() .getText(0, sc.getDocument() .getLength()), editor.getSketch() .getCodeIndex(sc))); } else { rawCode.append(scrapImportStatements(sc.getProgram(), editor .getSketch().getCodeIndex(sc))); } rawCode.append('\n'); } catch (Exception e) { System.err.println("Exception in preprocessCode() - bigCode " + e.toString()); } rawCode.append('\n'); } } } catch (Exception e) { log("Exception in preprocessCode()"); } String sourceAlt = rawCode.toString(); // Replace comments with whitespaces // sourceAlt = scrubComments(sourceAlt); // Find all int(*), replace with PApplet.parseInt(*) // \bint\s*\(\s*\b , i.e all exclusive "int(" String dataTypeFunc[] = { "int", "char", "float", "boolean", "byte" }; for (String dataType : dataTypeFunc) { String dataTypeRegexp = "\\b" + dataType + "\\s*\\("; Pattern pattern = Pattern.compile(dataTypeRegexp); Matcher matcher = pattern.matcher(sourceAlt); // while (matcher.find()) { // System.out.print("Start index: " + matcher.start()); // log(" End index: " + matcher.end() + " "); // log("-->" + matcher.group() + "<--"); // } sourceAlt = matcher.replaceAll("PApplet.parse" + Character.toUpperCase(dataType.charAt(0)) + dataType.substring(1) + "("); } // Find all #[web color] and replace with 0xff[webcolor] // Should be 6 digits only. final String webColorRegexp = "#{1}[A-F|a-f|0-9]{6}\\W"; Pattern webPattern = Pattern.compile(webColorRegexp); Matcher webMatcher = webPattern.matcher(sourceAlt); while (webMatcher.find()) { // log("Found at: " + webMatcher.start()); String found = sourceAlt.substring(webMatcher.start(), webMatcher.end()); // log("-> " + found); sourceAlt = webMatcher.replaceFirst("0xff" + found.substring(1)); webMatcher = webPattern.matcher(sourceAlt); } // Replace all color data types with int // Regex, Y U SO powerful? final String colorTypeRegex = "color(?![a-zA-Z0-9_])(?=\\[*)(?!(\\s*\\())"; Pattern colorPattern = Pattern.compile(colorTypeRegex); Matcher colorMatcher = colorPattern.matcher(sourceAlt); sourceAlt = colorMatcher.replaceAll("int"); checkForChangedImports(); className = (editor == null) ? "DefaultClass" : editor.getSketch() .getName(); // Check whether the code is being written in STATIC mode(no function // declarations) - append class declaration and void setup() declaration Matcher matcher = FUNCTION_DECL.matcher(sourceAlt); if (!matcher.find()) { sourceAlt = xqpreproc.prepareImports(programImports) + "public class " + className + " extends PApplet {\n" + "public void setup() {\n" + sourceAlt + "\nnoLoop();\n}\n" + "\n}\n"; staticMode = true; } else { sourceAlt = xqpreproc.prepareImports(programImports) + "public class " + className + " extends PApplet {\n" + sourceAlt + "\n}"; staticMode = false; } int position = sourceAlt.indexOf("{") + 1; mainClassOffset = 1; for (int i = 0; i <= position; i++) { if (sourceAlt.charAt(i) == '\n') { mainClassOffset++; } } if(staticMode) { mainClassOffset++; } //mainClassOffset += 2; // Handle unicode characters sourceAlt = substituteUnicode(sourceAlt); // log("-->\n" + sourceAlt + "\n<--"); // log("PDE code processed - " // + editor.getSketch().getName()); sourceCode = sourceAlt; return sourceAlt; } /** * The super method that highlights any ASTNode in the pde editor =D * @param node * @return true - if highlighting happened correctly. */ public boolean highlightNode(ASTNodeWrapper awrap){ try { int pdeoffsets[] = awrap.getPDECodeOffsets(this); int javaoffsets[] = awrap.getJavaCodeOffsets(this); scrollToErrorLine(editor, pdeoffsets[0], pdeoffsets[1],javaoffsets[1], javaoffsets[2]); return true; } catch (Exception e) { logE("Scrolling failed for " + awrap); // e.printStackTrace(); } return false; } public boolean highlightNode(ASTNode node){ ASTNodeWrapper awrap = new ASTNodeWrapper(node); return highlightNode(awrap); } /** * Scrolls to the error source in code. And selects the line text. Used by * XQErrorTable and ErrorBar * * @param errorIndex * - index of error */ public void scrollToErrorLine(int errorIndex) { if (editor == null) { return; } if (errorIndex < problemsList.size() && errorIndex >= 0) { Problem p = problemsList.get(errorIndex); scrollToErrorLine(p); } } public void scrollToErrorLine(Problem p) { if (editor == null) { return; } if (p == null) return; try { editor.toFront(); editor.getSketch().setCurrentCode(p.tabIndex); editor .setSelection(editor.getTextArea() .getLineStartNonWhiteSpaceOffset(p.lineNumber - 1) + editor.getTextArea() .getLineText(p.lineNumber - 1).trim().length(), editor.getTextArea() .getLineStartNonWhiteSpaceOffset(p.lineNumber - 1)); editor.getTextArea().scrollTo(p.lineNumber - 1, 0); editor.repaint(); } catch (Exception e) { System.err.println(e + " : Error while selecting text in scrollToErrorLine()"); e.printStackTrace(); } // log("---"); } /** * Static method for scroll to a particular line in the PDE. Also highlights * the length of the text. Requires the editor instance as arguement. * * @param edt * @param tabIndex * @param lineNoInTab * - line number in the corresponding tab * @param lineStartOffset * - selection start offset(from line start non-whitespace offset) * @param length * - length of selection * @return - true, if scroll was successful */ public static boolean scrollToErrorLine(Editor edt, int tabIndex, int lineNoInTab, int lineStartOffset, int length) { if (edt == null) { return false; } try { edt.toFront(); edt.getSketch().setCurrentCode(tabIndex); int lsno = edt.getTextArea() .getLineStartNonWhiteSpaceOffset(lineNoInTab - 1) + lineStartOffset; edt.setSelection(lsno, lsno + length); edt.getTextArea().scrollTo(lineNoInTab - 1, 0); edt.repaint(); log(lineStartOffset + " LSO,len " + length); } catch (Exception e) { System.err.println(e + " : Error while selecting text in static scrollToErrorLine()"); e.printStackTrace(); return false; } return true; } /** * Checks if import statements in the sketch have changed. If they have, * compiler classpath needs to be updated. */ private void checkForChangedImports() { // log("Imports: " + programImports.size() + // " Prev Imp: " // + previousImports.size()); if (programImports.size() != previousImports.size()) { // log(1); loadCompClass = true; previousImports = programImports; } else { for (int i = 0; i < programImports.size(); i++) { if (!programImports.get(i).getImportName().equals(previousImports .get(i).getImportName())) { // log(2); loadCompClass = true; previousImports = programImports; break; } } } // log("load..? " + loadCompClass); } private int pdeImportsCount; public int getPdeImportsCount() { return pdeImportsCount; } /** * Removes import statements from tabSource, replaces each with white spaces * and adds the import to the list of program imports * * @param tabProgram * - Code in a tab * @param tabNumber * - index of the tab * @return String - Tab code with imports replaced with white spaces */ private String scrapImportStatements(String tabProgram, int tabNumber) { //TODO: Commented out imports are still detected as main imports. pdeImportsCount = 0; String tabSource = new String(tabProgram); do { // log("-->\n" + sourceAlt + "\n<--"); String[] pieces = PApplet.match(tabSource, importRegexp); // Stop the loop if we've removed all the import lines if (pieces == null) { break; } String piece = pieces[1] + pieces[2] + pieces[3]; int len = piece.length(); // how much to trim out // programImports.add(piece); // the package name // find index of this import in the program int idx = tabSource.indexOf(piece); // System.out.print("Import -> " + piece); // log(" - " // + Base.countLines(tabSource.substring(0, idx)) + " tab " // + tabNumber); programImports.add(new ImportStatement(piece, tabNumber, Base .countLines(tabSource.substring(0, idx)))); // Remove the import from the main program // Substitute with white spaces String whiteSpace = ""; for (int j = 0; j < piece.length(); j++) { whiteSpace += " "; } tabSource = tabSource.substring(0, idx) + whiteSpace + tabSource.substring(idx + len); pdeImportsCount++; } while (true); // log(tabSource); return tabSource; } /** * Replaces non-ascii characters with their unicode escape sequences and * stuff. Used as it is from * processing.src.processing.mode.java.preproc.PdePreprocessor * * @param program * - Input String containing non ascii characters * @return String - Converted String */ public static String substituteUnicode(String program) { // check for non-ascii chars (these will be/must be in unicode format) char p[] = program.toCharArray(); int unicodeCount = 0; for (int i = 0; i < p.length; i++) { if (p[i] > 127) { unicodeCount++; } } if (unicodeCount == 0) { return program; } // if non-ascii chars are in there, convert to unicode escapes // add unicodeCount * 5.. replacing each unicode char // with six digit uXXXX sequence (xxxx is in hex) // (except for nbsp chars which will be a replaced with a space) int index = 0; char p2[] = new char[p.length + unicodeCount * 5]; for (int i = 0; i < p.length; i++) { if (p[i] < 128) { p2[index++] = p[i]; } else if (p[i] == 160) { // unicode for non-breaking space p2[index++] = ' '; } else { int c = p[i]; p2[index++] = '\\'; p2[index++] = 'u'; char str[] = Integer.toHexString(c).toCharArray(); // add leading zeros, so that the length is 4 // for (int i = 0; i < 4 - str.length; i++) p2[index++] = '0'; for (int m = 0; m < 4 - str.length; m++) p2[index++] = '0'; System.arraycopy(str, 0, p2, index, str.length); index += str.length; } } return new String(p2, 0, index); } /** * Stops the Error Checker Service thread */ public void stopThread() { stopThread = true; } /** * Pauses the Error Checker Service thread */ public void pauseThread() { pauseThread = true; } /** * Resumes the Error Checker Service thread */ public void resumeThread() { pauseThread = false; } public DebugEditor getEditor() { return editor; } // public static void log(String message){ // if(ExperimentalMode.DEBUG) // log(message); // } // // public static void log2(String message){ // if(ExperimentalMode.DEBUG) // System.out.print(message); // } public ArrayList<ImportStatement> getProgramImports() { return programImports; } } diff --git a/src/processing/mode/experimental/SketchOutline.java b/src/processing/mode/experimental/SketchOutline.java index b135a6f..f753d15 100644 --- a/src/processing/mode/experimental/SketchOutline.java +++ b/src/processing/mode/experimental/SketchOutline.java @@ -1,394 +1,390 @@ package processing.mode.experimental; import static processing.mode.experimental.ExperimentalMode.log; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowFocusListener; import java.io.File; import java.util.List; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.ScrollPaneConstants; import javax.swing.SwingWorker; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeSelectionModel; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import processing.app.Base; public class SketchOutline { protected JFrame frmOutlineView; protected ErrorCheckerService errorCheckerService; protected JScrollPane jsp; protected DefaultMutableTreeNode soNode, tempNode; protected final JTree soTree; protected JTextField searchField; protected DebugEditor editor; public SketchOutline(DefaultMutableTreeNode codeTree, ErrorCheckerService ecs) { errorCheckerService = ecs; editor = ecs.getEditor(); frmOutlineView = new JFrame(); frmOutlineView.setAlwaysOnTop(true); frmOutlineView.setUndecorated(true); Point tp = errorCheckerService.getEditor().ta.getLocationOnScreen(); // frmOutlineView.setBounds(tp.x // + errorCheckerService.getEditor().ta // .getWidth() - 300, tp.y, 300, // errorCheckerService.getEditor().ta.getHeight()); //TODO: ^Absolute dimensions are bad bro int minWidth = 200; frmOutlineView.setLayout(new BoxLayout(frmOutlineView.getContentPane(), BoxLayout.Y_AXIS)); JPanel panelTop = new JPanel(), panelBottom = new JPanel(); panelTop.setLayout(new BoxLayout(panelTop, BoxLayout.Y_AXIS)); panelBottom.setLayout(new BoxLayout(panelBottom, BoxLayout.Y_AXIS)); searchField = new JTextField(); searchField.setMinimumSize(new Dimension(minWidth, 25)); panelTop.add(searchField); jsp = new JScrollPane(); soNode = new DefaultMutableTreeNode(); generateSketchOutlineTree(soNode, codeTree); soNode = (DefaultMutableTreeNode) soNode.getChildAt(0); tempNode = soNode; soTree = new JTree(soNode); soTree.getSelectionModel() .setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); soTree.setRootVisible(false); soTree.setCellRenderer(new CustomCellRenderer()); for (int i = 0; i < soTree.getRowCount(); i++) { soTree.expandRow(i); } soTree.setSelectionRow(0); jsp.setViewportView(soTree); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); jsp.setMinimumSize(new Dimension(minWidth, 100)); panelBottom.add(jsp); frmOutlineView.add(panelTop); frmOutlineView.add(panelBottom); frmOutlineView.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frmOutlineView.setBounds(tp.x + errorCheckerService.getEditor().ta .getWidth() - minWidth, tp.y, minWidth, Math.min(editor.ta.getHeight(), 150)); frmOutlineView.setMinimumSize(new Dimension(minWidth, Math .min(errorCheckerService.getEditor().ta.getHeight(), 150))); frmOutlineView.pack(); frmOutlineView.setLocation(tp.x + errorCheckerService.getEditor().ta .getWidth() - frmOutlineView.getWidth(), frmOutlineView.getY() + (editor.ta.getHeight() - frmOutlineView .getHeight()) / 2); addListeners(); } protected boolean internalSelection = false; protected void addListeners() { searchField.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { if (soTree.getRowCount() == 0) return; internalSelection = true; if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { close(); } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) { if (soTree.getLastSelectedPathComponent() != null) { DefaultMutableTreeNode tnode = (DefaultMutableTreeNode) soTree .getLastSelectedPathComponent(); if (tnode.getUserObject() instanceof ASTNodeWrapper) { ASTNodeWrapper awrap = (ASTNodeWrapper) tnode.getUserObject(); errorCheckerService.highlightNode(awrap); close(); } } } else if (evt.getKeyCode() == KeyEvent.VK_UP) { if (soTree.getLastSelectedPathComponent() == null) { soTree.setSelectionRow(0); return; } int x = soTree.getLeadSelectionRow() - 1; int step = jsp.getVerticalScrollBar().getMaximum() / soTree.getRowCount(); if (x == -1) { x = soTree.getRowCount() - 1; jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMaximum()); } else { jsp.getVerticalScrollBar().setValue((jsp.getVerticalScrollBar() .getValue() - step)); } soTree.setSelectionRow(x); } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) { if (soTree.getLastSelectedPathComponent() == null) { soTree.setSelectionRow(0); return; } int x = soTree.getLeadSelectionRow() + 1; int step = jsp.getVerticalScrollBar().getMaximum() / soTree.getRowCount(); if (x == soTree.getRowCount()) { x = 0; jsp.getVerticalScrollBar().setValue(jsp.getVerticalScrollBar().getMinimum()); } else { jsp.getVerticalScrollBar().setValue((jsp.getVerticalScrollBar() .getValue() + step)); } soTree.setSelectionRow(x); } } }); searchField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { updateSelection(); } public void removeUpdate(DocumentEvent e) { updateSelection(); } public void changedUpdate(DocumentEvent e) { updateSelection(); } private void updateSelection(){ SwingWorker worker = new SwingWorker() { protected Object doInBackground() throws Exception { return null; } protected void done() { String text = searchField.getText().toLowerCase(); tempNode = new DefaultMutableTreeNode(); filterTree(text, tempNode, soNode); soTree.setModel(new DefaultTreeModel(tempNode)); ((DefaultTreeModel) soTree.getModel()).reload(); for (int i = 0; i < soTree.getRowCount(); i++) { soTree.expandRow(i); } internalSelection = true; soTree.setSelectionRow(0); } }; worker.execute(); } }); frmOutlineView.addWindowFocusListener(new WindowFocusListener() { public void windowLostFocus(WindowEvent e) { close(); } public void windowGainedFocus(WindowEvent e) { } }); soTree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if (internalSelection) { internalSelection = (false); return; } // log(e); SwingWorker worker = new SwingWorker() { protected Object doInBackground() throws Exception { return null; } protected void done() { if (soTree.getLastSelectedPathComponent() == null) { return; } DefaultMutableTreeNode tnode = (DefaultMutableTreeNode) soTree .getLastSelectedPathComponent(); if (tnode.getUserObject() == null) { return; } if (tnode.getUserObject() instanceof ASTNodeWrapper) { ASTNodeWrapper awrap = (ASTNodeWrapper) tnode.getUserObject(); // log(awrap); errorCheckerService.highlightNode(awrap); } } }; worker.execute(); } }); } protected boolean filterTree(String prefix, DefaultMutableTreeNode tree, DefaultMutableTreeNode mainTree) { if (mainTree.isLeaf()) { return (mainTree.getUserObject().toString().toLowerCase() .startsWith(prefix)); } boolean found = false; for (int i = 0; i < mainTree.getChildCount(); i++) { DefaultMutableTreeNode tNode = new DefaultMutableTreeNode( ((DefaultMutableTreeNode) mainTree .getChildAt(i)) .getUserObject()); if (filterTree(prefix, tNode, (DefaultMutableTreeNode) mainTree.getChildAt(i))) { found = true; tree.add(tNode); } } return found; } protected void generateSketchOutlineTree(DefaultMutableTreeNode node, DefaultMutableTreeNode codetree) { if (codetree == null) return; //log("Visi " + codetree + codetree.getUserObject().getClass().getSimpleName()); if (!(codetree.getUserObject() instanceof ASTNodeWrapper)) return; ASTNodeWrapper awnode = (ASTNodeWrapper) codetree.getUserObject(), aw2 = null; if (awnode.getNode() instanceof TypeDeclaration) { aw2 = new ASTNodeWrapper( ((TypeDeclaration) awnode.getNode()).getName(), ((TypeDeclaration) awnode.getNode()).getName() .toString()); } else if (awnode.getNode() instanceof MethodDeclaration) { aw2 = new ASTNodeWrapper( ((MethodDeclaration) awnode.getNode()).getName(), new CompletionCandidate( ((MethodDeclaration) awnode .getNode())) .toString()); } else if (awnode.getNode() instanceof FieldDeclaration) { FieldDeclaration fd = (FieldDeclaration) awnode.getNode(); for (VariableDeclarationFragment vdf : (List<VariableDeclarationFragment>) fd .fragments()) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode( new ASTNodeWrapper( vdf.getName(), new CompletionCandidate( vdf) .toString())); node.add(newNode); } return; } if (aw2 == null) return; DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(aw2); node.add(newNode); for (int i = 0; i < codetree.getChildCount(); i++) { generateSketchOutlineTree(newNode, (DefaultMutableTreeNode) codetree.getChildAt(i)); } } public void show() { frmOutlineView.setVisible(true); } public void close(){ frmOutlineView.setVisible(false); frmOutlineView.dispose(); } public boolean isVisible(){ return frmOutlineView.isVisible(); } protected class CustomCellRenderer extends DefaultTreeCellRenderer { protected final ImageIcon classIcon, fieldIcon, methodIcon; public CustomCellRenderer() { - String iconPath = "data" + File.separator + "icons"; - iconPath = (Base.getSketchbookFolder().getAbsolutePath()) - + File.separator + "modes" + File.separator - + editor.getMode().getClass().getSimpleName() + File.separator - + "data" + File.separator + "icons"; - ; - + String iconPath = editor.getMode().getContentFile("data") + .getAbsolutePath() + + File.separator + "icons"; classIcon = new ImageIcon(iconPath + File.separator + "class_obj.png"); methodIcon = new ImageIcon(iconPath + File.separator + "methpub_obj.png"); fieldIcon = new ImageIcon(iconPath + File.separator + "field_protected_obj.png"); } public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof DefaultMutableTreeNode) setIcon(getTreeIcon(value)); return this; } public javax.swing.Icon getTreeIcon(Object o) { if (((DefaultMutableTreeNode) o).getUserObject() instanceof ASTNodeWrapper) { ASTNodeWrapper awrap = (ASTNodeWrapper) ((DefaultMutableTreeNode) o) .getUserObject(); int type = awrap.getNode().getParent().getNodeType(); if (type == ASTNode.METHOD_DECLARATION) return methodIcon; if (type == ASTNode.TYPE_DECLARATION) return classIcon; if (type == ASTNode.VARIABLE_DECLARATION_FRAGMENT) return fieldIcon; } return null; } } }
false
false
null
null
diff --git a/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java b/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java index bde0e73..895be18 100644 --- a/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java +++ b/org.ollabaca.on.lang.ui/src/org/ollabaca/on/lang/ui/TextHoverProvider.java @@ -1,40 +1,40 @@ package org.ollabaca.on.lang.ui; import org.eclipse.emf.ecore.EModelElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.documentation.IEObjectDocumentationProvider; import org.eclipse.xtext.ui.editor.hover.html.DefaultEObjectHoverProvider; import org.ollabaca.on.Import; import org.ollabaca.on.Instance; import org.ollabaca.on.Slot; import org.ollabaca.on.Units; public class TextHoverProvider extends DefaultEObjectHoverProvider { Units units = new Units(); @Override protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); - } else if (element instanceof Slot) { - Slot self = (Slot) element; + } else if (o instanceof Slot) { + Slot self = (Slot) o; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); } }
true
true
protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); } else if (element instanceof Slot) { Slot self = (Slot) element; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); }
protected String getFirstLine(EObject o) { EModelElement element = null; if (o instanceof Import) { Import self = (Import) o; element = units.getPackage(self); } else if (o instanceof Instance) { Instance self = (Instance) o; element = units.getClassifier(self); } else if (o instanceof Slot) { Slot self = (Slot) o; element = units.getFeature(self); } if (element != null) { String doc = units.getDocumentation(element); if (doc != null) { return doc; } } return super.getFirstLine(o); }
diff --git a/perun-core/src/main/java/cz/metacentrum/perun/core/impl/Utils.java b/perun-core/src/main/java/cz/metacentrum/perun/core/impl/Utils.java index fccd22e83..afdca3261 100644 --- a/perun-core/src/main/java/cz/metacentrum/perun/core/impl/Utils.java +++ b/perun-core/src/main/java/cz/metacentrum/perun/core/impl/Utils.java @@ -1,753 +1,756 @@ package cz.metacentrum.perun.core.impl; import java.io.*; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.Normalizer; import java.text.Normalizer.Form; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import cz.metacentrum.perun.core.api.*; import org.apache.commons.httpclient.util.URIUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import cz.metacentrum.perun.core.api.exceptions.DiacriticNotAllowedException; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.MaxSizeExceededException; import cz.metacentrum.perun.core.api.exceptions.MinSizeExceededException; import cz.metacentrum.perun.core.api.exceptions.NumberNotInRangeException; import cz.metacentrum.perun.core.api.exceptions.NumbersNotAllowedException; import cz.metacentrum.perun.core.api.exceptions.SpaceNotAllowedException; import cz.metacentrum.perun.core.api.exceptions.SpecialCharsNotAllowedException; import cz.metacentrum.perun.core.api.exceptions.WrongPatternException; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.util.LinkedHashSet; /** * Utilities. */ public class Utils { private final static Logger log = LoggerFactory.getLogger(Utils.class); private final static Pattern patternForCommonNameParsing = Pattern.compile("(([\\w]*. )*)([\\p{L}-']+) ([\\p{L}-']+)[, ]*(.*)"); public final static String configurationsLocations = "/etc/perunv3/"; /** * Replaces dangerous characters. * Replaces : with - and spaces with _. * * @param str string to be normalized * @return normalized string */ public static String normalizeString(String str) { log.trace("Entering normalizeString: str='" + str + "'"); return str.replace(':', '-').replace(' ', '_'); } /** * Joins Strings or any objects into a String. Use as * <pre> * List<?> list = Arrays.asList("a", 1, 2.0); * String s = join(list,","); * </pre> * @param collection anything Iterable, like a {@link java.util.List} or {@link java.util.Collection} * @param separator any separator, like a comma * @return string with string representations of objects joined by separators */ public static String join(Iterable<?> collection, String separator) { Iterator<?> oIter; if (collection == null || (!(oIter = collection.iterator()).hasNext())) return ""; StringBuilder oBuilder = new StringBuilder(String.valueOf(oIter.next())); while (oIter.hasNext()) oBuilder.append(separator).append(oIter.next()); return oBuilder.toString(); } /** * Joins Strings or any objects into a String. Use as * <pre> * String[] sa = { "a", "b", "c"}; * String s = join(list,","); * </pre> * @param objs array of objects * @param separator any separator, like a comma * @return string with string representations of objects joined by separators */ public static String join(Object[] objs, String separator) { log.trace("Entering join: objs='" + objs + "', separator='" + separator + "'"); return join(Arrays.asList(objs),separator); } /** * Gets particular property from perun.properties file. * * @param propertyName name of the property * @return value of the property */ public static String getPropertyFromConfiguration(String propertyName) throws InternalErrorException { log.trace("Entering getPropertyFromConfiguration: propertyName='" + propertyName + "'"); notNull(propertyName, "propertyName"); // Load properties file with configuration Properties properties = new Properties(); try { // Get the path to the perun.properties file BufferedInputStream is = new BufferedInputStream(new FileInputStream(Utils.configurationsLocations + "perun.properties")); properties.load(is); is.close(); String property = properties.getProperty(propertyName); if (property == null) { throw new InternalErrorException("Property " + propertyName + " cannot be found in the configuration file"); } return property; } catch (FileNotFoundException e) { throw new InternalErrorException("Cannot find perun.properties file", e); } catch (IOException e) { throw new InternalErrorException("Cannot read perun.properties file", e); } } /** * Gets particular property from custom property file. * * @param propertyFile name of properties file * @param propertyName name of the property * @return value of the property */ public static String getPropertyFromCustomConfiguration(String propertyFile, String propertyName) throws InternalErrorException { log.trace("Entering getPropertyFromCustomConfiguration: propertyFile='" + propertyFile + "' propertyName='" + propertyName + "'"); notNull(propertyName, "propertyName"); notNull(propertyFile, "propertyFile"); // Load properties file with configuration Properties properties = new Properties(); try { // Get the path to the perun.properties file BufferedInputStream is = new BufferedInputStream(new FileInputStream(Utils.configurationsLocations + propertyFile)); properties.load(is); is.close(); String property = properties.getProperty(propertyName); if (property == null) { throw new InternalErrorException("Property " + propertyName + " cannot be found in the configuration file: "+propertyFile); } return property; } catch (FileNotFoundException e) { throw new InternalErrorException("Cannot find "+propertyFile+" file", e); } catch (IOException e) { throw new InternalErrorException("Cannot read "+propertyFile+" file", e); } } /** * Integer row mapper */ public static final RowMapper<Integer> ID_MAPPER = new RowMapper<Integer>() { public Integer mapRow(ResultSet rs, int i) throws SQLException { return rs.getInt("id"); } }; /** * String row mapper */ public static final RowMapper<String> STRING_MAPPER = new RowMapper<String>() { public String mapRow(ResultSet rs, int i) throws SQLException { return rs.getString("value"); } }; // FIXME prijde odstranit public static void checkPerunSession(PerunSession sess) throws InternalErrorException { notNull(sess, "sess"); } /** * Checks whether the object is null or not. * * @param e * @param name * @throws InternalErrorException which wraps NullPointerException */ public static void notNull(Object e, String name) throws InternalErrorException { if(e == null){ throw new InternalErrorException(new NullPointerException("'" + name + "' is null")); } } /** * Define min length of some entity name. * * @param name name of entity * @param minLength * @throws MinSizeExceededException */ public static void checkMinLength(String name, int minLength) throws MinSizeExceededException{ if(name.length()<minLength) throw new MinSizeExceededException("Length of name is too short! MinLength=" + minLength + ", ActualLength=" + name.length()); } /** * Define max length of some entity name. * * @param name name of entity * @param maxLength * @throws */ public static void checkMaxLength(String name, int maxLength) throws MaxSizeExceededException{ if(name.length()<maxLength) throw new MaxSizeExceededException("Length of name is too long! MaxLength=" + maxLength + ", ActualLength=" + name.length()); } /** * Define, if some entity contain a diacritic symbol. * * @param name name of entity * @throws DiacriticNotAllowedException */ public static void checkWithoutDiacritic(String name) throws DiacriticNotAllowedException{ if(!Normalizer.isNormalized(name, Form.NFKD))throw new DiacriticNotAllowedException("Name of the entity is not in the normalized form NFKD (diacritic not allowed)!");; } /** * Define, if some entity contain a special symbol * Special symbol is everything except - numbers, letters and space * * @param name name of entity * @throws SpecialCharsNotAllowedException */ public static void checkWithoutSpecialChars(String name) throws SpecialCharsNotAllowedException{ if(!name.matches("^[0-9 \\p{L}]*$")) throw new SpecialCharsNotAllowedException("The special chars in the name of entity are not allowed!"); } /** * Define, if some entity contain a special symbol * Special symbol is everything except - numbers, letters and space (and allowedSpecialChars) * The allowedSpecialChars are on the end of regular expresion, so the same rule must be observed. * (example, symbol - must be on the end of string) rules are the same like in regular expresion * * @param name name of entity * @param allowedSpecialChars this String must contain only special chars which are allowed * @throws SpecialCharsNotAllowedException */ public static void checkWithoutSpecialChars(String name, String allowedSpecialChars) throws SpecialCharsNotAllowedException{ if(!name.matches("^([0-9 \\p{L}" + allowedSpecialChars + "])*$")) throw new SpecialCharsNotAllowedException("The special chars (except " + allowedSpecialChars + ") in the name of entity are not allowed!"); } /** * Define, if some entity contain a number * * @param name * @throws NumbersNotAllowedException */ public static void checkWithoutNumbers(String name) throws NumbersNotAllowedException{ if(!name.matches("^([^0-9])*$")) throw new NumbersNotAllowedException("The numbers in the name of entity are not allowed!"); } /** * Define, if some entity contain a space * * @param name * @throws SpaceNotAllowedException */ public static void checkWithoutSpaces(String name)throws SpaceNotAllowedException{ if(name.contains(" ")) throw new SpaceNotAllowedException("The spaces in the name of entity are not allowed!"); } /** * Define, if some number is in range. * Example: number 4 is in range 4 - 12, number 3 is not * * @param number * @param lowestValue * @param highestValue * @throws NumberNotInRangeException */ public static void checkRangeOfNumbers(int number, int lowestValue, int highestValue) throws NumberNotInRangeException { if(number<lowestValue || number>highestValue) throw new NumberNotInRangeException("Number is not in range, Lowest="+lowestValue+" < Number="+number+" < Highest="+highestValue); } /** * Gets the next number from the sequence. This function hides differences in the databases engines. * * @param jdbc * @param sequenceName * @return new ID * @throws InternalErrorException */ public static int getNewId(Object jdbc, String sequenceName) throws InternalErrorException { String dbType = getPropertyFromConfiguration("perun.db.type"); String query = ""; if (dbType.equals("oracle")) { query = "select " + sequenceName + ".nextval from dual"; } else if (dbType.equals("postgresql")) { query = "select nextval('" + sequenceName + "')"; } else { throw new InternalErrorException("Unsupported DB type"); } // Decide which type of the JdbcTemplate is provided try { if (jdbc instanceof SimpleJdbcTemplate) { return ((SimpleJdbcTemplate) jdbc).queryForInt(query); } else if (jdbc instanceof JdbcTemplate) { return ((JdbcTemplate) jdbc).queryForInt(query); } } catch (RuntimeException e) { throw new InternalErrorException(e); } // Shouldn't ever happened throw new InternalErrorException("Unsupported DB type"); } /** * Returns current time in millis. Result of this call can then be used by function getRunningTime(). * * @return current time in millis. */ public static long startTimer() { return System.currentTimeMillis(); } /** * Returns difference between startTime and current time in millis. * * @param startTime * @return difference between current time in millis and startTime. */ public static long getRunningTime(long startTime) { return System.currentTimeMillis()-startTime; } /** * Scans all classes accessible from the context class loader which belong to the given package and subpackages. * * @param packageName The base package * @return The classes * @throws ClassNotFoundException * @throws IOException */ public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes; } /** * Parse raw string which contains name of the user. * Parsed name is split into the field titleBefore, firstName, lastName and titleAfter. * All is stored in the hashMap. * * @param rawName * @return HashMap contains entries with keys titleBefore, firstName, lastName and titleAfter. - * @throws InternalErrorException if some exception has been thrown in procc + * @throws InternalErrorException if some exception has been thrown in proc */ public static Map<String, String> parseCommonName(String rawName) throws InternalErrorException { Map<String, String> parsedName = new HashMap<String, String>(); String titleBefore = ""; String firstName = ""; String lastName = ""; String titleAfter = ""; + // replace all (double+)spaces with single space & trim input, so matcher can work correctly + rawName = rawName.replaceAll("\\s+", " ").trim(); + // If rawName contains only one word then use it only for lastName try { if (rawName.matches("^[\\s]*[\\S]+[\\s]*$")) { lastName = rawName.trim(); } else { Matcher matcher = patternForCommonNameParsing.matcher(rawName); matcher.find(); titleBefore = matcher.group(1).trim(); firstName = matcher.group(3); lastName = matcher.group(4); titleAfter = matcher.group(5); } } catch (Exception ex) { - throw new InternalErrorException("Problem with parsing of rawName ='" + rawName + "'",ex); + throw new InternalErrorException("Problem with parsing of rawName='" + rawName + "'", ex); } if (titleBefore.isEmpty()) titleBefore = null; parsedName.put("titleBefore", titleBefore); if (firstName.isEmpty()) firstName = null; parsedName.put("firstName", firstName); if (lastName.isEmpty()) lastName = null; parsedName.put("lastName", lastName); if (titleAfter.isEmpty()) titleAfter = null; parsedName.put("titleAfter", titleAfter); return parsedName; } /** * Recursive method used to find all classes in a given directory and subdirs. * * @param directory The base directory * @param packageName The package name for classes found inside the base directory * @return The classes * @throws ClassNotFoundException */ private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } } return classes; } /** * Return true, if char on position in text is escaped by '\' Return false, * if not. * * @param text text in which will be searching * @param position position in text <0-text.length> * @return true if char is escaped, false if not */ public static boolean isEscaped(String text, int position) { boolean escaped = false; while (text.charAt(position) == '\\') { escaped = !escaped; position--; if (position < 0) { return escaped; } } return escaped; } /** * Serialize map to string * * @param map * @return string of escaped map */ public static String serializeMapToString(Map<String, String> map) { if(map == null) return "\\0"; Map<String, String> attrNew = new HashMap<String, String>(map); Set<String> keys = new HashSet<String>(attrNew.keySet()); for(String s: keys) { attrNew.put("<" + BeansUtils.createEscaping(s) + ">", "<" + BeansUtils.createEscaping(attrNew.get(s)) + ">"); attrNew.remove(s); } return attrNew.toString(); } public static Attribute copyAttributeToViAttributeWithoutValue(Attribute copyFrom, Attribute copyTo) throws InternalErrorException { copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt()); copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy()); copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt()); copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy()); return copyTo; } public static Attribute copyAttributeToVirtualAttributeWithValue(Attribute copyFrom, Attribute copyTo) throws InternalErrorException { copyTo.setValue(copyFrom.getValue()); copyTo.setValueCreatedAt(copyFrom.getValueCreatedAt()); copyTo.setValueCreatedBy(copyFrom.getValueCreatedBy()); copyTo.setValueModifiedAt(copyFrom.getValueModifiedAt()); copyTo.setValueModifiedBy(copyFrom.getValueModifiedBy()); return copyTo; } /** * Method generates strings by pattern. * The pattern is string with square brackets, e.g. "a[1-3]b". Then the content of the brackets * is distributed, so the list is [a1b, a2b, a3c]. * Multibrackets are aslo allowed. For example "a[00-01]b[90-91]c" generates [a00b90c, a00b91c, a01b90c, a01b91c]. * * @param pattern * @return list of all generated strings */ public static List<String> generateStringsByPattern(String pattern) throws WrongPatternException { List<String> result = new ArrayList<String>(); // get chars between the brackets List<String> values = new ArrayList<String>(Arrays.asList(pattern.split("\\[[^\\]]*\\]"))); // get content of the brackets List<String> generators = new ArrayList<String>(); Pattern generatorPattern = Pattern.compile("\\[([^\\]]*)\\]"); Matcher m = generatorPattern.matcher(pattern); while (m.find()) { generators.add(m.group(1)); } // if values strings contain square brackets, wrong syntax, abort for (String value: values) { if (value.contains("]") || (value.contains("["))) { throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much closing brackets."); } } // if generators strings contain square brackets, wrong syntax, abort for (String generator: generators) { if (generator.contains("]") || (generator.contains("["))) { throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Too much opening brackets."); } } // list, that contains list for each generator, with already generated numbers List<List<String>> listOfGenerated = new ArrayList<List<String>>(); Pattern rangePattern = Pattern.compile("^(\\d+)-(\\d+)$"); for (String range: generators) { m = rangePattern.matcher(range); if (m.find()) { String start = m.group(1); String end = m.group(2); int startNumber; int endNumber; try { startNumber = Integer.parseInt(start); endNumber = Integer.parseInt(end); } catch (NumberFormatException ex) { throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Wrong format of the range."); } // if end is before start -> abort if (startNumber > endNumber) { throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. Start number has to be lower than end number."); } // find out, how many zeros are before start number int zerosInStart = 0; int counter = 0; while ( (start.charAt(counter) == '0') && (counter < start.length()-1) ) { zerosInStart++; counter++; } String zeros = start.substring(0, zerosInStart); int oldNumberOfDigits = String.valueOf(startNumber).length(); // list of already generated numbers List<String> generated = new ArrayList<String>(); while (endNumber >= startNumber) { // keep right number of zeros before number if (String.valueOf(startNumber).length() == oldNumberOfDigits +1) { if (!zeros.isEmpty()) zeros = zeros.substring(1); } generated.add(zeros + startNumber); oldNumberOfDigits = String.valueOf(startNumber).length(); startNumber++; } listOfGenerated.add(generated); } else { // range is not in the format number-number -> abort throw new WrongPatternException("The pattern \"" + pattern + "\" has a wrong syntax. The format numer-number not found."); } } // add values among the generated numbers as one item lists List<List<String>> listOfGeneratorsAndValues = new ArrayList<List<String>>(); int index = 0; for (List<String> list : listOfGenerated) { if (index < values.size()) { List<String> listWithValue = new ArrayList<>(); listWithValue.add(values.get(index)); listOfGeneratorsAndValues.add(listWithValue); index++; } listOfGeneratorsAndValues.add(list); } // complete list with remaining values for (int i = index; i < values.size(); i++) { List<String> listWithValue = new ArrayList<>(); listWithValue.add(values.get(i)); listOfGeneratorsAndValues.add(listWithValue); } // generate all posibilities return getCombinationsOfLists(listOfGeneratorsAndValues); } /** * Method generates all combinations of joining of strings. * It respects given order of lists. * Example: input: [[a,b],[c,d]], output: [ac,ad,bc,bd] * @param lists list of lists, which will be joined * @return all joined strings */ private static List<String> getCombinationsOfLists(List<List<String>> lists) { if (lists.isEmpty()) { // this should not happen return new ArrayList<>(); } if (lists.size() == 1) { return lists.get(0); } List<String> result = new ArrayList<String>(); List<String> list = lists.remove(0); // get recursively all posibilities without first list List<String> posibilities = getCombinationsOfLists(lists); // join all strings from first list with the others for (String item: list) { if (posibilities.isEmpty()) { result.add(item); } else { for (String itemToConcat : posibilities) { result.add(item + itemToConcat); } } } return result; } /** * Return encrypted version of input in UTF-8 by HmacSHA256 * * @param input input to encrypt * @return encrypted value */ public static String getMessageAuthenticationCode(String input) { if (input == null) throw new NullPointerException("input must not be null"); try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(getPropertyFromConfiguration("perun.mailchange.secretKey").getBytes("UTF-8"),"HmacSHA256")); byte[] macbytes = mac.doFinal(input.getBytes("UTF-8")); return new BigInteger(macbytes).toString(Character.MAX_RADIX); } catch (Exception e) { throw new RuntimeException(e); } } /** * Send validation email related to requested change of users preferred email. * * @param user user to change preferred email for * @param url base URL of running perun instance passed from RPC * @param email new email address to send notification to * @param changeId ID of change request in DB * @throws InternalErrorException */ public static void sendValidationEmail(User user, String url, String email, int changeId) throws InternalErrorException { // create mail sender JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost("localhost"); // create message SimpleMailMessage message = new SimpleMailMessage(); message.setTo(email); message.setFrom(getPropertyFromConfiguration("perun.mailchange.backupFrom")); message.setSubject("[Perun] New email address verification"); // get validation link params String i = Integer.toString(changeId, Character.MAX_RADIX); String m = Utils.getMessageAuthenticationCode(i); try { // !! There is a hard-requirement for Perun instance // to host GUI on same server as RPC like: "serverUrl/perun-gui/" URL urlObject = new URL(url); // use default if unknown rpc path String path = "/perun-gui/"; if (urlObject.getPath().contains("/perun-rpc-krb/")) { path = "/perun-gui-krb/"; } else if (urlObject.getPath().contains("/perun-rpc-fed/")) { path = "/perun-gui-fed/"; } else if (urlObject.getPath().contains("/perun-rpc-cert/")) { path = "/perun-gui-cert/"; } StringBuilder link = new StringBuilder(); link.append(urlObject.getProtocol()); link.append("://"); link.append(urlObject.getHost()); link.append(path); link.append("?i="); link.append(URLEncoder.encode(i, "UTF-8")); link.append("&m="); link.append(URLEncoder.encode(m, "UTF-8")); link.append("&u=" + user.getId()); // Build message String text = "Dear "+user.getDisplayName()+",\n\nWe've received request to change your preferred email address to: "+email+ ".\n\nTo confirm this change please use link below:\n\n"+link+"\n\n" + "Message is automatically generated." + "\n----------------------------------------------------------------" + "\nPerun - User and Resource Management System"; message.setText(text); mailSender.send(message); } catch (UnsupportedEncodingException ex) { throw new InternalErrorException("Unable to encode validation URL for mail change.", ex); } catch (MalformedURLException ex) { throw new InternalErrorException("Not valid URL of running Perun instance.", ex); } } } \ No newline at end of file
false
false
null
null
diff --git a/src/carrental/VehiclePanel.java b/src/carrental/VehiclePanel.java index 44c7b80..0f0445b 100644 --- a/src/carrental/VehiclePanel.java +++ b/src/carrental/VehiclePanel.java @@ -1,1066 +1,1086 @@ package carrental; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import javax.swing.table.DefaultTableModel; import javax.swing.text.JTextComponent; /** * This is the main panel regarding vehicles. * It contains JPanels for every relevant screen, when dealing with vehicles. * These are implemented as inner classes. * @author CNN * @version 2011-12-11 */ public class VehiclePanel extends SuperPanel { private Vehicle vehicleToView; //specific vehicle, used to view details private VehicleType vehicleTypeToView; //specific vehicle type, used to view details private ArrayList<Vehicle> vehicleList; private ArrayList<VehicleType> vehicleTypes; private GraphicAlternate graph; private CreatePanel createPanel; private ViewVehiclePanel viewVehiclePanel; private ViewVehicleTypePanel viewVehicleTypePanel; private ListPanel listPanel; /** * Sets up the vehiclepanel and all its subpanels. */ public VehiclePanel() { vehicleList = CarRental.getInstance().requestVehicles(); vehicleTypes = CarRental.getInstance().requestVehicleTypes(); createPanel = new CreatePanel(); viewVehiclePanel = new ViewVehiclePanel(); viewVehicleTypePanel = new ViewVehicleTypePanel(); listPanel = new ListPanel(); //Sets the different subpanels. Also adds them to this object with JPanel.add(). AssignAndAddSubPanels(new MainScreenPanel(), createPanel, viewVehiclePanel, new AddTypePanel(), viewVehicleTypePanel, listPanel); this.setPreferredSize(new Dimension(800, 600)); showMainScreenPanel(); } @Override public void showCreatePanel() { createPanel.update(); super.showCreatePanel(); } @Override public void showViewEntityPanel() { viewVehiclePanel.update(); super.showViewEntityPanel(); } @Override public void showListPanel() { listPanel.update(); super.showListPanel(); } @Override public void showViewTypePanel() { viewVehicleTypePanel.update(); super.showViewTypePanel(); } /** * This inner class creates a JPanel with an overview of reservations for the vehicles. */ public class MainScreenPanel extends JPanel { /** * Creates the panel with the overview. */ public MainScreenPanel() { graph = new GraphicAlternate(); graph.setPreferredSize(new Dimension(800, 600)); add(graph); } } /** * This inner class creates a JPanel with the functionality to create a vehicle. */ public class CreatePanel extends JPanel { private JTextField descriptionField, licensePlateField, vinField, drivenField; private JTextArea additionalArea; private DefaultComboBoxModel vehicleTypeComboModel; /** * Sets up the basic functionality needed to create a vehicle. */ public CreatePanel() { JPanel centerPanel, buttonPanel, vehicleTypePanel, descriptionPanel, licensePlatePanel, vinPanel, drivenPanel, additionalPanel; JLabel vehicleTypeLabel, descriptionLabel, licensePlateLabel, vinLabel, drivenLabel, kilometerLabel, additionalLabel; JScrollPane additionalScrollPane; JButton createButton, cancelButton; final JComboBox vehicleTypeCombo; final int defaultJTextFieldColumns = 20, strutDistance = 0; //Panel settings setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "Create a vehicle")); //Center Panel centerPanel = new JPanel(); centerPanel.setLayout( new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS)); centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 40)); add(centerPanel, BorderLayout.CENTER); //Colors setBackground( new Color(216, 216, 208)); centerPanel.setBackground( new Color(239, 240, 236)); //Vehicle Type vehicleTypeLabel = new JLabel("Vehicle Type"); vehicleTypeComboModel = new DefaultComboBoxModel(); vehicleTypeCombo = new JComboBox(vehicleTypeComboModel); for (VehicleType vehicleType : vehicleTypes) { vehicleTypeComboModel.addElement(vehicleType.getName()); } vehicleTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); vehicleTypePanel.add(Box.createRigidArea(new Dimension(5, 0))); vehicleTypePanel.add(vehicleTypeLabel); vehicleTypePanel.add(Box.createRigidArea(new Dimension(48 + strutDistance, 0))); vehicleTypePanel.add(vehicleTypeCombo); centerPanel.add(vehicleTypePanel); //Name descriptionLabel = new JLabel("Description"); descriptionField = new JTextField(defaultJTextFieldColumns); descriptionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); descriptionPanel.add(Box.createRigidArea(new Dimension(5, 0))); descriptionPanel.add(descriptionLabel); descriptionPanel.add(Box.createRigidArea(new Dimension(55 + strutDistance, 0))); descriptionPanel.add(descriptionField); centerPanel.add(descriptionPanel); //LicensePlate licensePlateLabel = new JLabel("License Plate"); licensePlateField = new JTextField(defaultJTextFieldColumns); licensePlatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); licensePlatePanel.add(Box.createRigidArea(new Dimension(5, 0))); licensePlatePanel.add(licensePlateLabel); licensePlatePanel.add(Box.createRigidArea(new Dimension(43 + strutDistance, 0))); licensePlatePanel.add(licensePlateField); centerPanel.add(licensePlatePanel); //VIN vinLabel = new JLabel("VIN"); vinField = new JTextField(defaultJTextFieldColumns); vinPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); vinPanel.add(Box.createRigidArea(new Dimension(5, 0))); vinPanel.add(vinLabel); vinPanel.add(Box.createRigidArea(new Dimension(101 + strutDistance, 0))); vinPanel.add(vinField); centerPanel.add(vinPanel); //Driven drivenLabel = new JLabel("Distance driven"); drivenField = new JTextField(defaultJTextFieldColumns); kilometerLabel = new JLabel("kilometers"); drivenPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); drivenPanel.add(Box.createRigidArea(new Dimension(5, 0))); drivenPanel.add(drivenLabel); drivenPanel.add(Box.createRigidArea(new Dimension(32 + strutDistance, 0))); drivenPanel.add(drivenField); drivenPanel.add(kilometerLabel); centerPanel.add(drivenPanel); //Additional Comment additionalLabel = new JLabel("Additional comments"); additionalArea = new JTextArea(5, 30); additionalScrollPane = new JScrollPane(additionalArea); additionalPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); additionalPanel.add(Box.createRigidArea(new Dimension(5, 0))); additionalPanel.add(additionalLabel); additionalPanel.add(Box.createRigidArea(new Dimension(strutDistance, 0))); additionalPanel.add(additionalScrollPane); centerPanel.add(additionalPanel); //ButtonPanels buttonPanel = new JPanel(); add(buttonPanel, BorderLayout.SOUTH); buttonPanel.setLayout( new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 15)); //add some space between the right edge of the screen buttonPanel.add(Box.createHorizontalGlue()); //cancel-Button cancelButton = new JButton("Cancel"); cancelButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(); showMainScreenPanel(); } }); buttonPanel.add(cancelButton); buttonPanel.add(Box.createRigidArea(new Dimension(5, 0))); //create-button createButton = new JButton("Create"); createButton.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!descriptionField.getText().trim().isEmpty() && !licensePlateField.getText().trim().isEmpty() && !vinField.getText().trim().isEmpty() && !drivenField.getText().trim().isEmpty()) { //Checks if VIN number is in use already boolean VinTaken = false; for (Vehicle vehicle : vehicleList) { if (vinField.getText().trim().toLowerCase(Locale.ENGLISH).equals(vehicle.getVin().toLowerCase(Locale.ENGLISH))) { VinTaken = true; } } if (!VinTaken) { try { Vehicle newVehicle = new Vehicle(CarRental.getInstance().requestNewVehicleId(), vehicleTypes.get(vehicleTypeCombo.getSelectedIndex()).getID(), descriptionField.getText().trim(), licensePlateField.getText().trim(), vinField.getText().trim(), Integer.parseInt(drivenField.getText().trim()), additionalArea.getText().trim()); CarRental.getInstance().saveVehicle(newVehicle); CarRental.getInstance().appendLog("Vehicle \"" + descriptionField.getText().trim() + "\" added to the database."); vehicleList = CarRental.getInstance().requestVehicles(); } catch (NumberFormatException ex) { CarRental.getInstance().appendLog("Your \"Distance driven\" field does not consist of numbers only or was too long. The vehicle wasn't created."); } } else { CarRental.getInstance().appendLog("A vehicle with VIN \"" + vinField.getText().trim() + "\" already exists."); } } else { CarRental.getInstance().appendLog("The vehicle wasn't created. Fill out the text fields."); } } }); buttonPanel.add(createButton); } /** * Updates the panel. Textfields are set blank and the vehicle types are updated. */ public void update() { //Check for an added type for the JComboBox vehicleTypeComboModel.removeAllElements(); for (VehicleType vehicleType : vehicleTypes) { vehicleTypeComboModel.addElement(vehicleType.getName()); } //Sets all text fields blank descriptionField.setText(null); licensePlateField.setText(null); vinField.setText(null); drivenField.setText(null); additionalArea.setText(null); } } /** * This inner class creates a JPanel which shows a certain vehicle. The vehicle is selected in the ListPanel-class */ public class ViewVehiclePanel extends JPanel { private JTextField descriptionField, licensePlateField, vinField, drivenField; private DefaultComboBoxModel vehicleTypeComboModel; private JComboBox vehicleTypeCombo; private JTextArea additionalArea; private DefaultTableModel reservationTableModel, maintenanceTableModel; /** * Sets up the basic funtionality needed to view a vehicle. */ public ViewVehiclePanel() { JPanel centerPanel, reservationPanel, maintenancePanel, buttonPanel, vehicleTypePanel, descriptionPanel, licensePlatePanel, vinPanel, drivenPanel, additionalPanel; JLabel vehicleTypeLabel, descriptionLabel, licensePlateLabel, vinLabel, drivenLabel, kilometerLabel, additionalLabel; JButton backButton, saveButton, deleteButton, viewSelectedTypeButton; JScrollPane reservationScrollPane, maintenanceScrollPane, additionalScrollPane; String[] tableColumn; JTable reservationTable, maintenanceTable; final int defaultJTextFieldColumns = 20, strutDistance = 0; //Panel settings setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "Viewing Vehicle")); //Center Panel centerPanel = new JPanel(); centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS)); centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 40)); add(centerPanel, BorderLayout.CENTER); //Colors setBackground(new Color(216, 216, 208)); centerPanel.setBackground(new Color(239, 240, 236)); //Vehicle Type vehicleTypeLabel = new JLabel("Vehicle Type"); vehicleTypeComboModel = new DefaultComboBoxModel(); vehicleTypeCombo = new JComboBox(vehicleTypeComboModel); //this JComboBox selections are added in the update() method viewSelectedTypeButton = new JButton("View selected Type"); viewSelectedTypeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { vehicleTypeToView = vehicleTypes.get(vehicleTypeCombo.getSelectedIndex()); showViewTypePanel(); CarRental.getInstance().appendLog("Showing vehicle type \"" + vehicleTypeToView.getName() + "\" now."); } }); vehicleTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); vehicleTypePanel.add(Box.createRigidArea(new Dimension(5, 0))); vehicleTypePanel.add(vehicleTypeLabel); vehicleTypePanel.add(Box.createRigidArea(new Dimension(48 + strutDistance, 0))); vehicleTypePanel.add(vehicleTypeCombo); vehicleTypePanel.add(Box.createRigidArea(new Dimension(5 + strutDistance, 0))); vehicleTypePanel.add(viewSelectedTypeButton); centerPanel.add(vehicleTypePanel); //Description descriptionLabel = new JLabel("Description"); descriptionField = new JTextField(defaultJTextFieldColumns); descriptionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); descriptionPanel.add(Box.createRigidArea(new Dimension(5, 0))); descriptionPanel.add(descriptionLabel); descriptionPanel.add(Box.createRigidArea(new Dimension(55 + strutDistance, 0))); descriptionPanel.add(descriptionField); centerPanel.add(descriptionPanel); //LicensePlate licensePlateLabel = new JLabel("License Plate"); licensePlateField = new JTextField(defaultJTextFieldColumns); licensePlatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); licensePlatePanel.add(Box.createRigidArea(new Dimension(5, 0))); licensePlatePanel.add(licensePlateLabel); licensePlatePanel.add(Box.createRigidArea(new Dimension(43 + strutDistance, 0))); licensePlatePanel.add(licensePlateField); centerPanel.add(licensePlatePanel); //VIN vinLabel = new JLabel("VIN"); vinField = new JTextField(defaultJTextFieldColumns); vinPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); vinPanel.add(Box.createRigidArea(new Dimension(5, 0))); vinPanel.add(vinLabel); vinPanel.add(Box.createRigidArea(new Dimension(101 + strutDistance, 0))); vinPanel.add(vinField); centerPanel.add(vinPanel); //Driven drivenLabel = new JLabel("Distance driven"); drivenField = new JTextField(defaultJTextFieldColumns); kilometerLabel = new JLabel("kilometers"); drivenPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); drivenPanel.add(Box.createRigidArea(new Dimension(5, 0))); drivenPanel.add(drivenLabel); drivenPanel.add(Box.createRigidArea(new Dimension(32 + strutDistance, 0))); drivenPanel.add(drivenField); - + drivenPanel.add(kilometerLabel); centerPanel.add(drivenPanel); //Additional Comment additionalLabel = new JLabel("Additional comments"); additionalArea = new JTextArea(3, 30); additionalScrollPane = new JScrollPane(additionalArea); additionalPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); additionalPanel.add(Box.createRigidArea(new Dimension(5, 0))); additionalPanel.add(additionalLabel); additionalPanel.add(Box.createRigidArea(new Dimension(strutDistance, 0))); additionalPanel.add(additionalScrollPane); centerPanel.add(additionalPanel); //Adding a small rigid area centerPanel.add(Box.createRigidArea(new Dimension(0, 5))); //ReservationPanel reservationPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); reservationPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 2), "Reservations")); reservationPanel.setBackground(new Color(216, 216, 208)); centerPanel.add(reservationPanel); //Creating the reservation table model tableColumn = new String[]{"Customer", "Phone number", "From", "To"}; reservationTableModel = new DefaultTableModel(tableColumn, 0); //Creating the JTable reservationTable = new JTable(reservationTableModel); reservationScrollPane = new JScrollPane(reservationTable); //Setting the default size for the table in this scrollpane reservationTable.setPreferredScrollableViewportSize(new Dimension(700, 100)); reservationPanel.add(reservationScrollPane); //Adding a small rigid area centerPanel.add(Box.createRigidArea(new Dimension(0, 5))); //MaintenancePanel maintenancePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); maintenancePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 2), "Maintenances")); maintenancePanel.setBackground(new Color(216, 216, 208)); centerPanel.add(maintenancePanel); //Creating the maintenance table model tableColumn = new String[]{"Maintenance type", "Service check", "From", "To"}; maintenanceTableModel = new DefaultTableModel(tableColumn, 0); //Creating the JTable maintenanceTable = new JTable(maintenanceTableModel); maintenanceScrollPane = new JScrollPane(maintenanceTable); //Setting the default size for the table in this scrollpane maintenanceTable.setPreferredScrollableViewportSize(new Dimension(700, 100)); maintenancePanel.add(maintenanceScrollPane); //ButtonPanels buttonPanel = new JPanel(); add(buttonPanel, BorderLayout.SOUTH); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 15)); //add some space between the right edge of the screen buttonPanel.add(Box.createHorizontalGlue()); //Cancel-Button backButton = new JButton("Back"); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showListPanel(); } }); buttonPanel.add(backButton); buttonPanel.add(Box.createRigidArea(new Dimension(5, 0))); //Delete-Button deleteButton = new JButton("Delete"); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - CarRental.getInstance().deleteVehicle(vehicleToView.getID()); - CarRental.getInstance().appendLog("Vehicle \"" + vehicleToView.getDescription() + "\" deleted from the database."); - vehicleList = CarRental.getInstance().requestVehicles(); - showListPanel(); + int tiedReservations = 0; + //checks for any reservations tied to the vehicle + for (Reservation reservation : CarRental.getInstance().requestReservations()) { + if (reservation.getVehicleID() == vehicleToView.getID()) { + tiedReservations++; + } + } + + if (tiedReservations == 0) { + //delete the maintenances tied to the vehilce, then the vehicle itself + for (Maintenance maintenance : CarRental.getInstance().requestMaintenances()) { + if (maintenance.getVehicleID() == vehicleToView.getID()) { + CarRental.getInstance().deleteMaintenance(maintenance.getID()); + CarRental.getInstance().appendLog("Maintenance #" + maintenance.getID() + " (tied to \"" + vehicleToView.getDescription() + "\") deleted from the database."); + } + } + //Delete the vehicle + CarRental.getInstance().deleteVehicle(vehicleToView.getID()); + CarRental.getInstance().appendLog("Vehicle \"" + vehicleToView.getDescription() + "\" deleted from the database."); + vehicleList = CarRental.getInstance().requestVehicles(); + showListPanel(); + } else { + CarRental.getInstance().appendLog("Vehicle \"" + vehicleToView.getDescription() + "\" cannot be deleted as it has " + tiedReservations + " reservation(s). Rearrange them first."); + } } }); buttonPanel.add(deleteButton); buttonPanel.add(Box.createRigidArea(new Dimension(5, 0))); //Create-button saveButton = new JButton("Save changes"); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { assert (vehicleToView != null); //VehicleToView should never be null here if (!descriptionField.getText().trim().isEmpty() && !licensePlateField.getText().trim().isEmpty() && !vinField.getText().trim().isEmpty() && !drivenField.getText().trim().isEmpty()) { //Checks if VIN number is in use already boolean VinTaken = false; for (Vehicle vehicle : vehicleList) { //TODO hvorfor virker !vehicle.equals(vehicleToView) ikke her!! if (vinField.getText().trim().equals(vehicle.getVin()) && vehicle.getID() != vehicleToView.getID()) { //if the vin is in use and it´s not from the currently viewed vehicle VinTaken = true; } } if (!VinTaken) { try { Vehicle updatedVehicle = new Vehicle(vehicleToView.getID(), vehicleTypes.get(vehicleTypeCombo.getSelectedIndex()).getID(), descriptionField.getText().trim(), licensePlateField.getText().trim(), vinField.getText().trim(), Integer.parseInt(drivenField.getText().trim()), additionalArea.getText().trim()); CarRental.getInstance().saveVehicle(updatedVehicle); CarRental.getInstance().appendLog("Vehicle \"" + descriptionField.getText().trim() + "\" changed in the database."); vehicleList = CarRental.getInstance().requestVehicles(); } catch (NumberFormatException ex) { CarRental.getInstance().appendLog("Your \"Distance driven\" field does not consist of numbers only or was too long. The vehicle wasn't created."); } } else { CarRental.getInstance().appendLog("Another vehicle with VIN \"" + vinField.getText().trim() + "\" already exists."); } } } }); buttonPanel.add(saveButton); } /** * Updates the panel to show the selected vehicle. This type is selected in the ViewVehiclePanel-class */ public void update() { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); ArrayList<Reservation> reservations = new ArrayList<Reservation>(); //The bookings are sorted into reservations - ArrayList<Maintenance> maintenances = new ArrayList<Maintenance>(); // and maintenances in the code String[] tableRow; int typeIndex = 0; //refresh the vehicle types in the Combobox and get the index to be displayed vehicleTypeComboModel.removeAllElements(); for (int i = 0; i < vehicleTypes.size(); i++) { vehicleTypeComboModel.addElement(vehicleTypes.get(i).getName()); //add the row if (vehicleTypes.get(i).getID() == vehicleToView.getVehicleType()) { typeIndex = i; } } //Refresh the textfields vehicleTypeCombo.setSelectedIndex(typeIndex); descriptionField.setText(vehicleToView.getDescription()); licensePlateField.setText(vehicleToView.getLicensePlate()); vinField.setText(vehicleToView.getVin()); drivenField.setText(Integer.toString(vehicleToView.getOdo())); additionalArea.setText(vehicleToView.getAdditional()); //Splits bookings into reservations and maintenances for (Booking booking : CarRental.getInstance().requestBookingsByVehicle(vehicleToView.getID())) { if (!booking.isMaintenance()) { reservations.add((Reservation) booking); } else { maintenances.add((Maintenance) booking); } } //Removes the old rows before adding the new ones reservationTableModel.setRowCount(0); maintenanceTableModel.setRowCount(0); //Add the rows with reservations for (Reservation reservation : reservations) { tableRow = new String[]{ CarRental.getInstance().requestCustomer(reservation.getCustomerID()).getName(), Integer.toString(CarRental.getInstance().requestCustomer(reservation.getCustomerID()).getTelephone()), dateFormat.format(reservation.getTStart()), dateFormat.format(reservation.getTEnd())}; reservationTableModel.addRow(tableRow); } assert (reservations.size() == reservationTableModel.getRowCount()) : "size: " + reservations.size() + " rows: " + reservationTableModel.getRowCount(); //Add the rows with maintenances for (Maintenance maintenance : maintenances) { String serviceCheck; if (CarRental.getInstance().requestMaintenanceType(maintenance.getTypeID()).getIs_service()) { serviceCheck = "Yes"; } else { serviceCheck = "No"; } tableRow = new String[]{ CarRental.getInstance().requestMaintenanceType(maintenance.getTypeID()).getName(), serviceCheck, dateFormat.format(maintenance.getTStart()), dateFormat.format(maintenance.getTEnd())}; maintenanceTableModel.addRow(tableRow); } assert (maintenances.size() == maintenanceTableModel.getRowCount()) : "size: " + maintenances.size() + " rows: " + maintenanceTableModel.getRowCount(); } } /** * This inner class creates a JPanel which shows a certain vehicle type. The vehicletype is selected in the ViewVehiclePanel-class */ public class ViewVehicleTypePanel extends JPanel { private JButton backButton, saveButton, deleteButton; private VehicleTypePanel vehicleTypePanel; /** * Sets up the basic funktionalitet needed to view a vehicle type. */ public ViewVehicleTypePanel() { //Panel settings setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "Viewing vehicle type")); setBackground(new Color(216, 216, 208)); //Create the panel for viewing the vehicle type. vehicleTypePanel = new VehicleTypePanel(); add(vehicleTypePanel, BorderLayout.CENTER); //Create the buttons needed //Back-button backButton = new JButton("Back"); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showViewEntityPanel(); CarRental.getInstance().appendLog("Showing vehicle \"" + vehicleToView.getDescription() + "\" now."); } }); //Delete-button deleteButton = new JButton("Delete"); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean inUse = false; for (Vehicle vehicle : vehicleList) { if (vehicle.getVehicleType() == vehicleTypeToView.getID()) { inUse = true; } } if (!inUse) { CarRental.getInstance().deleteVehicleType(vehicleTypeToView.getID()); CarRental.getInstance().appendLog("Vehicle type \"" + vehicleTypeToView.getName() + "\" deleted from the database."); vehicleTypes = CarRental.getInstance().requestVehicleTypes(); showViewEntityPanel(); } else { CarRental.getInstance().appendLog("Vehicle type \"" + vehicleTypeToView.getName() + "\" is in use by at least one car. Could not be deleted."); } } }); // Save changes-button saveButton = new JButton("Save changes"); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<JTextComponent> vehicleTypeTextList = vehicleTypePanel.getTextComponents(); if (!vehicleTypeTextList.get(0).getText().trim().isEmpty() && !vehicleTypeTextList.get(1).getText().trim().isEmpty() && !vehicleTypeTextList.get(2).getText().trim().isEmpty()) { //Checks if name is in use already boolean nameTaken = false; for (VehicleType vehicleType : vehicleTypes) { if (vehicleTypeTextList.get(0).getText().trim().toLowerCase(Locale.ENGLISH).equals(vehicleType.getName().toLowerCase(Locale.ENGLISH)) - && vehicleType.getID() != vehicleTypeToView.getID()) { //if the name is in use and it´s not from the currently viewed vehicle + && vehicleType.getID() != vehicleTypeToView.getID()) { //if the name is in use and it´s not from the currently viewed vehicle nameTaken = true; } } if (!nameTaken) { try { VehicleType updatedVehicleType = new VehicleType(vehicleTypeToView.getID(), vehicleTypeTextList.get(0).getText().trim(), vehicleTypeTextList.get(2).getText().trim(), Integer.parseInt(vehicleTypeTextList.get(1).getText().trim())); CarRental.getInstance().saveVehicleType(updatedVehicleType); CarRental.getInstance().appendLog("Vehicle type \"" + vehicleTypeTextList.get(0).getText().trim() + "\" changed in the database."); vehicleTypes = CarRental.getInstance().requestVehicleTypes(); //update ment for if name check is implemented } catch (NumberFormatException ex) { CarRental.getInstance().appendLog("Your \"price per day\" field does not consist of numbers only or was too long. The vehicle type wasn't created."); } } else { CarRental.getInstance().appendLog("Another vehicle type with the name \"" + vehicleTypeTextList.get(0).getText().trim() + "\" already exists."); } } else { CarRental.getInstance().appendLog("The vehicle type wasn't edited. You need to enter text in all the fields."); } } }); } /** * Updates the panel to show the selected vehicle type. This type is selected in the ViewVehiclePanel-class */ public void update() { vehicleTypePanel.setPanel(vehicleTypeToView, backButton, deleteButton, saveButton); } } /** * This inner class creates a JPanel with the functionality to create a new vehicle type. */ public class AddTypePanel extends JPanel { private JButton cancelButton, createButton; private VehicleTypePanel vehicleTypePanel; /** * Sets up the basic functionality needed to create a new vehicle type. */ public AddTypePanel() { //Panel settings setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "Create a vehicle type")); setBackground(new Color(216, 216, 208)); //Create the panel for viewing the vehicle type. vehicleTypePanel = new VehicleTypePanel(); //Create the buttons needed //Cancel-button cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { vehicleTypePanel.setPanel(null, null, null, null); //resets the panel showMainScreenPanel(); } }); // Create-button createButton = new JButton("Create"); createButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ArrayList<JTextComponent> vehicleTypeTextList = vehicleTypePanel.getTextComponents(); if (!vehicleTypeTextList.get(0).getText().trim().isEmpty() && !vehicleTypeTextList.get(1).getText().trim().isEmpty() && !vehicleTypeTextList.get(2).getText().trim().isEmpty()) { //Checks if name is in use already boolean nameTaken = false; for (VehicleType vehicleType : vehicleTypes) { if (vehicleTypeTextList.get(0).getText().trim().toLowerCase(Locale.ENGLISH).equals(vehicleType.getName().toLowerCase(Locale.ENGLISH))) { nameTaken = true; } } if (!nameTaken) { try { VehicleType newVehicleType = new VehicleType(CarRental.getInstance().requestNewVehicleTypeId(), vehicleTypeTextList.get(0).getText().trim(), vehicleTypeTextList.get(2).getText().trim(), Integer.parseInt(vehicleTypeTextList.get(1).getText().trim())); CarRental.getInstance().saveVehicleType(newVehicleType); CarRental.getInstance().appendLog("Vehicle type \"" + vehicleTypeTextList.get(0).getText().trim() + "\" added to the database."); vehicleTypes = CarRental.getInstance().requestVehicleTypes(); } catch (NumberFormatException ex) { CarRental.getInstance().appendLog("Your \"price per day\" field does not consist of numbers only or was too long. The vehicle type wasn't created."); } } else { CarRental.getInstance().appendLog("A vehicle type with the name \"" + vehicleTypeTextList.get(0).getText().trim() + "\" already exists."); } } else { CarRental.getInstance().appendLog("The vehicle type wasn't created. You need to enter text in all the fields."); } } }); vehicleTypePanel.setPanel(null, cancelButton, null, createButton); add(vehicleTypePanel, BorderLayout.CENTER); } } /** * This inner class creates a JPanel with a list of vehicles. It is possible to search in the list. */ public class ListPanel extends JPanel { private DefaultTableModel vehicleTableModel; private JComboBox vehicleTypeCombo; private DefaultComboBoxModel vehicleTypeComboModel; private JTextField descriptionField, licensePlateField, vinField, drivenField; private int currentVehicleTypeIndex = -1; //this is for storing the currently selected choice from the combobox. /** * Sets up the basic functionality needed to show the list of vehicles. */ public ListPanel() { JPanel centerPanel, vehicleListPanel, filterPanel, topFilterPanel, middleFilterPanel, bottomFilterPanel, buttonPanel; JLabel vehicleTypeLabel, descriptionLabel, licensePlateLabel, vinLabel, drivenLabel; JButton cancelButton, viewButton; final JTable vehicleTable; JScrollPane listScrollPane; final int defaultJTextFieldColumns = 20, strutDistance = 0; //Panel settings setLayout(new BorderLayout()); setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK), "List of vehicles")); //CenterPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS)); centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 40)); add(centerPanel, BorderLayout.CENTER); //VehicleListPanel. vehicleListPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //Colors setBackground(new Color(216, 216, 208)); //Creating the table model vehicleTableModel = new DefaultTableModel(new Object[]{"Type", "Description", "LicensePlate", "VIN", "Distance driven"}, 0); //Creating the JTable vehicleTable = new JTable(vehicleTableModel); listScrollPane = new JScrollPane(vehicleTable); //Setting the default size for the table in this scrollpane vehicleTable.setPreferredScrollableViewportSize(new Dimension(700, 200)); vehicleListPanel.add(listScrollPane); centerPanel.add(vehicleListPanel); //FilterPanel filterPanel = new JPanel(); filterPanel.setLayout(new BoxLayout(filterPanel, BoxLayout.PAGE_AXIS)); filterPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 2), "Filters")); centerPanel.add(filterPanel); //top row of filters topFilterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); filterPanel.add(topFilterPanel); //Vehicle Type vehicleTypeLabel = new JLabel("Vehicle Type"); vehicleTypeComboModel = new DefaultComboBoxModel(); vehicleTypeCombo = new JComboBox(vehicleTypeComboModel); vehicleTypeCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentVehicleTypeIndex == -1 && vehicleTypeCombo.getSelectedIndex() > 0) { //if the current selection hasn't been set and it was not just set to "All" filter(); currentVehicleTypeIndex = vehicleTypeCombo.getSelectedIndex(); } else if (currentVehicleTypeIndex > -1 && currentVehicleTypeIndex != vehicleTypeCombo.getSelectedIndex()) { filter(); currentVehicleTypeIndex = vehicleTypeCombo.getSelectedIndex(); } } }); topFilterPanel.add(vehicleTypeLabel); topFilterPanel.add(Box.createRigidArea(new Dimension(16 + strutDistance, 0))); topFilterPanel.add(vehicleTypeCombo); topFilterPanel.add(Box.createRigidArea(new Dimension(91, 0))); //Description descriptionLabel = new JLabel("Description"); descriptionField = new JTextField(defaultJTextFieldColumns); descriptionField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { filter(); } }); topFilterPanel.add(Box.createRigidArea(new Dimension(5, 0))); topFilterPanel.add(descriptionLabel); topFilterPanel.add(Box.createRigidArea(new Dimension(45 + strutDistance, 0))); topFilterPanel.add(descriptionField); //Middle Filter panel middleFilterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); filterPanel.add(middleFilterPanel); //LicensePlate licensePlateLabel = new JLabel("License Plate"); licensePlateField = new JTextField(defaultJTextFieldColumns); licensePlateField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { filter(); } }); middleFilterPanel.add(licensePlateLabel); middleFilterPanel.add(Box.createRigidArea(new Dimension(11 + strutDistance, 0))); middleFilterPanel.add(licensePlateField); //VIN vinLabel = new JLabel("VIN"); vinField = new JTextField(defaultJTextFieldColumns); vinField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { filter(); } }); middleFilterPanel.add(Box.createRigidArea(new Dimension(5, 0))); middleFilterPanel.add(vinLabel); middleFilterPanel.add(Box.createRigidArea(new Dimension(90 + strutDistance, 0))); middleFilterPanel.add(vinField); //Bottom Filter panel bottomFilterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); filterPanel.add(bottomFilterPanel); //Driven drivenLabel = new JLabel("Distance driven"); drivenField = new JTextField(defaultJTextFieldColumns); drivenField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { filter(); } }); bottomFilterPanel.add(drivenLabel); bottomFilterPanel.add(Box.createRigidArea(new Dimension(strutDistance, 0))); bottomFilterPanel.add(drivenField); //ButtonPanels buttonPanel = new JPanel(); add(buttonPanel, BorderLayout.SOUTH); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS)); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 15)); //add some space between the right edge of the screen buttonPanel.add(Box.createHorizontalGlue()); //cancel-Button cancelButton = new JButton("Back"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { update(); showMainScreenPanel(); } }); buttonPanel.add(cancelButton); buttonPanel.add(Box.createRigidArea(new Dimension(5, 0))); //View-button viewButton = new JButton("View selected"); viewButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (vehicleTable.getSelectedRow() >= 0) { //getSelectedRow returns -1 if no row is selected for (Vehicle vehicle : vehicleList) { if (vehicle.getVin().equals(vehicleTableModel.getValueAt(vehicleTable.getSelectedRow(), 3))) { vehicleToView = vehicle; break; } } showViewEntityPanel(); CarRental.getInstance().appendLog("Showing vehicle \"" + vehicleToView.getDescription() + "\" now."); } } }); buttonPanel.add(viewButton); } /** * Updates the panel to show an updated list of vehicles. */ public void update() { //reset the selected vehicle type currentVehicleTypeIndex = -1; //Delete exisiting rows vehicleTableModel.setRowCount(0); //Add the updated rows with vehicles for (Vehicle vehicle : vehicleList) { vehicleTableModel.addRow(new String[]{ CarRental.getInstance().requestVehicleType(vehicle.getVehicleType()).getName(), vehicle.getDescription(), vehicle.getLicensePlate(), vehicle.getVin(), Integer.toString(vehicle.getOdo())}); } assert (vehicleList.size() == vehicleTableModel.getRowCount()) : "size: " + vehicleList.size() + " rows: " + vehicleTableModel.getRowCount(); //Update the JComboBox vehicleTypeComboModel.removeAllElements(); vehicleTypeComboModel.addElement("All"); for (VehicleType vehicleType : vehicleTypes) { vehicleTypeComboModel.addElement(vehicleType.getName()); } //Sets all text fields blank descriptionField.setText(null); licensePlateField.setText(null); vinField.setText(null); drivenField.setText(null); } /** * Rearranges the list of vehicles so that only entries matching the filters will be shown. */ public void filter() { //Delete exisiting rows vehicleTableModel.setRowCount(0); //Add the rows that match the filter for (Vehicle vehicle : vehicleList) { //As long as - if (((vehicleTypeCombo.getSelectedIndex() == -1 || vehicleTypeCombo.getSelectedIndex() == 0) || //vehicle type is not chosen or set to "All" OR vehicle.getVehicleType() == vehicleTypes.get(vehicleTypeCombo.getSelectedIndex() - 1).getID()) && //Vehicle's type is the vehicle type chosen AND (descriptionField.getText().trim().isEmpty() || //description field is empty OR vehicle.getDescription().toLowerCase(Locale.ENGLISH).contains(descriptionField.getText().trim().toLowerCase(Locale.ENGLISH))) && //vehicles descripton equals the description given AND (licensePlateField.getText().trim().isEmpty() || //License plate field is empty OR vehicle.getLicensePlate().toLowerCase(Locale.ENGLISH).contains(licensePlateField.getText().trim().toLowerCase(Locale.ENGLISH))) && //vehicles license plate number equals the license plate number given AND (vinField.getText().trim().isEmpty() || //VIN field is empty OR vehicle.getVin().toLowerCase(Locale.ENGLISH).contains(vinField.getText().trim().toLowerCase(Locale.ENGLISH))) && //vehicles VIN equals the VIN given AND (drivenField.getText().trim().isEmpty() || //driven field is empty OR Integer.toString(vehicle.getOdo()).toLowerCase(Locale.ENGLISH).contains(drivenField.getText().trim().toLowerCase(Locale.ENGLISH)))) { //vehicles ODO equals the "distance driven" given // - does the vehicle match the filter, and following row is added to the table vehicleTableModel.addRow(new String[]{ CarRental.getInstance().requestVehicleType(vehicle.getVehicleType()).getName(), vehicle.getDescription(), vehicle.getLicensePlate(), vehicle.getVin(), Integer.toString(vehicle.getOdo())}); } } } } } \ No newline at end of file
false
false
null
null
diff --git a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java index 3b17e754..7a877c3f 100644 --- a/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java +++ b/src/java/org/hibernate/tool/hbm2x/HibernateConfigurationExporter.java @@ -1,196 +1,196 @@ /* * Created on 2004-12-03 * */ package org.hibernate.tool.hbm2x; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; /** * @author max * */ public class HibernateConfigurationExporter extends AbstractExporter { private Writer output; private Properties customProperties = new Properties(); public HibernateConfigurationExporter(Configuration configuration, File outputdir) { super(configuration, outputdir); } public HibernateConfigurationExporter() { } public Properties getCustomProperties() { return customProperties; } public void setCustomProperties(Properties customProperties) { this.customProperties = customProperties; } public Writer getOutput() { return output; } public void setOutput(Writer output) { this.output = output; } /* (non-Javadoc) * @see org.hibernate.tool.hbm2x.Exporter#finish() */ public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + - " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } } /** * @param pw * @param element */ private void dump(PrintWriter pw, boolean useClass, PersistentClass element) { if(useClass) { pw.println("<mapping class=\"" + element.getClassName() + "\"/>"); } else { pw.println("<mapping resource=\"" + getMappingFileResource(element) + "\"/>"); } Iterator directSubclasses = element.getDirectSubclasses(); while (directSubclasses.hasNext() ) { PersistentClass subclass = (PersistentClass) directSubclasses.next(); dump(pw, useClass, subclass); } } /** * @param element * @return */ private String getMappingFileResource(PersistentClass element) { return element.getClassName().replace('.', '/') + ".hbm.xml"; } public String getName() { return "cfg2cfgxml"; } /** * * @param text * @return String with escaped [<,>] special characters. */ public static String forXML(String text) { if (text == null) return null; final StringBuilder result = new StringBuilder(); char[] chars = text.toCharArray(); for (int i = 0; i < chars.length; i++){ char character = chars[i]; if (character == '<') { result.append("&lt;"); } else if (character == '>'){ result.append("&gt;"); } else { result.append(character); } } return result.toString(); } }
true
true
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
public void doStart() throws ExporterException { PrintWriter pw = null; File file = null; try { if(output==null) { file = new File(getOutputDirectory(), "hibernate.cfg.xml"); getTemplateHelper().ensureExistence(file); pw = new PrintWriter(new FileWriter(file) ); getArtifactCollector().addFile(file, "cfg.xml"); } else { pw = new PrintWriter(output); } pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE hibernate-configuration PUBLIC\r\n" + " \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\"\r\n" + " \"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd\">\r\n" + "<hibernate-configuration>"); boolean ejb3 = Boolean.valueOf((String)getProperties().get("ejb3")).booleanValue(); Map props = new TreeMap(); if(getConfiguration()!=null) { props.putAll(getConfiguration().getProperties() ); } if(customProperties!=null) { props.putAll(customProperties); } String sfname = (String) props.get(Environment.SESSION_FACTORY_NAME); pw.println(" <session-factory" + (sfname==null?"":" name=\"" + sfname + "\"") + ">"); Map ignoredProperties = new HashMap(); ignoredProperties.put(Environment.SESSION_FACTORY_NAME, null); ignoredProperties.put(Environment.HBM2DDL_AUTO, "false" ); ignoredProperties.put("hibernate.temp.use_jdbc_metadata_defaults", null ); ignoredProperties.put(Environment.TRANSACTION_MANAGER_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); Set set = props.entrySet(); Iterator iterator = set.iterator(); while (iterator.hasNext() ) { Map.Entry element = (Map.Entry) iterator.next(); String key = (String) element.getKey(); if(ignoredProperties.containsKey( key )) { Object ignoredValue = ignoredProperties.get( key ); if(ignoredValue == null || element.getValue().equals(ignoredValue)) { continue; } } if(key.startsWith("hibernate.") ) { // if not starting with hibernate. not relevant for cfg.xml pw.println(" <property name=\"" + key + "\">" + forXML(element.getValue().toString()) + "</property>"); } } if(getConfiguration()!=null) { Iterator classMappings = getConfiguration().getClassMappings(); while (classMappings.hasNext() ) { PersistentClass element = (PersistentClass) classMappings.next(); if(element instanceof RootClass) { dump(pw, ejb3, element); } } } pw.println(" </session-factory>\r\n" + "</hibernate-configuration>"); } catch (IOException e) { throw new ExporterException("Problems while creating hibernate.cfg.xml", e); } finally { if(pw!=null) { pw.flush(); pw.close(); } } }
diff --git a/core/src/com/clarkparsia/openrdf/query/sparql/ContextCollector.java b/core/src/com/clarkparsia/openrdf/query/sparql/ContextCollector.java index 87168ab..c007aac 100644 --- a/core/src/com/clarkparsia/openrdf/query/sparql/ContextCollector.java +++ b/core/src/com/clarkparsia/openrdf/query/sparql/ContextCollector.java @@ -1,163 +1,166 @@ /* * Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.clarkparsia.openrdf.query.sparql; import java.util.HashMap; import java.util.Map; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.algebra.Difference; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.Intersection; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.LeftJoin; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.Union; import org.openrdf.query.algebra.Var; import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import com.clarkparsia.utils.BasicUtils; /** * <p>Visitor implementation for the sesame query algebra which walks the tree and figures out the context for nodes in the algebra. The context for a node * is set on the highest node in the tree. That is, everything below it shares the same context.</p> * * @author Blazej Bulka * @since 0.3 * @version 0.3 */ public class ContextCollector extends QueryModelVisitorBase<Exception> { /** * Maps TupleExpr to contexts. This map contains only top-level expression elements * that share the given context (i.e., all elements below share the same context) -- * this is because of where contexts are being introduced into a SPARQL query -- all * elements sharing the same contexts are grouped together with a "GRAPH <ctx> { ... }" * clause. */ private Map<TupleExpr,Var> mContexts = new HashMap<TupleExpr,Var>(); private ContextCollector() { } static Map<TupleExpr,Var> collectContexts(TupleExpr theTupleExpr) throws Exception { ContextCollector aContextVisitor = new ContextCollector(); theTupleExpr.visit(aContextVisitor); return aContextVisitor.mContexts; } public void meet(Join theJoin) throws Exception { binaryOpMeet(theJoin, theJoin.getLeftArg(), theJoin.getRightArg()); } /** * @inheritDoc */ @Override public void meet(LeftJoin theJoin) throws Exception { binaryOpMeet(theJoin, theJoin.getLeftArg(), theJoin.getRightArg()); } /** * @inheritDoc */ @Override public void meet(Union theOp) throws Exception { binaryOpMeet(theOp, theOp.getLeftArg(), theOp.getRightArg()); } /** * @inheritDoc */ @Override public void meet(Difference theOp) throws Exception { binaryOpMeet(theOp, theOp.getLeftArg(), theOp.getRightArg()); } /** * @inheritDoc */ @Override public void meet(Intersection theOp) throws Exception { binaryOpMeet(theOp, theOp.getLeftArg(), theOp.getRightArg()); } /** * @inheritDoc */ @Override public void meet(final Filter theFilter) throws Exception { theFilter.getArg().visit(this); if (mContexts.containsKey(theFilter.getArg())) { Var aCtx = mContexts.get(theFilter.getArg()); mContexts.remove(theFilter.getArg()); mContexts.put(theFilter, aCtx); } } private void binaryOpMeet(TupleExpr theCurrentExpr, TupleExpr theLeftExpr, TupleExpr theRightExpr) throws Exception { theLeftExpr.visit(this); Var aLeftCtx = mContexts.get(theLeftExpr); theRightExpr.visit(this); Var aRightCtx = mContexts.get(theRightExpr); sameCtxCheck(theCurrentExpr, theLeftExpr, aLeftCtx, theRightExpr, aRightCtx); } /** * @inheritDoc */ @Override public void meet(StatementPattern thePattern) throws Exception { Var aCtxVar = thePattern.getContextVar(); if (aCtxVar != null) { mContexts.put(thePattern, aCtxVar); } } private void sameCtxCheck(TupleExpr theCurrentExpr, TupleExpr theLeftExpr, Var theLeftCtx, TupleExpr theRightExpr, Var theRightCtx) { if ((theLeftCtx == null) && (theRightCtx != null)) { mContexts.remove(theRightExpr); mContexts.put(theCurrentExpr, theRightCtx); } else if ((theLeftCtx != null) && (theRightCtx == null)) { mContexts.remove(theLeftExpr); mContexts.put(theCurrentExpr, theLeftCtx); } else if ((theLeftCtx != null) && (theRightCtx != null) && isSameCtx(theLeftCtx, theRightCtx)) { mContexts.remove(theLeftExpr); mContexts.remove(theRightExpr); mContexts.put(theCurrentExpr, theLeftCtx); } } private boolean isSameCtx(Var v1, Var v2) { if ((v1 != null && v1.getValue() != null) && (v2 != null && v2.getValue() != null)) { return v1.getValue().equals(v2.getValue()); } + else if ((v1 != null && v1.getName() != null) && (v2 != null && v2.getName() != null)) { + return v1.getName().equals(v2.getName()); + } return false; } } diff --git a/core/src/com/clarkparsia/openrdf/query/sparql/SparqlTupleExprRenderer.java b/core/src/com/clarkparsia/openrdf/query/sparql/SparqlTupleExprRenderer.java index ca19c8f..cb2631f 100644 --- a/core/src/com/clarkparsia/openrdf/query/sparql/SparqlTupleExprRenderer.java +++ b/core/src/com/clarkparsia/openrdf/query/sparql/SparqlTupleExprRenderer.java @@ -1,260 +1,264 @@ /* * Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.clarkparsia.openrdf.query.sparql; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.ValueExpr; import org.openrdf.query.algebra.Join; import org.openrdf.query.algebra.LeftJoin; import org.openrdf.query.algebra.Union; import org.openrdf.query.algebra.Difference; import org.openrdf.query.algebra.Intersection; import org.openrdf.query.algebra.Filter; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.ProjectionElemList; import org.openrdf.query.algebra.ProjectionElem; import org.openrdf.query.algebra.OrderElem; import org.openrdf.query.algebra.Var; import org.openrdf.query.algebra.BinaryTupleOperator; import org.openrdf.query.algebra.UnaryTupleOperator; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.parser.ParsedQuery; import org.openrdf.query.parser.sparql.SPARQLParser; import com.clarkparsia.openrdf.query.BaseTupleExprRenderer; import com.clarkparsia.openrdf.query.SesameQueryUtils; import com.clarkparsia.utils.BasicUtils; import java.util.HashMap; import java.util.Map; /** * <p>Extends the BaseTupleExprRenderer to provide support for rendering tuple expressions as SPARQL queries.</p> * * @author Michael Grove * @since 0.2 * @version 0.2.1 */ public class SparqlTupleExprRenderer extends BaseTupleExprRenderer { private StringBuffer mJoinBuffer = new StringBuffer(); private Map<TupleExpr,Var> mContexts = new HashMap<TupleExpr, Var>(); private int mIndent = 2; /** * @inheritDoc */ @Override public void reset() { super.reset(); mJoinBuffer = new StringBuffer(); mContexts.clear(); } /** * @inheritDoc */ public String render(final TupleExpr theExpr) throws Exception { mContexts = ContextCollector.collectContexts(theExpr); theExpr.visit(this); return mJoinBuffer.toString(); } private String indent() { return BasicUtils.repeat(' ', mIndent); } /** * @inheritDoc */ protected String renderValueExpr(final ValueExpr theExpr) throws Exception { return new SparqlValueExprRenderer().render(theExpr); } private void ctxOpen(TupleExpr theExpr) { Var aContext = mContexts.get(theExpr); if (aContext != null) { mJoinBuffer.append(indent()).append("GRAPH "); if (aContext.hasValue()) { mJoinBuffer.append(SesameQueryUtils.getSPARQLQueryString(aContext.getValue())); } else { mJoinBuffer.append("?").append(aContext.getName()); } mJoinBuffer.append(" {\n"); mIndent += 2; } } private void ctxClose(TupleExpr theExpr) { Var aContext = mContexts.get(theExpr); if (aContext != null) { mJoinBuffer.append("}"); mIndent -= 2; } } /** * @inheritDoc */ @Override public void meet(Join theJoin) throws Exception { ctxOpen(theJoin); theJoin.getLeftArg().visit(this); theJoin.getRightArg().visit(this); ctxClose(theJoin); } /** * @inheritDoc */ @Override public void meet(LeftJoin theJoin) throws Exception { + ctxOpen(theJoin); + theJoin.getLeftArg().visit(this); mJoinBuffer.append(indent()).append("OPTIONAL {\n"); mIndent+=2; theJoin.getRightArg().visit(this); if (theJoin.getCondition() != null) { mJoinBuffer.append(indent()).append("filter").append(renderValueExpr(theJoin.getCondition())).append("\n"); } mIndent-=2; mJoinBuffer.append(indent()).append("}.\n"); + + ctxClose(theJoin); } /** * Renders the tuple expression as a query string. It creates a new SparqlTupleExprRenderer rather than reusing * this one. * @param theExpr the expr to render * @return the rendered expression * @throws Exception if there is an error while rendering */ private String renderTupleExpr(TupleExpr theExpr) throws Exception { SparqlTupleExprRenderer aRenderer = new SparqlTupleExprRenderer(); // aRenderer.mProjection = new ArrayList<ProjectionElemList>(mProjection); // aRenderer.mDistinct = mDistinct; // aRenderer.mReduced = mReduced; // aRenderer.mExtensions = new HashMap<String, ValueExpr>(mExtensions); // aRenderer.mOrdering = new ArrayList<OrderElem>(mOrdering); // aRenderer.mLimit = mLimit; // aRenderer.mOffset = mOffset; aRenderer.mIndent = mIndent; aRenderer.mContexts = new HashMap<TupleExpr, Var>(mContexts); return aRenderer.render(theExpr); } /** * @inheritDoc */ @Override public void meet(Union theOp) throws Exception { ctxOpen(theOp); String aLeft = renderTupleExpr(theOp.getLeftArg()); if (aLeft.endsWith("\n")) { aLeft = aLeft.substring(0, aLeft.length()-1); } String aRight = renderTupleExpr(theOp.getRightArg()); if (aRight.endsWith("\n")) { aRight = aRight.substring(0, aRight.length()-1); } mJoinBuffer.append(indent()).append("{\n").append(aLeft).append("\n").append(indent()).append("}\n").append(indent()).append("union\n").append(indent()).append("{\n").append(aRight).append("\n").append(indent()).append("}.\n"); ctxClose(theOp); } /** * @inheritDoc */ @Override public void meet(Difference theOp) throws Exception { String aLeft = renderTupleExpr(theOp.getLeftArg()); String aRight = renderTupleExpr(theOp.getRightArg()); mJoinBuffer.append("\n{").append(aLeft).append("}").append("\nminus\n").append("{").append(aRight).append("}.\n"); } /** * @inheritDoc */ @Override public void meet(Intersection theOp) throws Exception { String aLeft = renderTupleExpr(theOp.getLeftArg()); String aRight = renderTupleExpr(theOp.getRightArg()); mJoinBuffer.append("\n").append(aLeft).append("}").append("\nintersection\n").append("{").append(aRight).append("}.\n"); } /** * @inheritDoc */ @Override public void meet(final Filter theFilter) throws Exception { ctxOpen(theFilter); if (theFilter.getArg() != null) { theFilter.getArg().visit(this); } mJoinBuffer.append(indent()).append("filter ").append(renderValueExpr(theFilter.getCondition())).append(".\n"); ctxClose(theFilter); } /** * @inheritDoc */ @Override public void meet(StatementPattern thePattern) throws Exception { ctxOpen(thePattern); mJoinBuffer.append(indent()).append(renderPattern(thePattern)); ctxClose(thePattern); } String renderPattern(StatementPattern thePattern) throws Exception { return renderValueExpr(thePattern.getSubjectVar()) + " " + renderValueExpr(thePattern.getPredicateVar()) + " " + "" + renderValueExpr(thePattern.getObjectVar()) + ".\n"; } public static void main(String[] args) throws Exception { ParsedQuery q = new SPARQLParser().parseQuery("ask { ?s ?p ?o }", "http://foo.com"); System.err.println(new SPARQLQueryRenderer().render(q)); } }
false
false
null
null
diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/vraptor2/MessageCreatorValidator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/vraptor2/MessageCreatorValidator.java index 7d288eef9..abfec24b0 100644 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/vraptor2/MessageCreatorValidator.java +++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/vraptor2/MessageCreatorValidator.java @@ -1,115 +1,118 @@ /*** * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource * 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. */ package br.com.caelum.vraptor.vraptor2; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.vraptor.i18n.FixedMessage; import org.vraptor.i18n.ValidationMessage; import org.vraptor.validator.ValidationErrors; import br.com.caelum.vraptor.Result; import br.com.caelum.vraptor.View; +import br.com.caelum.vraptor.core.Localization; import br.com.caelum.vraptor.core.MethodInfo; import br.com.caelum.vraptor.ioc.RequestScoped; import br.com.caelum.vraptor.resource.ResourceMethod; import br.com.caelum.vraptor.util.test.MockResult; import br.com.caelum.vraptor.validator.AbstractValidator; import br.com.caelum.vraptor.validator.Message; import br.com.caelum.vraptor.validator.ValidationException; import br.com.caelum.vraptor.validator.Validations; import br.com.caelum.vraptor.view.Results; import br.com.caelum.vraptor.view.ValidationViewsFactory; /** * The vraptor2 compatible messages creator. * * @author Guilherme Silveira */ @RequestScoped public class MessageCreatorValidator extends AbstractValidator { private final Result result; private final ValidationErrors errors; private final ResourceMethod resource; private final MethodInfo info; private boolean containsErrors; private final ValidationViewsFactory viewsFactory; + private final Localization localization; public MessageCreatorValidator(Result result, ValidationErrors errors, MethodInfo info, - ValidationViewsFactory viewsFactory) { + ValidationViewsFactory viewsFactory, Localization localization) { this.result = result; this.errors = errors; this.viewsFactory = viewsFactory; + this.localization = localization; this.resource = info.getResourceMethod(); this.info = info; } public void checking(Validations validations) { - List<Message> messages = validations.getErrors(); + List<Message> messages = validations.getErrors(localization.getBundle()); for (Message s : messages) { add(s); } } public void validate(Object object) { throw new UnsupportedOperationException("this feature is not supported by vraptor2"); } public <T extends View> T onErrorUse(Class<T> view) { if (!hasErrors()) { return new MockResult().use(view); // ignore anything, no errors // occurred } result.include("errors", errors); if (Info.isOldComponent(resource.getResource())) { info.setResult("invalid"); result.use(Results.page()).forward(); throw new ValidationException(new ArrayList<Message>()); } else { return viewsFactory.instanceFor(view, new ArrayList<Message>()); } } public void add(Message message) { containsErrors = true; this.errors.add(new FixedMessage(message.getCategory(), message.getMessage(), message.getCategory())); } public void addAll(Collection<? extends Message> messages) { for (Message message : messages) { this.add(message); } } public boolean hasErrors() { return containsErrors; } @Override protected List<Message> getErrors() { List<Message> messages = new ArrayList<Message>(); for (ValidationMessage message : errors) { messages.add(new br.com.caelum.vraptor.validator.ValidationMessage(message.getPath(), message.getCategory())); } return messages; } }
false
false
null
null
diff --git a/src/org/eclipse/jface/viewers/EditingSupport.java b/src/org/eclipse/jface/viewers/EditingSupport.java index 7d4d50a6..dd222a1c 100644 --- a/src/org/eclipse/jface/viewers/EditingSupport.java +++ b/src/org/eclipse/jface/viewers/EditingSupport.java @@ -1,115 +1,119 @@ /******************************************************************************* * Copyright (c) 2006, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Tom Schindl <tom.schindl@bestsolution.at> - initial API and implementation * fix in bug 151295,167325,201905 *******************************************************************************/ package org.eclipse.jface.viewers; import org.eclipse.core.runtime.Assert; /** * EditingSupport is the abstract superclass of the support for cell editing. * * @since 3.3 * */ public abstract class EditingSupport { private ColumnViewer viewer; /** * @param viewer * a new viewer */ public EditingSupport(ColumnViewer viewer) { Assert.isNotNull(viewer, "Viewer is not allowed to be null"); //$NON-NLS-1$ this.viewer = viewer; } /** * The editor to be shown * * @param element * the model element * @return the CellEditor */ protected abstract CellEditor getCellEditor(Object element); /** * Is the cell editable * * @param element * the model element * @return true if editable */ protected abstract boolean canEdit(Object element); /** * Get the value to set to the editor * * @param element * the model element * @return the value shown */ protected abstract Object getValue(Object element); /** - * Restore the value from the CellEditor - * + * Sets the new value on the given element. Note that implementers need to + * ensure that <code>getViewer().update(element, null)</code> or similar + * methods are called, either directly or through some kind of listener + * mechanism on the implementer's model, to cause the new value to appear in + * the viewer. + * * <p> - * <b>Subclasses should overwrite!</b> + * <b>Subclasses should overwrite.</b> * </p> - * + * * @param element * the model element * @param value * the new value */ protected abstract void setValue(Object element, Object value); /** * @return the viewer this editing support works for */ public ColumnViewer getViewer() { return viewer; } /** * Initialize the editor. Frameworks like Databinding can hook in here and provide * a customized implementation. <p><b>Standard customers should not overwrite this method but {@link #getValue(Object)}</b></p> * * @param cellEditor * the cell editor * @param cell * the cell the editor is working for */ protected void initializeCellEditorValue(CellEditor cellEditor, ViewerCell cell) { Object value = getValue(cell.getElement()); cellEditor.setValue(value); } /** * Save the value of the cell editor back to the model. Frameworks like Databinding can hook in here and provide * a customized implementation. <p><b>Standard customers should not overwrite this method but {@link #setValue(Object, Object)} </b></p> * @param cellEditor * the cell-editor * @param cell * the cell the editor is working for */ protected void saveCellEditorValue(CellEditor cellEditor, ViewerCell cell) { Object value = cellEditor.getValue(); setValue(cell.getElement(), value); } boolean isLegacySupport() { return false; } }
false
false
null
null
diff --git a/abjon/src/main/java/com/abjon/example/services/ArticlesResource.java b/abjon/src/main/java/com/abjon/example/services/ArticlesResource.java index f983911..34eb979 100644 --- a/abjon/src/main/java/com/abjon/example/services/ArticlesResource.java +++ b/abjon/src/main/java/com/abjon/example/services/ArticlesResource.java @@ -1,126 +1,127 @@ package com.abjon.example.services; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.UriInfo; import com.abjon.example.data.ArticleBean; import com.abjon.example.model.Article; @Path("/articles") public class ArticlesResource { @Context private UriInfo context; ArticleBean ab; /** * Creates a new instance */ public ArticlesResource() { try { ab = (ArticleBean) new InitialContext().lookup("java:module/ArticleBean"); } catch (NamingException ex) { Logger.getLogger(ArticlesResource.class.getName()).log(Level.SEVERE, null, ex); } } /** * Retrieves representation of an instance of com.abjon.research.ArticlesResource * @return an instance of java.lang.String */ @GET @Produces({MediaType.APPLICATION_JSON}) public List<Article> list() { System.err.println("CALLED LIST"); return (List<Article>)ab.findAll(); } @GET @Path("/{articleid}") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Article read(@PathParam("articleid") String sarticleid) { Long uid = new Long(Long.parseLong(sarticleid)); return ab.find(uid); } @POST @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Article create(Article a) { - System.err.append("CALLED CREATE!"); + System.err.append("CALLED CREATE"); if(a==null) { a = new Article(); a.setArticle("Ny"); } ab.create(a); return a; } @PUT @Path("/{articleid}") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Article update(@PathParam("articleid") String sarticleid,Article article) { - System.err.append("CALLED UPDATE!"); + Long articleid = Long.parseLong(sarticleid); + System.err.append("CALLED UPDATE on " + sarticleid); Article a = null; a = ab.find(articleid); a.setArticle(article.getArticle()); a.setLatitude(article.getLatitude()); a.setLongitude(article.getLongitude()); ab.edit(a); return a; } @DELETE @Path("/{articleid}") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public String destroy(@PathParam("articleid") String sarticleid) { Long articleid = Long.parseLong(sarticleid); Article a = null; a = ab.find(articleid); ab.remove(a); return "Success"; } }
false
false
null
null
diff --git a/src/main/java/tconstruct/client/ArmorControls.java b/src/main/java/tconstruct/client/ArmorControls.java index d11a53564..e7f33c461 100644 --- a/src/main/java/tconstruct/client/ArmorControls.java +++ b/src/main/java/tconstruct/client/ArmorControls.java @@ -1,220 +1,222 @@ package tconstruct.client; import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.Loader; +import cpw.mods.fml.common.Optional; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; import mantle.common.network.AbstractPacket; import modwarriors.notenoughkeys.api.Api; import modwarriors.notenoughkeys.api.KeyBindingPressedEvent; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import tconstruct.TConstruct; import tconstruct.armor.ArmorProxyClient; import tconstruct.armor.ArmorProxyCommon; import tconstruct.armor.PlayerAbilityHelper; import tconstruct.armor.items.TravelGear; import tconstruct.util.network.AccessoryInventoryPacket; import tconstruct.util.network.BeltPacket; import tconstruct.util.network.DoubleJumpPacket; import tconstruct.util.network.GogglePacket; public class ArmorControls { public static final String keybindCategory = "tconstruct.keybindings"; public static final String[] keyDescs = new String[] { "key.tarmor", "key.tgoggles", "key.tbelt", "key.tzoom" }; public static KeyBinding armorKey = new KeyBinding(keyDescs[0], 24, keybindCategory); public static KeyBinding toggleGoggles = new KeyBinding(keyDescs[1], 34, keybindCategory); public static KeyBinding beltSwap = new KeyBinding(keyDescs[2], 48, keybindCategory); public static KeyBinding zoomKey = new KeyBinding(keyDescs[3], 44, keybindCategory); //TODO: Make this hold, not toggle static KeyBinding jumpKey; static KeyBinding invKey; static Minecraft mc; boolean jumping; int midairJumps = 0; boolean climbing = false; boolean onGround = false; public static boolean zoom = false; boolean activeGoggles = false; //TODO: Set this on server login int currentTab = 1; // boolean onStilts = false; private final KeyBinding[] keys; public ArmorControls() { getVanillaKeyBindings(); this.keys = new KeyBinding[] { ArmorControls.armorKey, ArmorControls.toggleGoggles, ArmorControls.beltSwap, ArmorControls.zoomKey, null, null }; } public void registerKeys() { // Register bindings for (KeyBinding key : this.keys) { if (key != null) ClientRegistry.registerKeyBinding(key); } if (Loader.isModLoaded("notenoughkeys")) Api.registerMod(TConstruct.modID, ArmorControls.keyDescs); // Add mc keys this.keys[4] = ArmorControls.jumpKey; this.keys[5] = ArmorControls.invKey; } private static KeyBinding[] getVanillaKeyBindings() { mc = Minecraft.getMinecraft(); jumpKey = mc.gameSettings.keyBindJump; invKey = mc.gameSettings.keyBindInventory; return new KeyBinding[] { jumpKey, invKey }; } @SubscribeEvent public void mouseEvent(InputEvent.MouseInputEvent event) { if (!Loader.isModLoaded("notenoughkeys")) this.checkKeys(); } @SubscribeEvent public void keyEvent(InputEvent.KeyInputEvent event) { if (!Loader.isModLoaded("notenoughkeys")) this.checkKeys(); } + @Optional.Method(modid = "notenoughkeys") @SubscribeEvent public void keyEventSpecial(KeyBindingPressedEvent event) { this.keyPressed(event.keyBinding); } private void checkKeys() { for (KeyBinding key : this.keys) { if (this.isKeyActive(key.getKeyCode())) { this.keyPressed(key); } } } private boolean isKeyActive(int keyCode) { if (keyCode < 0) return Mouse.isButtonDown(keyCode + 100); else return Keyboard.isKeyDown(keyCode); } private void keyPressed(KeyBinding key) { if (key == ArmorControls.armorKey) { openArmorGui(); } if (key == ArmorControls.jumpKey) { if (mc.thePlayer.capabilities.isCreativeMode) return; if (jumping && midairJumps > 0) { mc.thePlayer.motionY = 0.42D; mc.thePlayer.fallDistance = 0; if (mc.thePlayer.isPotionActive(Potion.jump)) { mc.thePlayer.motionY += (double) ( (float) (mc.thePlayer.getActivePotionEffect(Potion.jump).getAmplifier() + 1) * 0.1F); } midairJumps--; resetFallDamage(); } if (!jumping) { jumping = mc.thePlayer.isAirBorne; ItemStack shoes = mc.thePlayer.getCurrentArmor(0); if (shoes != null && shoes.hasTagCompound() && shoes.getTagCompound() .hasKey("TinkerArmor")) { NBTTagCompound shoeTag = shoes.getTagCompound().getCompoundTag("TinkerArmor"); midairJumps += shoeTag.getInteger("Double-Jump"); } ItemStack wings = mc.thePlayer.getCurrentArmor(1); if (wings != null && wings.hasTagCompound() && wings.getTagCompound() .hasKey("TinkerArmor")) { NBTTagCompound shoeTag = wings.getTagCompound().getCompoundTag("TinkerArmor"); midairJumps += shoeTag.getInteger("Double-Jump"); } } } if (mc.currentScreen == null) { if (key == ArmorControls.toggleGoggles) { ItemStack goggles = mc.thePlayer.getCurrentArmor(3); if (goggles != null && goggles .getItem() instanceof TravelGear) //TODO: Genericize this { activeGoggles = !activeGoggles; PlayerAbilityHelper.toggleGoggles(mc.thePlayer, activeGoggles); toggleGoggles(); } } if (key == ArmorControls.beltSwap) { if (ArmorProxyClient.armorExtended.inventory[3] != null) { PlayerAbilityHelper.swapBelt(mc.thePlayer, ArmorProxyClient.armorExtended); toggleBelt(); } } if (key == ArmorControls.zoomKey) { zoom = !zoom; } } } public void landOnGround() { midairJumps = 0; jumping = false; } public void resetControls() { midairJumps = 0; jumping = false; climbing = false; onGround = false; } void resetFallDamage() { AbstractPacket packet = new DoubleJumpPacket(); updateServer(packet); } public static void openArmorGui() { AbstractPacket packet = new AccessoryInventoryPacket(ArmorProxyCommon.armorGuiID); updateServer(packet); } public static void openKnapsackGui() { AbstractPacket packet = new AccessoryInventoryPacket(ArmorProxyCommon.knapsackGuiID); updateServer(packet); } private void toggleGoggles() { AbstractPacket packet = new GogglePacket(activeGoggles); updateServer(packet); } private void toggleBelt() { AbstractPacket packet = new BeltPacket(); updateServer(packet); } static void updateServer(AbstractPacket abstractPacket) { TConstruct.packetPipeline.sendToServer(abstractPacket); } }
false
false
null
null
diff --git a/src/org/apache/xerces/impl/xs/XSLoaderImpl.java b/src/org/apache/xerces/impl/xs/XSLoaderImpl.java index 9f48badd..c0c772b0 100644 --- a/src/org/apache/xerces/impl/xs/XSLoaderImpl.java +++ b/src/org/apache/xerces/impl/xs/XSLoaderImpl.java @@ -1,325 +1,325 @@ /* - * Copyright 2004 The Apache Software Foundation. + * Copyright 2004,2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs; import org.apache.xerces.impl.xs.XMLSchemaLoader; import org.apache.xerces.impl.xs.util.XSGrammarPool; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XSGrammar; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.LSInputList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSLoader; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSNamedMap; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSTypeDefinition; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMException; import org.w3c.dom.DOMStringList; import org.w3c.dom.ls.LSInput; /** * <p>An implementation of XSLoader which wraps XMLSchemaLoader.</p> * * @xerces.internal * * @author Michael Glavassevich, IBM * * @version $Id$ */ public final class XSLoaderImpl implements XSLoader, DOMConfiguration { /** * Grammar pool. Need this to prevent us from * getting two grammars from the same namespace. */ private final XSGrammarPool fGrammarPool = new XSGrammarMerger(); /** Schema loader. **/ private final XMLSchemaLoader fSchemaLoader = new XMLSchemaLoader(); /** * No-args constructor. */ public XSLoaderImpl() { fSchemaLoader.setProperty(XMLSchemaLoader.XMLGRAMMAR_POOL, fGrammarPool); } /** * The configuration of a document. It maintains a table of recognized * parameters. Using the configuration, it is possible to change the * behavior of the load methods. The configuration may support the * setting of and the retrieval of the following non-boolean parameters * defined on the <code>DOMConfiguration</code> interface: * <code>error-handler</code> (<code>DOMErrorHandler</code>) and * <code>resource-resolver</code> (<code>LSResourceResolver</code>). * <br> The following list of boolean parameters is defined: * <dl> * <dt> * <code>"validate"</code></dt> * <dd> * <dl> * <dt><code>true</code></dt> * <dd>[required] (default) Validate an XML * Schema during loading. If validation errors are found, the error * handler is notified. </dd> * <dt><code>false</code></dt> * <dd>[optional] Do not * report errors during the loading of an XML Schema document. </dd> * </dl></dd> * </dl> */ public DOMConfiguration getConfig() { return this; } /** * Parses the content of XML Schema documents specified as the list of URI * references. If the URI contains a fragment identifier, the behavior * is not defined by this specification. * @param uri The list of URI locations. * @return An XSModel representing the schema documents. */ public XSModel loadURIList(StringList uriList) { int length = uriList.getLength(); if (length == 0) { return null; } try { fGrammarPool.clear(); for (int i = 0; i < length; ++i) { fSchemaLoader.loadGrammar(new XMLInputSource(null, uriList.item(i), null)); } return fGrammarPool.toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parses the content of XML Schema documents specified as a list of * <code>LSInput</code>s. * @param is The list of <code>LSInput</code>s from which the XML * Schema documents are to be read. * @return An XSModel representing the schema documents. */ public XSModel loadInputList(LSInputList is) { final int length = is.getLength(); if (length == 0) { return null; } try { fGrammarPool.clear(); for (int i = 0; i < length; ++i) { fSchemaLoader.loadGrammar(fSchemaLoader.dom2xmlInputSource(is.item(i))); } return fGrammarPool.toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parse an XML Schema document from a location identified by a URI * reference. If the URI contains a fragment identifier, the behavior is * not defined by this specification. * @param uri The location of the XML Schema document to be read. * @return An XSModel representing this schema. */ public XSModel loadURI(String uri) { try { fGrammarPool.clear(); return ((XSGrammar) fSchemaLoader.loadGrammar(new XMLInputSource(null, uri, null))).toXSModel(); } catch (Exception e){ fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parse an XML Schema document from a resource identified by a * <code>LSInput</code> . - * @param is The <code>DOMInputSource</code> from which the source + * @param is The <code>LSInput</code> from which the source * document is to be read. * @return An XSModel representing this schema. */ public XSModel load(LSInput is) { try { fGrammarPool.clear(); return ((XSGrammar) fSchemaLoader.loadGrammar(fSchemaLoader.dom2xmlInputSource(is))).toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#setParameter(java.lang.String, java.lang.Object) */ public void setParameter(String name, Object value) throws DOMException { fSchemaLoader.setParameter(name, value); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameter(java.lang.String) */ public Object getParameter(String name) throws DOMException { return fSchemaLoader.getParameter(name); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#canSetParameter(java.lang.String, java.lang.Object) */ public boolean canSetParameter(String name, Object value) { return fSchemaLoader.canSetParameter(name, value); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameterNames() */ public DOMStringList getParameterNames() { return fSchemaLoader.getParameterNames(); } /** * Grammar pool which merges grammars from the same namespace into one. This eliminates * duplicate named components. It doesn't ensure that the grammar is consistent, however * this no worse than than the behaviour of XMLSchemaLoader alone when used as an XSLoader. */ private static final class XSGrammarMerger extends XSGrammarPool { public XSGrammarMerger () {} public void putGrammar(Grammar grammar) { SchemaGrammar cachedGrammar = toSchemaGrammar(super.getGrammar(grammar.getGrammarDescription())); if (cachedGrammar != null) { SchemaGrammar newGrammar = toSchemaGrammar(grammar); if (newGrammar != null) { mergeSchemaGrammars(cachedGrammar, newGrammar); } } else { super.putGrammar(grammar); } } private SchemaGrammar toSchemaGrammar (Grammar grammar) { return (grammar instanceof SchemaGrammar) ? (SchemaGrammar) grammar : null; } private void mergeSchemaGrammars(SchemaGrammar cachedGrammar, SchemaGrammar newGrammar) { /** Add new top-level element declarations. **/ XSNamedMap map = newGrammar.getComponents(XSConstants.ELEMENT_DECLARATION); int length = map.getLength(); for (int i = 0; i < length; ++i) { XSElementDecl decl = (XSElementDecl) map.item(i); if (cachedGrammar.getGlobalElementDecl(decl.getName()) == null) { cachedGrammar.addGlobalElementDecl(decl); } } /** Add new top-level attribute declarations. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeDecl decl = (XSAttributeDecl) map.item(i); if (cachedGrammar.getGlobalAttributeDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeDecl(decl); } } /** Add new top-level type definitions. **/ map = newGrammar.getComponents(XSConstants.TYPE_DEFINITION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSTypeDefinition decl = (XSTypeDefinition) map.item(i); if (cachedGrammar.getGlobalTypeDecl(decl.getName()) == null) { cachedGrammar.addGlobalTypeDecl(decl); } } /** Add new top-level attribute group definitions. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeGroupDecl decl = (XSAttributeGroupDecl) map.item(i); if (cachedGrammar.getGlobalAttributeGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeGroupDecl(decl); } } /** Add new top-level model group definitions. **/ map = newGrammar.getComponents(XSConstants.MODEL_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSGroupDecl decl = (XSGroupDecl) map.item(i); if (cachedGrammar.getGlobalGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalGroupDecl(decl); } } /** Add new top-level notation declarations. **/ map = newGrammar.getComponents(XSConstants.NOTATION_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSNotationDecl decl = (XSNotationDecl) map.item(i); if (cachedGrammar.getGlobalNotationDecl(decl.getName()) == null) { cachedGrammar.addGlobalNotationDecl(decl); } } /** * Add all annotations. Since these components are not named it's * possible we'll add duplicate components. There isn't much we can * do. It's no worse than XMLSchemaLoader when used as an XSLoader. */ XSObjectList annotations = newGrammar.getAnnotations(); length = annotations.getLength(); for (int i = 0; i < length; ++i) { cachedGrammar.addAnnotation((XSAnnotationImpl) annotations.item(i)); } } public boolean containsGrammar(XMLGrammarDescription desc) { return false; } public Grammar getGrammar(XMLGrammarDescription desc) { return null; } public Grammar retrieveGrammar(XMLGrammarDescription desc) { return null; } public Grammar [] retrieveInitialGrammarSet (String grammarType) { return new Grammar[0]; } } } diff --git a/src/org/apache/xerces/xs/XSLoader.java b/src/org/apache/xerces/xs/XSLoader.java index e342325f..a35dbab1 100644 --- a/src/org/apache/xerces/xs/XSLoader.java +++ b/src/org/apache/xerces/xs/XSLoader.java @@ -1,89 +1,89 @@ /* - * Copyright 2003,2004 The Apache Software Foundation. + * Copyright 2003,2004,2006 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.xs; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.ls.LSInput; /** * An interface that provides a method to load XML Schema documents. This * interface uses the DOM Level 3 Core and Load and Save interfaces. */ public interface XSLoader { /** * The configuration of a document. It maintains a table of recognized * parameters. Using the configuration, it is possible to change the * behavior of the load methods. The configuration may support the * setting of and the retrieval of the following non-boolean parameters * defined on the <code>DOMConfiguration</code> interface: * <code>error-handler</code> (<code>DOMErrorHandler</code>) and * <code>resource-resolver</code> (<code>LSResourceResolver</code>). * <br> The following list of boolean parameters is defined: * <dl> * <dt> * <code>"validate"</code></dt> * <dd> * <dl> * <dt><code>true</code></dt> * <dd>[required] (default) Validate an XML * Schema during loading. If validation errors are found, the error * handler is notified. </dd> * <dt><code>false</code></dt> * <dd>[optional] Do not * report errors during the loading of an XML Schema document. </dd> * </dl></dd> * </dl> */ public DOMConfiguration getConfig(); /** * Parses the content of XML Schema documents specified as the list of URI * references. If the URI contains a fragment identifier, the behavior * is not defined by this specification. * @param uri The list of URI locations. * @return An XSModel representing the schema documents. */ public XSModel loadURIList(StringList uriList); /** * Parses the content of XML Schema documents specified as a list of * <code>LSInput</code>s. * @param is The list of <code>LSInput</code>s from which the XML * Schema documents are to be read. * @return An XSModel representing the schema documents. */ public XSModel loadInputList(LSInputList is); /** * Parse an XML Schema document from a location identified by a URI * reference. If the URI contains a fragment identifier, the behavior is * not defined by this specification. * @param uri The location of the XML Schema document to be read. * @return An XSModel representing this schema. */ public XSModel loadURI(String uri); /** * Parse an XML Schema document from a resource identified by a * <code>LSInput</code> . - * @param is The <code>DOMInputSource</code> from which the source + * @param is The <code>LSInput</code> from which the source * document is to be read. * @return An XSModel representing this schema. */ public XSModel load(LSInput is); }
false
false
null
null
diff --git a/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java b/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java index 8ede68781..4e209133a 100644 --- a/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java +++ b/cdm/src/test/java/ucar/nc2/dt/grid/TestReadandCountGrib.java @@ -1,89 +1,89 @@ /* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "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 UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.nc2.dt.grid; import junit.framework.*; import ucar.nc2.TestAll; /** Count geogrid objects - sanity check when anything changes. */ public class TestReadandCountGrib extends TestCase { public TestReadandCountGrib( String name) { super(name); } public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); - doOne("grib1/data/","ukm.wmo", 96, 49, 69, 32); + doOne("grib1/data/","ukm.wmo", 96, 49, 72, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); } private void doOne(String dir, String filename, int ngrids, int ncoordSys, int ncoordAxes, int nVertCooordAxes) throws Exception { dir = TestAll.upcShareTestDataDir+ "grid/grib/" + dir; TestReadandCount.doOne(dir, filename, ngrids, ncoordSys, ncoordAxes, nVertCooordAxes); } public static void main( String arg[]) throws Exception { // new TestReadandCount("dummy").doOne("C:/data/conventions/wrf/","wrf.nc", 33, 5, 7, 7); // missing TSLB new TestReadandCountGrib("dummy").testRead(); // missing TSLB //new TestReadandCount("dummy").doOne(TestAll.upcShareTestDataDir+"grid/grib/grib1/data/","ukm.wmo", 96, 49, 69, 32); } }
true
true
public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); doOne("grib1/data/","ukm.wmo", 96, 49, 69, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); }
public void testRead() throws Exception { // our grib reader doOne("grib1/data/","cfs.wmo", 51, 4, 6, 3); doOne("grib1/data/","eta218.grb", 14, 5, 7, 4); doOne("grib1/data/","extended.wmo", 8, 6, 10, 4); doOne("grib1/data/","ensemble.wmo", 24, 16, 18, 10); // doOne("grib1/data/","ecmf.wmo", 56, 44, 116, 58); doOne("grib1/data/","don_ETA.wmo", 28, 11, 13, 8); doOne("grib1/data/","pgbanl.fnl", 76, 15, 17, 14); doOne("grib1/data/","radar_national_rcm.grib", 1, 1, 3, 0); doOne("grib1/data/","radar_national.grib", 1, 1, 3, 0); //doOne("grib1/data/","thin.wmo", 240, 87, 117, 63); doOne("grib1/data/","ukm.wmo", 96, 49, 72, 32); doOne("grib1/data/","AVN.wmo", 22, 9, 11, 7); doOne("grib1/data/","AVN-I.wmo", 20, 8, 10, 7); // doOne("grib1/data/","MRF.wmo", 15, 8, 10, 6); // doOne("grib1/data/","OCEAN.wmo", 4, 4, 12, 0); doOne("grib1/data/","RUC.wmo", 27, 7, 10, 5); doOne("grib1/data/","RUC2.wmo", 44, 10, 13, 5); doOne("grib1/data/","WAVE.wmo", 28, 12, 24, 4); // doOne("grib2/data/","eta2.wmo", 35, 8, 10, 7); doOne("grib2/data/","ndfd.wmo", 1, 1, 3, 0); // doOne("grib2/data/","eta218.wmo", 57, 13, 18, 10); doOne("grib2/data/","PMSL_000", 1, 1, 3, 0); doOne("grib2/data/","CLDGRIB2.2005040905", 5, 1, 3, 0); doOne("grib2/data/","LMPEF_CLM_050518_1200.grb", 1, 1, 3, 0); doOne("grib2/data/","AVOR_000.grb", 1, 2, 4, 1); // doOne("grib2/data/","AVN.5deg.wmo", 117, 13, 15, 12); // */ //TestReadandCount.doOne(TestAll.upcShareTestDataDir+"ncml/nc/narr/", "narr-a_221_20070411_0600_000.grb", 48, 13, 15, 12); }
diff --git a/shadow-platformer/src/net/fourbytes/shadow/Coord.java b/shadow-platformer/src/net/fourbytes/shadow/Coord.java index 381eabd..e491459 100755 --- a/shadow-platformer/src/net/fourbytes/shadow/Coord.java +++ b/shadow-platformer/src/net/fourbytes/shadow/Coord.java @@ -1,29 +1,40 @@ package net.fourbytes.shadow; import java.util.ArrayList; import com.badlogic.gdx.math.Vector2; public class Coord { public static long get(int x, int y) { return (long)x << 32 | y & 0xFFFFFFFFL; } public static long get(float x, float y) { return get((int) x, (int) y); } public static int[] getXY(long l) { return new int[] {getX(l), getY(l)}; } public static int getX(long l) { return (int) (l >> 32); } public static int getY(long l) { return (int) (l); } + /** + * H4CK3D H04X F7W. 7R0L0L0L0L0~~<br> + * Seriously: Don't thrust hacked hoaxes. You will regret it. + */ + public static int get1337(int x) { + if (x > 0) {//TODO Check if >= 0 needed. + x++; + } + return x; + } + } diff --git a/shadow-platformer/src/net/fourbytes/shadow/Cursor.java b/shadow-platformer/src/net/fourbytes/shadow/Cursor.java index c1aa4d7..290f6a7 100755 --- a/shadow-platformer/src/net/fourbytes/shadow/Cursor.java +++ b/shadow-platformer/src/net/fourbytes/shadow/Cursor.java @@ -1,215 +1,217 @@ package net.fourbytes.shadow; import java.util.ArrayList; import java.util.Vector; import net.fourbytes.shadow.Input.Key; import net.fourbytes.shadow.Input.TouchPoint; import net.fourbytes.shadow.Input.TouchPoint.TouchMode; import net.fourbytes.shadow.blocks.BlockType; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.utils.Array; public class Cursor extends Entity { int id = -1; boolean render = false; Texture tex; Image img; Color color; public Cursor(Vector2 position, Layer layer) { this(position, layer, -1); } public Cursor(Vector2 position, Layer layer, int id) { super(position, layer); this.id = id; solid = false; tex = Images.getTexture("white"); color = new Color(1f, 1f, 1f, 0.5f); updateTexture(); } @Override public Image getImage() { return img; } @Override public TextureRegion getTexture() { return new TextureRegion(tex); } int button; public void tick() { TouchPoint tp = Input.touches.get(id); if (tp != null && tp.touchmode == TouchMode.Cursor) { pos.set(calcPos(tp.pos)); oldpos = tp.pos; button = tp.button; switch (tp.button) { case -1: amb(tp, true); break; case 0: lmb(tp, true); break; case 1: rmb(tp, true); break; case 2: mmb(tp, true); break; } render = true; } else { downtick = 0; switch (button) { case -1: amb(tp, false); break; case 0: lmb(tp, false); break; case 1: rmb(tp, false); break; case 2: mmb(tp, false); break; } } if (tp == null && id != -1) { layer.level.cursors.removeValue(this, true); } if (oldpos != null && id == -1) { pos.set(calcPos(oldpos)); } scroll(0); } int downtick = 0; boolean amb = false; int amode = 0; boolean lmb = false; boolean rmb = false; boolean mmb = false; public void amb(TouchPoint point, boolean isDown) { downtick++; if (isDown && !amb) { amode = 0; } if (isDown && amb) { switch (amode) { case 0: break; case 1: lmb(point, true); break; case 2: rmb(point, true); break; } } amb = isDown; } public void lmb(TouchPoint point, boolean isDown) { downtick++; if (isDown && (!lmb || downtick > 20)) { Block b = BlockType.getInstance("BlockPush", pos.x, pos.y, layer.level.player.layer); b.layer.add(b); } lmb = isDown; } public void rmb(TouchPoint point, boolean isDown) { downtick++; if (isDown && (!rmb || downtick > 20)) { - Array<Block> blocks = layer.level.player.layer.get(Coord.get(pos.x, pos.y)); + /*Array<Block> blocks = layer.level.player.layer.get(Coord.get(pos.x, pos.y)); if (blocks != null) { for (Block b : blocks) { b.layer.remove(b); } - } + }*/ + Entity e = new MobTest(new Vector2(pos), layer.level.player.layer); + e.layer.add(e); } rmb = isDown; } public void mmb(TouchPoint point, boolean isDown) { downtick++; if (isDown && (!mmb || downtick > 20)) { Block b = BlockType.getInstance("BlockWater", pos.x, pos.y, layer.level.player.layer); b.layer.add(b); } mmb = isDown; } Vector2 oldpos; Vector2 ppos = new Vector2(); public Vector2 calcPos(Vector2 apos) { if (oldpos == null) { oldpos = new Vector2(); } oldpos.set(apos); Vector2 pos = ppos; pos.set(apos); float tx = 0; float ty = 0; float g = 1f; float cx = Shadow.cam.camrec.x; float cy = Shadow.cam.camrec.y; float mx = (pos.x * (Shadow.vieww/Shadow.dispw)) * Shadow.cam.cam.zoom; float my = (pos.y * (Shadow.viewh/Shadow.disph)) * Shadow.cam.cam.zoom; tx = mx + cx; ty = my + cy; float otx = tx; float oty = ty; tx = (int)(tx/g); ty = (int)(ty/g); tx *= g; ty *= g; if (otx < 0) { tx-=g; } if (oty < 0) { ty-=g; } pos.set(tx, ty); return pos; } /** * Call after updating color */ public void updateTexture() { if (tex == null) { updateImage(); return; } updateImage(); } /** * Call after updating texture, runs automatically after {@link #updateTexture()}! */ public void updateImage() { if (tex == null) img = null; img = new Image(tex); img.setColor(color); } @Override public void preRender() { tmpimg = img; tmpimg.setColor(color); if (!render) { tmpimg.setColor(new Color(1f, 1f, 1f, 0f)); } super.preRender(); } @Override public void render() { if (render) { super.render(); } } public void scroll(int amount) { } } diff --git a/shadow-platformer/src/net/fourbytes/shadow/Layer.java b/shadow-platformer/src/net/fourbytes/shadow/Layer.java index c557fef..894d096 100755 --- a/shadow-platformer/src/net/fourbytes/shadow/Layer.java +++ b/shadow-platformer/src/net/fourbytes/shadow/Layer.java @@ -1,200 +1,200 @@ package net.fourbytes.shadow; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.World; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ArrayMap; import com.badlogic.gdx.utils.IntMap; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.LongMap; import com.badlogic.gdx.utils.ObjectMap; /** * Placeholder for the layers in the levels. Processing happens in {@link Level}. */ public class Layer { public static enum BlockMapSystem { coordinate, //Default, most performance, most garbage row, //performance decreased, less garbage column, //performance decreased, less garbage none //least performance, "no garbage" } public Level level; public Array<Block> blocks = new Array<Block>(true, 4096); public Array<Entity> entities = new Array<Entity>(true, 512); //protected ObjectMap<Coord, Array<Block>> blockmap = new ObjectMap<Coord, Array<Block>>(1024, 0.95f); protected IntMap<Array<Block>> rowmap = new IntMap<Array<Block>>(256); protected LongMap<Array<Block>> blockmap = new LongMap<Array<Block>>(1024); public Color tint = new Color(1f, 1f, 1f, 1f); public static BlockMapSystem bms = BlockMapSystem.coordinate; protected BlockMapSystem lastbms; - public static float round = 5f; + public static float round = 4f; public Layer(Level level) { this.level = level; } public void add(GameObject go) { if (this != level.mainLayer) { level.mainLayer.add(go); } if (go instanceof Block) { blocks.add((Block) go); Array<Block> al = get0(Coord.get((int)(go.pos.x/round), (int)(go.pos.y/round))); if (al == null) { al = put0(Coord.get((int)(go.pos.x/round), (int)(go.pos.y/round))); } al.add((Block) go); } else if (go instanceof Entity) { entities.add((Entity) go); } } public void remove(GameObject go) { if (this != level.mainLayer) { level.mainLayer.remove(go); } if (go instanceof Block) { blocks.removeValue((Block) go, true); Array al = get0(Coord.get((int)(go.pos.x/round), (int)(go.pos.y/round))); if (al != null) { al.removeValue((Block) go, true); if (al.size == 0) { remove0(Coord.get((int)(go.pos.x/round), (int)(go.pos.y/round))); } } } else if (go instanceof Entity) { entities.removeValue((Entity) go, true); } } public void move(Block b, long oldc, long newc) { if (this != level.mainLayer) { level.mainLayer.move(b, oldc, newc); } int oldx = Coord.getX(oldc); int oldy = Coord.getY(oldc); int newx = Coord.getX(newc); int newy = Coord.getY(newc); Array oal = get0(Coord.get((int)(oldx/round), (int)(oldy/round))); Array nal = get0(Coord.get((int)(newx/round), (int)(newy/round))); if (oal == nal) { return; } if (nal == null) { nal = put0(Coord.get((int)(newx/round), (int)(newy/round))); } if (oal != null) { oal.removeValue(b, true); if (oal.size == 0) { remove0(Coord.get((int)(oldx/round), (int)(oldy/round))); } } nal.add(b); } public Array<Block> get(long c) { int cx = Coord.getX(c); int cy = Coord.getY(c); Array<Block> vv = null; vv = get0(Coord.get((int)(cx/round), (int)(cy/round))); /* if (v == null) { v = new Array<Block>(true, 32); blockmap.put(c, v); } */ Array<Block> v = new Array<Block>(4); if (vv != null) { for (Block b : vv) { if (cx == (int)b.pos.x && cy == (int)b.pos.y) { v.add(b); } } } if (vv != null && vv.size == 0) { remove0(Coord.get((int)(cx/round), (int)(cy/round))); } return v; } protected Array<Block> get0(long c){ updateSystem0(); Array<Block> al = null; switch (bms) { case coordinate: al = blockmap.get(c); break; case row: al = rowmap.get(Coord.getY(c)); break; case column: al = rowmap.get(Coord.getX(c)); break; case none: al = blocks; break; } return al; } protected Array<Block> put0(long c){ updateSystem0(); Array<Block> al = null; switch (bms) { case coordinate: al = new Array<Block>(32); blockmap.put(c, al); break; case row: al = new Array<Block>(4); rowmap.put(Coord.getY(c), al); break; case column: al = new Array<Block>(4); rowmap.put(Coord.getX(c), al); break; case none: break; } return al; } protected void remove0(long c){ updateSystem0(); switch (bms) { case coordinate: blockmap.remove(c); break; case row: rowmap.remove(Coord.getY(c)); break; case column: rowmap.remove(Coord.getX(c)); break; case none: break; } } protected void updateSystem0() { if (lastbms != null && lastbms != bms) { //TODO change the system properly instead of throwing error throw new Error("Change of the blockmap system while in-level not supported!"); } } } diff --git a/shadow-platformer/src/net/fourbytes/shadow/blocks/BlockPush.java b/shadow-platformer/src/net/fourbytes/shadow/blocks/BlockPush.java index 5bd7ceb..2065eb0 100755 --- a/shadow-platformer/src/net/fourbytes/shadow/blocks/BlockPush.java +++ b/shadow-platformer/src/net/fourbytes/shadow/blocks/BlockPush.java @@ -1,183 +1,183 @@ package net.fourbytes.shadow.blocks; import java.util.ArrayList; import java.util.Random; import java.util.Vector; import net.fourbytes.shadow.Block; import net.fourbytes.shadow.Coord; import net.fourbytes.shadow.Entity; import net.fourbytes.shadow.Garbage; import net.fourbytes.shadow.Images; import net.fourbytes.shadow.Mob; import net.fourbytes.shadow.Player; import net.fourbytes.shadow.TypeBlock; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.utils.Array; public class BlockPush extends BlockType { Vector2 lastpos; int gframe = 0; int oframe = 0; int pframe = 0; public BlockPush() { } public static Random rand = new Random(); @Override public void tick() { block.interactive = true; gframe--; if (gframe <= 0) { boolean free = true; /*for (Block b : block.layer.blocks) { if (!b.solid) continue; float rad = 0.1f; Rectangle er = new Rectangle(block.pos.x+rad, block.pos.y+1+rad, block.rec.width-rad*2, block.rec.height-rad*2); Rectangle or = new Rectangle(b.pos.x, b.pos.y, b.rec.width, b.rec.height); if (or.overlaps(er)) { free = false; } if (!free) break; }*/ Array<Block> al = block.layer.get(Coord.get(block.pos.x, block.pos.y+1)); if (al != null) { for (Block b : al) { if (b instanceof TypeBlock && ((TypeBlock)b).type instanceof BlockFluid) { free = false; break; } if (!b.solid) continue; free = false; break; } } if (free) { if (lastpos == null) { lastpos = new Vector2(); } lastpos.set(block.pos); int lastx = (int)block.pos.x; int lasty = (int)block.pos.y; block.pos.add(0, 1); int newx = (int)block.pos.x; int newy = (int)block.pos.y; block.layer.move(block, Coord.get(lastx, lasty), Coord.get(newx, newy)); gframe = 18; oframe = 15; } } if (oframe > 0) { oframe--; } if (lastpos != null) { if (oframe > 0) { block.renderoffs.set(lastpos.x-block.pos.x, lastpos.y-block.pos.y, 0f, 0f); float fac = 383f/512f; for (int i = 0; i < 15-oframe; i++) { block.renderoffs.x *= fac; block.renderoffs.y *= fac; } } else { block.renderoffs.set(0f, 0f, 0f, 0f); } } if (pframe > 0) { pframe--; } } @Override public TextureRegion getTexture() { return new TextureRegion(Images.getTexture("block_push")); } @Override public void collide(Entity e) { if (e instanceof Player) { Player p = (Player) e; - if ((int)(p.pos.y) == (int)(block.pos.y+p.rec.height) && pframe <= 0) { + if (Coord.get1337((int)(p.pos.y)) == (int)(block.pos.y+p.rec.height) && pframe <= 0) { //if (pframe <= 0) { int dir = p.facingLeft?-1:1; push(dir, 0); } } } public boolean push(int dir, int count) { boolean free = true; /*for (Block b : block.layer.blocks) { if (!b.solid) continue; float rad = 0.1f; Rectangle er = new Rectangle(block.pos.x+dir+rad, block.pos.y+rad, block.rec.width-rad*2, block.rec.height-rad*2); Rectangle or = new Rectangle(b.pos.x, b.pos.y, b.rec.width, b.rec.height); if (or.overlaps(er)) { if (b instanceof TypeBlock && ((TypeBlock)b).type instanceof BlockPush && count < 6) { ((BlockPush)((TypeBlock)b).type).push(dir, count+1); free = false; pframe = 4; } else { free = false; } } if (!free) break; }*/ Array<Block> al = block.layer.get(Coord.get(block.pos.x+dir, block.pos.y)); if (al != null) { for (Block b : al) { if (b instanceof TypeBlock && ((TypeBlock)b).type instanceof BlockFluid) { free = false; break; } if (!b.solid) continue; if (b instanceof TypeBlock && ((TypeBlock)b).type instanceof BlockPush && count < 6) { ((BlockPush)((TypeBlock)b).type).push(dir, count+1); free = false; pframe = 4; break; } free = false; break; //if (!free) break; } } if (free) { if (lastpos == null) { lastpos = new Vector2(); } lastpos.set(block.pos); int lastx = (int)block.pos.x; int lasty = (int)block.pos.y; block.pos.add(dir, 0); int newx = (int)block.pos.x; int newy = (int)block.pos.y; block.layer.move(block, Coord.get(lastx, lasty), Coord.get(newx, newy)); block.renderoffs.set(lastpos.x-block.pos.x, lastpos.y-block.pos.y, 0f, 0f); oframe = 15; pframe = 2; } return free; } }
false
false
null
null
diff --git a/src/edu/sc/seis/sod/subsetter/network/TemporaryNetwork.java b/src/edu/sc/seis/sod/subsetter/network/TemporaryNetwork.java index ec2978ce5..473c74382 100755 --- a/src/edu/sc/seis/sod/subsetter/network/TemporaryNetwork.java +++ b/src/edu/sc/seis/sod/subsetter/network/TemporaryNetwork.java @@ -1,20 +1,20 @@ package edu.sc.seis.sod.subsetter.network; import java.util.regex.Pattern; import edu.iris.Fissures.IfNetwork.NetworkAttr; /** * @author groves Created on May 4, 2005 */ public class TemporaryNetwork implements NetworkSubsetter { public boolean accept(NetworkAttr attr) { return isTemporary(attr.get_code()); } public static boolean isTemporary(String code) { return p.matcher(code).matches(); } - private static Pattern p = Pattern.compile("X|Y|Z"); + private static Pattern p = Pattern.compile("[XYZ].?"); } diff --git a/test/unit/edu/sc/seis/sod/subsetter/network/TemporaryNetworkTest.java b/test/unit/edu/sc/seis/sod/subsetter/network/TemporaryNetworkTest.java new file mode 100644 index 000000000..b07842043 --- /dev/null +++ b/test/unit/edu/sc/seis/sod/subsetter/network/TemporaryNetworkTest.java @@ -0,0 +1,21 @@ +package edu.sc.seis.sod.subsetter.network; + +import edu.iris.Fissures.IfNetwork.NetworkAttr; +import edu.sc.seis.fissuresUtil.mockFissures.IfNetwork.MockNetworkAttr; +import junit.framework.TestCase; + + +public class TemporaryNetworkTest extends TestCase { + + public void testTempNet() { + TemporaryNetwork subsetter = new TemporaryNetwork(); + NetworkAttr x = MockNetworkAttr.createNetworkAttr(); + x.get_id().network_code = "X"; + assertTrue(subsetter.accept(x)); + NetworkAttr xa = MockNetworkAttr.createNetworkAttr(); + xa.get_id().network_code = "XA"; + assertTrue(subsetter.accept(xa)); + NetworkAttr other = MockNetworkAttr.createOtherNetworkAttr(); + assertFalse(subsetter.accept(other)); + } +}
false
false
null
null
diff --git a/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.java b/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.java index 8c82a7f81..41d5a3003 100644 --- a/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.java +++ b/src/main/org/codehaus/groovy/classgen/VerifierCodeVisitor.java @@ -1,135 +1,135 @@ /* $Id$ Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved. Redistribution and use of this software and associated documentation ("Software"), with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain copyright statements and notices. Redistributions must also contain a copy of this document. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name "groovy" must not be used to endorse or promote products derived from this Software without prior written permission of The Codehaus. For written permission, please contact info@codehaus.org. 4. Products derived from this Software may not be called "groovy" nor may "groovy" appear in their names without prior written permission of The Codehaus. "groovy" is a registered trademark of The Codehaus. 5. Due credit should be given to The Codehaus - http://groovy.codehaus.org/ THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED 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 CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.codehaus.groovy.classgen; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.stmt.ForStatement; import org.codehaus.groovy.ast.expr.BinaryExpression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.FieldExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.syntax.RuntimeParserException; import org.codehaus.groovy.syntax.RuntimeParserException; import org.objectweb.asm.Constants; /** * Verifies the method code * * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> * @version $Revision$ */ public class VerifierCodeVisitor extends CodeVisitorSupport implements Constants { private Verifier verifier; VerifierCodeVisitor(Verifier verifier) { this.verifier = verifier; } public void visitMethodCallExpression(MethodCallExpression call) { assertValidIdentifier(call.getMethod(), "method name", call); super.visitMethodCallExpression(call); } public void visitForLoop(ForStatement expression) { assertValidIdentifier(expression.getVariable(), "for loop variable name", expression); super.visitForLoop(expression); } public void visitPropertyExpression(PropertyExpression expression) { - assertValidIdentifier(expression.getProperty(), "property name", expression); + // assertValidIdentifier(expression.getProperty(), "property name", expression); // This has been commented out to fix the issue Groovy-843 super.visitPropertyExpression(expression); } public void visitFieldExpression(FieldExpression expression) { assertValidIdentifier(expression.getFieldName(), "field name", expression); super.visitFieldExpression(expression); } public void visitVariableExpression(VariableExpression expression) { assertValidIdentifier(expression.getVariable(), "variable name", expression); super.visitVariableExpression(expression); } public void visitBinaryExpression(BinaryExpression expression) { /* if (verifier.getClassNode().isScript() && expression.getOperation().getType() == Token.EQUAL) { // lets turn variable assignments into property assignments Expression left = expression.getLeftExpression(); if (left instanceof VariableExpression) { VariableExpression varExp = (VariableExpression) left; //System.out.println("Converting variable expression: " + varExp.getVariable()); PropertyExpression propExp = new PropertyExpression(VariableExpression.THIS_EXPRESSION, varExp.getVariable()); expression.setLeftExpression(propExp); } } */ super.visitBinaryExpression(expression); } public static void assertValidIdentifier(String name, String message, ASTNode node) { int size = name.length(); if (size <= 0) { throw new RuntimeParserException("Invalid " + message + ". Identifier must not be empty", node); } char firstCh = name.charAt(0); if (!Character.isJavaIdentifierStart(firstCh) || firstCh == '$') { throw new RuntimeParserException("Invalid " + message + ". Must start with a letter but was: " + name, node); } for (int i = 1; i < size; i++) { char ch = name.charAt(i); if (!Character.isJavaIdentifierPart(ch)) { throw new RuntimeParserException("Invalid " + message + ". Invalid character at position: " + (i + 1) + " of value: " + ch + " in name: " + name, node); } } } } diff --git a/src/test/UberTestCase2.java b/src/test/UberTestCase2.java index ffe216795..19ad8d69a 100644 --- a/src/test/UberTestCase2.java +++ b/src/test/UberTestCase2.java @@ -1,131 +1,132 @@ /** * to prevent a JVM startup-shutdown time per test, it should be more efficient to * collect the tests together into a suite. * * @author <a href="mailto:jeremy.rayner@bigfoot.com">Jeremy Rayner</a> * @version $Revision$ */ import junit.framework.*; public class UberTestCase2 extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(); suite.addTestSuite(groovy.bugs.ArrayMethodCallBug.class); suite.addTestSuite(groovy.bugs.AsBoolBug.class); suite.addTestSuite(groovy.bugs.ClassGeneratorFixesTest.class); suite.addTestSuite(groovy.bugs.ClassInScriptBug.class); suite.addTestSuite(groovy.bugs.ClosuresInScriptBug.class); suite.addTestSuite(groovy.bugs.ClosureWithStaticVariablesBug.class); suite.addTestSuite(groovy.bugs.ConstructorParameterBug.class); suite.addTestSuite(groovy.bugs.DoubleSizeParametersBug.class); suite.addTestSuite(groovy.bugs.Groovy278_Bug.class); suite.addTestSuite(groovy.bugs.Groovy303_Bug.class); suite.addTestSuite(groovy.bugs.Groovy308_Bug.class); suite.addTestSuite(groovy.bugs.Groovy558_616_Bug.class); suite.addTestSuite(groovy.bugs.Groovy593_Bug.class); suite.addTestSuite(groovy.bugs.Groovy666_Bug.class); suite.addTestSuite(groovy.bugs.Groovy675_Bug.class); suite.addTestSuite(groovy.bugs.Groovy770_Bug.class); suite.addTestSuite(groovy.bugs.Groovy779_Bug.class); suite.addTestSuite(groovy.bugs.Groovy831_Bug.class); suite.addTestSuite(groovy.bugs.IanMaceysBug.class); suite.addTestSuite(groovy.bugs.InterfaceImplBug.class); suite.addTestSuite(groovy.bugs.MarkupInScriptBug.class); suite.addTestSuite(groovy.bugs.MethodPointerBug.class); suite.addTestSuite(groovy.bugs.PrimitivePropertyBug.class); suite.addTestSuite(groovy.bugs.ScriptBug.class); suite.addTestSuite(groovy.bugs.SeansBug.class); suite.addTestSuite(groovy.bugs.StaticMethodCallBug.class); suite.addTestSuite(groovy.bugs.SubscriptOnPrimitiveTypeArrayBug.class); suite.addTestSuite(groovy.bugs.SubscriptOnStringArrayBug.class); suite.addTestSuite(groovy.lang.GroovyShellTest.class); suite.addTestSuite(groovy.lang.GStringTest.class); suite.addTestSuite(groovy.lang.IntRangeTest.class); - suite.addTestSuite(groovy.lang.MetaClassTest.class); + suite.addTestSuite(groovy.lang.PropertyNameBug.class); + suite.addTestSuite(groovy.lang.RangeTest.class); suite.addTestSuite(groovy.lang.RangeTest.class); suite.addTestSuite(groovy.lang.ScriptIntegerDivideTest.class); suite.addTestSuite(groovy.lang.ScriptPrintTest.class); suite.addTestSuite(groovy.lang.ScriptTest.class); suite.addTestSuite(groovy.lang.SequenceTest.class); suite.addTestSuite(groovy.lang.TupleTest.class); suite.addTestSuite(groovy.mock.example.SandwichMakerTest.class); suite.addTestSuite(groovy.mock.MockTest.class); suite.addTestSuite(groovy.model.TableModelTest.class); //todo - error in some test environments suite.addTestSuite(groovy.security.RunAllGroovyScriptsSuite.class); //todo - error in some test environments suite.addTestSuite(groovy.security.RunOneGroovyScript.class); //todo - error in some test environments suite.addTestSuite(groovy.security.SecurityTest.class); //todo - error in some test environments suite.addTestSuite(groovy.security.SecurityTestSupport.class); //todo - error in some test environments suite.addTestSuite(groovy.security.SignedJarTest.class); suite.addTestSuite(groovy.sql.PersonTest.class); suite.addTestSuite(groovy.sql.SqlCompleteTest.class); suite.addTestSuite(groovy.sql.SqlCompleteWithoutDataSourceTest.class); suite.addTestSuite(groovy.sql.SqlTest.class); suite.addTestSuite(groovy.sql.SqlWithBuilderTest.class); suite.addTestSuite(groovy.sql.SqlWithTypedResultsTest.class); suite.addTestSuite(groovy.sql.SqlRowsTest.class); suite.addTestSuite(groovy.text.TemplateTest.class); suite.addTestSuite(groovy.tree.NodePrinterTest.class); suite.addTestSuite(groovy.txn.TransactionTest.class); suite.addTestSuite(groovy.util.EmptyScriptTest.class); suite.addTestSuite(groovy.util.MBeanTest.class); suite.addTestSuite(groovy.util.NodeTest.class); suite.addTestSuite(groovy.util.XmlParserTest.class); suite.addTestSuite(groovy.util.BuilderSupportTest.class); // no idea - tugs crazy streaming stuff suite.addTestSuite(groovy.xml.DOMTest.class); suite.addTestSuite(groovy.xml.MarkupTest.class); suite.addTestSuite(groovy.xml.MarkupWithWriterTest.class); suite.addTestSuite(groovy.xml.NamespaceDOMTest.class); suite.addTestSuite(groovy.xml.SAXTest.class); suite.addTestSuite(groovy.xml.SmallNamespaceDOMTest.class); suite.addTestSuite(groovy.xml.VerboseDOMTest.class); suite.addTestSuite(groovy.xml.XmlTest.class); return suite; } // no tests inside (should we have an AbstractGroovyTestCase???) // suite.addTestSuite(groovy.bugs.TestSupport.class); // suite.addTestSuite(groovy.sql.TestHelper.class); // suite.addTestSuite(groovy.swing.Demo.class); // The following classes appear in target/test-classes but do not extend junit.framework.TestCase // // suite.addTestSuite(cheese.Cheddar.class); // suite.addTestSuite(cheese.Provolone.class); // suite.addTestSuite(groovy.bugs.Cheese.class); // suite.addTestSuite(groovy.bugs.MyRange.class); // suite.addTestSuite(groovy.bugs.Scholastic.class); // suite.addTestSuite(groovy.bugs.SimpleModel.class); // suite.addTestSuite(groovy.DummyInterface.class); // suite.addTestSuite(groovy.DummyMethods.class); // suite.addTestSuite(groovy.gravy.Build.class); // suite.addTestSuite(groovy.j2ee.J2eeConsole.class); // suite.addTestSuite(groovy.lang.DerivedScript.class); // suite.addTestSuite(groovy.lang.DummyGString.class); // suite.addTestSuite(groovy.lang.MockWriter.class); // suite.addTestSuite(groovy.mock.example.CheeseSlicer.class); // suite.addTestSuite(groovy.mock.example.SandwichMaker.class); // suite.addTestSuite(groovy.model.MvcDemo.class); // suite.addTestSuite(groovy.OuterUser.class); // suite.addTestSuite(groovy.script.AtomTestScript.class); // suite.addTestSuite(groovy.script.Entry.class); // suite.addTestSuite(groovy.script.Feed.class); // suite.addTestSuite(groovy.script.PackageScript.class); // suite.addTestSuite(groovy.script.Person.class); // suite.addTestSuite(groovy.sql.Person.class); // suite.addTestSuite(groovy.swing.MyTableModel.class); // suite.addTestSuite(groovy.swing.SwingDemo.class); // suite.addTestSuite(groovy.swing.TableDemo.class); // suite.addTestSuite(groovy.swing.TableLayoutDemo.class); // suite.addTestSuite(groovy.txn.TransactionBean.class); // suite.addTestSuite(groovy.txn.TransactionBuilder.class); // suite.addTestSuite(groovy.util.Dummy.class); // suite.addTestSuite(groovy.util.DummyMBean.class); // suite.addTestSuite(groovy.util.SpoofTask.class); // suite.addTestSuite(groovy.util.SpoofTaskContainer.class); // suite.addTestSuite(groovy.xml.TestXmlSupport.class); }
false
false
null
null
diff --git a/src/com/dgis/input/evdev/EventDevice.java b/src/com/dgis/input/evdev/EventDevice.java index 0d6b784..e0408cc 100644 --- a/src/com/dgis/input/evdev/EventDevice.java +++ b/src/com/dgis/input/evdev/EventDevice.java @@ -1,505 +1,503 @@ package com.dgis.input.evdev; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import sun.reflect.generics.reflectiveObjects.NotImplementedException; - /* * Copyright (C) 2009 Giacomo Ferrari * This file is part of evdev-java. * evdev-java 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. * * evdev-java 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 evdev-java. If not, see <http://www.gnu.org/licenses/>. */ /** * Represents a connection to a Linux Evdev device. * For additional info, see input/input.txt and input/input-programming.txt in the Linux kernel Documentation. * IMPORTANT: If you want higher-level access for your joystick/pad/whatever, check com.dgis.input.evdev.devices * for useful drivers to make your life easier! * Copyright (C) 2009 Giacomo Ferrari * @author Giacomo Ferrari */ interface IEventDevice { /** * @return The version of Evdev reported by the kernel. */ public int getEvdevVersion(); /** * @return the bus ID of the attached device. */ public short getBusID(); /** * @return the vendor ID of the attached device. */ public short getVendorID(); /** * @return the product ID of the attached device. */ public short getProductID(); /** * @return the version ID of the attached device. */ public short getVersionID(); /** * @return the name of the attached device. */ public String getDeviceName(); /** * @return A mapping from device supported event types to list of supported event codes. */ public Map<Integer, List<Integer>> getSupportedEvents(); /** * Obtains the configurable parameters of an absolute axis (value, min, max, fuzz, flatspot) from the device. * @param axis The axis number (an event code under event type 3 (abs)). * @return The parameters, or null if there was an error. Modifications to this object will be reflected in the device. */ public InputAxisParameters getAxisParameters(int axis); /** * Adds an event listener to this device. * When an event is received from Evdev, all InputListeners registered * will be notified by a call to event(). * If the listener is already on the listener list, * this method has no effect. * @param list The listener to add. Must not be null. */ public void addListener(InputListener list); /** * Removes an event listener to this device. * If the listener is not on the listener list, * this method has no effect. * @param list The listener to remove. Must not be null. */ public void removeListener(InputListener list); /** * Releases all resources held by this EventDevice. No more events will be generated. * It is impossible to restart an EventDevice once this method is called. */ public void close(); } /** * Driver for a Linux Evdev character device. * * Copyright (C) 2009 Giacomo Ferrari * @author Giacomo Ferrari */ public class EventDevice implements IEventDevice{ /** * Notify these guys about input events. */ private List<InputListener> listeners = new ArrayList<InputListener>(); /** * Device filename we're using. */ String device; /** * Attached to device we're using. */ private FileChannel deviceInput; private ByteBuffer inputBuffer = ByteBuffer.allocate(InputEvent.STRUCT_SIZE_BYTES); /** * When this is true, the reader thread should terminate ASAP. */ private volatile boolean terminate = false; /** * This thread repeatedly calls readEvent(). */ private Thread readerThread; private short[] idResponse = new short[4]; private int evdevVersionResponse; private String deviceNameResponse; /** * Maps supported event types (keys) to lists of supported event codes. */ private HashMap<Integer, List<Integer>> supportedEvents = new HashMap<Integer, List<Integer>>(); /** * Ensures only one instance of InputAxisParameters is created for each axis (more would be wasteful). */ private HashMap<Integer, InputAxisParameters> axisParams = new HashMap<Integer, InputAxisParameters>(); /** * Create an EventDevice by connecting to the provided device filename. * If the device file is accessible, open it and begin listening for events. * @param device The path to the device file. Usually one of /dev/input/event* * @throws IOException If the device is not found, or is otherwise inaccessible. */ public EventDevice(String device) throws IOException { System.loadLibrary("evdev-java"); this.device = device; inputBuffer.order(ByteOrder.LITTLE_ENDIAN); initDevice(); } /** * Get various ID info. Then, open the file, get the channel, and start the reader thread. * @throws IOException */ private void initDevice() throws IOException { if(!ioctlGetID(device, idResponse)) { System.err.println("WARN: couldn't get device ID: "+device); Arrays.fill(idResponse, (short)0); } evdevVersionResponse = ioctlGetEvdevVersion(device); byte[] devName = new byte[255]; if(ioctlGetDeviceName(device, devName)) { deviceNameResponse = new String(devName); } else { System.err.println("WARN: couldn't get device name: "+device); deviceNameResponse = "Unknown Device"; } readSupportedEvents(); FileInputStream fis = new FileInputStream(device); deviceInput = fis.getChannel(); readerThread = new Thread() { @Override public void run() { while(!terminate) { InputEvent ev = readEvent(); distributeEvent(ev); } } }; readerThread.setDaemon(true); /* We don't want this thread to prevent the JVM from terminating */ readerThread.start(); } /** * Get supported events from device, and place into supportedEvents. * Adapted from evtest.c. */ private void readSupportedEvents() { //System.out.println("Detecting device capabilities..."); long[][] bit = new long[InputEvent.EV_MAX][NBITS(InputEvent.KEY_MAX)]; ioctlEVIOCGBIT(device, bit[0], 0, bit[0].length); /* Loop over event types */ for (int i = 0; i < InputEvent.EV_MAX; i++) { if (testBit(bit[0], i)) { /* Is this event supported? */ //System.out.printf(" Event type %d\n", i); if (i==0) continue; ArrayList<Integer> supportedTypes = new ArrayList<Integer>(); ioctlEVIOCGBIT(device, bit[i], i, InputEvent.KEY_MAX); /* Loop over event codes for type */ for (int j = 0; j < InputEvent.KEY_MAX; j++) if (testBit(bit[i], j)) { /* Is this event code supported? */ //System.out.printf(" Event code %d\n", j); supportedTypes.add(j); } supportedEvents.put(i, supportedTypes); } } } private boolean testBit(long[] array, int bit) { return ((array[LONG(bit)] >>> OFF(bit)) & 1)!=0; } private int LONG(int x) { return x/(64); } private int OFF(int x) { return x%(64); } private int NBITS(int x) { return ((((x)-1)/(8*8))+1); } /** * Distribute an event to all registered listeners. * @param ev The event to distribute. */ private void distributeEvent(InputEvent ev) { synchronized (listeners) { for(InputListener il : listeners) { il.event(ev); } } } /** * Obtain an InputEvent from the input channel. Delegate to InputEvent for parsing. * @return */ private InputEvent readEvent() { try { /* Read exactly the amount of bytes specified by InputEvent.STRUCT_SIZE_BYTES (intrinsic size of inputBuffer)*/ inputBuffer.clear(); while(inputBuffer.hasRemaining()) deviceInput.read(inputBuffer); /* We want to read now */ inputBuffer.flip(); /* Delegate parsing to InputEvent.parse() */ return InputEvent.parse(inputBuffer.asShortBuffer(), device); } catch (IOException e ) { return null; } } /** * @see com.dgis.input.evdev.IEventDevice#close() */ @Override public void close() { terminate=true; try { readerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } try { deviceInput.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @see com.dgis.input.evdev.IEventDevice#getBusID() */ @Override public short getBusID() { return idResponse[InputEvent.ID_BUS]; } /** * @see com.dgis.input.evdev.IEventDevice#getDeviceName() */ @Override public String getDeviceName() { return deviceNameResponse; } /** * @see com.dgis.input.evdev.IEventDevice#getProductID() */ @Override public short getProductID() { // TODO Auto-generated method stub return idResponse[InputEvent.ID_PRODUCT]; } /** * @see com.dgis.input.evdev.IEventDevice#getSupportedEvents() */ @Override public Map<Integer, List<Integer>> getSupportedEvents() { return supportedEvents; } /** * @see com.dgis.input.evdev.IEventDevice#getVendorID() */ @Override public short getVendorID() { return idResponse[InputEvent.ID_VENDOR]; } /** * @see com.dgis.input.evdev.IEventDevice#getEvdevVersion() */ @Override public int getEvdevVersion() { return evdevVersionResponse; } /** * @see com.dgis.input.evdev.IEventDevice#getVersionID() */ @Override public short getVersionID() { return idResponse[InputEvent.ID_VERSION]; } @Override public InputAxisParameters getAxisParameters(int axis) { InputAxisParameters params; if((params = axisParams.get(axis)) == null) { params = new InputAxisParametersImpl(this, axis); axisParams.put(axis, params); } return params; } /** * @see com.dgis.input.evdev.IEventDevice#addListener(com.dgis.input.evdev.InputListener) */ @Override public void addListener(InputListener list) { synchronized (listeners) { listeners.add(list); } } /** * @see com.dgis.input.evdev.IEventDevice#removeListener(com.dgis.input.evdev.InputListener) */ @Override public void removeListener(InputListener list) { synchronized (listeners) { listeners.remove(list); } } public String getDevicePath() { return device; } ////BEGIN JNI METHODS//// native boolean ioctlGetID(String device, short[] resp); native int ioctlGetEvdevVersion(String device); native boolean ioctlGetDeviceName(String device, byte[] resp); native boolean ioctlEVIOCGBIT(String device, long[] resp, int start, int stop); native boolean ioctlEVIOCGABS(String device, int[] resp, int axis); } class InputAxisParametersImpl implements InputAxisParameters { private EventDevice device; private int axis; private int value, min, max, fuzz, flat; public InputAxisParametersImpl(EventDevice device, int axis) { this.device = device; this.axis = axis; readStatus(); } /** * Repopulate values stored in this class with values read from the device. */ private void readStatus() { int[] resp = new int[5]; device.ioctlEVIOCGABS(device.device, resp, axis); value = resp[0]; min = resp[1]; max = resp[2]; fuzz = resp[3]; flat = resp[4]; } /** * Repopulate values stored in the device with values read from this class. */ private void writeStatus() { - throw new NotImplementedException(); + throw new Error("Not implemented yet!"); } public int getValue() { synchronized (this) { readStatus(); return value; } } public void setValue(int value) { synchronized (this) { this.value = value; writeStatus(); } } public int getMin() { synchronized (this) { readStatus(); return min; } } public void setMin(int min) { synchronized (this) { this.min = min; writeStatus(); } } public int getMax() { synchronized (this) { readStatus(); return max; } } public void setMax(int max) { synchronized (this) { this.max = max; writeStatus(); } } public int getFuzz() { synchronized (this) { readStatus(); return fuzz; } } public void setFuzz(int fuzz) { synchronized (this) { this.fuzz = fuzz; writeStatus(); } } public int getFlat() { synchronized (this) { readStatus(); return flat; } } public void setFlat(int flat) { synchronized (this) { this.flat = flat; writeStatus(); } } @Override public String toString() { return "Value: " + getValue() + " Min: " + getMin() + " Max: " + getMax() + " Fuzz: " + getFuzz() + " Flat: " + getFlat(); } } \ No newline at end of file
false
false
null
null
diff --git a/apps/xgap/org/molgenis/xgap/test/XqtlSeleniumTest.java b/apps/xgap/org/molgenis/xgap/test/XqtlSeleniumTest.java index fb90776cb..1dc3de5fa 100644 --- a/apps/xgap/org/molgenis/xgap/test/XqtlSeleniumTest.java +++ b/apps/xgap/org/molgenis/xgap/test/XqtlSeleniumTest.java @@ -1,944 +1,944 @@ package org.molgenis.xgap.test; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.molgenis.MolgenisOptions.MapperImplementation; import org.molgenis.framework.db.Database; import org.molgenis.util.DetectOS; import org.openqa.selenium.server.RemoteControlConfiguration; import org.openqa.selenium.server.SeleniumServer; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import app.DatabaseFactory; import app.servlet.UsedMolgenisOptions; import boot.Helper; import boot.RunStandalone; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.HttpCommandProcessor; import com.thoughtworks.selenium.Selenium; import filehandling.storage.StorageHandler; /** * * The complete xQTL Selenium web test. * Has a section for init/helpers and section for the real tests. * */ public class XqtlSeleniumTest { boolean gbicdev_dontrunthis = false; /** ******************************************************************* ************************* Init and helpers ********************** ******************************************************************* */ Selenium selenium; String pageLoadTimeout = "30000"; boolean tomcat = false; private static UsedMolgenisOptions usedOptions; public static void deleteDatabase() throws Exception { if(new UsedMolgenisOptions().mapper_implementation == MapperImplementation.JPA) //any JPA database { /** * NOTE: requires a database 'xqtlworkbench' to exist! */ Map<String, Object> configOptions = new HashMap<String, Object>(); configOptions.put("hibernate.hbm2ddl.auto", "create-drop"); DatabaseFactory.create(configOptions); } else //assuming HSQL standalone database, the xQTL default { File dbDir = new File("hsqldb"); if (dbDir.exists()) { FileUtils.deleteDirectory(dbDir); } else { //throw new Exception("HSQL database directory does not exist"); } // if (dbDir.list().length != 1) // { // throw new Exception("HSQL database directory does not contain 1 file (.svn) after deletion! it contains: " // + dbDir.list().toString()); // } } } /** Waits for an element to be present */ public void waitForElementToBePresent(String locator) { selenium.waitForCondition("var value = selenium.isElementPresent('" + locator.replace("'", "\\'") + "'); value == true", pageLoadTimeout); } /** Waits for an element to be visible */ public void waitForElementToBeVisible(String locator) { waitForElementToBePresent(locator); selenium.waitForCondition("var value = selenium.isVisible('" + locator.replace("'", "\\'") + "'); value == true", pageLoadTimeout); } public static void deleteStorage(String appName) throws Exception { // get storage folder and delete it completely // throws exceptions if anything goes wrong Database db = DatabaseFactory.create(); int appNameLength = appName.length(); String storagePath = new StorageHandler(db).getFileStorage(true, db).getAbsolutePath(); File storageRoot = new File(storagePath.substring(0, storagePath.length() - appNameLength)); FileUtils.deleteDirectory(storageRoot); } /** * Configure Selenium server and delete the database */ @BeforeClass public void start() throws Exception { usedOptions = new UsedMolgenisOptions(); int webserverPort = 8080; if (!tomcat) webserverPort = Helper.getAvailablePort(11040, 10); String seleniumUrl = "http://localhost:" + webserverPort + "/"; String seleniumHost = "localhost"; String seleniumBrowser = "firefox"; int seleniumPort = Helper.getAvailablePort(11050, 10); RemoteControlConfiguration rcc = new RemoteControlConfiguration(); rcc.setSingleWindow(true); rcc.setPort(seleniumPort); try { SeleniumServer server = new SeleniumServer(false, rcc); server.boot(); } catch (Exception e) { throw new IllegalStateException("Cannot start selenium server: ", e); } HttpCommandProcessor proc = new HttpCommandProcessor(seleniumHost, seleniumPort, seleniumBrowser, seleniumUrl); selenium = new DefaultSelenium(proc); selenium.start(); deleteDatabase(); if (!tomcat) new RunStandalone(webserverPort); } /** * Stop Selenium server and remove files */ @AfterClass public void stop() throws Exception { selenium.stop(); deleteStorage(usedOptions.appName); } /** * Start the app and verify home page */ @Test public void startup() throws InterruptedException { selenium.open("/" + usedOptions.appName + "/molgenis.do"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.getTitle().toLowerCase().contains("xQTL workbench".toLowerCase())); Assert.assertTrue(selenium.isTextPresent("Welcome")); Assert.assertEquals(selenium.getText("link=R api"), "R api"); } /** * Login as admin and redirect */ @Test(dependsOnMethods = { "startup" }) public void login() throws InterruptedException { clickAndWait("link=Login"); waitForElementToBePresent("link=Register"); Assert.assertEquals(selenium.getText("link=Register"), "Register"); selenium.type("id=username", "admin"); selenium.type("id=password", "admin"); clickAndWait("id=Login"); // note: page now redirects to the Home screen ('auth_redirect' in // properties) Assert.assertTrue(selenium .isTextPresent("You are logged in as admin, and the database does not contain any investigations or other users.")); } /** * Press 'Load' example data */ @Test(dependsOnMethods = { "login" }) public void loadExampleData() throws InterruptedException { selenium.type("id=inputBox", storagePath()); clickAndWait("id=loadExamples"); Assert.assertTrue(selenium.isTextPresent("File path '" + storagePath() + "' was validated and the dataloader succeeded")); } /** * Function that sets the application to a 'default' state after setting up. * All downstream test functions require this to be done. */ @Test(dependsOnMethods = { "loadExampleData" }) public void returnHome() throws InterruptedException { clickAndWait("id=ClusterDemo_tab_button"); } /** * Helper function. Click a target and wait. */ public void clickAndWait(String target) { selenium.click(target); selenium.waitForPageToLoad(pageLoadTimeout); } /** * Helper function. Get DOM property using JavaScript. */ public String propertyScript(String element, String property) { return "var x = window.document.getElementById('" + element + "'); window.document.defaultView.getComputedStyle(x,null).getPropertyValue('" + property + "');"; } /** * Helper function. Get the storage path to use in test. */ public String storagePath() { String storagePath = new File(".").getAbsolutePath() + File.separator + "tmp_selenium_test_data"; if (DetectOS.getOS().startsWith("windows")) { return storagePath.replace("\\", "/"); } else { return storagePath; } } /** ******************************************************************* ************************** Assorted tests *********************** ******************************************************************* */ @Test(dependsOnMethods = { "returnHome" }) public void exploreExampleData() throws InterruptedException { // browse to Overview and check links clickAndWait("id=Investigations_tab_button"); clickAndWait("id=Overview_tab_button"); Assert.assertTrue(selenium.isTextPresent("Metabolite (24)")); // click link to a matrix and check values clickAndWait("link=metaboliteexpression"); Assert.assertTrue(selenium.isTextPresent("942") && selenium.isTextPresent("4857") && selenium.isTextPresent("20716")); //restore state clickAndWait("id=remove_filter_0"); } @Test(dependsOnMethods = { "returnHome" }) public void compactView() throws InterruptedException { // browse to Data tab clickAndWait("id=Investigations_tab_button"); clickAndWait("id=Datas_tab_button"); // assert if the hide investigation and data table rows are hidden Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "none"); Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "none"); // click both unhide buttons selenium.click("id=Investigations_collapse_button_id"); selenium.click("id=Datas_collapse_button_id"); // assert if the hide investigation and data table rows are exposed Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "table-row"); Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "table-row"); // click both unhide buttons selenium.click("id=Investigations_collapse_button_id"); selenium.click("id=Datas_collapse_button_id"); // assert if the hide investigation and data table rows are hidden again Assert.assertEquals(selenium.getEval(propertyScript("Investigations_collapse_tr_id", "display")), "none"); Assert.assertEquals(selenium.getEval(propertyScript("Datas_collapse_tr_id", "display")), "none"); } @Test(dependsOnMethods = { "returnHome" }) public void individualForms() throws Exception { // browse to individuals clickAndWait("id=Investigations_tab_button"); clickAndWait("id=BasicAnnotations_tab_button"); clickAndWait("id=Individuals_tab_button"); clickAndWait("id=first_Individuals"); // check some values here Assert.assertEquals(selenium.getText("//form[@id='Individuals_form']/div[3]/div/div/table/tbody/tr[7]/td[4]"), "X7"); Assert.assertTrue(selenium.isTextPresent("xgap_rqtl_straintype_riself")); // switch to edit view and check some values there too clickAndWait("id=Individuals_editview"); Assert.assertEquals(selenium.getValue("id=Individual_name"), "X1"); - Assert.assertEquals(selenium.getText("css=#Individual_ontologyReference_chzn > a.chzn-single > span"), + Assert.assertEquals(selenium.getText("css=#Individual_ontologyReference_chzn_c_0 > span"), "xgap_rqtl_straintype_riself"); Assert.assertEquals( selenium.getText("//img[@onclick=\"if ($('#Individuals_form').valid() && validateForm(document.forms.Individuals_form,new Array())) {setInput('Individuals_form','_self','','Individuals','update','iframe'); document.forms.Individuals_form.submit();}\"]"), ""); // click add new, wait for popup, and select it selenium.click("id=Individuals_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); // fill in the form and click add selenium.type("id=Individual_name", "testindv"); clickAndWait("id=Add"); // select main window and check if add was successful selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1")); // page back and forth and check values clickAndWait("id=prev_Individuals"); Assert.assertEquals(selenium.getValue("id=Individual_name"), "X193"); clickAndWait("id=last_Individuals"); Assert.assertEquals(selenium.getValue("id=Individual_name"), "testindv"); // delete the test individual and check if it happened selenium.click("id=delete_Individuals"); Assert.assertEquals(selenium.getConfirmation(), "You are about to delete a record. If you click [yes] you won't be able to undo this operation."); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1")); } @Test(dependsOnMethods = { "returnHome" }) public void enumInput() throws Exception { // browse to 'Data' view and expand compact view clickAndWait("id=Investigations_tab_button"); clickAndWait("id=Datas_tab_button"); selenium.click("id=Datas_collapse_button_id"); // assert content of enum fields Assert.assertEquals( selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.8.1"), "Individual\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeProbeSetSampleSpotSNPPromoterChipPeak"); Assert.assertEquals( selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.9.1"), "Metabolite\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeProbeSetSampleSpotSNPPromoterChipPeak"); // change Individual to Gene and save selenium.click("css=#Data_FeatureType_chzn > a.chzn-single > span"); selenium.click("id=Data_FeatureType_chzn_o_3"); selenium.click("id=save_Datas"); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1")); // expand compact view again and check value has changed selenium.click("id=Datas_collapse_button_id"); Assert.assertEquals( selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.8.1"), "Gene\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeProbeSetSampleSpotSNPPromoterChipPeak"); // change back to Individual and save selenium.click("css=#Data_FeatureType_chzn > a.chzn-single > span"); selenium.click("id=Data_FeatureType_chzn_o_4"); clickAndWait("id=save_Datas"); Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1")); // expand compact view again and check value is back to normal again selenium.click("id=Datas_collapse_button_id"); Assert.assertEquals( selenium.getTable("css=#Datas_form > div.screenbody > div.screenpadding > table > tbody > tr > td > table.8.1"), "Individual\n\nChromosomeDerivedTraitEnvironmentalFactorGeneIndividualMarkerMassPeakMeasurementMetabolitePanelProbeProbeSetSampleSpotSNPPromoterChipPeak"); } @Test(dependsOnMethods = { "returnHome" }) public void qtlImporter() throws Exception { // not much to test here, cannot upload actual files // could only be tested on an API level, or manually // go to Import data and check the screen contents of the QTL importer clickAndWait("id=ImportDataMenu_tab_button"); clickAndWait("id=QTLWizard_tab_button"); Assert.assertTrue(selenium.isTextPresent("Again, your individuals must be in the first line.")); Assert.assertEquals(selenium.getText("name=invSelect"), "ClusterDemo"); Assert.assertEquals(selenium.getText("name=cross"),"xgap_rqtl_straintype_f2xgap_rqtl_straintype_bcxgap_rqtl_straintype_riselfxgap_rqtl_straintype_risibxgap_rqtl_straintype_4wayxgap_rqtl_straintype_dhxgap_rqtl_straintype_specialxgap_rqtl_straintype_naturalxgap_rqtl_straintype_parentalxgap_rqtl_straintype_f1xgap_rqtl_straintype_rccxgap_rqtl_straintype_cssxgap_rqtl_straintype_unknownxgap_rqtl_straintype_other"); Assert.assertEquals(selenium.getText("name=trait"),"MeasurementDerivedTraitEnvironmentalFactorGeneMarkerMassPeakMetaboliteProbe"); // try pressing a button and see if the error pops up clickAndWait("id=upload_genotypes"); Assert.assertTrue(selenium.isTextPresent("No file selected")); } @Test(dependsOnMethods = { "returnHome" }) public void runMapping() throws Exception { // we're not going to test actual execution, just page around // go to Run QTL mapping clickAndWait("id=Cluster_tab_button"); Assert.assertTrue(selenium.isTextPresent("This is the main menu for starting a new analysis")); // page from starting page to Step 2 clickAndWait("id=start_new_analysis"); Assert.assertEquals(selenium.getValue("name=outputDataName"), "MyOutput"); clickAndWait("id=toStep2"); Assert.assertTrue(selenium.isTextPresent("You have selected: Rqtl_analysis")); Assert.assertEquals(selenium.getText("name=phenotypes"), "Fu_LCMS_data"); // go back to starting page clickAndWait("id=toStep1"); clickAndWait("id=toStep0"); // go to job manager clickAndWait("id=view_running_analysis"); Assert.assertTrue(selenium.isTextPresent("No running analysis to display.")); // go back to starting page clickAndWait("id=back_to_start"); Assert.assertTrue(selenium.isTextPresent("No settings saved.")); } @Test(dependsOnMethods = { "returnHome" }) public void configureAnalysis() throws Exception { // browse to Configure Analysis and check values clickAndWait("id=AnalysisSettings_tab_button"); Assert.assertEquals(selenium.getTable("css=table.listtable.1.3"), "Rqtl_analysis"); Assert.assertEquals(selenium.getTable("css=table.listtable.1.4"), "This is a basic QTL analysis performed in the R environment for statistical computing, powered by th..."); if(gbicdev_dontrunthis){ // browse to R scripts and add a script clickAndWait("id=RScripts_tab_button"); selenium.click("id=RScripts_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); selenium.type("id=RScript_name", "test"); selenium.type("id=RScript_Extension", "r"); selenium.click("css=span"); //from: http://blog.browsermob.com/2011/03/selenium-tips-wait-with-waitforcondition/ //"Now for the killer part, for sites that use jQuery, if all you need is to confirm there aren't any active asynchronous requests, then the following does the trick:" selenium.waitForCondition("selenium.browserbot.getUserWindow().$.active == 0", "10000"); selenium.click("css=span"); clickAndWait("id=Add"); // add content and save selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1")); Assert.assertTrue(selenium.isTextPresent("No file found. Please upload it here.")); selenium.type("name=inputTextArea", "content"); clickAndWait("id=uploadTextArea"); Assert.assertFalse(selenium.isTextPresent("No file found. Please upload it here.")); // delete script and content selenium.click("id=delete_RScripts"); Assert.assertEquals(selenium.getConfirmation(), "You are about to delete a record. If you click [yes] you won't be able to undo this operation."); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1")); } // browse to Tag data and click the hide/show buttons clickAndWait("id=MatrixWizard_tab_button"); Assert.assertTrue(selenium .isTextPresent("This screen provides an overview of all data matrices stored in your database.")); Assert.assertTrue(selenium.isTextPresent("ClusterDemo / genotypes")); Assert.assertTrue(selenium.isTextPresent("Rqtl_data -> genotypes")); clickAndWait("id=hide_verified"); Assert.assertTrue(selenium.isTextPresent("Nothing to display")); clickAndWait("id=show_verified"); Assert.assertTrue(selenium.isTextPresent("Binary")); } @Test(dependsOnMethods = { "returnHome" }) public void searchDbPlugin() throws Exception { // browse to Search clickAndWait("id=SearchMenu_tab_button"); clickAndWait("id=SimpleDbSearch_tab_button"); selenium.type("name=searchThis", "ee"); clickAndWait("id=simple_search"); Assert.assertTrue(selenium.isTextPresent("Found 2 result(s)")); Assert.assertTrue(selenium.isTextPresent("Type: BinaryDataMatrix")); selenium.type("name=searchThis", "e"); clickAndWait("id=simple_search"); Assert.assertTrue(selenium.isTextPresent("Found 336 result(s)")); Assert.assertTrue(selenium.isTextPresent("xgap_rqtl_straintype_special")); Assert.assertTrue(selenium.isTextPresent("Arabidopsis_thaliana")); Assert.assertTrue(selenium.isTextPresent("metaboliteexpression")); Assert.assertTrue(selenium.isTextPresent("X193")); Assert.assertTrue(selenium.isTextPresent("Ler_x_Cvi")); Assert.assertTrue(selenium.isTextPresent("chrIV")); Assert.assertTrue(selenium.isTextPresent("Isohamnetindeoxyhesoxyldihexoside")); Assert.assertTrue(selenium.isTextPresent("EG113L115C")); selenium.type("name=searchThis", ""); clickAndWait("id=simple_search"); Assert.assertTrue(selenium.isTextPresent("null")); } @Test(dependsOnMethods = { "returnHome" }) public void molgenisFileMenu() throws Exception { // browse to chromosomes and click 'Update selected' in File clickAndWait("id=Investigations_tab_button"); clickAndWait("id=BasicAnnotations_tab_button"); clickAndWait("Chromosomes_tab_button"); selenium.click("id=Chromosomes_menu_Edit"); selenium.click("id=Chromosomes_edit_update_selected_submenuitem"); // select the popup and verify the message selenium.waitForPopUp("molgenis_edit_update_selected", "5000"); selenium.selectWindow("name=molgenis_edit_update_selected"); Assert.assertTrue(selenium.isTextPresent("No records were selected for updating.")); // cancel and select main window selenium.click("id=Cancel"); selenium.selectWindow("title=xQTL workbench"); // TODO: select records, update 2+, verify values changed, change them // back, verify values changed back // TODO: Add in batch/upload CSV(as best as possible w/o uploading) // TODO: Upload CSV file (as best as possible w/o uploading) } @Test(dependsOnMethods = { "returnHome" }) public void userRoleMenuVisibility() throws Exception { if(gbicdev_dontrunthis) { //find out if admin can see the correct tabs Assert.assertTrue(selenium.isTextPresent("Home*Browse data*Upload data*Run QTL mapping*Configure analysis*Search / report*Utilities*Admin panel")); clickAndWait("id=Admin_tab_button"); Assert.assertTrue(selenium.isTextPresent("Users and permissions*Database status*File storage*Install R packages*Admin utilities")); clickAndWait("id=OtherAdmin_tab_button"); Assert.assertTrue(selenium.isTextPresent("Job table*ROnline")); String whatBiologistCanSee = "Browse data*Upload data*Run QTL mapping*Search / report*Utilities"; //logout and see if the correct tabs are visible clickAndWait("link=Logout"); Assert.assertTrue(selenium.isTextPresent("Home")); Assert.assertFalse(selenium.isTextPresent(whatBiologistCanSee)); //login as biologist and see if the correct tabs are visible clickAndWait("link=Login"); waitForElementToBePresent("link=Register"); selenium.type("id=username", "bio-user"); selenium.type("id=password", "bio"); clickAndWait("id=Login"); waitForElementToBePresent("link=Logout"); Assert.assertTrue(selenium.isTextPresent("Home*" + whatBiologistCanSee)); Assert.assertFalse(selenium.isTextPresent("Configure analysis")); Assert.assertFalse(selenium.isTextPresent("Admin panel")); clickAndWait("id=Utilities_tab_button"); clickAndWait("id=Tools_tab_button"); Assert.assertTrue(selenium.isTextPresent("Format names*Rename duplicates")); Assert.assertFalse(selenium.isTextPresent("KEGG converter")); Assert.assertFalse(selenium.isTextPresent("ROnline")); //login as bioinformatician and see if the correct tabs are visible //clickAndWait("id=UserLogin_tab_button"); clickAndWait("link=Logout"); waitForElementToBePresent("link=Login"); clickAndWait("link=Login"); waitForElementToBePresent("link=Register"); selenium.type("id=username", "bioinfo-user"); selenium.type("id=password", "bioinfo"); clickAndWait("id=Login"); waitForElementToBePresent("link=Logout"); Assert.assertTrue(selenium.isTextPresent("Home*" + whatBiologistCanSee)); Assert.assertTrue(selenium.isTextPresent("Configure analysis")); Assert.assertFalse(selenium.isTextPresent("Admin panel")); clickAndWait("id=Utilities_tab_button"); clickAndWait("id=Tools_tab_button"); Assert.assertTrue(selenium.isTextPresent("Format names*Rename duplicates*KEGG converter")); //log back in as admin clickAndWait("link=Logout"); waitForElementToBePresent("link=Login"); clickAndWait("link=Login"); waitForElementToBePresent("link=Register"); selenium.type("id=username", "admin"); selenium.type("id=password", "admin"); clickAndWait("id=Login"); } } @Test(dependsOnMethods = { "returnHome" }) public void namePolicy() throws Exception { //find out of the strict policy is in effect for entities // browse to individuals clickAndWait("id=Investigations_tab_button"); clickAndWait("id=BasicAnnotations_tab_button"); clickAndWait("Individuals_tab_button"); // click add new, wait for popup, and select it selenium.click("id=Individuals_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); // fill in the form and click add selenium.type("id=Individual_name", "#"); clickAndWait("id=Add"); // select main window and check if add failed selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Illegal character (#) in name '#'. Use only a-z, A-Z, 0-9, and underscore.")); // click add new, wait for popup, and select it selenium.click("id=Individuals_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); // fill in the form and click add selenium.type("id=Individual_name", "1"); clickAndWait("id=Add"); // select main window and check if add failed selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Name '1' is not allowed to start with a numeral (1).")); //find out of the strict policy is in effect for data matrix (files) clickAndWait("id=Datas_tab_button"); Assert.assertTrue(selenium.isTextPresent("metaboliteexpression")); // click add new, wait for popup, and select it selenium.click("id=Datas_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); // fill in the form and click add selenium.type("id=Data_name", "#"); clickAndWait("id=Add"); // select main window and check if add failed selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD FAILED: Illegal character (#) in name '#'. Use only a-z, A-Z, 0-9, and underscore.")); // click add new, wait for popup, and select it selenium.click("id=Datas_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); // fill in the form and click add // notice the name is allowed, but not OK for files! selenium.type("id=Data_name", "metaboliteExpression"); clickAndWait("id=Add"); // select main window and check if add succeeded selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1")); //add some content and try to save - this must fail selenium.type("id=matrixInputTextArea", "qw er\nty 1 2"); clickAndWait("id=matrixUploadTextArea"); Assert.assertTrue(selenium.isTextPresent("There is already a storage file named 'metaboliteexpression' which is used when escaping the name 'metaboliteExpression'. Please rename your Data matrix or contact your admin.")); // delete the test data and check if it happened selenium.click("id=delete_Datas"); Assert.assertEquals(selenium.getConfirmation(), "You are about to delete a record. If you click [yes] you won't be able to undo this operation."); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1")); } @Test(dependsOnMethods = { "returnHome" }) public void guiNestingXrefDefault() throws Exception { // find out if nested forms by XREF display this relation by default // when adding new entities // browse to individuals clickAndWait("id=Investigations_tab_button"); clickAndWait("id=BasicAnnotations_tab_button"); clickAndWait("Individuals_tab_button"); // click add new, wait for popup, and select it selenium.click("id=Individuals_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); //check if the proper xreffed investigation is selected Assert.assertEquals(selenium.getText("css=span"), "ClusterDemo"); //cancel and return selenium.click("id=cancel"); selenium.selectWindow("title=xQTL workbench"); //change and save selenium.type("id=Investigation_name", "TestIfThisWorks"); clickAndWait("id=save_Investigations"); Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1")); // click add new, wait for popup, and select it selenium.click("id=Individuals_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); //check if the proper xreffed investigation is selected Assert.assertEquals(selenium.getText("css=span"), "TestIfThisWorks"); //cancel and return selenium.click("id=cancel"); selenium.selectWindow("title=xQTL workbench"); //revert and save selenium.type("id=Investigation_name", "ClusterDemo"); clickAndWait("id=save_Investigations"); Assert.assertTrue(selenium.isTextPresent("UPDATE SUCCESS: affected 1")); } @Test(dependsOnMethods = { "returnHome" }) public void startAnalysis() throws Exception { // start a default analysis and check if jobs have // been created, regardless of further outcome // start QTL mapping clickAndWait("id=Cluster_tab_button"); clickAndWait("id=start_new_analysis"); clickAndWait("id=toStep2"); clickAndWait("id=startAnalysis"); Assert.assertTrue(selenium.isTextPresent("Refresh page every")); Assert.assertTrue(selenium.isTextPresent("Running analysis")); Assert.assertTrue(selenium.isTextPresent("[view all local logs]")); //check created job/subjobs clickAndWait("id=Admin_tab_button"); clickAndWait("id=OtherAdmin_tab_button"); clickAndWait("id=Jobs_tab_button"); Assert.assertTrue(selenium.isTextPresent("Rqtl_analysis")); Assert.assertEquals(selenium.getText("css=#Job_ComputeResource_chzn > a.chzn-single > span"), "local"); Assert.assertTrue(selenium.isTextPresent("MyOutput*Subjobs*1 - 6 of 6")); } @Test(dependsOnMethods = { "returnHome" }) public void databaseStatusPlugin() throws Exception { clickAndWait("id=Admin_tab_button"); clickAndWait("id=DatabaseSettings_tab_button"); Assert.assertTrue(selenium.getHtmlSource().contains("Load example data (may take a minute)")); Assert.assertTrue(selenium.isTextPresent("org.molgenis.xgap.decoratoroverriders")); clickAndWait("id=loadExampleData"); Assert.assertTrue(selenium.isTextPresent("BEWARE: Existing users found, skipping adding example users!")); Assert.assertTrue(selenium.isTextPresent("Investigation(s) present in the database, will not continue to load datamodel / reset db.")); Assert.assertTrue(selenium.isTextPresent("DataLoader ended")); } @Test(dependsOnMethods = { "returnHome" }) public void fileStoragePlugin() throws Exception { clickAndWait("id=Admin_tab_button"); clickAndWait("id=FileStorage_tab_button"); Assert.assertTrue(selenium.isTextPresent("File storage property status:")); Assert.assertTrue(selenium.isTextPresent("Properties are set")); clickAndWait("id=filestorage_setpath"); Assert.assertTrue(selenium.isTextPresent("Could not set file storage: Properties already present. Please delete first.")); } @Test(dependsOnMethods = { "returnHome" }) public void findQtlPlugin() throws Exception { clickAndWait("id=SearchMenu_tab_button"); clickAndWait("id=QtlFinderPublic2_tab_button"); Assert.assertTrue(selenium.isTextPresent("Search")); clickAndWait("id=search"); Assert.assertTrue(selenium.isTextPresent("Please enter a search term")); } @Test(dependsOnMethods = { "returnHome" }) public void tagDataPlugin() throws Exception { clickAndWait("id=AnalysisSettings_tab_button"); clickAndWait("id=MatrixWizard_tab_button"); Assert.assertTrue(selenium.isTextPresent("Tag data")); clickAndWait("id=tagdata_0"); //click to add the tag clickAndWait("id=tagdata_0"); //click to get error Assert.assertTrue(selenium.isTextPresent("Violation of unique constraint")); Assert.assertTrue(selenium.isTextPresent("duplicate value(s) for column(s) NAME,DATANAME")); } @Test(dependsOnMethods = { "returnHome" }) public void rqtlUploadPlugin() throws Exception { clickAndWait("id=ImportDataMenu_tab_button"); clickAndWait("id=QTLWizard_tab_button"); Assert.assertTrue(selenium.isTextPresent("Your individuals must be in the first line")); clickAndWait("id=upload_genotypes"); Assert.assertTrue(selenium.isTextPresent("No file selected")); } @Test(dependsOnMethods = { "returnHome" }) public void excelUploadPlugin() throws Exception { clickAndWait("id=ImportDataMenu_tab_button"); clickAndWait("id=ExcelWizard_tab_button"); Assert.assertTrue(selenium.isTextPresent("Upload Excel file with your data")); clickAndWait("id=upload_excel"); Assert.assertTrue(selenium.isTextPresent("No file selected")); } @Test(dependsOnMethods = { "returnHome" }) public void fileUploadPlugin() throws Exception { clickAndWait("id=ImportDataMenu_tab_button"); clickAndWait("id=Files_tab_button"); Assert.assertTrue(selenium.isTextPresent("Navigate files")); //add new file record selenium.click("id=Files_edit_new"); selenium.waitForPopUp("molgenis_edit_new", "30000"); selenium.selectWindow("name=molgenis_edit_new"); selenium.type("id=InvestigationFile_name", "MyInvestigationFile"); selenium.type("id=InvestigationFile_Extension", "txt"); selenium.click("css=span"); //from: http://blog.browsermob.com/2011/03/selenium-tips-wait-with-waitforcondition/ //"Now for the killer part, for sites that use jQuery, if all you need is to confirm there aren't any active asynchronous requests, then the following does the trick:" //selenium.waitForCondition("selenium.browserbot.getUserWindow().$.active == 0", "10000"); Thread.sleep(500); selenium.click("css=span"); //select 'ClusterDemo' this way clickAndWait("id=Add"); // add content and save selenium.selectWindow("title=xQTL workbench"); Assert.assertTrue(selenium.isTextPresent("ADD SUCCESS: affected 1")); Assert.assertTrue(selenium.isTextPresent("No file found. Please upload it here.")); //no file: expect error clickAndWait("id=upload_file"); Assert.assertTrue(selenium.isTextPresent("No file selected")); //cleanup selenium.click("id=delete_Files"); Assert.assertEquals(selenium.getConfirmation(), "You are about to delete a record. If you click [yes] you won't be able to undo this operation."); selenium.waitForPageToLoad(pageLoadTimeout); Assert.assertTrue(selenium.isTextPresent("REMOVE SUCCESS: affected 1")); } @Test(dependsOnMethods = { "returnHome" }) public void pageMatrix() throws Exception { // page around in the matrix and see if the correct // values are displayed in the viewer } @Test(dependsOnMethods = { "returnHome" }) public void dataXrefOptions() throws Exception { //check if the XREF options for Dataset / DataName / DataValue are correct //behaviour: currently not well defined: but DataValue shows XREF options outside //of the DataName scope.. weird } @Test(dependsOnMethods = { "returnHome" }) public void addMatrix() throws Exception { // add a new matrix record // add data by typing in the text area and store // - as binary // - as database // - as csv // backend deletes inbetween } }
true
false
null
null
diff --git a/xsl-saxon/src/com/nwalsh/saxon/Text.java b/xsl-saxon/src/com/nwalsh/saxon/Text.java index c39345bff..69de167f9 100644 --- a/xsl-saxon/src/com/nwalsh/saxon/Text.java +++ b/xsl-saxon/src/com/nwalsh/saxon/Text.java @@ -1,199 +1,199 @@ // Text - Saxon extension element for inserting text package com.nwalsh.saxon; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.MalformedURLException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.URIResolver; import javax.xml.transform.Source; import com.icl.saxon.Context; import com.icl.saxon.style.StyleElement; import com.icl.saxon.output.Outputter; import com.icl.saxon.expr.Expression; /** * <p>Saxon extension element for inserting text * * <p>$Id$</p> * * <p>Copyright (C) 2000 Norman Walsh.</p> * * <p>This class provides a * <a href="http://saxon.sourceforge.net/">Saxon</a> * extension element for inserting text into a result tree.</p> * * <p><b>Change Log:</b></p> * <dl> * <dt>1.0</dt> * <dd><p>Initial release.</p></dd> * </dl> * * @author Norman Walsh * <a href="mailto:ndw@nwalsh.com">ndw@nwalsh.com</a> * * @version $Id$ * */ public class Text extends StyleElement { /** * <p>Constructor for Text</p> * * <p>Does nothing.</p> */ public Text() { } /** * <p>Is this element an instruction?</p> * * <p>Yes, it is.</p> * * @return true */ public boolean isInstruction() { return true; } /** * <p>Can this element contain a template-body?</p> * * <p>Yes, it can, but only so that it can contain xsl:fallback.</p> * * @return true */ public boolean mayContainTemplateBody() { return true; } /** * <p>Validate the arguments</p> * * <p>The element must have an href attribute.</p> */ public void prepareAttributes() throws TransformerConfigurationException { // Get mandatory href attribute String fnAtt = getAttribute("href"); if (fnAtt == null) { reportAbsence("href"); } } /** Validate that the element occurs in a reasonable place. */ public void validate() throws TransformerConfigurationException { checkWithinTemplate(); } /** * <p>Insert the text of the file into the result tree</p> * * <p>Processing this element inserts the contents of the URL named * by the href attribute into the result tree as plain text.</p> * * <p>Optional encoding attribute can specify encoding of resource. * If not specified default system encoding is used.</p> * */ public void process( Context context ) throws TransformerException { Outputter out = context.getOutputter(); String hrefAtt = getAttribute("href"); Expression hrefExpr = makeAttributeValueTemplate(hrefAtt); String href = hrefExpr.evaluateAsString(context); String encodingAtt = getAttribute("encoding"); Expression encodingExpr = makeAttributeValueTemplate(encodingAtt); String encoding = encodingExpr.evaluateAsString(context); String baseURI = context.getContextNodeInfo().getBaseURI(); URIResolver resolver = context.getController().getURIResolver(); if (resolver != null) { Source source = resolver.resolve(href, baseURI); href = source.getSystemId(); } URL baseURL = null; URL fileURL = null; try { baseURL = new URL(baseURI); } catch (MalformedURLException e0) { // what the!? baseURL = null; } try { try { fileURL = new URL(baseURL, href); } catch (MalformedURLException e1) { try { fileURL = new URL(baseURL, "file:" + href); } catch (MalformedURLException e2) { System.out.println("Cannot open " + href); return; } } InputStreamReader isr = null; if (encoding.equals("") == true) isr = new InputStreamReader(fileURL.openStream()); else isr = new InputStreamReader(fileURL.openStream(), encoding); BufferedReader is = new BufferedReader(isr); final int BUFFER_SIZE = 4096; char chars[] = new char[BUFFER_SIZE]; char nchars[] = new char[BUFFER_SIZE]; int len = 0; int i = 0; int carry = -1; while ((len = is.read(chars)) > 0) { // various new lines are normalized to LF to prevent blank lines // between lines int nlen = 0; for (i=0; i<len; i++) { // is current char CR? if (chars[i] == '\r') { if (i < (len - 1)) { // skip it if next char is LF if (chars[i+1] == '\n') continue; // single CR -> LF to normalize MAC line endings nchars[nlen] = '\n'; nlen++; continue; } else { // if CR is last char of buffer we must look ahead carry = is.read(); nchars[nlen] = '\n'; nlen++; if (carry == '\n') { carry = -1; } break; } } nchars[nlen] = chars[i]; nlen++; } - out.writeContent(nchars, 0, nlen); + out.writeContent(nchars, 0, nlen-1); // handle look aheaded character if (carry != -1) out.writeContent(String.valueOf((char)carry)); carry = -1; } is.close(); } catch (Exception e) { System.out.println("Cannot read " + href); } } } diff --git a/xsl-xalan/src/com/nwalsh/xalan/Text.java b/xsl-xalan/src/com/nwalsh/xalan/Text.java index 36f3b227a..3e6b4bf0f 100644 --- a/xsl-xalan/src/com/nwalsh/xalan/Text.java +++ b/xsl-xalan/src/com/nwalsh/xalan/Text.java @@ -1,197 +1,197 @@ // Text - Xalan extension element for inserting text package com.nwalsh.xalan; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.URIResolver; import org.apache.xalan.extensions.XSLProcessorContext; import org.apache.xalan.templates.ElemExtensionCall; import org.apache.xalan.transformer.TransformerImpl; /** * <p>Xalan extension element for inserting text * * <p>$Id$</p> * * <p>Copyright (C) 2001 Norman Walsh.</p> * * <p>This class provides a * <a href="http://xml.apache.org/xalan-j/">Xalan</a> * extension element for inserting text into a result tree.</p> * * <p><b>Change Log:</b></p> * <dl> * <dt>1.0</dt> * <dd><p>Initial release.</p></dd> * </dl> * * @author Norman Walsh * <a href="mailto:ndw@nwalsh.com">ndw@nwalsh.com</a> * * @version $Id$ * */ public class Text { /** * <p>Constructor for Text</p> * * <p>Does nothing.</p> */ public Text() { } public String insertfile(XSLProcessorContext context, ElemExtensionCall elem) throws MalformedURLException, FileNotFoundException, IOException, TransformerException { String href = getFilename(context, elem); String encoding = getEncoding(context, elem); String baseURI = context.getTransformer().getBaseURLOfSource(); URIResolver resolver = context.getTransformer().getURIResolver(); if (resolver != null) { Source source = resolver.resolve(href, baseURI); href = source.getSystemId(); } URL baseURL = null; URL fileURL = null; try { baseURL = new URL(baseURI); } catch (MalformedURLException e1) { try { baseURL = new URL("file:" + baseURI); } catch (MalformedURLException e2) { System.out.println("Cannot find base URI for " + baseURI); baseURL = null; } } String text = ""; try { try { fileURL = new URL(baseURL, href); } catch (MalformedURLException e1) { try { fileURL = new URL(baseURL, "file:" + href); } catch (MalformedURLException e2) { System.out.println("Cannot open " + href); return ""; } } InputStreamReader isr = null; if (encoding.equals("") == true) isr = new InputStreamReader(fileURL.openStream()); else isr = new InputStreamReader(fileURL.openStream(), encoding); BufferedReader is = new BufferedReader(isr); final int BUFFER_SIZE = 4096; char chars[] = new char[BUFFER_SIZE]; char nchars[] = new char[BUFFER_SIZE]; int len = 0; int i = 0; int carry = -1; while ((len = is.read(chars)) > 0) { // various new lines are normalized to LF to prevent blank lines // between lines int nlen = 0; for (i=0; i<len; i++) { // is current char CR? if (chars[i] == '\r') { if (i < (len - 1)) { // skip it if next char is LF if (chars[i+1] == '\n') continue; // single CR -> LF to normalize MAC line endings nchars[nlen] = '\n'; nlen++; continue; } else { // if CR is last char of buffer we must look ahead carry = is.read(); nchars[nlen] = '\n'; nlen++; if (carry == '\n') { carry = -1; } break; } } nchars[nlen] = chars[i]; nlen++; } - text += String.valueOf(nchars, 0, nlen); + text += String.valueOf(nchars, 0, nlen-1); // handle look aheaded character if (carry != -1) text += String.valueOf((char)carry); carry = -1; } is.close(); } catch (Exception e) { System.out.println("Cannot read " + href); } return text; } private String getFilename(XSLProcessorContext context, ElemExtensionCall elem) throws java.net.MalformedURLException, java.io.FileNotFoundException, java.io.IOException, javax.xml.transform.TransformerException { String fileName; fileName = ((ElemExtensionCall)elem).getAttribute ("href", context.getContextNode(), context.getTransformer()); if ("".equals(fileName)) { context.getTransformer().getMsgMgr().error(elem, "No 'href' on text, or not a filename"); } return fileName; } private String getEncoding(XSLProcessorContext context, ElemExtensionCall elem) throws java.net.MalformedURLException, java.io.FileNotFoundException, java.io.IOException, javax.xml.transform.TransformerException { String encoding; encoding = ((ElemExtensionCall)elem).getAttribute ("encoding", context.getContextNode(), context.getTransformer()); if (encoding == null) { return ""; } else { return encoding; } } }
false
false
null
null
diff --git a/src/org/irmacard/androidmanagement/SettingsActivity.java b/src/org/irmacard/androidmanagement/SettingsActivity.java index e3221aa..6d65de6 100644 --- a/src/org/irmacard/androidmanagement/SettingsActivity.java +++ b/src/org/irmacard/androidmanagement/SettingsActivity.java @@ -1,88 +1,88 @@ /** * CredentialDetailActivity.java * * 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/>. * * Copyright (C) Wouter Lueks, Radboud University Nijmegen, Februari 2013. */ package org.irmacard.androidmanagement; import android.os.Bundle; import android.support.v4.app.FragmentActivity; /** * An activity representing a single Credential detail screen. This activity is * only used on handset devices. On tablet-size devices, item details are * presented side-by-side with a list of items in a * {@link CredentialListActivity}. * <p> * This activity is mostly just a 'shell' activity containing nothing more than * a {@link CredentialDetailFragment}. */ public class SettingsActivity extends FragmentActivity implements SettingsFragmentActivityI { public static final int RESULT_CHANGE_CARD_PIN = RESULT_FIRST_USER; public static final int RESULT_CHANGE_CRED_PIN = RESULT_FIRST_USER + 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.activity_log); + setContentView(R.layout.activity_settings); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } } @Override public void onChangeCardPIN() { setResult(RESULT_CHANGE_CARD_PIN); finish(); } @Override public void onChangeCredPIN() { setResult(RESULT_CHANGE_CRED_PIN); finish(); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); // Show the Up button in the action bar. if(getActionBar() != null) { // TODO: workaround for now, figure out what is really going on here. getActionBar().setDisplayHomeAsUpEnabled(true); } // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { // Create the detail fragment and add it to the activity // using a fragment transaction. SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putSerializable( SettingsFragment.ARG_CARD_VERSION, getIntent().getSerializableExtra( SettingsFragment.ARG_CARD_VERSION)); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.settings_container, fragment).commit(); } }
diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooter.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooter.java index 213363d6..4799d5c3 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooter.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/SurefireBooter.java @@ -1,915 +1,915 @@ package org.apache.maven.surefire.booter; /* * 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. */ import org.apache.maven.surefire.Surefire; import org.apache.maven.surefire.booter.output.FileOutputConsumerProxy; import org.apache.maven.surefire.booter.output.ForkingStreamConsumer; import org.apache.maven.surefire.booter.output.OutputConsumer; import org.apache.maven.surefire.booter.output.StandardOutputConsumer; import org.apache.maven.surefire.booter.output.SupressFooterOutputConsumerProxy; import org.apache.maven.surefire.booter.output.SupressHeaderOutputConsumerProxy; import org.apache.maven.surefire.testset.TestSetFailedException; import org.apache.maven.surefire.util.NestedRuntimeException; import org.apache.maven.surefire.util.UrlUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.cli.StreamConsumer; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author Jason van Zyl * @author Emmanuel Venisse * @version $Id$ */ public class SurefireBooter { private List reports = new ArrayList(); private List classPathUrls = new ArrayList(); private List surefireClassPathUrls = new ArrayList(); private List surefireBootClassPathUrls = new ArrayList(); private List testSuites = new ArrayList(); private boolean redirectTestOutputToFile = false; // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- private ForkConfiguration forkConfiguration; private static final int TESTS_SUCCEEDED_EXIT_CODE = 0; private static final int TESTS_FAILED_EXIT_CODE = 255; private static Method assertionStatusMethod; /** * @deprecated because the IsolatedClassLoader is really isolated - no parent. */ private boolean childDelegation = true; private File reportsDirectory; /** * This field is set to true if it's running from main. * It's used to help decide what classloader to use. */ private final boolean isForked; static { try { assertionStatusMethod = ClassLoader.class.getMethod( "setDefaultAssertionStatus", new Class[]{boolean.class} ); } catch ( NoSuchMethodException e ) { assertionStatusMethod = null; } } public SurefireBooter() { isForked = false; } private SurefireBooter( boolean isForked ) { this.isForked = isForked; } // ---------------------------------------------------------------------- // Accessors // ---------------------------------------------------------------------- public void addReport( String report ) { addReport( report, null ); } public void addReport( String report, Object[] constructorParams ) { reports.add( new Object[]{report, constructorParams} ); } public void addTestSuite( String suiteClassName, Object[] constructorParams ) { testSuites.add( new Object[]{suiteClassName, constructorParams} ); } public void addClassPathUrl( String path ) { if ( !classPathUrls.contains( path ) ) { classPathUrls.add( path ); } } public void addSurefireClassPathUrl( String path ) { if ( !surefireClassPathUrls.contains( path ) ) { surefireClassPathUrls.add( path ); } } public void addSurefireBootClassPathUrl( String path ) { if ( !surefireBootClassPathUrls.contains( path ) ) { surefireBootClassPathUrls.add( path ); } } /** * When forking, setting this to true will make the test output to be saved in a file * instead of showing it on the standard output * * @param redirectTestOutputToFile */ public void setRedirectTestOutputToFile( boolean redirectTestOutputToFile ) { this.redirectTestOutputToFile = redirectTestOutputToFile; } /** * Set the directory where reports will be saved * * @param reportsDirectory the directory */ public void setReportsDirectory( File reportsDirectory ) { this.reportsDirectory = reportsDirectory; } /** * Get the directory where reports will be saved */ public File getReportsDirectory() { return reportsDirectory; } public void setForkConfiguration( ForkConfiguration forkConfiguration ) { this.forkConfiguration = forkConfiguration; } public boolean run() throws SurefireBooterForkException, SurefireExecutionException { boolean result; if ( ForkConfiguration.FORK_NEVER.equals( forkConfiguration.getForkMode() ) ) { result = runSuitesInProcess(); } else if ( ForkConfiguration.FORK_ONCE.equals( forkConfiguration.getForkMode() ) ) { result = runSuitesForkOnce(); } else if ( ForkConfiguration.FORK_ALWAYS.equals( forkConfiguration.getForkMode() ) ) { result = runSuitesForkPerTestSet(); } else { throw new SurefireExecutionException( "Unknown forkmode: " + forkConfiguration.getForkMode(), null ); } return result; } private boolean runSuitesInProcess( String testSet, Properties results ) throws SurefireExecutionException { if ( testSuites.size() != 1 ) { throw new IllegalArgumentException( "Cannot only specify testSet for single test suites" ); } // TODO: replace with plexus //noinspection CatchGenericClass,OverlyBroadCatchBlock ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader testsClassLoader = useSystemClassLoader() ? ClassLoader.getSystemClassLoader() : createClassLoader( classPathUrls, null, childDelegation, true ); // TODO: assertions = true shouldn't be required for this CL if we had proper separation (see TestNG) ClassLoader surefireClassLoader = createClassLoader( surefireClassPathUrls, testsClassLoader, true ); Class surefireClass = surefireClassLoader.loadClass( Surefire.class.getName() ); Object surefire = surefireClass.newInstance(); Method run = surefireClass.getMethod( "run", new Class[]{List.class, Object[].class, String.class, ClassLoader.class, ClassLoader.class, Properties.class} ); Thread.currentThread().setContextClassLoader( testsClassLoader ); Boolean result = (Boolean) run.invoke( surefire, new Object[]{reports, testSuites.get( 0 ), testSet, surefireClassLoader, testsClassLoader, results} ); return result.booleanValue(); } catch ( InvocationTargetException e ) { throw new SurefireExecutionException( e.getTargetException().getMessage(), e.getTargetException() ); } catch ( Exception e ) { throw new SurefireExecutionException( "Unable to instantiate and execute Surefire", e ); } finally { Thread.currentThread().setContextClassLoader( oldContextClassLoader ); } } private boolean runSuitesInProcess() throws SurefireExecutionException { // TODO: replace with plexus //noinspection CatchGenericClass,OverlyBroadCatchBlock ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { // The test classloader must be constructed first to avoid issues with commons-logging until we properly // separate the TestNG classloader ClassLoader testsClassLoader = useSystemClassLoader() ? getClass().getClassLoader() // ClassLoader.getSystemClassLoader() : createClassLoader( classPathUrls, null, childDelegation, true ); ClassLoader surefireClassLoader = createClassLoader( surefireClassPathUrls, testsClassLoader, true ); Class surefireClass = surefireClassLoader.loadClass( Surefire.class.getName() ); Object surefire = surefireClass.newInstance(); Method run = surefireClass.getMethod( "run", new Class[]{List.class, List.class, ClassLoader.class, ClassLoader.class} ); Thread.currentThread().setContextClassLoader( testsClassLoader ); Boolean result = (Boolean) run.invoke( surefire, new Object[]{reports, testSuites, surefireClassLoader, testsClassLoader} ); return result.booleanValue(); } catch ( InvocationTargetException e ) { throw new SurefireExecutionException( e.getTargetException().getMessage(), e.getTargetException() ); } catch ( Exception e ) { throw new SurefireExecutionException( "Unable to instantiate and execute Surefire", e ); } finally { Thread.currentThread().setContextClassLoader( oldContextClassLoader ); } } private boolean runSuitesForkOnce() throws SurefireBooterForkException { return forkSuites( testSuites, true, true ); } private boolean runSuitesForkPerTestSet() throws SurefireBooterForkException { ClassLoader testsClassLoader; ClassLoader surefireClassLoader; try { testsClassLoader = createClassLoader( classPathUrls, null, false, true ); // TODO: assertions = true shouldn't be required if we had proper separation (see TestNG) surefireClassLoader = createClassLoader( surefireClassPathUrls, testsClassLoader, false, true ); } catch ( MalformedURLException e ) { throw new SurefireBooterForkException( "Unable to create classloader to find test suites", e ); } boolean failed = false; boolean showHeading = true; Properties properties = new Properties(); for ( Iterator i = testSuites.iterator(); i.hasNext(); ) { Object[] testSuite = (Object[]) i.next(); Map testSets = getTestSets( testSuite, testsClassLoader, surefireClassLoader ); for ( Iterator j = testSets.keySet().iterator(); j.hasNext(); ) { String testSet = (String) j.next(); boolean showFooter = !j.hasNext() && !i.hasNext(); boolean result = forkSuite( testSuite, testSet, showHeading, showFooter, properties ); if ( !result ) { failed = true; } showHeading = false; } } return !failed; } private Map getTestSets( Object[] testSuite, ClassLoader testsClassLoader, ClassLoader surefireClassLoader ) throws SurefireBooterForkException { String className = (String) testSuite[0]; Object[] params = (Object[]) testSuite[1]; Object suite; try { suite = Surefire.instantiateObject( className, params, surefireClassLoader ); } catch ( TestSetFailedException e ) { throw new SurefireBooterForkException( e.getMessage(), e.getCause() ); } catch ( ClassNotFoundException e ) { throw new SurefireBooterForkException( "Unable to find class for test suite '" + className + "'", e ); } catch ( NoSuchMethodException e ) { throw new SurefireBooterForkException( "Unable to find appropriate constructor for test suite '" + className + "': " + e.getMessage(), e ); } Map testSets; try { Method m = suite.getClass().getMethod( "locateTestSets", new Class[]{ClassLoader.class} ); testSets = (Map) m.invoke( suite, new Object[]{testsClassLoader} ); } catch ( IllegalAccessException e ) { throw new SurefireBooterForkException( "Error obtaining test sets", e ); } catch ( NoSuchMethodException e ) { throw new SurefireBooterForkException( "Error obtaining test sets", e ); } catch ( InvocationTargetException e ) { throw new SurefireBooterForkException( e.getTargetException().getMessage(), e.getTargetException() ); } return testSets; } private boolean forkSuites( List testSuites, boolean showHeading, boolean showFooter ) throws SurefireBooterForkException { Properties properties = new Properties(); setForkProperties( testSuites, properties ); return fork( properties, showHeading, showFooter ); } private boolean forkSuite( Object[] testSuite, String testSet, boolean showHeading, boolean showFooter, Properties properties ) throws SurefireBooterForkException { setForkProperties( Collections.singletonList( testSuite ), properties ); properties.setProperty( "testSet", testSet ); return fork( properties, showHeading, showFooter ); } private void setForkProperties( List testSuites, Properties properties ) { addPropertiesForTypeHolder( reports, properties, "report." ); addPropertiesForTypeHolder( testSuites, properties, "testSuite." ); - for ( int i = 0; i < classPathUrls.size() && useSystemClassLoader(); i++ ) + for ( int i = 0; i < classPathUrls.size() && !useSystemClassLoader(); i++ ) { String url = (String) classPathUrls.get( i ); properties.setProperty( "classPathUrl." + i, url ); } for ( int i = 0; i < surefireClassPathUrls.size(); i++ ) { String url = (String) surefireClassPathUrls.get( i ); properties.setProperty( "surefireClassPathUrl." + i, url ); } properties.setProperty( "childDelegation", String.valueOf( childDelegation ) ); properties.setProperty( "useSystemClassLoader", String.valueOf( useSystemClassLoader() ) ); } private File writePropertiesFile( String name, Properties properties ) throws IOException { File file = File.createTempFile( name, "tmp" ); file.deleteOnExit(); writePropertiesFile( file, name, properties ); return file; } private void writePropertiesFile( File file, String name, Properties properties ) throws IOException { FileOutputStream out = new FileOutputStream( file ); try { properties.store( out, name ); } finally { IOUtil.close( out ); } } private void addPropertiesForTypeHolder( List typeHolderList, Properties properties, String propertyPrefix ) { for ( int i = 0; i < typeHolderList.size(); i++ ) { Object[] report = (Object[]) typeHolderList.get( i ); String className = (String) report[0]; Object[] params = (Object[]) report[1]; properties.setProperty( propertyPrefix + i, className ); if ( params != null ) { String paramProperty = convert( params[0] ); String typeProperty = params[0].getClass().getName(); for ( int j = 1; j < params.length; j++ ) { paramProperty += "|"; typeProperty += "|"; if ( params[j] != null ) { paramProperty += convert( params[j] ); typeProperty += params[j].getClass().getName(); } } properties.setProperty( propertyPrefix + i + ".params", paramProperty ); properties.setProperty( propertyPrefix + i + ".types", typeProperty ); } } } private String convert( Object param ) { if ( param instanceof File[] ) { String s = "["; File[] f = (File[]) param; for ( int i = 0; i < f.length; i++ ) { s += f[i]; if ( i > 0 ) { s += ","; } } return s + "]"; } else { return param.toString(); } } private final boolean useSystemClassLoader() { return forkConfiguration.isUseSystemClassLoader() && ( isForked || forkConfiguration.isForking() ); } private boolean fork( Properties properties, boolean showHeading, boolean showFooter ) throws SurefireBooterForkException { File surefireProperties; File systemProperties = null; try { surefireProperties = writePropertiesFile( "surefire", properties ); if ( forkConfiguration.getSystemProperties() != null ) { systemProperties = writePropertiesFile( "surefire", forkConfiguration.getSystemProperties() ); } } catch ( IOException e ) { throw new SurefireBooterForkException( "Error creating properties files for forking", e ); } List bootClasspath = new ArrayList( surefireBootClassPathUrls.size() + classPathUrls.size() ); bootClasspath.addAll( surefireBootClassPathUrls ); if ( useSystemClassLoader() ) { bootClasspath.addAll( classPathUrls ); } Commandline cli = forkConfiguration.createCommandLine( bootClasspath, useSystemClassLoader() ); cli.createArgument().setFile( surefireProperties ); if ( systemProperties != null ) { cli.createArgument().setFile( systemProperties ); } StreamConsumer out = getForkingStreamConsumer( showHeading, showFooter, redirectTestOutputToFile ); StreamConsumer err = getForkingStreamConsumer( showHeading, showFooter, redirectTestOutputToFile ); if ( forkConfiguration.isDebug() ) { System.out.println( "Forking command line: " + cli ); } int returnCode; try { returnCode = CommandLineUtils.executeCommandLine( cli, out, err ); } catch ( CommandLineException e ) { throw new SurefireBooterForkException( "Error while executing forked tests.", e ); } if ( surefireProperties != null && surefireProperties.exists() ) { FileInputStream inStream = null; try { inStream = new FileInputStream( surefireProperties ); properties.load( inStream ); } catch ( FileNotFoundException e ) { throw new SurefireBooterForkException( "Unable to reload properties file from forked process", e ); } catch ( IOException e ) { throw new SurefireBooterForkException( "Unable to reload properties file from forked process", e ); } finally { IOUtil.close( inStream ); } } return returnCode == 0; } private static ClassLoader createClassLoader( List classPathUrls, ClassLoader parent, boolean assertionsEnabled ) throws MalformedURLException { return createClassLoader( classPathUrls, parent, false, assertionsEnabled ); } private static ClassLoader createClassLoader( List classPathUrls, ClassLoader parent, boolean childDelegation, boolean assertionsEnabled ) throws MalformedURLException { List urls = new ArrayList(); for ( Iterator i = classPathUrls.iterator(); i.hasNext(); ) { String url = (String) i.next(); if ( url != null ) { File f = new File( url ); urls.add( UrlUtils.getURL( f ) ); } } IsolatedClassLoader classLoader = new IsolatedClassLoader( parent, childDelegation ); if ( assertionStatusMethod != null ) { try { Object[] args = new Object[]{assertionsEnabled ? Boolean.TRUE : Boolean.FALSE}; if ( parent != null ) { assertionStatusMethod.invoke( parent, args ); } assertionStatusMethod.invoke( classLoader, args ); } catch ( IllegalAccessException e ) { throw new NestedRuntimeException( "Unable to access the assertion enablement method", e ); } catch ( InvocationTargetException e ) { throw new NestedRuntimeException( "Unable to invoke the assertion enablement method", e ); } } for ( Iterator iter = urls.iterator(); iter.hasNext(); ) { URL url = (URL) iter.next(); classLoader.addURL( url ); } return classLoader; } private static List processStringList( String stringList ) { String sl = stringList; if ( sl.startsWith( "[" ) && sl.endsWith( "]" ) ) { sl = sl.substring( 1, sl.length() - 1 ); } List list = new ArrayList(); String[] stringArray = StringUtils.split( sl, "," ); for ( int i = 0; i < stringArray.length; i++ ) { list.add( stringArray[i].trim() ); } return list; } private static Properties loadProperties( File file ) throws IOException { Properties p = new Properties(); if ( file != null && file.exists() ) { FileInputStream inStream = new FileInputStream( file ); try { p.load( inStream ); } finally { IOUtil.close( inStream ); } } return p; } private static void setSystemProperties( File file ) throws IOException { Properties p = loadProperties( file ); for ( Iterator i = p.keySet().iterator(); i.hasNext(); ) { String key = (String) i.next(); System.setProperty( key, p.getProperty( key ) ); } } private static Object[] constructParamObjects( String paramProperty, String typeProperty ) { Object[] paramObjects = null; if ( paramProperty != null ) { // bit of a glitch that it need sto be done twice to do an odd number of vertical bars (eg |||, |||||). String[] params = StringUtils.split( StringUtils.replace( StringUtils.replace( paramProperty, "||", "| |" ), "||", "| |" ), "|" ); String[] types = StringUtils.split( StringUtils.replace( StringUtils.replace( typeProperty, "||", "| |" ), "||", "| |" ), "|" ); paramObjects = new Object[params.length]; for ( int i = 0; i < types.length; i++ ) { if ( types[i].trim().length() == 0 ) { params[i] = null; } else if ( types[i].equals( String.class.getName() ) ) { paramObjects[i] = params[i]; } else if ( types[i].equals( File.class.getName() ) ) { paramObjects[i] = new File( params[i] ); } else if ( types[i].equals( File[].class.getName() ) ) { List stringList = processStringList( params[i] ); File[] fileList = new File[stringList.size()]; for ( int j = 0; j < stringList.size(); j++ ) { fileList[j] = new File( (String) stringList.get( j ) ); } paramObjects[i] = fileList; } else if ( types[i].equals( ArrayList.class.getName() ) ) { paramObjects[i] = processStringList( params[i] ); } else if ( types[i].equals( Boolean.class.getName() ) ) { paramObjects[i] = Boolean.valueOf( params[i] ); } else if ( types[i].equals( Integer.class.getName() ) ) { paramObjects[i] = Integer.valueOf( params[i] ); } else { // TODO: could attempt to construct with a String constructor if needed throw new IllegalArgumentException( "Unknown parameter type: " + types[i] ); } } } return paramObjects; } /** * This method is invoked when Surefire is forked - this method parses and * organizes the arguments passed to it and then calls the Surefire class' * run method. * <p/> * The system exit code will be 1 if an exception is thrown. * * @param args */ public static void main( String[] args ) throws Throwable { //noinspection CatchGenericClass,OverlyBroadCatchBlock try { if ( args.length > 1 ) { setSystemProperties( new File( args[1] ) ); } File surefirePropertiesFile = new File( args[0] ); Properties p = loadProperties( surefirePropertiesFile ); SurefireBooter surefireBooter = new SurefireBooter( true ); ForkConfiguration forkConfiguration = new ForkConfiguration(); forkConfiguration.setForkMode( "never" ); surefireBooter.setForkConfiguration( forkConfiguration ); for ( Enumeration e = p.propertyNames(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); if ( name.startsWith( "report." ) && !name.endsWith( ".params" ) && !name.endsWith( ".types" ) ) { String className = p.getProperty( name ); String params = p.getProperty( name + ".params" ); String types = p.getProperty( name + ".types" ); surefireBooter.addReport( className, constructParamObjects( params, types ) ); } else if ( name.startsWith( "testSuite." ) && !name.endsWith( ".params" ) && !name.endsWith( ".types" ) ) { String className = p.getProperty( name ); String params = p.getProperty( name + ".params" ); String types = p.getProperty( name + ".types" ); surefireBooter.addTestSuite( className, constructParamObjects( params, types ) ); } else if ( name.startsWith( "classPathUrl." ) ) { surefireBooter.addClassPathUrl( p.getProperty( name ) ); } else if ( name.startsWith( "surefireClassPathUrl." ) ) { surefireBooter.addSurefireClassPathUrl( p.getProperty( name ) ); } else if ( name.startsWith( "surefireBootClassPathUrl." ) ) { surefireBooter.addSurefireBootClassPathUrl( p.getProperty( name ) ); } else if ( "childDelegation".equals( name ) ) { surefireBooter.childDelegation = Boolean.valueOf( p.getProperty( "childDelegation" ) ).booleanValue(); } else if ( "useSystemClassLoader".equals( name ) ) { surefireBooter.forkConfiguration.setUseSystemClassLoader( Boolean.valueOf( p.getProperty( "useSystemClassLoader" ) ).booleanValue() ); } } String testSet = p.getProperty( "testSet" ); boolean result; if ( testSet != null ) { result = surefireBooter.runSuitesInProcess( testSet, p ); } else { result = surefireBooter.runSuitesInProcess(); } surefireBooter.writePropertiesFile( surefirePropertiesFile, "surefire", p ); //noinspection CallToSystemExit System.exit( result ? TESTS_SUCCEEDED_EXIT_CODE : TESTS_FAILED_EXIT_CODE ); } catch ( Throwable t ) { // Just throwing does getMessage() and a local trace - we want to call printStackTrace for a full trace //noinspection UseOfSystemOutOrSystemErr t.printStackTrace( System.err ); //noinspection ProhibitedExceptionThrown,CallToSystemExit System.exit( 1 ); } } public void setChildDelegation( boolean childDelegation ) { this.childDelegation = childDelegation; } private StreamConsumer getForkingStreamConsumer( boolean showHeading, boolean showFooter, boolean redirectTestOutputToFile ) { OutputConsumer outputConsumer = new StandardOutputConsumer(); if ( redirectTestOutputToFile ) { outputConsumer = new FileOutputConsumerProxy( outputConsumer, getReportsDirectory() ); } if ( !showHeading ) { outputConsumer = new SupressHeaderOutputConsumerProxy( outputConsumer ); } if ( !showFooter ) { outputConsumer = new SupressFooterOutputConsumerProxy( outputConsumer ); } return new ForkingStreamConsumer( outputConsumer ); } }
true
false
null
null
diff --git a/silvertrout/plugins/Suggester.java b/silvertrout/plugins/Suggester.java index ea268fd..a655fe8 100644 --- a/silvertrout/plugins/Suggester.java +++ b/silvertrout/plugins/Suggester.java @@ -1,130 +1,130 @@ /* _______ __ __ _______ __ * | __|__| |.--.--.-----.----.|_ _|.----.-----.--.--.| |_ * |__ | | || | | -__| _| | | | _| _ | | || _| * |_______|__|__| \___/|_____|__| |___| |__| |_____|_____||____| * * Copyright 2008 - Gustav Tiger, Henrik Steen and Gustav Sothell * * 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 silvertrout.plugins; import java.nio.ByteBuffer; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.HashSet; import java.util.HashMap; import java.net.URL; import java.net.HttpURLConnection; import silvertrout.Channel; import silvertrout.User; import silvertrout.commons.ConnectHelper; /** * JBT-plugin to fetch google suggestions * * Beta version with URL and URLConnection support. Tries to do some charset * conversion based on HTTP headers. TODO: Check meta tag for additional * information about charset. * * @author reggna * @author tigge * @version Beta 3.0 */ public class Suggester extends silvertrout.Plugin { /* connection information */ private static final int port = 80; private static final String connection = "http"; private static final String server = "google.se"; private static final String file = "/search?&q="; /* Max content length (in bytes) to grab to check for header */ private static final int maxContentLength = 16384; /* A list containing words that will not be checked */ private HashSet<String> blackList; /* A map containing all words that have previously been checked, and any */ /* suggestions connected to that word */ private HashMap<String, String> old; /** * Constructor, initiates the hashmap och hashset * Adding some words to the blackList */ public Suggester() { blackList = new HashSet<String>(); old = new HashMap<String, String>(); blackList.add("hej"); } @Override public void onPrivmsg(User user, Channel channel, String message) { /* restrict to the channel #it06 for test purpose */ if (channel == null || !channel.getName().equals("#it06")) { return; } for (String s : message.split(" ")) { /* check if the message contains a username, if so: change the message */ /* to something in the blacklist */ for (User u : channel.getUsers().keySet()) { if (s.contains(u.getNickname())) { s = "hej"; } } /* if the message is in the blacklist, go to the next one */ if (blackList.contains(s)) { continue; } /* do we have this word in our "vocabulary" (old), else we check google */ String t; if (old.containsKey(s)) { t = old.get(s); } else { t = getSuggestion(s); } old.put(s, t); /* if we have found a suggestion, print it to the channel */ if (t != null) { channel.sendPrivmsg(t); } } } /** * Method that google a word, and returns the "did you mean: ..."-suggestion * connected to that word * *@param s the string to check for suggestion *@return The google "did you mean: ..."-suggestion, or null if not found */ - private static String getSuggestion(String s) { - // Find suggestion - String titlePattern = "(?i)class=p><b><i>([^<]+)"; - Pattern pt = Pattern.compile(titlePattern); - Matcher mt = pt.matcher(ConnectHelper.Connect(connection, server, - file + s, port, maxContentLength)); - - if (mt.find()) { - return mt.group(1); - } - return null; + private static String getSuggestion(String s) { + String suggestion = ConnectHelper.Connect(connection, server, file + s, + port, maxContentLength); + suggestion = suggestion.substring(suggestion.indexOf("class=p><b><i>")+14); + suggestion = suggestion.substring(0, suggestion.indexOf("<")); + if(suggestion.indexOf(">") > 0) return null; + return suggestion; + } + + public static void main(String[] args){ + System.out.println(getSuggestion(args[0])); } }
true
false
null
null
diff --git a/hazelcast/src/main/java/com/hazelcast/cluster/MemberRemover.java b/hazelcast/src/main/java/com/hazelcast/cluster/MemberRemover.java index 97e90c7ed2..727cfccd5b 100644 --- a/hazelcast/src/main/java/com/hazelcast/cluster/MemberRemover.java +++ b/hazelcast/src/main/java/com/hazelcast/cluster/MemberRemover.java @@ -1,66 +1,64 @@ /* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. 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. */ package com.hazelcast.cluster; import com.hazelcast.impl.Node; import com.hazelcast.impl.spi.NodeServiceImpl; import com.hazelcast.impl.spi.Operation; import com.hazelcast.nio.Address; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; public class MemberRemover extends Operation { private Address deadAddress = null; public MemberRemover() { } public MemberRemover(Address deadAddress) { super(); this.deadAddress = deadAddress; } // public void process() { // if (conn != null) { // Address endpoint = conn.getEndPoint(); // if (endpoint != null && endpoint.equals(getNode().getMasterAddress())) { // getNode().clusterManager.removeAddress(deadAddress); // } // } // } public void run() { final NodeServiceImpl nodeService = (NodeServiceImpl) getNodeService(); Node node = nodeService.getNode(); Address caller = getCaller(); if (caller != null && caller.equals(node.getMasterAddress())) { node.clusterService.removeAddress(deadAddress); } } public void readInternal(DataInput in) throws IOException { - super.readData(in); deadAddress = new Address(); deadAddress.readData(in); } public void writeInternal(DataOutput out) throws IOException { - super.writeData(out); deadAddress.writeData(out); } }
false
false
null
null
diff --git a/src/de/dhbw/wbs/Seminarplanung.java b/src/de/dhbw/wbs/Seminarplanung.java index c7015f1..8155f35 100644 --- a/src/de/dhbw/wbs/Seminarplanung.java +++ b/src/de/dhbw/wbs/Seminarplanung.java @@ -1,246 +1,249 @@ package de.dhbw.wbs; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; public final class Seminarplanung { private static final SimpleDateFormat lectureTimeFormat = new SimpleDateFormat("hh:mm"); /** * @param args */ public static void main(String[] args) { HashMap<Integer, Lecture> lectures = new HashMap<Integer, Lecture>(); HashMap<Integer, Group> groups = new HashMap<Integer, Group>(); ArrayList<Lecturer> lecturers = new ArrayList<Lecturer>(); ArrayList<Room> rooms = new ArrayList<Room>(); if (args.length != 3) { System.err.println("Expecting three file names as arguments."); System.exit(1); } String lectureFileName = args[0]; String depFileName = args[1]; String timeFileName = args[2]; // 1. Parsen try { /* * Parse 1st file - lectures * * Lecture No;subject;lecturer;group number;duration;room */ BufferedReader lectureReader = new BufferedReader(new FileReader(lectureFileName)); // Skip the header line lectureReader.readLine(); CSVParser lectureParser = new CSVParser(lectureReader); for (String[] elems : lectureParser.parse()) { Lecture lecture = new Lecture(); Integer groupNumber = new Integer(elems[3]); Group group = groups.get(groupNumber); if (group == null) { group = new Group(groupNumber); groups.put(groupNumber, group); } lecture.setGroup(group); Lecturer lecturer = new Lecturer(elems[2]); lecture.setLecturer(lecturer); lecturers.add(lecturer); Room room = new Room(Integer.parseInt(elems[5])); lecture.setRoom(room); rooms.add(room); lecture.setNumber(Integer.parseInt(elems[0])); lecture.setName(elems[1]); lecture.setDuration(Integer.parseInt(elems[4])); lectures.put(new Integer(lecture.getNumber()), lecture); } /* * Parse 2nd file - lecture dependencies * * basic lecture;required lecture;;;; */ BufferedReader depReader = new BufferedReader(new FileReader(depFileName)); // Skip the header line depReader.readLine(); CSVParser depParser = new CSVParser(depReader); for (String[] elems : depParser.parse()) { Lecture basicLecture = lectures.get(new Integer(elems[0])); Lecture dependentLecture = lectures.get(new Integer(elems[1])); dependentLecture.addRequiredLecture(basicLecture); } /* * Parse 3rd file - time information * group number;lecture number;start time */ BufferedReader timeReader = new BufferedReader(new FileReader(timeFileName)); // Skip the header line timeReader.readLine(); CSVParser timeParser = new CSVParser(timeReader); for (String[] elems : timeParser.parse()) { Lecture lecture = lectures.get(new Integer(elems[1])); Group group = groups.get(new Integer(elems[0])); if (group != lecture.getGroup()) { System.err.println("Error: The group number for lecture " + elems[1] + "(" + lecture.getName() + ") as supplied in file " + timeFileName + " does not match the group " + "number from file " + lectureFileName); System.exit(1); } Date startTime = null; try { startTime = lectureTimeFormat.parse(elems[2]); } catch (ParseException exc) { System.err.println("Error: Invalid time format " + elems[2] + " in file " + args[2] + ". Expect hh:mm notation."); System.exit(1); } Calendar cal = Calendar.getInstance(); cal.setTime(startTime); lecture.setStartTime(cal); } } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); System.exit(1); } catch (IOException e) { e.printStackTrace(); System.exit(2); } // 2. Check consistency /* * 2.1 A lecture may only take place of the group has already heard all lectures that this * lecture depends on */ for (Lecture dependentLecture : lectures.values()) { if (dependentLecture.isTakingPlace()) { for (Lecture requiredLecture : dependentLecture.getRequiredLectures()) { assertTrue(dependentLecture.getGroup() == requiredLecture.getGroup(), "Lecture " + dependentLecture.getName() + "depends on lecture " + requiredLecture.getName() + ", but the two lectures are held in different groups."); if (!requiredLecture.isTakingPlace()) { abort("Lecture " + dependentLecture + " depends on lecture " + requiredLecture + ", but this lecture is not taught at all."); } else { AllenRelation allenRelation = AllenRelation.getAllenRelation(requiredLecture.getTimeSpan(), dependentLecture.getTimeSpan()); switch (allenRelation) { case BEFORE: case MEETS: break; default: abort("Lecture " + dependentLecture + " depends on lecture " + requiredLecture + ", but this lecture is not taught before the other lecture\n" + "(Allen relation between required and dependent lecture is " + allenRelation.name() + ")"); } } } } } /* * 2.2 Lectures of the same group or the same lecturer may not overlap. * One room can be used for only one lecture at a given point of time. */ for (Lecturer lecturer : lecturers) { final Lecturer lecturerCopy = lecturer; Predicate<Lecture> lecturerPredicate = new Predicate<Lecture>() { @Override public boolean matches(Lecture aLecture) { return aLecture.getLecturer().equals(lecturerCopy); } }; - checkForOverlap(lecturerPredicate.filter(lectures.values())); + abortIfOverlap(lecturerPredicate.filter(lectures.values()), + "lectures of the same lecturer may not overlap"); } for (Group group : groups.values()) { final Group groupCopy = group; Predicate<Lecture> groupPredicate = new Predicate<Lecture>() { @Override public boolean matches(Lecture aLecture) { return aLecture.getGroup().equals(groupCopy); } }; - checkForOverlap(groupPredicate.filter(lectures.values())); + abortIfOverlap(groupPredicate.filter(lectures.values()), + "lectures of the same group may not overlap"); } for (Room room : rooms) { final Room roomCopy = room; Predicate<Lecture> roomPredicate = new Predicate<Lecture>() { @Override public boolean matches(Lecture aLecture) { return aLecture.getRoom().equals(roomCopy); } }; - checkForOverlap(roomPredicate.filter(lectures.values())); + abortIfOverlap(roomPredicate.filter(lectures.values()), + "lectures in the same room may not overlap"); } /* * 2.3 There has to be a break between two lectures of length two for both the lecturerers and the * seminar group. */ // TODO System.out.println("All checks passed. File appears to be valid."); System.exit(0); } - private static void checkForOverlap(ArrayList<Lecture> lectures) { + private static void abortIfOverlap(ArrayList<Lecture> lectures, String cond) { for (Lecture lecture1 : lectures) { for (Lecture lecture2 : lectures) { if (lecture1 == lecture2) continue; if (lecture1.overlapsWith(lecture2)) - abort("Lecture " + lecture1.getName() + " overlaps with lecture " + lecture2.getName() + "\n"); + abort("Lecture " + lecture1.toString() + " overlaps with lecture " + lecture2.toString() + ", but " + cond + "\n"); } } } private static void abort(String errMsg) { System.err.println(errMsg); System.err.println("Abort."); System.exit(1); } private static void assertTrue(boolean assertion, String errMsg) { if (!assertion) abort(errMsg); } }
false
false
null
null
diff --git a/src/net/slipcor/pvparena/classes/PACheck.java b/src/net/slipcor/pvparena/classes/PACheck.java index e596ea3e..4b07e07f 100644 --- a/src/net/slipcor/pvparena/classes/PACheck.java +++ b/src/net/slipcor/pvparena/classes/PACheck.java @@ -1,542 +1,544 @@ package net.slipcor.pvparena.classes; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.entity.PlayerDeathEvent; import com.nodinchan.ncbukkit.loader.Loadable; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.arena.ArenaTeam; import net.slipcor.pvparena.commands.PAA_Region; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.loadables.ArenaGoal; import net.slipcor.pvparena.loadables.ArenaModule; import net.slipcor.pvparena.managers.StatisticsManager; import net.slipcor.pvparena.managers.TeamManager; /** * <pre>PVP Arena Check class</pre> * * This class parses a complex check. * * It is called staticly to iterate over all needed/possible modules * to return one committing module (inside the result) and to make * modules listen to the checked events if necessary * * @author slipcor * * @version v0.9.3 */ public class PACheck { private int priority = 0; private String error = null; private String modName = null; private Debug db = new Debug(9); /** * * @return the error message */ public String getError() { return error; } /** * * @return the module name returning the current result */ public String getModName() { return modName; } /** * * @return the PACR priority */ public int getPriority() { return priority; } /** * * @return true if there was an error */ public boolean hasError() { return error != null; } /** * set the error message * @param error the error message */ public void setError(Loadable loadable, String error) { modName = loadable.getName(); db.i(modName + " is setting error to: " + error); this.error = error; this.priority += 1000; } /** * set the priority * @param priority the priority */ public void setPriority(Loadable loadable, int priority) { modName = loadable.getName(); db.i(modName + " is setting priority to: " + priority); this.priority = priority; } public static boolean handleCommand(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkCommand(res, args[0]); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) return false; commit.commitCommand(sender, args); return true; } public static boolean handleEnd(Arena arena, boolean force) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkEnd(res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) { return false; } commit.commitEnd(force); return true; } public static int handleGetLives(Arena arena, ArenaPlayer ap) { PACheck res = new PACheck(); int priority = 0; for (ArenaGoal mod : arena.getGoals()) { res = mod.getLives(res, ap); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); } } if (res.hasError()) { return Integer.valueOf(res.getError()); } return 0; } public static void handleInteract(Arena arena, Player player, Block clickedBlock) { int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkInteract(res, player, clickedBlock); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } commit.commitInteract(player, clickedBlock); } public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); - if (team == null) { + if (team == null && args != null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; + } else if (team == null) { + arena.msg(sender, Language.parse(MSG.ERROR_JOIN_ARENA_FULL)); } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); } public static void handlePlayerDeath(Arena arena, Player player, PlayerDeathEvent event) { boolean doesRespawn = true; int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkPlayerDeath(res, player); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { // lives if (res.getError().equals("0")) { doesRespawn = false; } } StatisticsManager.kill(arena, player.getLastDamageCause().getEntity(), player, doesRespawn); event.setDeathMessage(null); if (!arena.getArenaConfig().getBoolean(CFG.PLAYER_DROPSINVENTORY)) { event.getDrops().clear(); } if (commit == null) { // no mod handles player deaths, default to infinite lives. Respawn player arena.unKillPlayer(player, event.getEntity().getLastDamageCause().getCause(), player.getKiller()); return; } commit.commitPlayerDeath(player, doesRespawn, res.getError(), event); for (ArenaGoal g : arena.getGoals()) { g.parsePlayerDeath(player, player.getLastDamageCause()); } for (ArenaModule m : PVPArena.instance.getAmm().getModules()) { if (m.isActive(arena)) { m.parsePlayerDeath(arena, player, player.getLastDamageCause()); } } } public static boolean handleSetFlag(Player player, Block block) { Arena arena = PAA_Region.activeSelections.get(player.getName()); if (arena == null) { return false; } int priority = 0; PACheck res = new PACheck(); ArenaGoal commit = null; for (ArenaGoal mod : arena.getGoals()) { res = mod.checkSetFlag(res, player, block); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(Bukkit.getConsoleSender(), Language.parse(MSG.ERROR_ERROR, res.getError())); return false; } if (commit == null) { return false; } return commit.commitSetFlag(player, block); } public static void handleSpectate(Arena arena, CommandSender sender) { int priority = 0; PACheck res = new PACheck(); // priority will be set by flags, the max priority will be called ArenaModule commit = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, false); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } commit.commitSpectate(arena, (Player) sender); /* for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { commit.parseSpectate(arena, (Player) sender); } }*/ } public static void handleStart(Arena arena, ArenaPlayer ap, CommandSender sender) { PACheck res = new PACheck(); ArenaModule commit = null; int priority = 0; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkStart(arena, ap, res); } if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commit = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commit = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (commit == null) { return; } arena.teleportAllToSpawn(); } } /* * AVAILABLE PACheckResults: * * ArenaGoal.checkCommand() => ArenaGoal.commitCommand() * ( onCommand() ) * > default: nothing * * * ArenaGoal.checkEnd() => ArenaGoal.commitEnd() * ( ArenaGoalManager.checkEndAndCommit(arena) ) < used * > 1: PlayerLives * > 2: PlayerDeathMatch * > 3: TeamLives * > 4: TeamDeathMatch * > 5: Flags * * ArenaGoal.checkInteract() => ArenaGoal.commitInteract() * ( PlayerListener.onPlayerInteract() ) * > 5: Flags * * ArenaGoal.checkJoin() => ArenaGoal.commitJoin() * ( PAG_Join ) < used * > default: tp inside * * ArenaGoal.checkPlayerDeath() => ArenaGoal.commitPlayerDeath() * ( PlayerLister.onPlayerDeath() ) * > 1: PlayerLives * > 2: PlayerDeathMatch * > 3: TeamLives * > 4: TeamDeathMatch * > 5: Flags * * ArenaGoal.checkSetFlag() => ArenaGoal.commitSetFlag() * ( PlayerListener.onPlayerInteract() ) * > 5: Flags * * ================================= * * ArenaModule.checkJoin() * ( PAG_Join | PAG_Spectate ) < used * > 1: StandardLounge * > 2: BattlefieldJoin * > default: nothing * * ArenaModule.checkStart() * ( PAI_Ready ) < used * > default: nothing * */
false
true
public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); if (team == null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); }
public static void handleJoin(Arena arena, CommandSender sender, String[] args) { int priority = 0; PACheck res = new PACheck(); ArenaModule commModule = null; for (ArenaModule mod : PVPArena.instance.getAmm().getModules()) { if (mod.isActive(arena)) { res = mod.checkJoin(arena, sender, res, true); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commModule = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commModule = null; } } } if (res.hasError() && !res.getModName().equals("LateLounge")) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.NOTICE_NOTICE, res.getError())); return; } ArenaGoal commGoal = null; for (ArenaGoal mod : PVPArena.instance.getAgm().getTypes()) { res = mod.checkJoin(sender, res); if (res.getPriority() > priority && priority >= 0) { // success and higher priority priority = res.getPriority(); commGoal = mod; } else if (res.getPriority() < 0 || priority < 0) { // fail priority = res.getPriority(); commGoal = null; } } if (res.hasError()) { arena.msg(sender, Language.parse(MSG.ERROR_ERROR, res.getError())); return; } if (args.length < 1) { // usage: /pa {arenaname} join | join an arena args = new String[]{TeamManager.calcFreeTeam(arena)}; } ArenaTeam team = arena.getTeam(args[0]); if (team == null && args != null) { arena.msg(sender, Language.parse(MSG.ERROR_TEAMNOTFOUND, args[0])); return; } else if (team == null) { arena.msg(sender, Language.parse(MSG.ERROR_JOIN_ARENA_FULL)); } if ((commModule == null) || (commGoal == null)) { if (commModule != null) { commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); return; } if (commGoal != null) { commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(sender, team); return; } // both null, just put the joiner to some spawn if (!arena.tryJoin((Player) sender, team)) { return; } if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } PVPArena.instance.getAgm().initiate(arena, (Player) sender); if (arena.getFighters().size() == 2) { arena.broadcast(Language.parse(MSG.FIGHT_BEGINS)); arena.setFightInProgress(true); for (ArenaPlayer p : arena.getFighters()) { if (p.getName().equals(sender.getName())) { continue; } arena.tpPlayerToCoordName(p.get(), (arena.isFreeForAll()?"":p.getArenaTeam().getName()) + "spawn"); } } return; } commModule.commitJoin(arena, (Player) sender, team); PVPArena.instance.getAmm().parseJoin(res, arena, (Player) sender, team); commGoal.commitJoin(sender, team); //PVPArena.instance.getAgm().parseJoin(res, arena, (Player) sender, team); }
diff --git a/src/gameLogic/Board.java b/src/gameLogic/Board.java index 0e34451..529c53f 100644 --- a/src/gameLogic/Board.java +++ b/src/gameLogic/Board.java @@ -1,53 +1,58 @@ package gameLogic; public class Board { private Square[][] board; public Board(int width, int height) { if (width < 1 || height < 1) throw new IllegalArgumentException("Board size must be greater than 0"); board = new Square[width][height]; } public int getWidth() { return board.length; } public int getHeight() { return board[0].length; } public boolean hasGameObject(Position p) { return (!board[p.getX()][p.getY()].isEmpty()); } public Square getSquare(Position p) { return board[p.getX()][p.getY()]; } void addGameObject(GameObjectType obj, Position p) { board[p.getX()][p.getY()].addGameObject(new GameObject(obj)); } + void addGameObject(GameObject obj, Position p) + { + board[p.getX()][p.getY()].addGameObject(obj); + } + void clearSquare(Position p) { board[p.getX()][p.getY()].clear(); } void removeGameObject(GameObject obj, Position p) { board[p.getX()][p.getY()].removeGameObject(obj); } void removeFruit(Position p) { board[p.getX()][p.getY()].removeFruit(); } } \ No newline at end of file diff --git a/src/gameLogic/Session.java b/src/gameLogic/Session.java index 2f79d56..ad4f89f 100644 --- a/src/gameLogic/Session.java +++ b/src/gameLogic/Session.java @@ -1,243 +1,244 @@ package gameLogic; import java.util.*; public class Session { private Board board; private HashMap<Integer, Snake> snakes; private HashMap<Snake, Integer> score; private HashMap<String, GameObjectType> objects; private GameState currentGameState; private long thinkingTime; private int growthFrequency; private int turnsUntilGrowth; private int turn = 0; private int numberOfSnakes = 0; public Session(int boardWidth, int boardHeight, int growthFrequency, long thinkingTime) { board = createStandardBoard(boardWidth, boardHeight); snakes = new HashMap<Integer, Snake>(); score = new HashMap<Snake, Integer>(); objects = new HashMap<String, GameObjectType>(); initGameObjects(); this.growthFrequency = growthFrequency; this.thinkingTime = thinkingTime; turnsUntilGrowth = growthFrequency; } public void addSnake(Snake newSnake) { if (newSnake == null) throw new IllegalArgumentException("Trying to add a null Snake."); snakes.put(++numberOfSnakes, newSnake); score.put(newSnake, 0); } private void removeSnake(int id) { snakes.remove(id); numberOfSnakes--; } private void removeSnake(Snake snake) { for (Map.Entry<Integer, Snake> snakeEntry : snakes.entrySet()) { if (snakeEntry.getValue().equals(snake)) { snakes.remove(snake); return; } } throw new IllegalArgumentException("No such snake exists."); } public Board getBoard() { return board; } public Set<Snake> getSnakes() { return new HashSet<Snake>(snakes.values()); } /** * Move all the snakes simultaneously. In addition to movement, it also checks for collision, * kills colliding snakes, adds point when fruit is eaten, and updates the gamestate. */ public void tick() { boolean growth = checkForGrowth(); HashMap<Snake, Direction> moves = getDecisionsFromSnakes(); moveAllSnakes(moves, growth); ArrayList<Snake> deadSnakes = checkForCollision(); removeDeadSnakes(deadSnakes); updateGameState(); } private boolean checkForGrowth() { boolean grow = false; if (--turnsUntilGrowth < 1) { grow = true; turnsUntilGrowth = growthFrequency; } return grow; } /** * Returns a HashMap, with each position containing a Snake object and * the Direction towards which the given snake wishes to move next turn. * Spawns a single thread for each participating snake, then waits until * their allotted time is up. If a snake hasn't responed yet, it's direction * is defaulted to Direction.FORWARD. * @return The HashMap containing snakes and their next moves. */ private HashMap<Snake, Direction> getDecisionsFromSnakes() { BrainDecision[] decisionThreads = new BrainDecision[numberOfSnakes]; int arrpos = 0; HashMap<Snake, Direction> moves = new HashMap<Snake, Direction>(); //~ Using a HashMap here since I'm unsure of the sorting order of snakes.values() below. //~ Prepare some decision threads. for (Snake snake : snakes.values()) { BrainDecision bd = new BrainDecision(snake, currentGameState); decisionThreads[arrpos++] = bd; } //~ Start all the decision threads. for (int i = 0; i < decisionThreads.length; i++) decisionThreads[i].start(); //~ Chill out while the snakes are thinking. try { Thread.sleep(thinkingTime); } catch (InterruptedException e) { System.out.println(e); } for (int i = 0; i < decisionThreads.length; i++) { BrainDecision decision = decisionThreads[i]; Snake currentSnake = decision.getSnake(); Direction nextMove; if (!decision.isAlive()) { nextMove = decision.getNextMove(); } else //~ This snake has taken too long to decide, and will automatically move forward. { nextMove = new Direction(Direction.FORWARD); Snake slowSnake = decision.getSnake(); slowSnake.tooSlowFault(); } moves.put(currentSnake, nextMove); } return moves; } private void moveAllSnakes(HashMap<Snake, Direction> moves, boolean growSnakes) { for (Map.Entry<Snake, Direction> snakeMove : moves.entrySet()) { moveSnake(snakeMove.getKey(), snakeMove.getValue(), growSnakes); } } private ArrayList<Snake> checkForCollision() { ArrayList<Snake> deadSnakes = new ArrayList<Snake>(); for (Snake snake : snakes.values()) { Position head = snake.getHead(); Square square = board.getSquare(head); if (square.isLethal()) { - //~ NOTE: This seems fucked up. Won't snakes move, and then collide with their own heads? - deadSnakes.add(snake); - System.out.println("TERMINATE SNAKE."); + if (square.hasWall() || square.hasSnake() && (square.getSnakes().contains(snake))) + { + deadSnakes.add(snake); + System.out.println("TERMINATE SNAKE."); + } } if (square.hasFruit()) { int fruitValue = square.eatFruit(); int oldScore = score.get(snake); int newScore = oldScore + fruitValue; score.put(snake, newScore); } } return deadSnakes; } private void removeDeadSnakes(ArrayList<Snake> dead) { Iterator<Snake> deadSnakeIter = dead.iterator(); while (deadSnakeIter.hasNext()) { removeSnake(deadSnakeIter.next()); } } private void moveSnake(Snake snake, Direction dir, boolean grow) { Position currentHeadPosition = snake.getHead(); Position currentTailPosition = snake.getTail(); Position newHeadPosition = dir.calculateNextPosition(currentHeadPosition); - board.addGameObject(objects.get("SnakeSegment"), newHeadPosition); + board.addGameObject(snake, newHeadPosition); snake.moveHead(newHeadPosition); if (!grow) { - //~ NOTE board.removeGameObject(how do we get the right segment GameObject?) + board.removeGameObject(snake, currentTailPosition); snake.removeTail(); } } private void updateGameState() { turn++; currentGameState = new GameState(board, snakes, turn, turnsUntilGrowth); } /** * Generates a standard snake board, sized width x height, with lethal walls around the edges. * @param width Desired board height. * @param height Desired board width. * @return The newly generated board. */ private Board createStandardBoard(int width, int height) { board = new Board(width, height); GameObjectType wall = objects.get("Wall"); for (int x = 0; x < width; x++) { Position bottomRowPos = new Position(x, 0); Position topRowPos = new Position(x, height-1); board.addGameObject(wall, bottomRowPos); board.addGameObject(wall, topRowPos); } for (int y = 0; y < height; y++) { Position leftmostColumnPos = new Position(0, y); Position rightmostColumnPos = new Position(width-1, y); board.addGameObject(wall, leftmostColumnPos); board.addGameObject(wall, rightmostColumnPos); } return board; } private void initGameObjects() { objects.put("Wall", new GameObjectType("Wall", true)); - objects.put("SnakeSegment", new GameObjectType("SnakeSegment", true)); objects.put("Fruit", new GameObjectType("Fruit", false, 1)); } }
false
false
null
null
diff --git a/solr/src/java/org/apache/solr/handler/component/TermsComponent.java b/solr/src/java/org/apache/solr/handler/component/TermsComponent.java index 3386b81bf..1ac33c13a 100644 --- a/solr/src/java/org/apache/solr/handler/component/TermsComponent.java +++ b/solr/src/java/org/apache/solr/handler/component/TermsComponent.java @@ -1,488 +1,488 @@ package org.apache.solr.handler.component; /** * 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. */ import org.apache.lucene.index.*; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.StringHelper; import org.apache.noggit.CharArr; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.*; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.common.util.StrUtils; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.StrField; import org.apache.solr.request.SimpleFacets.CountPair; import org.apache.solr.search.SolrIndexReader; import org.apache.solr.util.BoundedTreeSet; import org.apache.solr.client.solrj.response.TermsResponse; import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * Return TermEnum information, useful for things like auto suggest. * * @see org.apache.solr.common.params.TermsParams * See Lucene's TermEnum class */ public class TermsComponent extends SearchComponent { public static final int UNLIMITED_MAX_COUNT = -1; public static final String COMPONENT_NAME = "terms"; @Override public void prepare(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (params.getBool(TermsParams.TERMS, false)) { rb.doTerms = true; } // TODO: temporary... this should go in a different component. String shards = params.get(ShardParams.SHARDS); if (shards != null) { if (params.get(ShardParams.SHARDS_QT) == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "No shards.qt parameter specified"); } List<String> lst = StrUtils.splitSmart(shards, ",", true); rb.shards = lst.toArray(new String[lst.size()]); } } public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); - Terms terms = lfields.terms(field); + Terms terms = lfields == null ? null : lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } } int resolveRegexpFlags(SolrParams params) { String[] flagParams = params.getParams(TermsParams.TERMS_REGEXP_FLAG); if (flagParams == null) { return 0; } int flags = 0; for (String flagParam : flagParams) { try { flags |= TermsParams.TermsRegexpFlag.valueOf(flagParam.toUpperCase(Locale.ENGLISH)).getValue(); } catch (IllegalArgumentException iae) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Unknown terms regex flag '" + flagParam + "'"); } } return flags; } @Override public int distributedProcess(ResponseBuilder rb) throws IOException { if (!rb.doTerms) { return ResponseBuilder.STAGE_DONE; } if (rb.stage == ResponseBuilder.STAGE_EXECUTE_QUERY) { TermsHelper th = rb._termsHelper; if (th == null) { th = rb._termsHelper = new TermsHelper(); th.init(rb.req.getParams()); } ShardRequest sreq = createShardQuery(rb.req.getParams()); rb.addRequest(this, sreq); } if (rb.stage < ResponseBuilder.STAGE_EXECUTE_QUERY) { return ResponseBuilder.STAGE_EXECUTE_QUERY; } else { return ResponseBuilder.STAGE_DONE; } } @Override public void handleResponses(ResponseBuilder rb, ShardRequest sreq) { if (!rb.doTerms || (sreq.purpose & ShardRequest.PURPOSE_GET_TERMS) == 0) { return; } TermsHelper th = rb._termsHelper; if (th != null) { for (ShardResponse srsp : sreq.responses) { th.parse((NamedList) srsp.getSolrResponse().getResponse().get("terms")); } } } @Override public void finishStage(ResponseBuilder rb) { if (!rb.doTerms || rb.stage != ResponseBuilder.STAGE_EXECUTE_QUERY) { return; } TermsHelper ti = rb._termsHelper; NamedList terms = ti.buildResponse(); rb.rsp.add("terms", terms); rb._termsHelper = null; } private ShardRequest createShardQuery(SolrParams params) { ShardRequest sreq = new ShardRequest(); sreq.purpose = ShardRequest.PURPOSE_GET_TERMS; // base shard request on original parameters sreq.params = new ModifiableSolrParams(params); // don't pass through the shards param sreq.params.remove(ShardParams.SHARDS); // remove any limits for shards, we want them to return all possible // responses // we want this so we can calculate the correct counts // dont sort by count to avoid that unnecessary overhead on the shards sreq.params.remove(TermsParams.TERMS_MAXCOUNT); sreq.params.remove(TermsParams.TERMS_MINCOUNT); sreq.params.set(TermsParams.TERMS_LIMIT, -1); sreq.params.set(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_INDEX); // TODO: is there a better way to handle this? String qt = params.get(CommonParams.QT); if (qt != null) { sreq.params.add(CommonParams.QT, qt); } return sreq; } public class TermsHelper { // map to store returned terms private HashMap<String, HashMap<String, TermsResponse.Term>> fieldmap; private SolrParams params; public TermsHelper() { fieldmap = new HashMap<String, HashMap<String, TermsResponse.Term>>(5); } public void init(SolrParams params) { this.params = params; String[] fields = params.getParams(TermsParams.TERMS_FIELD); if (fields != null) { for (String field : fields) { // TODO: not sure 128 is the best starting size // It use it because that is what is used for facets fieldmap.put(field, new HashMap<String, TermsResponse.Term>(128)); } } } public void parse(NamedList terms) { // exit if there is no terms if (terms == null) { return; } TermsResponse termsResponse = new TermsResponse(terms); // loop though each field and add each term+freq to map for (String key : fieldmap.keySet()) { HashMap<String, TermsResponse.Term> termmap = fieldmap.get(key); List<TermsResponse.Term> termlist = termsResponse.getTerms(key); // skip this field if there are no terms if (termlist == null) { continue; } // loop though each term for (TermsResponse.Term tc : termlist) { String term = tc.getTerm(); if (termmap.containsKey(term)) { TermsResponse.Term oldtc = termmap.get(term); oldtc.addFrequency(tc.getFrequency()); termmap.put(term, oldtc); } else { termmap.put(term, tc); } } } } public NamedList buildResponse() { NamedList response = new SimpleOrderedMap(); // determine if we are going index or count sort boolean sort = !TermsParams.TERMS_SORT_INDEX.equals(params.get( TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); // init minimum frequency long freqmin = 1; String s = params.get(TermsParams.TERMS_MINCOUNT); if (s != null) freqmin = Long.parseLong(s); // init maximum frequency, default to max int long freqmax = -1; s = params.get(TermsParams.TERMS_MAXCOUNT); if (s != null) freqmax = Long.parseLong(s); if (freqmax < 0) { freqmax = Long.MAX_VALUE; } // init limit, default to max int long limit = 10; s = params.get(TermsParams.TERMS_LIMIT); if (s != null) limit = Long.parseLong(s); if (limit < 0) { limit = Long.MAX_VALUE; } // loop though each field we want terms from for (String key : fieldmap.keySet()) { NamedList fieldterms = new SimpleOrderedMap(); TermsResponse.Term[] data = null; if (sort) { data = getCountSorted(fieldmap.get(key)); } else { data = getLexSorted(fieldmap.get(key)); } // loop though each term until we hit limit int cnt = 0; for (TermsResponse.Term tc : data) { if (tc.getFrequency() >= freqmin && tc.getFrequency() <= freqmax) { fieldterms.add(tc.getTerm(), num(tc.getFrequency())); cnt++; } if (cnt >= limit) { break; } } response.add(key, fieldterms); } return response; } // use <int> tags for smaller facet counts (better back compatibility) private Number num(long val) { if (val < Integer.MAX_VALUE) return (int) val; else return val; } // based on code from facets public TermsResponse.Term[] getLexSorted(HashMap<String, TermsResponse.Term> data) { TermsResponse.Term[] arr = data.values().toArray(new TermsResponse.Term[data.size()]); Arrays.sort(arr, new Comparator<TermsResponse.Term>() { public int compare(TermsResponse.Term o1, TermsResponse.Term o2) { return o1.getTerm().compareTo(o2.getTerm()); } }); return arr; } // based on code from facets public TermsResponse.Term[] getCountSorted(HashMap<String, TermsResponse.Term> data) { TermsResponse.Term[] arr = data.values().toArray(new TermsResponse.Term[data.size()]); Arrays.sort(arr, new Comparator<TermsResponse.Term>() { public int compare(TermsResponse.Term o1, TermsResponse.Term o2) { long freq1 = o1.getFrequency(); long freq2 = o2.getFrequency(); if (freq2 < freq1) { return -1; } else if (freq1 < freq2) { return 1; } else { return o1.getTerm().compareTo(o2.getTerm()); } } }); return arr; } } public String getVersion() { return "$Revision$"; } public String getSourceId() { return "$Id$"; } public String getSource() { return "$URL$"; } public String getDescription() { return "A Component for working with Term Enumerators"; } }
true
true
public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); Terms terms = lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } }
public void process(ResponseBuilder rb) throws IOException { SolrParams params = rb.req.getParams(); if (!params.getBool(TermsParams.TERMS, false)) return; String[] fields = params.getParams(TermsParams.TERMS_FIELD); NamedList termsResult = new SimpleOrderedMap(); rb.rsp.add("terms", termsResult); if (fields == null || fields.length==0) return; int limit = params.getInt(TermsParams.TERMS_LIMIT, 10); if (limit < 0) { limit = Integer.MAX_VALUE; } String lowerStr = params.get(TermsParams.TERMS_LOWER); String upperStr = params.get(TermsParams.TERMS_UPPER); boolean upperIncl = params.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); boolean lowerIncl = params.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); boolean sort = !TermsParams.TERMS_SORT_INDEX.equals( params.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT)); int freqmin = params.getInt(TermsParams.TERMS_MINCOUNT, 1); int freqmax = params.getInt(TermsParams.TERMS_MAXCOUNT, UNLIMITED_MAX_COUNT); if (freqmax<0) { freqmax = Integer.MAX_VALUE; } String prefix = params.get(TermsParams.TERMS_PREFIX_STR); String regexp = params.get(TermsParams.TERMS_REGEXP_STR); Pattern pattern = regexp != null ? Pattern.compile(regexp, resolveRegexpFlags(params)) : null; boolean raw = params.getBool(TermsParams.TERMS_RAW, false); SolrIndexReader sr = rb.req.getSearcher().getReader(); Fields lfields = MultiFields.getFields(sr); for (String field : fields) { NamedList fieldTerms = new NamedList(); termsResult.add(field, fieldTerms); Terms terms = lfields == null ? null : lfields.terms(field); if (terms == null) { // no terms for this field continue; } FieldType ft = raw ? null : rb.req.getSchema().getFieldTypeNoEx(field); if (ft==null) ft = new StrField(); // prefix must currently be text BytesRef prefixBytes = prefix==null ? null : new BytesRef(prefix); BytesRef upperBytes = null; if (upperStr != null) { upperBytes = new BytesRef(); ft.readableToIndexed(upperStr, upperBytes); } BytesRef lowerBytes; if (lowerStr == null) { // If no lower bound was specified, use the prefix lowerBytes = prefixBytes; } else { lowerBytes = new BytesRef(); if (raw) { // TODO: how to handle binary? perhaps we don't for "raw"... or if the field exists // perhaps we detect if the FieldType is non-character and expect hex if so? lowerBytes = new BytesRef(lowerStr); } else { lowerBytes = new BytesRef(); ft.readableToIndexed(lowerStr, lowerBytes); } } TermsEnum termsEnum = terms.iterator(); BytesRef term = null; if (lowerBytes != null) { if (termsEnum.seek(lowerBytes, true) == TermsEnum.SeekStatus.END) { termsEnum = null; } else { term = termsEnum.term(); //Only advance the enum if we are excluding the lower bound and the lower Term actually matches if (lowerIncl == false && term.equals(lowerBytes)) { term = termsEnum.next(); } } } else { // position termsEnum on first term term = termsEnum.next(); } int i = 0; BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null); CharArr external = new CharArr(); while (term != null && (i<limit || sort)) { boolean externalized = false; // did we fill in "external" yet for this term? // stop if the prefix doesn't match if (prefixBytes != null && !term.startsWith(prefixBytes)) break; if (pattern != null) { // indexed text or external text? // TODO: support "raw" mode? external.reset(); ft.indexedToReadable(term, external); if (!pattern.matcher(external).matches()) { term = termsEnum.next(); continue; } } if (upperBytes != null) { int upperCmp = term.compareTo(upperBytes); // if we are past the upper term, or equal to it (when don't include upper) then stop. if (upperCmp>0 || (upperCmp==0 && !upperIncl)) break; } // This is a good term in the range. Check if mincount/maxcount conditions are satisfied. int docFreq = termsEnum.docFreq(); if (docFreq >= freqmin && docFreq <= freqmax) { // add the term to the list if (sort) { queue.add(new CountPair<BytesRef, Integer>(new BytesRef(term), docFreq)); } else { // TODO: handle raw somehow if (!externalized) { external.reset(); ft.indexedToReadable(term, external); } String label = external.toString(); fieldTerms.add(label, docFreq); i++; } } term = termsEnum.next(); } if (sort) { for (CountPair<BytesRef, Integer> item : queue) { if (i >= limit) break; external.reset(); ft.indexedToReadable(item.key, external); fieldTerms.add(external.toString(), item.val); i++; } } } }
diff --git a/src/com/android/phone/CallNotifier.java b/src/com/android/phone/CallNotifier.java index f67d7a76..4f28c712 100755 --- a/src/com/android/phone/CallNotifier.java +++ b/src/com/android/phone/CallNotifier.java @@ -1,2127 +1,2127 @@ /* * Copyright (C) 2006 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.internal.telephony.Call; import com.android.internal.telephony.CallerInfo; import com.android.internal.telephony.CallerInfoAsyncQuery; import com.android.internal.telephony.cdma.CdmaCallWaitingNotification; import com.android.internal.telephony.cdma.SignalToneUtil; import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaDisplayInfoRec; import com.android.internal.telephony.cdma.CdmaInformationRecords.CdmaSignalInfoRec; import com.android.internal.telephony.Connection; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneBase; import com.android.internal.telephony.CallManager; import android.app.ActivityManagerNative; import android.content.Context; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.AsyncResult; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.os.SystemProperties; import android.os.Vibrator; import android.provider.CallLog.Calls; import android.provider.Settings; import android.telephony.PhoneNumberUtils; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; /** * Phone app module that listens for phone state changes and various other * events from the telephony layer, and triggers any resulting UI behavior * (like starting the Ringer and Incoming Call UI, playing in-call tones, * updating notifications, writing call log entries, etc.) */ public class CallNotifier extends Handler implements CallerInfoAsyncQuery.OnQueryCompleteListener { private static final String LOG_TAG = "CallNotifier"; private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1); private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2); // Maximum time we allow the CallerInfo query to run, // before giving up and falling back to the default ringtone. private static final int RINGTONE_QUERY_WAIT_TIME = 500; // msec // Timers related to CDMA Call Waiting // 1) For displaying Caller Info // 2) For disabling "Add Call" menu option once User selects Ignore or CW Timeout occures private static final int CALLWAITING_CALLERINFO_DISPLAY_TIME = 20000; // msec private static final int CALLWAITING_ADDCALL_DISABLE_TIME = 30000; // msec // Time to display the DisplayInfo Record sent by CDMA network private static final int DISPLAYINFO_NOTIFICATION_TIME = 2000; // msec /** The singleton instance. */ private static CallNotifier sInstance; // Boolean to keep track of whether or not a CDMA Call Waiting call timed out. // // This is CDMA-specific, because with CDMA we *don't* get explicit // notification from the telephony layer that a call-waiting call has // stopped ringing. Instead, when a call-waiting call first comes in we // start a 20-second timer (see CALLWAITING_CALLERINFO_DISPLAY_DONE), and // if the timer expires we clean up the call and treat it as a missed call. // // If this field is true, that means that the current Call Waiting call // "timed out" and should be logged in Call Log as a missed call. If it's // false when we reach onCdmaCallWaitingReject(), we can assume the user // explicitly rejected this call-waiting call. // // This field is reset to false any time a call-waiting call first comes // in, and after cleaning up a missed call-waiting call. It's only ever // set to true when the CALLWAITING_CALLERINFO_DISPLAY_DONE timer fires. // // TODO: do we really need a member variable for this? Don't we always // know at the moment we call onCdmaCallWaitingReject() whether this is an // explicit rejection or not? // (Specifically: when we call onCdmaCallWaitingReject() from // PhoneUtils.hangupRingingCall() that means the user deliberately rejected // the call, and if we call onCdmaCallWaitingReject() because of a // CALLWAITING_CALLERINFO_DISPLAY_DONE event that means that it timed // out...) private boolean mCallWaitingTimeOut = false; // values used to track the query state private static final int CALLERINFO_QUERY_READY = 0; private static final int CALLERINFO_QUERYING = -1; // the state of the CallerInfo Query. private int mCallerInfoQueryState; // object used to synchronize access to mCallerInfoQueryState private Object mCallerInfoQueryStateGuard = new Object(); // Event used to indicate a query timeout. private static final int RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT = 100; // Events from the Phone object: private static final int PHONE_STATE_CHANGED = 1; private static final int PHONE_NEW_RINGING_CONNECTION = 2; private static final int PHONE_DISCONNECT = 3; private static final int PHONE_UNKNOWN_CONNECTION_APPEARED = 4; private static final int PHONE_INCOMING_RING = 5; private static final int PHONE_STATE_DISPLAYINFO = 6; private static final int PHONE_STATE_SIGNALINFO = 7; private static final int PHONE_CDMA_CALL_WAITING = 8; private static final int PHONE_ENHANCED_VP_ON = 9; private static final int PHONE_ENHANCED_VP_OFF = 10; private static final int PHONE_RINGBACK_TONE = 11; private static final int PHONE_RESEND_MUTE = 12; // Events generated internally: private static final int PHONE_MWI_CHANGED = 21; private static final int PHONE_BATTERY_LOW = 22; private static final int CALLWAITING_CALLERINFO_DISPLAY_DONE = 23; private static final int CALLWAITING_ADDCALL_DISABLE_TIMEOUT = 24; private static final int DISPLAYINFO_NOTIFICATION_DONE = 25; private static final int EVENT_OTA_PROVISION_CHANGE = 26; private static final int CDMA_CALL_WAITING_REJECT = 27; private static final int UPDATE_IN_CALL_NOTIFICATION = 28; // Emergency call related defines: private static final int EMERGENCY_TONE_OFF = 0; private static final int EMERGENCY_TONE_ALERT = 1; private static final int EMERGENCY_TONE_VIBRATE = 2; private PhoneApp mApplication; private CallManager mCM; private Ringer mRinger; private BluetoothHandsfree mBluetoothHandsfree; private CallLogAsync mCallLog; private boolean mSilentRingerRequested; // ToneGenerator instance for playing SignalInfo tones private ToneGenerator mSignalInfoToneGenerator; // The tone volume relative to other sounds in the stream SignalInfo private static final int TONE_RELATIVE_VOLUME_SIGNALINFO = 80; private Call.State mPreviousCdmaCallState; private boolean mVoicePrivacyState = false; private boolean mIsCdmaRedialCall = false; // Emergency call tone and vibrate: private int mIsEmergencyToneOn; private int mCurrentEmergencyToneState = EMERGENCY_TONE_OFF; private EmergencyTonePlayerVibrator mEmergencyTonePlayerVibrator; // Ringback tone player private InCallTonePlayer mInCallRingbackTonePlayer; // Call waiting tone player private InCallTonePlayer mCallWaitingTonePlayer; // Cached AudioManager private AudioManager mAudioManager; /** * Initialize the singleton CallNotifier instance. * This is only done once, at startup, from PhoneApp.onCreate(). */ /* package */ static CallNotifier init(PhoneApp app, Phone phone, Ringer ringer, BluetoothHandsfree btMgr, CallLogAsync callLog) { synchronized (CallNotifier.class) { if (sInstance == null) { sInstance = new CallNotifier(app, phone, ringer, btMgr, callLog); } else { Log.wtf(LOG_TAG, "init() called multiple times! sInstance = " + sInstance); } return sInstance; } } /** Private constructor; @see init() */ private CallNotifier(PhoneApp app, Phone phone, Ringer ringer, BluetoothHandsfree btMgr, CallLogAsync callLog) { mApplication = app; mCM = app.mCM; mCallLog = callLog; mAudioManager = (AudioManager) mApplication.getSystemService(Context.AUDIO_SERVICE); registerForNotifications(); // Instantiate the ToneGenerator for SignalInfo and CallWaiting // TODO: We probably don't need the mSignalInfoToneGenerator instance // around forever. Need to change it so as to create a ToneGenerator instance only // when a tone is being played and releases it after its done playing. try { mSignalInfoToneGenerator = new ToneGenerator(AudioManager.STREAM_VOICE_CALL, TONE_RELATIVE_VOLUME_SIGNALINFO); } catch (RuntimeException e) { Log.w(LOG_TAG, "CallNotifier: Exception caught while creating " + "mSignalInfoToneGenerator: " + e); mSignalInfoToneGenerator = null; } mRinger = ringer; mBluetoothHandsfree = btMgr; TelephonyManager telephonyManager = (TelephonyManager)app.getSystemService( Context.TELEPHONY_SERVICE); telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR | PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR); } @Override public void handleMessage(Message msg) { switch (msg.what) { case PHONE_NEW_RINGING_CONNECTION: if (DBG) log("RINGING... (new)"); onNewRingingConnection((AsyncResult) msg.obj); mSilentRingerRequested = false; break; case PHONE_INCOMING_RING: // repeat the ring when requested by the RIL, and when the user has NOT // specifically requested silence. if (msg.obj != null && ((AsyncResult) msg.obj).result != null) { PhoneBase pb = (PhoneBase)((AsyncResult)msg.obj).result; if ((pb.getState() == Phone.State.RINGING) && (mSilentRingerRequested == false)) { if (DBG) log("RINGING... (PHONE_INCOMING_RING event)"); mRinger.ring(); } else { if (DBG) log("RING before NEW_RING, skipping"); } } break; case PHONE_STATE_CHANGED: onPhoneStateChanged((AsyncResult) msg.obj); break; case PHONE_DISCONNECT: if (DBG) log("DISCONNECT"); onDisconnect((AsyncResult) msg.obj); break; case PHONE_UNKNOWN_CONNECTION_APPEARED: onUnknownConnectionAppeared((AsyncResult) msg.obj); break; case RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT: // CallerInfo query is taking too long! But we can't wait // any more, so start ringing NOW even if it means we won't // use the correct custom ringtone. Log.w(LOG_TAG, "CallerInfo query took too long; manually starting ringer"); // In this case we call onCustomRingQueryComplete(), just // like if the query had completed normally. (But we're // going to get the default ringtone, since we never got // the chance to call Ringer.setCustomRingtoneUri()). onCustomRingQueryComplete(); break; case PHONE_MWI_CHANGED: onMwiChanged(mApplication.phone.getMessageWaitingIndicator()); break; case PHONE_BATTERY_LOW: onBatteryLow(); break; case PHONE_CDMA_CALL_WAITING: if (DBG) log("Received PHONE_CDMA_CALL_WAITING event"); onCdmaCallWaiting((AsyncResult) msg.obj); break; case CDMA_CALL_WAITING_REJECT: Log.i(LOG_TAG, "Received CDMA_CALL_WAITING_REJECT event"); onCdmaCallWaitingReject(); break; case CALLWAITING_CALLERINFO_DISPLAY_DONE: Log.i(LOG_TAG, "Received CALLWAITING_CALLERINFO_DISPLAY_DONE event"); mCallWaitingTimeOut = true; onCdmaCallWaitingReject(); break; case CALLWAITING_ADDCALL_DISABLE_TIMEOUT: if (DBG) log("Received CALLWAITING_ADDCALL_DISABLE_TIMEOUT event ..."); // Set the mAddCallMenuStateAfterCW state to true mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true); mApplication.updateInCallScreen(); break; case PHONE_STATE_DISPLAYINFO: if (DBG) log("Received PHONE_STATE_DISPLAYINFO event"); onDisplayInfo((AsyncResult) msg.obj); break; case PHONE_STATE_SIGNALINFO: if (DBG) log("Received PHONE_STATE_SIGNALINFO event"); onSignalInfo((AsyncResult) msg.obj); break; case DISPLAYINFO_NOTIFICATION_DONE: if (DBG) log("Received Display Info notification done event ..."); CdmaDisplayInfo.dismissDisplayInfoRecord(); break; case EVENT_OTA_PROVISION_CHANGE: if (DBG) log("EVENT_OTA_PROVISION_CHANGE..."); mApplication.handleOtaspEvent(msg); break; case PHONE_ENHANCED_VP_ON: if (DBG) log("PHONE_ENHANCED_VP_ON..."); if (!mVoicePrivacyState) { int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY; new InCallTonePlayer(toneToPlay).start(); mVoicePrivacyState = true; // Update the VP icon: if (DBG) log("- updating notification for VP state..."); NotificationMgr.getDefault().updateInCallNotification(); } break; case PHONE_ENHANCED_VP_OFF: if (DBG) log("PHONE_ENHANCED_VP_OFF..."); if (mVoicePrivacyState) { int toneToPlay = InCallTonePlayer.TONE_VOICE_PRIVACY; new InCallTonePlayer(toneToPlay).start(); mVoicePrivacyState = false; // Update the VP icon: if (DBG) log("- updating notification for VP state..."); NotificationMgr.getDefault().updateInCallNotification(); } break; case PHONE_RINGBACK_TONE: onRingbackTone((AsyncResult) msg.obj); break; case PHONE_RESEND_MUTE: onResendMute(); break; case UPDATE_IN_CALL_NOTIFICATION: NotificationMgr.getDefault().updateInCallNotification(); break; default: // super.handleMessage(msg); } } PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onMessageWaitingIndicatorChanged(boolean mwi) { onMwiChanged(mwi); } @Override public void onCallForwardingIndicatorChanged(boolean cfi) { onCfiChanged(cfi); } }; /** * Handles a "new ringing connection" event from the telephony layer. */ private void onNewRingingConnection(AsyncResult r) { Connection c = (Connection) r.result; if (DBG) log("onNewRingingConnection(): " + c); Call ringing = c.getCall(); Phone phone = ringing.getPhone(); // Check for a few cases where we totally ignore incoming calls. if (ignoreAllIncomingCalls(phone)) { // Immediately reject the call, without even indicating to the user // that an incoming call occurred. (This will generally send the // caller straight to voicemail, just as if we *had* shown the // incoming-call UI and the user had declined the call.) PhoneUtils.hangupRingingCall(ringing); return; } if (c == null) { Log.w(LOG_TAG, "CallNotifier.onNewRingingConnection(): null connection!"); // Should never happen, but if it does just bail out and do nothing. return; } if (!c.isRinging()) { Log.i(LOG_TAG, "CallNotifier.onNewRingingConnection(): connection not ringing!"); // This is a very strange case: an incoming call that stopped // ringing almost instantly after the onNewRingingConnection() // event. There's nothing we can do here, so just bail out // without doing anything. (But presumably we'll log it in // the call log when the disconnect event comes in...) return; } // Stop any signalInfo tone being played on receiving a Call stopSignalInfoTone(); Call.State state = c.getState(); // State will be either INCOMING or WAITING. if (VDBG) log("- connection is ringing! state = " + state); // if (DBG) PhoneUtils.dumpCallState(mPhone); // No need to do any service state checks here (like for // "emergency mode"), since in those states the SIM won't let // us get incoming connections in the first place. // TODO: Consider sending out a serialized broadcast Intent here // (maybe "ACTION_NEW_INCOMING_CALL"), *before* starting the // ringer and going to the in-call UI. The intent should contain // the caller-id info for the current connection, and say whether // it would be a "call waiting" call or a regular ringing call. // If anybody consumed the broadcast, we'd bail out without // ringing or bringing up the in-call UI. // // This would give 3rd party apps a chance to listen for (and // intercept) new ringing connections. An app could reject the // incoming call by consuming the broadcast and doing nothing, or // it could "pick up" the call (without any action by the user!) // via some future TelephonyManager API. // // See bug 1312336 for more details. // We'd need to protect this with a new "intercept incoming calls" // system permission. // Obtain a partial wake lock to make sure the CPU doesn't go to // sleep before we finish bringing up the InCallScreen. // (This will be upgraded soon to a full wake lock; see // showIncomingCall().) if (VDBG) log("Holding wake lock on new incoming connection."); mApplication.requestWakeState(PhoneApp.WakeState.PARTIAL); // - don't ring for call waiting connections // - do this before showing the incoming call panel if (PhoneUtils.isRealIncomingCall(state)) { startIncomingCallQuery(c); } else { if (VDBG) log("- starting call waiting tone..."); if (mCallWaitingTonePlayer == null) { mCallWaitingTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_CALL_WAITING); mCallWaitingTonePlayer.start(); } // in this case, just fall through like before, and call // showIncomingCall(). if (DBG) log("- showing incoming call (this is a WAITING call)..."); showIncomingCall(); } // Note we *don't* post a status bar notification here, since // we're not necessarily ready to actually show the incoming call // to the user. (For calls in the INCOMING state, at least, we // still need to run a caller-id query, and we may not even ring // at all if the "send directly to voicemail" flag is set.) // // Instead, we update the notification (and potentially launch the // InCallScreen) from the showIncomingCall() method, which runs // when the caller-id query completes or times out. if (VDBG) log("- onNewRingingConnection() done."); } /** * Determines whether or not we're allowed to present incoming calls to the * user, based on the capabilities and/or current state of the device. * * If this method returns true, that means we should immediately reject the * current incoming call, without even indicating to the user that an * incoming call occurred. * * (We only reject incoming calls in a few cases, like during an OTASP call * when we can't interrupt the user, or if the device hasn't completed the * SetupWizard yet. We also don't allow incoming calls on non-voice-capable * devices. But note that we *always* allow incoming calls while in ECM.) * * @return true if we're *not* allowed to present an incoming call to * the user. */ private boolean ignoreAllIncomingCalls(Phone phone) { // Incoming calls are totally ignored on non-voice-capable devices. if (!PhoneApp.sVoiceCapable) { // ...but still log a warning, since we shouldn't have gotten this // event in the first place! (Incoming calls *should* be blocked at // the telephony layer on non-voice-capable capable devices.) Log.w(LOG_TAG, "Got onNewRingingConnection() on non-voice-capable device! Ignoring..."); return true; } // In ECM (emergency callback mode), we ALWAYS allow incoming calls // to get through to the user. (Note that ECM is applicable only to // voice-capable CDMA devices). if (PhoneUtils.isPhoneInEcm(phone)) { if (DBG) log("Incoming call while in ECM: always allow..."); return false; } // Incoming calls are totally ignored if the device isn't provisioned yet. boolean provisioned = Settings.Secure.getInt(mApplication.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0) != 0; if (!provisioned) { Log.i(LOG_TAG, "Ignoring incoming call: not provisioned"); return true; } // Incoming calls are totally ignored if an OTASP call is active. if (TelephonyCapabilities.supportsOtasp(phone)) { boolean activateState = (mApplication.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_ACTIVATION); boolean dialogState = (mApplication.cdmaOtaScreenState.otaScreenState == OtaUtils.CdmaOtaScreenState.OtaScreenState.OTA_STATUS_SUCCESS_FAILURE_DLG); boolean spcState = mApplication.cdmaOtaProvisionData.inOtaSpcState; if (spcState) { Log.i(LOG_TAG, "Ignoring incoming call: OTA call is active"); return true; } else if (activateState || dialogState) { // We *are* allowed to receive incoming calls at this point. // But clear out any residual OTASP UI first. // TODO: It's an MVC violation to twiddle the OTA UI state here; // we should instead provide a higher-level API via OtaUtils. if (dialogState) mApplication.dismissOtaDialogs(); mApplication.clearOtaState(); mApplication.clearInCallScreenMode(); return false; } } // Normal case: allow this call to be presented to the user. return false; } /** * Helper method to manage the start of incoming call queries */ private void startIncomingCallQuery(Connection c) { // TODO: cache the custom ringer object so that subsequent // calls will not need to do this query work. We can keep // the MRU ringtones in memory. We'll still need to hit // the database to get the callerinfo to act as a key, // but at least we can save the time required for the // Media player setup. The only issue with this is that // we may need to keep an eye on the resources the Media // player uses to keep these ringtones around. // make sure we're in a state where we can be ready to // query a ringtone uri. boolean shouldStartQuery = false; synchronized (mCallerInfoQueryStateGuard) { if (mCallerInfoQueryState == CALLERINFO_QUERY_READY) { mCallerInfoQueryState = CALLERINFO_QUERYING; shouldStartQuery = true; } } if (shouldStartQuery) { // create a custom ringer using the default ringer first mRinger.setCustomRingtoneUri(Settings.System.DEFAULT_RINGTONE_URI); // query the callerinfo to try to get the ringer. PhoneUtils.CallerInfoToken cit = PhoneUtils.startGetCallerInfo( mApplication, c, this, this); // if this has already been queried then just ring, otherwise // we wait for the alloted time before ringing. if (cit.isFinal) { if (VDBG) log("- CallerInfo already up to date, using available data"); onQueryComplete(0, this, cit.currentInfo); } else { if (VDBG) log("- Starting query, posting timeout message."); sendEmptyMessageDelayed(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT, RINGTONE_QUERY_WAIT_TIME); } // The call to showIncomingCall() will happen after the // queries are complete (or time out). } else { // This should never happen; its the case where an incoming call // arrives at the same time that the query is still being run, // and before the timeout window has closed. EventLog.writeEvent(EventLogTags.PHONE_UI_MULTIPLE_QUERY); // In this case, just log the request and ring. if (VDBG) log("RINGING... (request to ring arrived while query is running)"); mRinger.ring(); // in this case, just fall through like before, and call // showIncomingCall(). if (DBG) log("- showing incoming call (couldn't start query)..."); showIncomingCall(); } } /** * Performs the final steps of the onNewRingingConnection sequence: * starts the ringer, and brings up the "incoming call" UI. * * Normally, this is called when the CallerInfo query completes (see * onQueryComplete()). In this case, onQueryComplete() has already * configured the Ringer object to use the custom ringtone (if there * is one) for this caller. So we just tell the Ringer to start, and * proceed to the InCallScreen. * * But this method can *also* be called if the * RINGTONE_QUERY_WAIT_TIME timeout expires, which means that the * CallerInfo query is taking too long. In that case, we log a * warning but otherwise we behave the same as in the normal case. * (We still tell the Ringer to start, but it's going to use the * default ringtone.) */ private void onCustomRingQueryComplete() { boolean isQueryExecutionTimeExpired = false; synchronized (mCallerInfoQueryStateGuard) { if (mCallerInfoQueryState == CALLERINFO_QUERYING) { mCallerInfoQueryState = CALLERINFO_QUERY_READY; isQueryExecutionTimeExpired = true; } } if (isQueryExecutionTimeExpired) { // There may be a problem with the query here, since the // default ringtone is playing instead of the custom one. Log.w(LOG_TAG, "CallerInfo query took too long; falling back to default ringtone"); EventLog.writeEvent(EventLogTags.PHONE_UI_RINGER_QUERY_ELAPSED); } // Make sure we still have an incoming call! // // (It's possible for the incoming call to have been disconnected // while we were running the query. In that case we better not // start the ringer here, since there won't be any future // DISCONNECT event to stop it!) // // Note we don't have to worry about the incoming call going away // *after* this check but before we call mRinger.ring() below, // since in that case we *will* still get a DISCONNECT message sent // to our handler. (And we will correctly stop the ringer when we // process that event.) if (mCM.getState() != Phone.State.RINGING) { Log.i(LOG_TAG, "onCustomRingQueryComplete: No incoming call! Bailing out..."); // Don't start the ringer *or* bring up the "incoming call" UI. // Just bail out. return; } // Ring, either with the queried ringtone or default one. if (VDBG) log("RINGING... (onCustomRingQueryComplete)"); mRinger.ring(); // ...and display the incoming call to the user: if (DBG) log("- showing incoming call (custom ring query complete)..."); showIncomingCall(); } private void onUnknownConnectionAppeared(AsyncResult r) { Phone.State state = mCM.getState(); if (state == Phone.State.OFFHOOK) { // basically do onPhoneStateChanged + display the incoming call UI onPhoneStateChanged(r); if (DBG) log("- showing incoming call (unknown connection appeared)..."); showIncomingCall(); } } /** * Informs the user about a new incoming call. * * In most cases this means "bring up the full-screen incoming call * UI". However, if an immersive activity is running, the system * NotificationManager will instead pop up a small notification window * on top of the activity. * * Watch out: be sure to call this method only once per incoming call, * or otherwise we may end up launching the InCallScreen multiple * times (which can lead to slow responsiveness and/or visible * glitches.) * * Note this method handles only the onscreen UI for incoming calls; * the ringer and/or vibrator are started separately (see the various * calls to Ringer.ring() in this class.) * * @see NotificationMgr.updateNotificationAndLaunchIncomingCallUi() */ private void showIncomingCall() { if (DBG) log("showIncomingCall()..."); // Before bringing up the "incoming call" UI, force any system // dialogs (like "recent tasks" or the power dialog) to close first. try { ActivityManagerNative.getDefault().closeSystemDialogs("call"); } catch (RemoteException e) { } // Go directly to the in-call screen. // (No need to do anything special if we're already on the in-call // screen; it'll notice the phone state change and update itself.) // But first, grab a full wake lock. We do this here, before we // even fire off the InCallScreen intent, to make sure the // ActivityManager doesn't try to pause the InCallScreen as soon // as it comes up. (See bug 1648751.) // // And since the InCallScreen isn't visible yet (we haven't even // fired off the intent yet), we DON'T want the screen to actually // come on right now. So *before* acquiring the wake lock we need // to call preventScreenOn(), which tells the PowerManager that // the screen should stay off even if someone's holding a full // wake lock. (This prevents any flicker during the "incoming // call" sequence. The corresponding preventScreenOn(false) call // will come from the InCallScreen when it's finally ready to be // displayed.) // // TODO: this is all a temporary workaround. The real fix is to add // an Activity attribute saying "this Activity wants to wake up the // phone when it's displayed"; that way the ActivityManager could // manage the wake locks *and* arrange for the screen to come on at // the exact moment that the InCallScreen is ready to be displayed. // (See bug 1648751.) // // TODO: also, we should probably *not* do any of this if the // screen is already on(!) mApplication.preventScreenOn(true); mApplication.requestWakeState(PhoneApp.WakeState.FULL); // Post the "incoming call" notification *and* include the // fullScreenIntent that'll launch the incoming-call UI. // (This will usually take us straight to the incoming call // screen, but if an immersive activity is running it'll just // appear as a notification.) if (DBG) log("- updating notification from showIncomingCall()..."); NotificationMgr.getDefault().updateNotificationAndLaunchIncomingCallUi(); } /** * Updates the phone UI in response to phone state changes. * * Watch out: certain state changes are actually handled by their own * specific methods: * - see onNewRingingConnection() for new incoming calls * - see onDisconnect() for calls being hung up or disconnected */ private void onPhoneStateChanged(AsyncResult r) { Phone.State state = mCM.getState(); if (VDBG) log("onPhoneStateChanged: state = " + state); // Turn status bar notifications on or off depending upon the state // of the phone. Notification Alerts (audible or vibrating) should // be on if and only if the phone is IDLE. NotificationMgr.getDefault().getStatusBarMgr() .enableNotificationAlerts(state == Phone.State.IDLE); Phone fgPhone = mCM.getFgPhone(); if (fgPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { if ((fgPhone.getForegroundCall().getState() == Call.State.ACTIVE) && ((mPreviousCdmaCallState == Call.State.DIALING) || (mPreviousCdmaCallState == Call.State.ALERTING))) { if (mIsCdmaRedialCall) { int toneToPlay = InCallTonePlayer.TONE_REDIAL; new InCallTonePlayer(toneToPlay).start(); } // Stop any signal info tone when call moves to ACTIVE state stopSignalInfoTone(); } mPreviousCdmaCallState = fgPhone.getForegroundCall().getState(); } // Have the PhoneApp recompute its mShowBluetoothIndication // flag based on the (new) telephony state. // There's no need to force a UI update since we update the // in-call notification ourselves (below), and the InCallScreen // listens for phone state changes itself. mApplication.updateBluetoothIndication(false); // Update the proximity sensor mode (on devices that have a // proximity sensor). mApplication.updatePhoneState(state); if (state == Phone.State.OFFHOOK) { // stop call waiting tone if needed when answering if (mCallWaitingTonePlayer != null) { mCallWaitingTonePlayer.stopTone(); mCallWaitingTonePlayer = null; } if (VDBG) log("onPhoneStateChanged: OFF HOOK"); // make sure audio is in in-call mode now PhoneUtils.setAudioMode(mCM); // if the call screen is showing, let it handle the event, // otherwise handle it here. if (!mApplication.isShowingCallScreen()) { mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT); mApplication.requestWakeState(PhoneApp.WakeState.SLEEP); } // Since we're now in-call, the Ringer should definitely *not* // be ringing any more. (This is just a sanity-check; we // already stopped the ringer explicitly back in // PhoneUtils.answerCall(), before the call to phone.acceptCall().) // TODO: Confirm that this call really *is* unnecessary, and if so, // remove it! if (DBG) log("stopRing()... (OFFHOOK state)"); mRinger.stopRing(); // Post a request to update the "in-call" status bar icon. // // We don't call NotificationMgr.updateInCallNotification() // directly here, for two reasons: // (1) a single phone state change might actually trigger multiple // onPhoneStateChanged() callbacks, so this prevents redundant // updates of the notification. // (2) we suppress the status bar icon while the in-call UI is // visible (see updateInCallNotification()). But when launching // an outgoing call the phone actually goes OFFHOOK slightly // *before* the InCallScreen comes up, so the delay here avoids a // brief flicker of the icon at that point. if (DBG) log("- posting UPDATE_IN_CALL_NOTIFICATION request..."); // Remove any previous requests in the queue removeMessages(UPDATE_IN_CALL_NOTIFICATION); final int IN_CALL_NOTIFICATION_UPDATE_DELAY = 1000; // msec sendEmptyMessageDelayed(UPDATE_IN_CALL_NOTIFICATION, IN_CALL_NOTIFICATION_UPDATE_DELAY); } if (fgPhone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { Connection c = fgPhone.getForegroundCall().getLatestConnection(); if ((c != null) && (PhoneNumberUtils.isEmergencyNumber(c.getAddress()))) { if (VDBG) log("onPhoneStateChanged: it is an emergency call."); Call.State callState = fgPhone.getForegroundCall().getState(); if (mEmergencyTonePlayerVibrator == null) { mEmergencyTonePlayerVibrator = new EmergencyTonePlayerVibrator(); } if (callState == Call.State.DIALING || callState == Call.State.ALERTING) { mIsEmergencyToneOn = Settings.System.getInt( mApplication.getContentResolver(), Settings.System.EMERGENCY_TONE, EMERGENCY_TONE_OFF); if (mIsEmergencyToneOn != EMERGENCY_TONE_OFF && mCurrentEmergencyToneState == EMERGENCY_TONE_OFF) { if (mEmergencyTonePlayerVibrator != null) { mEmergencyTonePlayerVibrator.start(); } } } else if (callState == Call.State.ACTIVE) { if (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF) { if (mEmergencyTonePlayerVibrator != null) { mEmergencyTonePlayerVibrator.stop(); } } } } } if ((fgPhone.getPhoneType() == Phone.PHONE_TYPE_GSM) || (fgPhone.getPhoneType() == Phone.PHONE_TYPE_SIP)) { Call.State callState = mCM.getActiveFgCallState(); if (!callState.isDialing()) { // If call get activated or disconnected before the ringback // tone stops, we have to stop it to prevent disturbing. if (mInCallRingbackTonePlayer != null) { mInCallRingbackTonePlayer.stopTone(); mInCallRingbackTonePlayer = null; } } } } void updateCallNotifierRegistrationsAfterRadioTechnologyChange() { if (DBG) Log.d(LOG_TAG, "updateCallNotifierRegistrationsAfterRadioTechnologyChange..."); // Unregister all events from the old obsolete phone mCM.unregisterForNewRingingConnection(this); mCM.unregisterForPreciseCallStateChanged(this); mCM.unregisterForDisconnect(this); mCM.unregisterForUnknownConnection(this); mCM.unregisterForIncomingRing(this); mCM.unregisterForCallWaiting(this); mCM.unregisterForDisplayInfo(this); mCM.unregisterForSignalInfo(this); mCM.unregisterForCdmaOtaStatusChange(this); mCM.unregisterForRingbackTone(this); mCM.unregisterForResendIncallMute(this); // Release the ToneGenerator used for playing SignalInfo and CallWaiting if (mSignalInfoToneGenerator != null) { mSignalInfoToneGenerator.release(); } // Clear ringback tone player mInCallRingbackTonePlayer = null; // Clear call waiting tone player mCallWaitingTonePlayer = null; mCM.unregisterForInCallVoicePrivacyOn(this); mCM.unregisterForInCallVoicePrivacyOff(this); // Register all events new to the new active phone registerForNotifications(); } private void registerForNotifications() { mCM.registerForNewRingingConnection(this, PHONE_NEW_RINGING_CONNECTION, null); mCM.registerForPreciseCallStateChanged(this, PHONE_STATE_CHANGED, null); mCM.registerForDisconnect(this, PHONE_DISCONNECT, null); mCM.registerForUnknownConnection(this, PHONE_UNKNOWN_CONNECTION_APPEARED, null); mCM.registerForIncomingRing(this, PHONE_INCOMING_RING, null); mCM.registerForCdmaOtaStatusChange(this, EVENT_OTA_PROVISION_CHANGE, null); mCM.registerForCallWaiting(this, PHONE_CDMA_CALL_WAITING, null); mCM.registerForDisplayInfo(this, PHONE_STATE_DISPLAYINFO, null); mCM.registerForSignalInfo(this, PHONE_STATE_SIGNALINFO, null); mCM.registerForInCallVoicePrivacyOn(this, PHONE_ENHANCED_VP_ON, null); mCM.registerForInCallVoicePrivacyOff(this, PHONE_ENHANCED_VP_OFF, null); mCM.registerForRingbackTone(this, PHONE_RINGBACK_TONE, null); mCM.registerForResendIncallMute(this, PHONE_RESEND_MUTE, null); } /** * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface. * refreshes the CallCard data when it called. If called with this * class itself, it is assumed that we have been waiting for the ringtone * and direct to voicemail settings to update. */ public void onQueryComplete(int token, Object cookie, CallerInfo ci) { if (cookie instanceof Long) { if (VDBG) log("CallerInfo query complete, posting missed call notification"); NotificationMgr.getDefault().notifyMissedCall(ci.name, ci.phoneNumber, ci.phoneLabel, ((Long) cookie).longValue()); } else if (cookie instanceof CallNotifier) { if (VDBG) log("CallerInfo query complete (for CallNotifier), " + "updating state for incoming call.."); // get rid of the timeout messages removeMessages(RINGER_CUSTOM_RINGTONE_QUERY_TIMEOUT); boolean isQueryExecutionTimeOK = false; synchronized (mCallerInfoQueryStateGuard) { if (mCallerInfoQueryState == CALLERINFO_QUERYING) { mCallerInfoQueryState = CALLERINFO_QUERY_READY; isQueryExecutionTimeOK = true; } } //if we're in the right state if (isQueryExecutionTimeOK) { // send directly to voicemail. if (ci.shouldSendToVoicemail) { if (DBG) log("send to voicemail flag detected. hanging up."); PhoneUtils.hangupRingingCall(mCM.getFirstActiveRingingCall()); return; } // set the ringtone uri to prepare for the ring. if (ci.contactRingtoneUri != null) { if (DBG) log("custom ringtone found, setting up ringer."); Ringer r = ((CallNotifier) cookie).mRinger; r.setCustomRingtoneUri(ci.contactRingtoneUri); } // ring, and other post-ring actions. onCustomRingQueryComplete(); } } } private void onDisconnect(AsyncResult r) { if (VDBG) log("onDisconnect()... CallManager state: " + mCM.getState()); mVoicePrivacyState = false; Connection c = (Connection) r.result; if (c != null) { Log.d(LOG_TAG, "onDisconnect: cause = " + c.getDisconnectCause() + ", incoming = " + c.isIncoming() + ", date = " + c.getCreateTime()); } else { Log.w(LOG_TAG, "onDisconnect: null connection"); } int autoretrySetting = 0; if ((c != null) && (c.getCall().getPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA)) { autoretrySetting = android.provider.Settings.System.getInt(mApplication. getContentResolver(),android.provider.Settings.System.CALL_AUTO_RETRY, 0); } // Stop any signalInfo tone being played when a call gets ended stopSignalInfoTone(); if ((c != null) && (c.getCall().getPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA)) { // Resetting the CdmaPhoneCallState members mApplication.cdmaPhoneCallState.resetCdmaPhoneCallState(); // Remove Call waiting timers removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE); removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT); } // Stop the ringer if it was ringing (for an incoming call that // either disconnected by itself, or was rejected by the user.) // // TODO: We technically *shouldn't* stop the ringer if the // foreground or background call disconnects while an incoming call // is still ringing, but that's a really rare corner case. // It's safest to just unconditionally stop the ringer here. // CDMA: For Call collision cases i.e. when the user makes an out going call // and at the same time receives an Incoming Call, the Incoming Call is given // higher preference. At this time framework sends a disconnect for the Out going // call connection hence we should *not* be stopping the ringer being played for // the Incoming Call Call ringingCall = mCM.getFirstActiveRingingCall(); if (ringingCall.getPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA) { if (PhoneUtils.isRealIncomingCall(ringingCall.getState())) { // Also we need to take off the "In Call" icon from the Notification // area as the Out going Call never got connected if (DBG) log("cancelCallInProgressNotifications()... (onDisconnect)"); NotificationMgr.getDefault().cancelCallInProgressNotifications(); } else { if (DBG) log("stopRing()... (onDisconnect)"); mRinger.stopRing(); } } else { // GSM if (DBG) log("stopRing()... (onDisconnect)"); mRinger.stopRing(); } // stop call waiting tone if needed when disconnecting if (mCallWaitingTonePlayer != null) { mCallWaitingTonePlayer.stopTone(); mCallWaitingTonePlayer = null; } // If this is the end of an OTASP call, pass it on to the PhoneApp. if (c != null && TelephonyCapabilities.supportsOtasp(c.getCall().getPhone())) { final String number = c.getAddress(); if (c.getCall().getPhone().isOtaSpNumber(number)) { if (DBG) log("onDisconnect: this was an OTASP call!"); mApplication.handleOtaspDisconnect(); } } // Check for the various tones we might need to play (thru the // earpiece) after a call disconnects. int toneToPlay = InCallTonePlayer.TONE_NONE; // The "Busy" or "Congestion" tone is the highest priority: if (c != null) { Connection.DisconnectCause cause = c.getDisconnectCause(); if (cause == Connection.DisconnectCause.BUSY) { if (DBG) log("- need to play BUSY tone!"); toneToPlay = InCallTonePlayer.TONE_BUSY; } else if (cause == Connection.DisconnectCause.CONGESTION) { if (DBG) log("- need to play CONGESTION tone!"); toneToPlay = InCallTonePlayer.TONE_CONGESTION; } else if (((cause == Connection.DisconnectCause.NORMAL) || (cause == Connection.DisconnectCause.LOCAL)) && (mApplication.isOtaCallInActiveState())) { if (DBG) log("- need to play OTA_CALL_END tone!"); toneToPlay = InCallTonePlayer.TONE_OTA_CALL_END; } else if (cause == Connection.DisconnectCause.CDMA_REORDER) { if (DBG) log("- need to play CDMA_REORDER tone!"); toneToPlay = InCallTonePlayer.TONE_REORDER; } else if (cause == Connection.DisconnectCause.CDMA_INTERCEPT) { if (DBG) log("- need to play CDMA_INTERCEPT tone!"); toneToPlay = InCallTonePlayer.TONE_INTERCEPT; } else if (cause == Connection.DisconnectCause.CDMA_DROP) { if (DBG) log("- need to play CDMA_DROP tone!"); toneToPlay = InCallTonePlayer.TONE_CDMA_DROP; } else if (cause == Connection.DisconnectCause.OUT_OF_SERVICE) { if (DBG) log("- need to play OUT OF SERVICE tone!"); toneToPlay = InCallTonePlayer.TONE_OUT_OF_SERVICE; } else if (cause == Connection.DisconnectCause.UNOBTAINABLE_NUMBER) { if (DBG) log("- need to play TONE_UNOBTAINABLE_NUMBER tone!"); toneToPlay = InCallTonePlayer.TONE_UNOBTAINABLE_NUMBER; } else if (cause == Connection.DisconnectCause.ERROR_UNSPECIFIED) { if (DBG) log("- DisconnectCause is ERROR_UNSPECIFIED: play TONE_CALL_ENDED!"); toneToPlay = InCallTonePlayer.TONE_CALL_ENDED; } } // If we don't need to play BUSY or CONGESTION, then play the // "call ended" tone if this was a "regular disconnect" (i.e. a // normal call where one end or the other hung up) *and* this // disconnect event caused the phone to become idle. (In other // words, we *don't* play the sound if one call hangs up but // there's still an active call on the other line.) // TODO: We may eventually want to disable this via a preference. if ((toneToPlay == InCallTonePlayer.TONE_NONE) && (mCM.getState() == Phone.State.IDLE) && (c != null)) { Connection.DisconnectCause cause = c.getDisconnectCause(); if ((cause == Connection.DisconnectCause.NORMAL) // remote hangup || (cause == Connection.DisconnectCause.LOCAL)) { // local hangup if (VDBG) log("- need to play CALL_ENDED tone!"); toneToPlay = InCallTonePlayer.TONE_CALL_ENDED; mIsCdmaRedialCall = false; } } if (mCM.getState() == Phone.State.IDLE) { // Don't reset the audio mode or bluetooth/speakerphone state // if we still need to let the user hear a tone through the earpiece. if (toneToPlay == InCallTonePlayer.TONE_NONE) { resetAudioStateAfterDisconnect(); } NotificationMgr.getDefault().cancelCallInProgressNotifications(); // If the InCallScreen is *not* in the foreground, forcibly // dismiss it to make sure it won't still be in the activity // history. (But if it *is* in the foreground, don't mess // with it; it needs to be visible, displaying the "Call // ended" state.) if (!mApplication.isShowingCallScreen()) { if (VDBG) log("onDisconnect: force InCallScreen to finish()"); mApplication.dismissCallScreen(); } else { if (VDBG) log("onDisconnect: In call screen. Set short timeout."); mApplication.clearUserActivityTimeout(); } } if (c != null) { final String number = c.getAddress(); final long date = c.getCreateTime(); final long duration = c.getDurationMillis(); final Connection.DisconnectCause cause = c.getDisconnectCause(); final Phone phone = c.getCall().getPhone(); // Set the "type" to be displayed in the call log (see constants in CallLog.Calls) final int callLogType; if (c.isIncoming()) { callLogType = (cause == Connection.DisconnectCause.INCOMING_MISSED ? Calls.MISSED_TYPE : Calls.INCOMING_TYPE); } else { callLogType = Calls.OUTGOING_TYPE; } if (VDBG) log("- callLogType: " + callLogType + ", UserData: " + c.getUserData()); { final CallerInfo ci = getCallerInfoFromConnection(c); // May be null. final String logNumber = getLogNumber(c, ci); if (DBG) log("- onDisconnect(): logNumber set to: " + /*logNumber*/ "xxxxxxx"); // TODO: In getLogNumber we use the presentation from // the connection for the CNAP. Should we use the one // below instead? (comes from caller info) // For international calls, 011 needs to be logged as + final int presentation = getPresentation(c, ci); if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) { if ((PhoneNumberUtils.isEmergencyNumber(number)) && (mCurrentEmergencyToneState != EMERGENCY_TONE_OFF)) { if (mEmergencyTonePlayerVibrator != null) { mEmergencyTonePlayerVibrator.stop(); } } } // On some devices, to avoid accidental redialing of // emergency numbers, we *never* log emergency calls to // the Call Log. (This behavior is set on a per-product // basis, based on carrier requirements.) final boolean okToLogEmergencyNumber = mApplication.getResources().getBoolean( R.bool.allow_emergency_numbers_in_call_log); // Don't call isOtaSpNumber() on phones that don't support OTASP. final boolean isOtaspNumber = TelephonyCapabilities.supportsOtasp(phone) && phone.isOtaSpNumber(number); final boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(number); // Don't log emergency numbers if the device doesn't allow it, // and never log OTASP calls. final boolean okToLogThisCall = (!isEmergencyNumber || okToLogEmergencyNumber) && !isOtaspNumber; if (okToLogThisCall) { CallLogAsync.AddCallArgs args = new CallLogAsync.AddCallArgs( mApplication, ci, logNumber, presentation, callLogType, date, duration); mCallLog.addCall(args); } } if (callLogType == Calls.MISSED_TYPE) { // Show the "Missed call" notification. // (Note we *don't* do this if this was an incoming call that // the user deliberately rejected.) showMissedCallNotification(c, date); } // Possibly play a "post-disconnect tone" thru the earpiece. // We do this here, rather than from the InCallScreen // activity, since we need to do this even if you're not in // the Phone UI at the moment the connection ends. if (toneToPlay != InCallTonePlayer.TONE_NONE) { if (VDBG) log("- starting post-disconnect tone (" + toneToPlay + ")..."); new InCallTonePlayer(toneToPlay).start(); // TODO: alternatively, we could start an InCallTonePlayer // here with an "unlimited" tone length, // and manually stop it later when this connection truly goes // away. (The real connection over the network was closed as soon // as we got the BUSY message. But our telephony layer keeps the // connection open for a few extra seconds so we can show the // "busy" indication to the user. We could stop the busy tone // when *that* connection's "disconnect" event comes in.) } if (mCM.getState() == Phone.State.IDLE) { // Release screen wake locks if the in-call screen is not // showing. Otherwise, let the in-call screen handle this because // it needs to show the call ended screen for a couple of // seconds. if (!mApplication.isShowingCallScreen()) { if (VDBG) log("- NOT showing in-call screen; releasing wake locks!"); mApplication.setScreenTimeout(PhoneApp.ScreenTimeoutDuration.DEFAULT); mApplication.requestWakeState(PhoneApp.WakeState.SLEEP); } else { if (VDBG) log("- still showing in-call screen; not releasing wake locks."); } } else { if (VDBG) log("- phone still in use; not releasing wake locks."); } if (((mPreviousCdmaCallState == Call.State.DIALING) || (mPreviousCdmaCallState == Call.State.ALERTING)) && (!PhoneNumberUtils.isEmergencyNumber(number)) && (cause != Connection.DisconnectCause.INCOMING_MISSED ) && (cause != Connection.DisconnectCause.NORMAL) && (cause != Connection.DisconnectCause.LOCAL) && (cause != Connection.DisconnectCause.INCOMING_REJECTED)) { if (!mIsCdmaRedialCall) { if (autoretrySetting == InCallScreen.AUTO_RETRY_ON) { // TODO: (Moto): The contact reference data may need to be stored and use // here when redialing a call. For now, pass in NULL as the URI parameter. PhoneUtils.placeCall(mApplication, phone, number, null, false, null); mIsCdmaRedialCall = true; } else { mIsCdmaRedialCall = false; } } else { mIsCdmaRedialCall = false; } } } } /** * Resets the audio mode and speaker state when a call ends. */ private void resetAudioStateAfterDisconnect() { if (VDBG) log("resetAudioStateAfterDisconnect()..."); if (mBluetoothHandsfree != null) { mBluetoothHandsfree.audioOff(); } // call turnOnSpeaker() with state=false and store=true even if speaker // is already off to reset user requested speaker state. PhoneUtils.turnOnSpeaker(mApplication, false, true); PhoneUtils.setAudioMode(mCM); } private void onMwiChanged(boolean visible) { if (VDBG) log("onMwiChanged(): " + visible); // "Voicemail" is meaningless on non-voice-capable devices, // so ignore MWI events. if (!PhoneApp.sVoiceCapable) { // ...but still log a warning, since we shouldn't have gotten this // event in the first place! // (PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR events // *should* be blocked at the telephony layer on non-voice-capable // capable devices.) Log.w(LOG_TAG, "Got onMwiChanged() on non-voice-capable device! Ignoring..."); return; } NotificationMgr.getDefault().updateMwi(visible); } /** * Posts a delayed PHONE_MWI_CHANGED event, to schedule a "retry" for a * failed NotificationMgr.updateMwi() call. */ /* package */ void sendMwiChangedDelayed(long delayMillis) { Message message = Message.obtain(this, PHONE_MWI_CHANGED); sendMessageDelayed(message, delayMillis); } private void onCfiChanged(boolean visible) { if (VDBG) log("onCfiChanged(): " + visible); NotificationMgr.getDefault().updateCfi(visible); } /** * Indicates whether or not this ringer is ringing. */ boolean isRinging() { return mRinger.isRinging(); } /** * Stops the current ring, and tells the notifier that future * ring requests should be ignored. */ void silenceRinger() { mSilentRingerRequested = true; if (DBG) log("stopRing()... (silenceRinger)"); mRinger.stopRing(); } /** * Restarts the ringer after having previously silenced it. * * (This is a no-op if the ringer is actually still ringing, or if the * incoming ringing call no longer exists.) */ /* package */ void restartRinger() { if (DBG) log("restartRinger()..."); if (isRinging()) return; // Already ringing; no need to restart. final Call ringingCall = mCM.getFirstActiveRingingCall(); // Don't check ringingCall.isRinging() here, since that'll be true // for the WAITING state also. We only allow the ringer for // regular INCOMING calls. if (DBG) log("- ringingCall state: " + ringingCall.getState()); if (ringingCall.getState() == Call.State.INCOMING) { mRinger.ring(); } } /** * Posts a PHONE_BATTERY_LOW event, causing us to play a warning * tone if the user is in-call. */ /* package */ void sendBatteryLow() { Message message = Message.obtain(this, PHONE_BATTERY_LOW); sendMessage(message); } private void onBatteryLow() { if (DBG) log("onBatteryLow()..."); // A "low battery" warning tone is now played by // StatusBarPolicy.updateBattery(). } /** * Helper class to play tones through the earpiece (or speaker / BT) * during a call, using the ToneGenerator. * * To use, just instantiate a new InCallTonePlayer * (passing in the TONE_* constant for the tone you want) * and start() it. * * When we're done playing the tone, if the phone is idle at that * point, we'll reset the audio routing and speaker state. * (That means that for tones that get played *after* a call * disconnects, like "busy" or "congestion" or "call ended", you * should NOT call resetAudioStateAfterDisconnect() yourself. * Instead, just start the InCallTonePlayer, which will automatically * defer the resetAudioStateAfterDisconnect() call until the tone * finishes playing.) */ private class InCallTonePlayer extends Thread { private int mToneId; private int mState; // The possible tones we can play. public static final int TONE_NONE = 0; public static final int TONE_CALL_WAITING = 1; public static final int TONE_BUSY = 2; public static final int TONE_CONGESTION = 3; public static final int TONE_BATTERY_LOW = 4; public static final int TONE_CALL_ENDED = 5; public static final int TONE_VOICE_PRIVACY = 6; public static final int TONE_REORDER = 7; public static final int TONE_INTERCEPT = 8; public static final int TONE_CDMA_DROP = 9; public static final int TONE_OUT_OF_SERVICE = 10; public static final int TONE_REDIAL = 11; public static final int TONE_OTA_CALL_END = 12; public static final int TONE_RING_BACK = 13; public static final int TONE_UNOBTAINABLE_NUMBER = 14; // The tone volume relative to other sounds in the stream private static final int TONE_RELATIVE_VOLUME_HIPRI = 80; private static final int TONE_RELATIVE_VOLUME_LOPRI = 50; // Buffer time (in msec) to add on to tone timeout value. // Needed mainly when the timeout value for a tone is the // exact duration of the tone itself. private static final int TONE_TIMEOUT_BUFFER = 20; // The tone state private static final int TONE_OFF = 0; private static final int TONE_ON = 1; private static final int TONE_STOPPED = 2; InCallTonePlayer(int toneId) { super(); mToneId = toneId; mState = TONE_OFF; } @Override public void run() { - if (VDBG) log("InCallTonePlayer.run(toneId = " + mToneId + ")..."); + log("InCallTonePlayer.run(toneId = " + mToneId + ")..."); int toneType = 0; // passed to ToneGenerator.startTone() int toneVolume; // passed to the ToneGenerator constructor int toneLengthMillis; int phoneType = mCM.getFgPhone().getPhoneType(); switch (mToneId) { case TONE_CALL_WAITING: toneType = ToneGenerator.TONE_SUP_CALL_WAITING; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; // Call waiting tone is stopped by stopTone() method toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER; break; case TONE_BUSY: if (phoneType == Phone.PHONE_TYPE_CDMA) { toneType = ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT; toneVolume = TONE_RELATIVE_VOLUME_LOPRI; toneLengthMillis = 1000; } else if ((phoneType == Phone.PHONE_TYPE_GSM) || (phoneType == Phone.PHONE_TYPE_SIP)) { toneType = ToneGenerator.TONE_SUP_BUSY; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 4000; } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } break; case TONE_CONGESTION: toneType = ToneGenerator.TONE_SUP_CONGESTION; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 4000; break; case TONE_BATTERY_LOW: // For now, use ToneGenerator.TONE_PROP_ACK (two quick // beeps). TODO: is there some other ToneGenerator // tone that would be more appropriate here? Or // should we consider adding a new custom tone? toneType = ToneGenerator.TONE_PROP_ACK; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 1000; break; case TONE_CALL_ENDED: toneType = ToneGenerator.TONE_PROP_PROMPT; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 200; break; case TONE_OTA_CALL_END: if (mApplication.cdmaOtaConfigData.otaPlaySuccessFailureTone == OtaUtils.OTA_PLAY_SUCCESS_FAILURE_TONE_ON) { toneType = ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 750; } else { toneType = ToneGenerator.TONE_PROP_PROMPT; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 200; } break; case TONE_VOICE_PRIVACY: toneType = ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 5000; break; case TONE_REORDER: toneType = ToneGenerator.TONE_CDMA_REORDER; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 4000; break; case TONE_INTERCEPT: toneType = ToneGenerator.TONE_CDMA_ABBR_INTERCEPT; toneVolume = TONE_RELATIVE_VOLUME_LOPRI; toneLengthMillis = 500; break; case TONE_CDMA_DROP: case TONE_OUT_OF_SERVICE: toneType = ToneGenerator.TONE_CDMA_CALLDROP_LITE; toneVolume = TONE_RELATIVE_VOLUME_LOPRI; toneLengthMillis = 375; break; case TONE_REDIAL: toneType = ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE; toneVolume = TONE_RELATIVE_VOLUME_LOPRI; toneLengthMillis = 5000; break; case TONE_RING_BACK: toneType = ToneGenerator.TONE_SUP_RINGTONE; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; // Call ring back tone is stopped by stopTone() method toneLengthMillis = Integer.MAX_VALUE - TONE_TIMEOUT_BUFFER; break; case TONE_UNOBTAINABLE_NUMBER: toneType = ToneGenerator.TONE_SUP_ERROR; toneVolume = TONE_RELATIVE_VOLUME_HIPRI; toneLengthMillis = 4000; break; default: throw new IllegalArgumentException("Bad toneId: " + mToneId); } // If the mToneGenerator creation fails, just continue without it. It is // a local audio signal, and is not as important. ToneGenerator toneGenerator; try { int stream; if (mBluetoothHandsfree != null) { stream = mBluetoothHandsfree.isAudioOn() ? AudioManager.STREAM_BLUETOOTH_SCO: AudioManager.STREAM_VOICE_CALL; } else { stream = AudioManager.STREAM_VOICE_CALL; } toneGenerator = new ToneGenerator(stream, toneVolume); // if (DBG) log("- created toneGenerator: " + toneGenerator); } catch (RuntimeException e) { Log.w(LOG_TAG, "InCallTonePlayer: Exception caught while creating ToneGenerator: " + e); toneGenerator = null; } // Using the ToneGenerator (with the CALL_WAITING / BUSY / // CONGESTION tones at least), the ToneGenerator itself knows // the right pattern of tones to play; we do NOT need to // manually start/stop each individual tone, or manually // insert the correct delay between tones. (We just start it // and let it run for however long we want the tone pattern to // continue.) // // TODO: When we stop the ToneGenerator in the middle of a // "tone pattern", it sounds bad if we cut if off while the // tone is actually playing. Consider adding API to the // ToneGenerator to say "stop at the next silent part of the // pattern", or simply "play the pattern N times and then // stop." boolean needToStopTone = true; boolean okToPlayTone = false; if (toneGenerator != null) { int ringerMode = mAudioManager.getRingerMode(); if (phoneType == Phone.PHONE_TYPE_CDMA) { if (toneType == ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD) { if ((ringerMode != AudioManager.RINGER_MODE_SILENT) && (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) { if (DBG) log("- InCallTonePlayer: start playing call tone=" + toneType); okToPlayTone = true; needToStopTone = false; } } else if ((toneType == ToneGenerator.TONE_CDMA_NETWORK_BUSY_ONE_SHOT) || (toneType == ToneGenerator.TONE_CDMA_REORDER) || (toneType == ToneGenerator.TONE_CDMA_ABBR_REORDER) || (toneType == ToneGenerator.TONE_CDMA_ABBR_INTERCEPT) || (toneType == ToneGenerator.TONE_CDMA_CALLDROP_LITE)) { if (ringerMode != AudioManager.RINGER_MODE_SILENT) { if (DBG) log("InCallTonePlayer:playing call fail tone:" + toneType); okToPlayTone = true; needToStopTone = false; } } else if ((toneType == ToneGenerator.TONE_CDMA_ALERT_AUTOREDIAL_LITE) || (toneType == ToneGenerator.TONE_CDMA_ALERT_NETWORK_LITE)) { if ((ringerMode != AudioManager.RINGER_MODE_SILENT) && (ringerMode != AudioManager.RINGER_MODE_VIBRATE)) { if (DBG) log("InCallTonePlayer:playing tone for toneType=" + toneType); okToPlayTone = true; needToStopTone = false; } } else { // For the rest of the tones, always OK to play. okToPlayTone = true; } } else { // Not "CDMA" okToPlayTone = true; } synchronized (this) { if (okToPlayTone && mState != TONE_STOPPED) { mState = TONE_ON; toneGenerator.startTone(toneType); try { wait(toneLengthMillis + TONE_TIMEOUT_BUFFER); } catch (InterruptedException e) { Log.w(LOG_TAG, "InCallTonePlayer stopped: " + e); } if (needToStopTone) { toneGenerator.stopTone(); } } // if (DBG) log("- InCallTonePlayer: done playing."); toneGenerator.release(); mState = TONE_OFF; } } // Finally, do the same cleanup we otherwise would have done // in onDisconnect(). // // (But watch out: do NOT do this if the phone is in use, // since some of our tones get played *during* a call (like // CALL_WAITING and BATTERY_LOW) and we definitely *don't* // want to reset the audio mode / speaker / bluetooth after // playing those! // This call is really here for use with tones that get played // *after* a call disconnects, like "busy" or "congestion" or // "call ended", where the phone has already become idle but // we need to defer the resetAudioStateAfterDisconnect() call // till the tone finishes playing.) if (mCM.getState() == Phone.State.IDLE) { resetAudioStateAfterDisconnect(); } } public void stopTone() { synchronized (this) { if (mState == TONE_ON) { notify(); } mState = TONE_STOPPED; } } } /** * Displays a notification when the phone receives a DisplayInfo record. */ private void onDisplayInfo(AsyncResult r) { // Extract the DisplayInfo String from the message CdmaDisplayInfoRec displayInfoRec = (CdmaDisplayInfoRec)(r.result); if (displayInfoRec != null) { String displayInfo = displayInfoRec.alpha; if (DBG) log("onDisplayInfo: displayInfo=" + displayInfo); CdmaDisplayInfo.displayInfoRecord(mApplication, displayInfo); // start a 2 second timer sendEmptyMessageDelayed(DISPLAYINFO_NOTIFICATION_DONE, DISPLAYINFO_NOTIFICATION_TIME); } } /** * Helper class to play SignalInfo tones using the ToneGenerator. * * To use, just instantiate a new SignalInfoTonePlayer * (passing in the ToneID constant for the tone you want) * and start() it. */ private class SignalInfoTonePlayer extends Thread { private int mToneId; SignalInfoTonePlayer(int toneId) { super(); mToneId = toneId; } @Override public void run() { - if (DBG) log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")..."); + log("SignalInfoTonePlayer.run(toneId = " + mToneId + ")..."); if (mSignalInfoToneGenerator != null) { //First stop any ongoing SignalInfo tone mSignalInfoToneGenerator.stopTone(); //Start playing the new tone if its a valid tone mSignalInfoToneGenerator.startTone(mToneId); } } } /** * Plays a tone when the phone receives a SignalInfo record. */ private void onSignalInfo(AsyncResult r) { // Signal Info are totally ignored on non-voice-capable devices. if (!PhoneApp.sVoiceCapable) { Log.w(LOG_TAG, "Got onSignalInfo() on non-voice-capable device! Ignoring..."); return; } if (PhoneUtils.isRealIncomingCall(mCM.getFirstActiveRingingCall().getState())) { // Do not start any new SignalInfo tone when Call state is INCOMING // and stop any previous SignalInfo tone which is being played stopSignalInfoTone(); } else { // Extract the SignalInfo String from the message CdmaSignalInfoRec signalInfoRec = (CdmaSignalInfoRec)(r.result); // Only proceed if a Signal info is present. if (signalInfoRec != null) { boolean isPresent = signalInfoRec.isPresent; if (DBG) log("onSignalInfo: isPresent=" + isPresent); if (isPresent) {// if tone is valid int uSignalType = signalInfoRec.signalType; int uAlertPitch = signalInfoRec.alertPitch; int uSignal = signalInfoRec.signal; if (DBG) log("onSignalInfo: uSignalType=" + uSignalType + ", uAlertPitch=" + uAlertPitch + ", uSignal=" + uSignal); //Map the Signal to a ToneGenerator ToneID only if Signal info is present int toneID = SignalToneUtil.getAudioToneFromSignalInfo (uSignalType, uAlertPitch, uSignal); //Create the SignalInfo tone player and pass the ToneID new SignalInfoTonePlayer(toneID).start(); } } } } /** * Stops a SignalInfo tone in the following condition * 1 - On receiving a New Ringing Call * 2 - On disconnecting a call * 3 - On answering a Call Waiting Call */ /* package */ void stopSignalInfoTone() { if (DBG) log("stopSignalInfoTone: Stopping SignalInfo tone player"); new SignalInfoTonePlayer(ToneGenerator.TONE_CDMA_SIGNAL_OFF).start(); } /** * Plays a Call waiting tone if it is present in the second incoming call. */ private void onCdmaCallWaiting(AsyncResult r) { // Remove any previous Call waiting timers in the queue removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE); removeMessages(CALLWAITING_ADDCALL_DISABLE_TIMEOUT); // Set the Phone Call State to SINGLE_ACTIVE as there is only one connection // else we would not have received Call waiting mApplication.cdmaPhoneCallState.setCurrentCallState( CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE); // Display the incoming call to the user if the InCallScreen isn't // already in the foreground. if (!mApplication.isShowingCallScreen()) { if (DBG) log("- showing incoming call (CDMA call waiting)..."); showIncomingCall(); } // Start timer for CW display mCallWaitingTimeOut = false; sendEmptyMessageDelayed(CALLWAITING_CALLERINFO_DISPLAY_DONE, CALLWAITING_CALLERINFO_DISPLAY_TIME); // Set the mAddCallMenuStateAfterCW state to false mApplication.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(false); // Start the timer for disabling "Add Call" menu option sendEmptyMessageDelayed(CALLWAITING_ADDCALL_DISABLE_TIMEOUT, CALLWAITING_ADDCALL_DISABLE_TIME); // Extract the Call waiting information CdmaCallWaitingNotification infoCW = (CdmaCallWaitingNotification) r.result; int isPresent = infoCW.isPresent; if (DBG) log("onCdmaCallWaiting: isPresent=" + isPresent); if (isPresent == 1 ) {//'1' if tone is valid int uSignalType = infoCW.signalType; int uAlertPitch = infoCW.alertPitch; int uSignal = infoCW.signal; if (DBG) log("onCdmaCallWaiting: uSignalType=" + uSignalType + ", uAlertPitch=" + uAlertPitch + ", uSignal=" + uSignal); //Map the Signal to a ToneGenerator ToneID only if Signal info is present int toneID = SignalToneUtil.getAudioToneFromSignalInfo(uSignalType, uAlertPitch, uSignal); //Create the SignalInfo tone player and pass the ToneID new SignalInfoTonePlayer(toneID).start(); } } /** * Posts a event causing us to clean up after rejecting (or timing-out) a * CDMA call-waiting call. * * This method is safe to call from any thread. * @see onCdmaCallWaitingReject() */ /* package */ void sendCdmaCallWaitingReject() { sendEmptyMessage(CDMA_CALL_WAITING_REJECT); } /** * Performs Call logging based on Timeout or Ignore Call Waiting Call for CDMA, * and finally calls Hangup on the Call Waiting connection. * * This method should be called only from the UI thread. * @see sendCdmaCallWaitingReject() */ private void onCdmaCallWaitingReject() { final Call ringingCall = mCM.getFirstActiveRingingCall(); // Call waiting timeout scenario if (ringingCall.getState() == Call.State.WAITING) { // Code for perform Call logging and missed call notification Connection c = ringingCall.getLatestConnection(); if (c != null) { String number = c.getAddress(); int presentation = c.getNumberPresentation(); final long date = c.getCreateTime(); final long duration = c.getDurationMillis(); final int callLogType = mCallWaitingTimeOut ? Calls.MISSED_TYPE : Calls.INCOMING_TYPE; // get the callerinfo object and then log the call with it. Object o = c.getUserData(); final CallerInfo ci; if ((o == null) || (o instanceof CallerInfo)) { ci = (CallerInfo) o; } else { ci = ((PhoneUtils.CallerInfoToken) o).currentInfo; } // Do final CNAP modifications of logNumber prior to logging [mimicking // onDisconnect()] final String logNumber = PhoneUtils.modifyForSpecialCnapCases( mApplication, ci, number, presentation); final int newPresentation = (ci != null) ? ci.numberPresentation : presentation; if (DBG) log("- onCdmaCallWaitingReject(): logNumber set to: " + logNumber + ", newPresentation value is: " + newPresentation); CallLogAsync.AddCallArgs args = new CallLogAsync.AddCallArgs( mApplication, ci, logNumber, presentation, callLogType, date, duration); mCallLog.addCall(args); if (callLogType == Calls.MISSED_TYPE) { // Add missed call notification showMissedCallNotification(c, date); } else { // Remove Call waiting 20 second display timer in the queue removeMessages(CALLWAITING_CALLERINFO_DISPLAY_DONE); } // Hangup the RingingCall connection for CW PhoneUtils.hangup(c); } //Reset the mCallWaitingTimeOut boolean mCallWaitingTimeOut = false; } } /** * Return the private variable mPreviousCdmaCallState. */ /* package */ Call.State getPreviousCdmaCallState() { return mPreviousCdmaCallState; } /** * Return the private variable mVoicePrivacyState. */ /* package */ boolean getVoicePrivacyState() { return mVoicePrivacyState; } /** * Return the private variable mIsCdmaRedialCall. */ /* package */ boolean getIsCdmaRedialCall() { return mIsCdmaRedialCall; } /** * Helper function used to show a missed call notification. */ private void showMissedCallNotification(Connection c, final long date) { PhoneUtils.CallerInfoToken info = PhoneUtils.startGetCallerInfo(mApplication, c, this, Long.valueOf(date)); if (info != null) { // at this point, we've requested to start a query, but it makes no // sense to log this missed call until the query comes back. if (VDBG) log("showMissedCallNotification: Querying for CallerInfo on missed call..."); if (info.isFinal) { // it seems that the query we have actually is up to date. // send the notification then. CallerInfo ci = info.currentInfo; // Check number presentation value; if we have a non-allowed presentation, // then display an appropriate presentation string instead as the missed // call. String name = ci.name; String number = ci.phoneNumber; if (ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) { name = mApplication.getString(R.string.private_num); } else if (ci.numberPresentation != Connection.PRESENTATION_ALLOWED) { name = mApplication.getString(R.string.unknown); } else { number = PhoneUtils.modifyForSpecialCnapCases(mApplication, ci, number, ci.numberPresentation); } NotificationMgr.getDefault().notifyMissedCall(name, number, ci.phoneLabel, date); } } else { // getCallerInfo() can return null in rare cases, like if we weren't // able to get a valid phone number out of the specified Connection. Log.w(LOG_TAG, "showMissedCallNotification: got null CallerInfo for Connection " + c); } } /** * Inner class to handle emergency call tone and vibrator */ private class EmergencyTonePlayerVibrator { private final int EMG_VIBRATE_LENGTH = 1000; // ms. private final int EMG_VIBRATE_PAUSE = 1000; // ms. private final long[] mVibratePattern = new long[] { EMG_VIBRATE_LENGTH, EMG_VIBRATE_PAUSE }; private ToneGenerator mToneGenerator; private Vibrator mEmgVibrator; /** * constructor */ public EmergencyTonePlayerVibrator() { } /** * Start the emergency tone or vibrator. */ private void start() { if (VDBG) log("call startEmergencyToneOrVibrate."); int ringerMode = mAudioManager.getRingerMode(); if ((mIsEmergencyToneOn == EMERGENCY_TONE_ALERT) && (ringerMode == AudioManager.RINGER_MODE_NORMAL)) { - if (VDBG) log("Play Emergency Tone."); + log("EmergencyTonePlayerVibrator.start(): emergency tone..."); mToneGenerator = new ToneGenerator (AudioManager.STREAM_VOICE_CALL, InCallTonePlayer.TONE_RELATIVE_VOLUME_HIPRI); if (mToneGenerator != null) { mToneGenerator.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK); mCurrentEmergencyToneState = EMERGENCY_TONE_ALERT; } } else if (mIsEmergencyToneOn == EMERGENCY_TONE_VIBRATE) { - if (VDBG) log("Play Emergency Vibrate."); + log("EmergencyTonePlayerVibrator.start(): emergency vibrate..."); mEmgVibrator = new Vibrator(); if (mEmgVibrator != null) { mEmgVibrator.vibrate(mVibratePattern, 0); mCurrentEmergencyToneState = EMERGENCY_TONE_VIBRATE; } } } /** * If the emergency tone is active, stop the tone or vibrator accordingly. */ private void stop() { if (VDBG) log("call stopEmergencyToneOrVibrate."); if ((mCurrentEmergencyToneState == EMERGENCY_TONE_ALERT) && (mToneGenerator != null)) { mToneGenerator.stopTone(); mToneGenerator.release(); } else if ((mCurrentEmergencyToneState == EMERGENCY_TONE_VIBRATE) && (mEmgVibrator != null)) { mEmgVibrator.cancel(); } mCurrentEmergencyToneState = EMERGENCY_TONE_OFF; } } private void onRingbackTone(AsyncResult r) { boolean playTone = (Boolean)(r.result); if (playTone == true) { // Only play when foreground call is in DIALING or ALERTING. // to prevent a late coming playtone after ALERTING. // Don't play ringback tone if it is in play, otherwise it will cut // the current tone and replay it if (mCM.getActiveFgCallState().isDialing() && mInCallRingbackTonePlayer == null) { mInCallRingbackTonePlayer = new InCallTonePlayer(InCallTonePlayer.TONE_RING_BACK); mInCallRingbackTonePlayer.start(); } } else { if (mInCallRingbackTonePlayer != null) { mInCallRingbackTonePlayer.stopTone(); mInCallRingbackTonePlayer = null; } } } /** * Toggle mute and unmute requests while keeping the same mute state */ private void onResendMute() { boolean muteState = PhoneUtils.getMute(); PhoneUtils.setMute(!muteState); PhoneUtils.setMute(muteState); } /** * Retrieve the phone number from the caller info or the connection. * * For incoming call the number is in the Connection object. For * outgoing call we use the CallerInfo phoneNumber field if * present. All the processing should have been done already (CDMA vs GSM numbers). * * If CallerInfo is missing the phone number, get it from the connection. * Apply the Call Name Presentation (CNAP) transform in the connection on the number. * * @param conn The phone connection. * @param info The CallerInfo. Maybe null. * @return the phone number. */ private String getLogNumber(Connection conn, CallerInfo callerInfo) { String number = null; if (conn.isIncoming()) { number = conn.getAddress(); } else { // For emergency and voicemail calls, // CallerInfo.phoneNumber does *not* contain a valid phone // number. Instead it contains an I18N'd string such as // "Emergency Number" or "Voice Mail" so we get the number // from the connection. if (null == callerInfo || TextUtils.isEmpty(callerInfo.phoneNumber) || callerInfo.isEmergencyNumber() || callerInfo.isVoiceMailNumber()) { if (conn.getCall().getPhone().getPhoneType() == Phone.PHONE_TYPE_CDMA) { // In cdma getAddress() is not always equals to getOrigDialString(). number = conn.getOrigDialString(); } else { number = conn.getAddress(); } } else { number = callerInfo.phoneNumber; } } if (null == number) { return null; } else { int presentation = conn.getNumberPresentation(); // Do final CNAP modifications. number = PhoneUtils.modifyForSpecialCnapCases(mApplication, callerInfo, number, presentation); if (!PhoneNumberUtils.isUriNumber(number)) { number = PhoneNumberUtils.stripSeparators(number); } if (VDBG) log("getLogNumber: " + number); return number; } } /** * Get the caller info. * * @param conn The phone connection. * @return The CallerInfo associated with the connection. Maybe null. */ private CallerInfo getCallerInfoFromConnection(Connection conn) { CallerInfo ci = null; Object o = conn.getUserData(); if ((o == null) || (o instanceof CallerInfo)) { ci = (CallerInfo) o; } else { ci = ((PhoneUtils.CallerInfoToken) o).currentInfo; } return ci; } /** * Get the presentation from the callerinfo if not null otherwise, * get it from the connection. * * @param conn The phone connection. * @param info The CallerInfo. Maybe null. * @return The presentation to use in the logs. */ private int getPresentation(Connection conn, CallerInfo callerInfo) { int presentation; if (null == callerInfo) { presentation = conn.getNumberPresentation(); } else { presentation = callerInfo.numberPresentation; if (DBG) log("- getPresentation(): ignoring connection's presentation: " + conn.getNumberPresentation()); } if (DBG) log("- getPresentation: presentation: " + presentation); return presentation; } private void log(String msg) { Log.d(LOG_TAG, msg); } }
false
false
null
null
diff --git a/src/edu/cmu/cs/diamond/pathfind/PathFind.java b/src/edu/cmu/cs/diamond/pathfind/PathFind.java index 729cfed..2be2cf2 100644 --- a/src/edu/cmu/cs/diamond/pathfind/PathFind.java +++ b/src/edu/cmu/cs/diamond/pathfind/PathFind.java @@ -1,491 +1,503 @@ /* * PathFind -- a Diamond system for pathology * * Copyright (c) 2008-2009 Carnegie Mellon University * All rights reserved. * * PathFind is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2. * * PathFind 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 PathFind. If not, see <http://www.gnu.org/licenses/>. * * Linking PathFind statically or dynamically with other modules is * making a combined work based on PathFind. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of * PathFind give you permission to combine PathFind with free software * programs or libraries that are released under the GNU LGPL or the * Eclipse Public License 1.0. You may copy and distribute such a system * following the terms of the GNU GPL for PathFind and the licenses of * the other code concerned, provided that you include the source code of * that other code when and as the GNU GPL requires distribution of source * code. * * Note that people who make modified versions of PathFind are not * obligated to grant this special exception for their modified versions; * it is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. */ package edu.cmu.cs.diamond.pathfind; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import edu.cmu.cs.diamond.opendiamond.*; import edu.cmu.cs.openslide.OpenSlide; import edu.cmu.cs.openslide.gui.OpenSlideView; +import edu.cmu.cs.openslide.gui.SelectionListModel; public class PathFind extends JFrame { private class OpenCaseAction extends AbstractAction { public OpenCaseAction() { super("Open Case..."); } @Override public void actionPerformed(ActionEvent e) { int returnVal = jfc.showDialog(PathFind.this, "Open"); if (returnVal == JFileChooser.APPROVE_OPTION) { File slide = jfc.getSelectedFile(); setSlide(slide); } } } private class DefineScopeAction extends AbstractAction { public DefineScopeAction() { super("Define Scope"); } @Override public void actionPerformed(ActionEvent e) { try { cookieMap = CookieMap.createDefaultCookieMap(); } catch (IOException e1) { e1.printStackTrace(); } } } private class CreateMacroAction extends AbstractAction { public CreateMacroAction() { super("New Macro..."); } @Override public void actionPerformed(ActionEvent e) { String enteredName = JOptionPane.showInputDialog(PathFind.this, "Enter the name of the new macro:"); if (enteredName == null) { return; } String newName = enteredName.replace(" ", "_") + ".txt"; try { File newFile = new File(macrosDir, newName); createNewMacro(newFile); editMacro(newFile); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } qp.populateMacroListModel(); } } private static class ExitAction extends AbstractAction { public ExitAction() { super("Exit"); } @Override public void actionPerformed(ActionEvent e) { System.exit(0); } } private final SearchPanel searchPanel; private final JPanel selectionPanel; private final JList savedSelections; private final File macrosDir; private DefaultListModel ssModel; private final QueryPanel qp; private final PairedSlideView psv = new PairedSlideView(); private CookieMap cookieMap; private final JFileChooser jfc = new JFileChooser(); public PathFind(String ijDir, String extraPluginsDir, String jreDir, File slide) throws IOException { super("PathFind"); setSize(1000, 750); setMinimumSize(new Dimension(1000, 500)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfc.setAcceptAllFileFilterUsed(false); jfc.setFileFilter(OpenSlide.getFileFilter()); cookieMap = CookieMap.createDefaultCookieMap(); // slides in middle add(psv); // query bar at bottom macrosDir = new File(ijDir, "macros"); qp = new QueryPanel(this, new File(ijDir), macrosDir, new File( extraPluginsDir), new File(jreDir)); add(qp, BorderLayout.SOUTH); // menubar setJMenuBar(createMenuBar()); // search results at top searchPanel = new SearchPanel(this); searchPanel.setVisible(false); add(searchPanel, BorderLayout.NORTH); // save selections at left selectionPanel = new JPanel(new BorderLayout()); savedSelections = new JList(); savedSelections.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); savedSelections.setLayoutOrientation(JList.VERTICAL); selectionPanel.add(new JScrollPane(savedSelections, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)); selectionPanel.setBorder(BorderFactory .createTitledBorder("Saved Selections")); selectionPanel.setPreferredSize(new Dimension(280, 100)); savedSelections.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { Shape selection = (Shape) savedSelections.getSelectedValue(); psv.getSlide().addSelection(selection); - psv.getSlide().centerOnSelection(); + psv.getSlide().centerOnSelection( + savedSelections.getSelectedIndex()); } }); add(selectionPanel, BorderLayout.WEST); if (slide != null) { setSlide(slide); } } private void setSlide(File slide) { OpenSlide os = new OpenSlide(slide); setSlide(os, slide.getName()); } void editMacro(final File macro) throws IOException { // read in macro FileInputStream in = new FileInputStream(macro); String text; try { text = new String(Util.readFully(in), "UTF-8"); } finally { try { in.close(); } catch (IOException e) { } } // editor final JTextArea textArea = new JTextArea(text, 25, 80); textArea.setEditable(true); textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); JScrollPane textPane = new JScrollPane(textArea); textPane .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); textPane.setMinimumSize(new Dimension(10, 10)); // top panel JPanel top = new JPanel(); top.setLayout(new FlowLayout()); // save JButton saveButton = new JButton("Save"); top.add(saveButton); // delete JButton deleteButton = new JButton("Delete"); top.add(deleteButton); // frame final JFrame editorFrame = new JFrame(macro.getName()); editorFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); editorFrame.add(textPane); editorFrame.add(top, BorderLayout.NORTH); editorFrame.pack(); editorFrame.setVisible(true); // actions deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (JOptionPane.showConfirmDialog(editorFrame, "Really delete macro “" + macro.getName() + "”?", "Confirm Deletion", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) { editorFrame.dispose(); macro.delete(); qp.populateMacroListModel(); } } }); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String text = textArea.getText(); try { File tmp = File.createTempFile("pathfind", ".tmp", macrosDir); tmp.deleteOnExit(); // write out FileWriter out = new FileWriter(tmp); try { out.write(text); } finally { try { out.close(); } catch (IOException e1) { } } tmp.renameTo(macro); editorFrame.dispose(); } catch (IOException e1) { e1.printStackTrace(); } } }); } void createNewMacro(File newFile) throws IOException { // create a blank file if it doesn't exist if (!newFile.createNewFile()) { JOptionPane.showMessageDialog(PathFind.this, "Macro “" + newFile.getName() + "” already exists."); } } private JMenuBar createMenuBar() { JMenuBar mb = new JMenuBar(); JMenu m = new JMenu("PathFind"); mb.add(m); m.add(new OpenCaseAction()); m.add(new DefineScopeAction()); m.add(new CreateMacroAction()); m.add(new JSeparator()); m.add(new ExitAction()); return mb; } public void startSearch(int threshold, byte[] macroBlob, String macroName) throws IOException, InterruptedException { System.out.println("start search"); SearchFactory factory = createFactory(threshold, macroBlob, macroName); searchPanel.beginSearch(factory.createSearch(null), factory); } public void stopSearch() throws InterruptedException { searchPanel.endSearch(); } private SearchFactory createFactory(int threshold, byte[] macroBlob, String macroName) throws IOException { List<Filter> filters = new ArrayList<Filter>(); String macroName2 = macroName.replace(' ', '_'); InputStream in = null; // imagej try { in = new FileInputStream("/opt/snapfind/lib/fil_imagej_exec.so"); FilterCode c = new FilterCode(in); List<String> dependencies = Collections.emptyList(); List<String> arguments = Arrays.asList(new String[] { macroName2 }); Filter imagej = new Filter("imagej", c, "f_eval_imagej_exec", "f_init_imagej_exec", "f_fini_imagej_exec", threshold, dependencies, arguments, macroBlob); filters.add(imagej); } finally { try { in.close(); } catch (IOException e) { } } try { in = new FileInputStream("/opt/snapfind/lib/fil_rgb.so"); FilterCode c = new FilterCode(in); List<String> dependencies = Collections.emptyList(); List<String> arguments = Collections.emptyList(); Filter rgb = new Filter("RGB", c, "f_eval_img2rgb", "f_init_img2rgb", "f_fini_img2rgb", 1, dependencies, arguments); filters.add(rgb); } finally { try { in.close(); } catch (IOException e) { } } try { in = new FileInputStream("/opt/snapfind/lib/fil_thumb.so"); FilterCode c = new FilterCode(in); List<String> dependencies = Arrays.asList(new String[] { "RGB" }); List<String> arguments = Arrays .asList(new String[] { "200", "150" }); Filter thumb = new Filter("thumbnail", c, "f_eval_thumbnailer", "f_init_thumbnailer", "f_fini_thumbnailer", 1, dependencies, arguments, macroBlob); filters.add(thumb); } finally { try { in.close(); } catch (IOException e) { } } // make a new factory SearchFactory factory = new SearchFactory(filters, Arrays .asList(new String[] { "RGB" }), cookieMap); return factory; } + private void saveSelection(OpenSlideView wv) { + SelectionListModel slm = wv.getSelectionListModel(); + + if (slm.getSize() > 0) { + Shape s = slm.get(slm.getSize() - 1); + ssModel.addElement(s); + } + } + void setSlide(OpenSlide openslide, String title) { final OpenSlideView wv = createNewView(openslide, title, true); psv.setSlide(wv); wv.getInputMap() .put(KeyStroke.getKeyStroke("INSERT"), "save selection"); wv.getActionMap().put("save selection", new AbstractAction() { public void actionPerformed(ActionEvent e) { + saveSelection(wv); } }); ssModel = new SavedSelectionModel(wv); savedSelections.setModel(ssModel); savedSelections.setCellRenderer(new SavedSelectionCellRenderer(wv)); psv.revalidate(); psv.repaint(); } void setResult(Icon result, String title) { psv.setResult(result); } private OpenSlideView createNewView(OpenSlide openslide, String title, boolean zoomToFit) { OpenSlideView wv = new OpenSlideView(openslide, zoomToFit); wv.setBorder(BorderFactory.createTitledBorder(title)); return wv; } public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("usage: " + PathFind.class.getName() + " ij_dir extra_plugins_dir jre_dir"); return; } final String ijDir = args[0]; final String extraPluginsDir = args[1]; final String jreDir = args[2]; final File slide; if (args.length == 4) { slide = new File(args[3]); } else { slide = null; } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { PathFind pf; try { pf = new PathFind(ijDir, extraPluginsDir, jreDir, slide); pf.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } }); } public BufferedImage getSelectionAsImage(int selection) { - Shape s = psv.getSlide().getSelection(); + Shape s = psv.getSlide().getSelectionListModel().get(selection); if (s == null) { return null; } Rectangle2D bb = s.getBounds2D(); if (bb.getWidth() * bb.getHeight() > 6000 * 6000) { throw new SelectionTooBigException(); } // move selection AffineTransform at = AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY()); s = at.createTransformedShape(s); BufferedImage img = new BufferedImage((int) bb.getWidth(), (int) bb .getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); g.setBackground(Color.WHITE); g.clearRect(0, 0, img.getWidth(), img.getHeight()); g.clip(s); psv.getSlide().getOpenSlide().paintRegion(g, 0, 0, (int) bb.getX(), (int) bb.getY(), img.getWidth(), img.getHeight(), 1.0); g.dispose(); return img; } public OpenSlideView getSlide() { return psv.getSlide(); } } diff --git a/src/edu/cmu/cs/diamond/pathfind/QueryPanel.java b/src/edu/cmu/cs/diamond/pathfind/QueryPanel.java index 844c8db..4d30c17 100644 --- a/src/edu/cmu/cs/diamond/pathfind/QueryPanel.java +++ b/src/edu/cmu/cs/diamond/pathfind/QueryPanel.java @@ -1,358 +1,358 @@ /* * PathFind -- a Diamond system for pathology * * Copyright (c) 2008-2009 Carnegie Mellon University * All rights reserved. * * PathFind is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 2. * * PathFind 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 PathFind. If not, see <http://www.gnu.org/licenses/>. * * Linking PathFind statically or dynamically with other modules is * making a combined work based on PathFind. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of * PathFind give you permission to combine PathFind with free software * programs or libraries that are released under the GNU LGPL or the * Eclipse Public License 1.0. You may copy and distribute such a system * following the terms of the GNU GPL for PathFind and the licenses of * the other code concerned, provided that you include the source code of * that other code when and as the GNU GPL requires distribution of source * code. * * Note that people who make modified versions of PathFind are not * obligated to grant this special exception for their modified versions; * it is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. */ package edu.cmu.cs.diamond.pathfind; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.swing.*; import edu.cmu.cs.diamond.opendiamond.Util; public final class QueryPanel extends JPanel { public final String[] ijCmd; public final File ijDir; public class Macro { private final String name; private final String macroName; public Macro(String name, String macroName) { this.name = name; this.macroName = macroName; } @Override public String toString() { return name; } public double runMacro() { // make hourglass setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); File imgFile = null; double result = Double.NaN; try { // grab image - BufferedImage img = pf.getSelectionAsImage(); + BufferedImage img = pf.getSelectionAsImage(0); // JFrame jf = new JFrame(); // jf.add(new JLabel(new ImageIcon(img))); // jf.setVisible(true); // jf.pack(); // write tmp image BufferedOutputStream out = null; try { imgFile = File.createTempFile("pathfind", ".ppm"); imgFile.deleteOnExit(); out = new BufferedOutputStream( new FileOutputStream(imgFile)); out.write("P6\n".getBytes()); out.write(Integer.toString(img.getWidth()).getBytes()); out.write('\n'); out.write(Integer.toString(img.getHeight()).getBytes()); out.write("\n255\n".getBytes()); for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { int pixel = img.getRGB(x, y); out.write((pixel >> 16) & 0xFF); out.write((pixel >> 8) & 0xFF); out.write(pixel & 0xFF); } } } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } // run macro List<String> processArgs = new ArrayList<String>(); processArgs.addAll(Arrays.asList(ijCmd)); processArgs.add(imgFile.getPath()); processArgs.add("-batch"); processArgs.add(macroName); ProcessBuilder pb = new ProcessBuilder(processArgs); pb.directory(ijDir); try { StringBuilder sb = new StringBuilder(); Process p = pb.start(); BufferedInputStream pOut = new BufferedInputStream(p .getInputStream()); int data; while ((data = pOut.read()) != -1) { sb.append((char) data); } pOut.close(); String sr = sb.toString(); System.out.println(sr); String srr[] = sr.split("\n"); result = Double.parseDouble(srr[2]); } catch (IOException e) { e.printStackTrace(); } } finally { // delete temp if (imgFile != null) { imgFile.delete(); } // reset hourglass setCursor(null); } return result / 10000.0; } public String getMacroName() { return macroName; } } private final PathFind pf; private final JComboBox macroComboBox; private final JLabel resultField; private double result = Double.NaN; private final JButton computeButton; private final JButton searchButton; private final JButton stopButton; private final JSpinner threshold; private final DefaultComboBoxModel macroListModel = new DefaultComboBoxModel(); private final File extraPluginsDir; private final JButton editButton; private final File macrosDir; public QueryPanel(PathFind pathFind, File ijDir, File macrosDir, File extraPluginsDir, File jreDir) { this.ijDir = ijDir; this.macrosDir = macrosDir; this.extraPluginsDir = extraPluginsDir; macrosDir.mkdir(); System.out.printf("macrosDir: %s\nextraPluginsDir: %s\n", macrosDir, extraPluginsDir); populateMacroListModel(); this.ijCmd = new String[] { new File(jreDir + File.separator + "bin" + File.separator + "java").getAbsolutePath(), "-jar", "ij.jar" }; setLayout(new BorderLayout()); pf = pathFind; Box b = Box.createHorizontalBox(); // add macro list macroComboBox = new JComboBox(macroListModel); macroComboBox.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel r = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String name = ((File) value).getName().replace("_", " ") .replaceAll("\\.txt$", ""); r.setText(name); return r; } }); b.add(macroComboBox); // edit editButton = new JButton("Edit"); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File f = (File) macroComboBox.getSelectedItem(); try { pf.editMacro(f); } catch (IOException e1) { e1.printStackTrace(); } } }); b.add(editButton); b.add(Box.createHorizontalStrut(10)); // add compute button computeButton = new JButton("Calculate"); computeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File f = (File) macroComboBox.getSelectedItem(); Macro m = new Macro(f.getName(), f.getAbsolutePath()); result = m.runMacro(); updateResultField(); } }); b.add(computeButton); b.add(Box.createHorizontalStrut(10)); // add result resultField = new JLabel(); resultField.setPreferredSize(new Dimension(100, 1)); clearResult(); b.add(resultField); // add divider b.add(new JSeparator(SwingConstants.VERTICAL)); // add search range b.add(new JLabel("Threshold: ")); threshold = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); b.add(threshold); b.add(Box.createHorizontalStrut(10)); // add search button searchButton = new JButton("Search"); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { File f = (File) macroComboBox.getSelectedItem(); String name = f.getName().replaceAll("\\.txt$", ""); runRemoteMacro(name); } catch (InterruptedException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }); b.add(searchButton); // add stop button stopButton = new JButton("Stop"); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { pf.stopSearch(); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } } }); b.add(stopButton); b.add(Box.createHorizontalGlue()); add(b); } void populateMacroListModel() { macroListModel.removeAllElements(); File[] files = macrosDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".txt"); } }); Collections.sort(Arrays.asList(files)); for (File f : files) { macroListModel.addElement(f); } } private void updateResultField() { resultField.setText("Result: " + Double.toString(result)); } public void clearResult() { result = Double.NaN; updateResultField(); } private void runRemoteMacro(String macroName) throws InterruptedException, IOException { File mm = new File(QueryPanel.this.ijDir + "/macros", macroName + ".txt"); byte blob1[] = Util.quickTar(extraPluginsDir); byte blob2[] = Util.quickTar(new File[] { mm }); byte macroBlob[] = new byte[blob1.length + blob2.length]; System.arraycopy(blob1, 0, macroBlob, 0, blob1.length); System.arraycopy(blob2, 0, macroBlob, blob1.length, blob2.length); pf.startSearch((int) ((Number) threshold.getValue()).doubleValue(), macroBlob, macroName); } }
false
false
null
null
diff --git a/src/org/eclipse/core/internal/events/BuildContext.java b/src/org/eclipse/core/internal/events/BuildContext.java index 1358041d..a9943ff8 100644 --- a/src/org/eclipse/core/internal/events/BuildContext.java +++ b/src/org/eclipse/core/internal/events/BuildContext.java @@ -1,226 +1,226 @@ /******************************************************************************* * Copyright (c) 2010 Broadcom Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Broadcom Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.events; import org.eclipse.core.resources.IBuildConfiguration; import java.util.*; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; /** - * @noextend This class is not intended to be subclassed by clients. + * Concrete implementation of a build context */ public class BuildContext implements IBuildContext { /** The build configuration for which this context applies. */ private final IBuildConfiguration buildConfiguration; /** The build order for the build that this context is part of. */ private final IBuildConfiguration[] buildOrder; /** The position in the build order array that this project configuration is. */ private final int buildOrderPosition; private static final IBuildConfiguration[] EMPTY_BUILD_CONFIGURATION_ARRAY = new IBuildConfiguration[0]; /** Cached lists of referenced and referencing projects and project configurations */ private IProject[] cachedReferencedProjects = null; private IBuildConfiguration[] cachedReferencedBuildConfigurations = null; private IProject[] cachedReferencingProjects = null; private IBuildConfiguration[] cachedReferencingBuildConfigurations = null; /** * Create an empty build context for the given project configuration. * @param buildConfiguration the project configuration being built, that we need the context for */ public BuildContext(IBuildConfiguration buildConfiguration) { this.buildConfiguration = buildConfiguration; buildOrder = EMPTY_BUILD_CONFIGURATION_ARRAY; buildOrderPosition = -1; } /** * Create a build context for the given project configuration. * @param buildConfiguration the project configuration being built, that we need the context for * @param buildOrder the build order for the entire build, indicating how cycles etc. have been resolved */ public BuildContext(IBuildConfiguration buildConfiguration, IBuildConfiguration[] buildOrder) { this.buildConfiguration = buildConfiguration; this.buildOrder = buildOrder; int position = -1; for (int i = 0; i < buildOrder.length; i++) { if (buildOrder[i].equals(buildConfiguration)) { position = i; break; } } buildOrderPosition = position; Assert.isTrue(-1 <= buildOrderPosition && buildOrderPosition < buildOrder.length); } /* * (non-Javadoc) * @see org.eclipse.core.resources.IBuildContext#getAllReferencedProjects() */ public IProject[] getAllReferencedProjects() { if (cachedReferencedBuildConfigurations == null) cachedReferencedBuildConfigurations = computeReferenced(); if (cachedReferencedProjects == null) cachedReferencedProjects = projectConfigurationsToProjects(cachedReferencedBuildConfigurations); return (IProject[]) cachedReferencedProjects.clone(); } /* * (non-Javadoc) * @see org.eclipse.core.resources.IBuildContext#getAllReferencedBuildConfigurations() */ public IBuildConfiguration[] getAllReferencedBuildConfigurations() { if (cachedReferencedBuildConfigurations == null) cachedReferencedBuildConfigurations = computeReferenced(); return (IBuildConfiguration[]) cachedReferencedBuildConfigurations.clone(); } /* * (non-Javadoc) * @see org.eclipse.core.resources.IBuildContext#getAllReferencingProjects() */ public IProject[] getAllReferencingProjects() { if (cachedReferencingBuildConfigurations == null) cachedReferencingBuildConfigurations = computeReferencing(); if (cachedReferencingProjects == null) cachedReferencingProjects = projectConfigurationsToProjects(cachedReferencingBuildConfigurations); return (IProject[]) cachedReferencingProjects.clone(); } /* * (non-Javadoc) * @see org.eclipse.core.resources.IBuildContext#getAllReferencingBuildConfigurations() */ public IBuildConfiguration[] getAllReferencingBuildConfigurations() { if (cachedReferencingBuildConfigurations == null) cachedReferencingBuildConfigurations = computeReferencing(); return (IBuildConfiguration[]) cachedReferencingBuildConfigurations.clone(); } private IBuildConfiguration[] computeReferenced() { Set previousConfigs = new HashSet(); for (int i = 0; i < buildOrderPosition; i++) previousConfigs.add(buildOrder[i]); // Do a depth first search of the project configuration's references to construct // the references graph. return computeReachable(buildConfiguration, previousConfigs, new GetChildrenFunctor() { public IBuildConfiguration[] run(IBuildConfiguration configuration) { try { return configuration.getProject().getReferencedBuildConfigurations(configuration); } catch (CoreException e) { return EMPTY_BUILD_CONFIGURATION_ARRAY; } } }); } private IBuildConfiguration[] computeReferencing() { Set subsequentConfigs = new HashSet(); for (int i = buildOrderPosition+1; i < buildOrder.length; i++) subsequentConfigs.add(buildOrder[i]); // Do a depth first search of the project configuration's referencing configurations // to construct the referencing graph. return computeReachable(buildConfiguration, subsequentConfigs, new GetChildrenFunctor() { public IBuildConfiguration[] run(IBuildConfiguration configuration) { return configuration.getProject().getReferencingBuildConfigurations(configuration); } }); } private static interface GetChildrenFunctor { IBuildConfiguration[] run(IBuildConfiguration configuration); } /** * Perform a depth first search from the given root using the a functor to * get the children for each item. * @returns A set containing all the reachable project configurations from the given root. */ private IBuildConfiguration[] computeReachable(IBuildConfiguration root, Set filter, GetChildrenFunctor getChildren) { Set result = new HashSet(); Stack stack = new Stack(); stack.push(root); Set visited = new HashSet(); if (filter.contains(root)) result.add(root); while (!stack.isEmpty()) { IBuildConfiguration configuration = (IBuildConfiguration) stack.pop(); visited.add(configuration); IBuildConfiguration[] refs = getChildren.run(configuration); for (int i = 0; i < refs.length; i++) { IBuildConfiguration ref = refs[i]; if (!filter.contains(ref)) continue; // Avoid exploring cycles if (visited.contains(ref)) continue; result.add(ref); stack.push(ref); } } return (IBuildConfiguration[]) result.toArray(new IBuildConfiguration[result.size()]); } /** * Convert a list of project configurations to projects, while removing duplicates. */ private IProject[] projectConfigurationsToProjects(IBuildConfiguration[] configs) { Set set = new HashSet(); for (int i = 0; i < configs.length; i++) set.add(configs[i].getProject()); return (IProject[]) set.toArray(new IProject[set.size()]); } /* * (non-Javadoc) * @see Object#hashCode() */ public int hashCode() { final int prime = 31; int result = 1; result = prime * result + buildOrderPosition; result = prime * result + buildConfiguration.hashCode(); for (int i = 0; i < buildOrder.length; i++) result = prime * result + buildOrder[i].hashCode(); return result; } /* * (non-Javadoc) * @see Object#equals(Object) */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; BuildContext context = (BuildContext) obj; if (buildOrderPosition != context.buildOrderPosition) return false; if (!buildConfiguration.equals(context.buildConfiguration)) return false; if (!Arrays.equals(buildOrder, context.buildOrder)) return false; return true; } } diff --git a/src/org/eclipse/core/internal/resources/ProjectDescription.java b/src/org/eclipse/core/internal/resources/ProjectDescription.java index 6dde5f57..3aac38e2 100644 --- a/src/org/eclipse/core/internal/resources/ProjectDescription.java +++ b/src/org/eclipse/core/internal/resources/ProjectDescription.java @@ -1,866 +1,876 @@ /******************************************************************************* * Copyright (c) 2000, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Martin Oberhuber (Wind River) - [245937] setLinkLocation() detects non-change * Serge Beauchamp (Freescale Semiconductor) - [229633] Project Path Variable Support * Markus Schorn (Wind River) - [306575] Save snapshot location with project * Broadcom Corporation - build configurations and references *******************************************************************************/ package org.eclipse.core.internal.resources; import java.net.URI; import java.util.*; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.internal.events.BuildCommand; import org.eclipse.core.internal.utils.FileUtil; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; public class ProjectDescription extends ModelObject implements IProjectDescription { private static final ICommand[] EMPTY_COMMAND_ARRAY = new ICommand[0]; // constants private static final IProject[] EMPTY_PROJECT_ARRAY = new IProject[0]; private static final IBuildConfigReference[] EMPTY_BUILD_CONFIG_REFERENCE_ARRAY = new IBuildConfigReference[0]; private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final String EMPTY_STR = ""; //$NON-NLS-1$ private static final BuildConfiguration[] DEFAULT_BUILD_CONFIGS = new BuildConfiguration[]{new BuildConfiguration()}; protected static boolean isReading = false; //flags to indicate when we are in the middle of reading or writing a // workspace description //these can be static because only one description can be read at once. protected static boolean isWriting = false; protected ICommand[] buildSpec = EMPTY_COMMAND_ARRAY; /* * Cached union of static and dynamic references (duplicates omitted). * This cache is not persisted. */ protected HashMap/*<String, IBuildConfigReference[]>*/ cachedRefs = new HashMap(); /* * Cached union of static and dynamic build config references (duplicates omitted). * This cache is not persisted. */ protected IProject[] cachedProjectRefs = null; /* * Cached dynamic project references, generated from build config references (duplicates omitted). * This cache is not persisted. */ protected IProject[] cachedDynamicProjectRefs = null; /* * Cached static project references, generated from build config references (duplicates omitted). * This cache is not persisted. */ protected IProject[] cachedStaticProjectRefs = null; protected String comment = EMPTY_STR; /** * Map of (IPath -> LinkDescription) pairs for each linked resource * in this project, where IPath is the project relative path of the resource. */ protected HashMap linkDescriptions = null; /** * Map of (IPath -> LinkedList<FilterDescription>) pairs for each filtered resource * in this project, where IPath is the project relative path of the resource. */ protected HashMap filterDescriptions = null; /** * Map of (String -> VariableDescription) pairs for each variable in this * project, where String is the name of the variable. */ protected HashMap variableDescriptions = null; // fields protected URI location = null; protected String[] natures = EMPTY_STRING_ARRAY; protected BuildConfiguration[] buildConfigs = DEFAULT_BUILD_CONFIGS; protected Set buildConfigIds = null; /** Map from config id in this project -> build configurations in other projects */ protected HashMap/*<String, IBuildConfigReference[]>*/ staticRefs = new HashMap(); protected HashMap/*<String, IBuildConfigReference[]>*/ dynamicRefs = new HashMap(); protected URI snapshotLocation= null; public ProjectDescription() { super(); } public Object clone() { ProjectDescription clone = (ProjectDescription) super.clone(); //don't want the clone to have access to our internal link locations table or builders clone.linkDescriptions = null; clone.filterDescriptions = null; if (variableDescriptions != null) clone.variableDescriptions = (HashMap) variableDescriptions.clone(); clone.staticRefs = (HashMap) staticRefs.clone(); clone.dynamicRefs = (HashMap) dynamicRefs.clone(); clone.cachedRefs = new HashMap(); clone.buildSpec = getBuildSpec(true); return clone; } /* (non-Javadoc) * @see IProjectDescription#getBuildSpec() */ public ICommand[] getBuildSpec() { return getBuildSpec(true); } public ICommand[] getBuildSpec(boolean makeCopy) { //thread safety: copy reference in case of concurrent write ICommand[] oldCommands = this.buildSpec; if (oldCommands == null) return EMPTY_COMMAND_ARRAY; if (!makeCopy) return oldCommands; ICommand[] result = new ICommand[oldCommands.length]; for (int i = 0; i < result.length; i++) result[i] = (ICommand) ((BuildCommand) oldCommands[i]).clone(); return result; } /* (non-Javadoc) * @see IProjectDescription#getComment() */ public String getComment() { return comment; } /** * Returns the link location for the given resource name. Returns null if * no such link exists. */ public URI getLinkLocationURI(IPath aPath) { if (linkDescriptions == null) return null; LinkDescription desc = (LinkDescription) linkDescriptions.get(aPath); return desc == null ? null : desc.getLocationURI(); } /** * Returns the filter for the given resource name. Returns null if * no such filter exists. */ synchronized public LinkedList/*<FilterDescription>*/ getFilter(IPath aPath) { if (filterDescriptions == null) return null; return (LinkedList /*<FilterDescription> */) filterDescriptions.get(aPath); } /** * Returns the map of link descriptions (IPath (project relative path) -> LinkDescription). * Since this method is only used internally, it never creates a copy. * Returns null if the project does not have any linked resources. */ public HashMap getLinks() { return linkDescriptions; } /** * Returns the map of filter descriptions (IPath (project relative path) -> LinkedList<FilterDescription>). * Since this method is only used internally, it never creates a copy. * Returns null if the project does not have any filtered resources. */ public HashMap getFilters() { return filterDescriptions; } /** * Returns the map of variable descriptions (String (variable name) -> * VariableDescription). Since this method is only used internally, it never * creates a copy. Returns null if the project does not have any variables. */ public HashMap getVariables() { return variableDescriptions; } /** * @see IProjectDescription#getLocation() * @deprecated */ public IPath getLocation() { if (location == null) return null; return FileUtil.toPath(location); } /* (non-Javadoc) * @see IProjectDescription#getLocationURI() */ public URI getLocationURI() { return location; } /* (non-Javadoc) * @see IProjectDescription#getNatureIds() */ public String[] getNatureIds() { return getNatureIds(true); } public String[] getNatureIds(boolean makeCopy) { if (natures == null) return EMPTY_STRING_ARRAY; return makeCopy ? (String[]) natures.clone() : natures; } /** * Returns the URI to load a resource snapshot from. * May return <code>null</code> if no snapshot is set. * <p> * <strong>EXPERIMENTAL</strong>. This constant has been added as * part of a work in progress. There is no guarantee that this API will * work or that it will remain the same. Please do not use this API without * consulting with the Platform Core team. * </p> * @return the snapshot location URI, * or <code>null</code>. * @see IProject#loadSnapshot(int, URI, IProgressMonitor) * @see #setSnapshotLocationURI(URI) * @since 3.6 */ public URI getSnapshotLocationURI() { return snapshotLocation; } /* (non-Javadoc) * @see IProjectDescription#hasNature(String) */ public boolean hasNature(String natureID) { String[] natureIDs = getNatureIds(false); for (int i = 0; i < natureIDs.length; ++i) if (natureIDs[i].equals(natureID)) return true; return false; } /** * Returns true if any private attributes of the description have changed. * Private attributes are those that are not stored in the project description * file (.project). */ public boolean hasPrivateChanges(ProjectDescription description) { if (!dynamicRefs.equals(description.dynamicRefs)) return true; IPath otherLocation = description.getLocation(); if (location == null) return otherLocation != null; return !location.equals(otherLocation); } /** * Returns true if any public attributes of the description have changed. * Public attributes are those that are stored in the project description * file (.project). */ public boolean hasPublicChanges(ProjectDescription description) { if (!getName().equals(description.getName())) return true; if (!comment.equals(description.getComment())) return true; //don't bother optimizing if the order has changed if (!Arrays.equals(buildSpec, description.getBuildSpec(false))) return true; if (!staticRefs.equals(description.staticRefs)) return true; if (!Arrays.equals(natures, description.getNatureIds(false))) return true; if (!Arrays.equals(buildConfigs, description.buildConfigs)) return true; HashMap otherFilters = description.getFilters(); if ((filterDescriptions == null) && (otherFilters != null)) return otherFilters != null; if ((filterDescriptions != null) && !filterDescriptions.equals(otherFilters)) return true; HashMap otherVariables = description.getVariables(); if ((variableDescriptions == null) && (otherVariables != null)) return true; if ((variableDescriptions != null) && !variableDescriptions.equals(otherVariables)) return true; final HashMap otherLinks = description.getLinks(); if (linkDescriptions != otherLinks) { if (linkDescriptions == null || !linkDescriptions.equals(otherLinks)) return true; } final URI otherSnapshotLoc= description.getSnapshotLocationURI(); if (snapshotLocation != otherSnapshotLoc) { if (snapshotLocation == null || !snapshotLocation.equals(otherSnapshotLoc)) return true; } return false; } /* (non-Javadoc) * @see IProjectDescription#newCommand() */ public ICommand newCommand() { return new BuildCommand(); } /* (non-Javadoc) * @see IProjectDescription#setBuildSpec(ICommand[]) */ public void setBuildSpec(ICommand[] value) { Assert.isLegal(value != null); //perform a deep copy in case clients perform further changes to the command ICommand[] result = new ICommand[value.length]; for (int i = 0; i < result.length; i++) { result[i] = (ICommand) ((BuildCommand) value[i]).clone(); //copy the reference to any builder instance from the old build spec //to preserve builder states if possible. for (int j = 0; j < buildSpec.length; j++) { if (result[i].equals(buildSpec[j])) { ((BuildCommand) result[i]).setBuilders(((BuildCommand) buildSpec[j]).getBuilders()); break; } } } buildSpec = result; } /* (non-Javadoc) * @see IProjectDescription#setComment(String) */ public void setComment(String value) { comment = value; } /** * Sets the map of link descriptions (String name -> LinkDescription). * Since this method is only used internally, it never creates a copy. May * pass null if this project does not have any linked resources */ public void setLinkDescriptions(HashMap linkDescriptions) { this.linkDescriptions = linkDescriptions; } /** * Sets the description of a link. Setting to a description of null will * remove the link from the project description. * @return <code>true</code> if the description was actually changed, * <code>false</code> otherwise. * @since 3.5 returns boolean (was void before) */ public boolean setLinkLocation(IPath path, LinkDescription description) { HashMap tempMap = linkDescriptions; if (description != null) { //addition or modification if (tempMap == null) tempMap = new HashMap(10); else //copy on write to protect against concurrent read tempMap = (HashMap) tempMap.clone(); Object oldValue = tempMap.put(path, description); if (oldValue!=null && description.equals(oldValue)) { //not actually changed anything return false; } linkDescriptions = tempMap; } else { //removal if (tempMap == null) return false; //copy on write to protect against concurrent access HashMap newMap = (HashMap) tempMap.clone(); Object oldValue = newMap.remove(path); if (oldValue == null) { //not actually changed anything return false; } linkDescriptions = newMap.size() == 0 ? null : newMap; } return true; } /** * Sets the map of filter descriptions (String name -> LinkedList<LinkDescription>). * Since this method is only used internally, it never creates a copy. May * pass null if this project does not have any filtered resources */ public void setFilterDescriptions(HashMap filterDescriptions) { this.filterDescriptions = filterDescriptions; } /** * Sets the map of variable descriptions (String name -> * VariableDescription). Since this method is only used internally, it never * creates a copy. May pass null if this project does not have any variables */ public void setVariableDescriptions(HashMap variableDescriptions) { this.variableDescriptions = variableDescriptions; } /** * Add the description of a filter. Setting to a description of null will * remove the filter from the project description. */ synchronized public void addFilter(IPath path, FilterDescription description) { Assert.isNotNull(description); if (filterDescriptions == null) filterDescriptions = new HashMap(10); LinkedList/*<FilterDescription>*/ descList = (LinkedList /*<FilterDescription> */) filterDescriptions.get(path); if (descList == null) { descList = new LinkedList/*<FilterDescription>*/(); filterDescriptions.put(path, descList); } descList.add(description); } /** * Add the description of a filter. Setting to a description of null will * remove the filter from the project description. */ synchronized public void removeFilter(IPath path, FilterDescription description) { if (filterDescriptions != null) { LinkedList/*<FilterDescription>*/ descList = (LinkedList /*<FilterDescription> */) filterDescriptions.get(path); if (descList != null) { descList.remove(description); if (descList.size() == 0) { filterDescriptions.remove(path); if (filterDescriptions.size() == 0) filterDescriptions = null; } } } } /** * Sets the description of a variable. Setting to a description of null will * remove the variable from the project description. * @return <code>true</code> if the description was actually changed, * <code>false</code> otherwise. * @since 3.5 */ public boolean setVariableDescription(String name, VariableDescription description) { HashMap tempMap = variableDescriptions; if (description != null) { // addition or modification if (tempMap == null) tempMap = new HashMap(10); else // copy on write to protect against concurrent read tempMap = (HashMap) tempMap.clone(); Object oldValue = tempMap.put(name, description); if (oldValue!=null && description.equals(oldValue)) { //not actually changed anything return false; } variableDescriptions = tempMap; } else { // removal if (tempMap == null) return false; // copy on write to protect against concurrent access HashMap newMap = (HashMap) tempMap.clone(); Object oldValue = newMap.remove(name); if (oldValue == null) { //not actually changed anything return false; } variableDescriptions = newMap.size() == 0 ? null : newMap; } return true; } /** * set the filters for a given resource. Setting to a description of null will * remove the filter from the project description. * @return <code>true</code> if the description was actually changed, * <code>false</code> otherwise. */ synchronized public boolean setFilters(IPath path, LinkedList/*<FilterDescription>*/ descriptions) { if (descriptions != null) { // addition if (filterDescriptions == null) filterDescriptions = new HashMap(10); Object oldValue = filterDescriptions.put(path, descriptions); if (oldValue!=null && descriptions.equals(oldValue)) { //not actually changed anything return false; } } else { // removal if (filterDescriptions == null) return false; Object oldValue = filterDescriptions.remove(path); if (oldValue == null) { //not actually changed anything return false; } if (filterDescriptions.size() == 0) filterDescriptions = null; } return true; } /* (non-Javadoc) * @see IProjectDescription#setLocation(IPath) */ public void setLocation(IPath path) { this.location = path == null ? null : URIUtil.toURI(path); } public void setLocationURI(URI location) { this.location = location; } /* (non-Javadoc) * @see IProjectDescription#setName(String) */ public void setName(String value) { super.setName(value); } /* (non-Javadoc) * @see IProjectDescription#setNatureIds(String[]) */ public void setNatureIds(String[] value) { natures = (String[]) value.clone(); } /** * Sets the location URI for a project snapshot that may be * loaded automatically when the project is created in a workspace. * <p> * <strong>EXPERIMENTAL</strong>. This method has been added as * part of a work in progress. There is no guarantee that this API will * work or that it will remain the same. Please do not use this API without * consulting with the Platform Core team. * </p> * @param snapshotLocation the location URI or * <code>null</code> to clear the setting * @see IProject#loadSnapshot(int, URI, IProgressMonitor) * @see #getSnapshotLocationURI() * @since 3.6 */ public void setSnapshotLocationURI(URI snapshotLocation) { this.snapshotLocation = snapshotLocation; } public URI getGroupLocationURI(IPath projectRelativePath) { return LinkDescription.VIRTUAL_LOCATION; } /** * Returns the union of the description's static and dynamic build config references, * for the config with the given name, with duplicates omitted. The calculation is * optimized by caching the result. * Returns an empty array if the given configId does not exist in the description. */ public IBuildConfigReference[] getAllBuildConfigReferences(String configId, boolean makeCopy) { if (!hasBuildConfig(configId)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; if (!cachedRefs.containsKey(configId)) { IBuildConfigReference[] statik = getReferencedProjectConfigs(configId, false); IBuildConfigReference[] dynamic = getDynamicConfigReferences(configId, false); if (dynamic.length == 0) { cachedRefs.put(configId, statik); } else if (statik.length == 0) { cachedRefs.put(configId, dynamic); } else { //combine all references IBuildConfigReference[] result = new IBuildConfigReference[dynamic.length + statik.length]; System.arraycopy(statik, 0, result, 0, statik.length); System.arraycopy(dynamic, 0, result, statik.length, dynamic.length); cachedRefs.put(configId, copyAndRemoveDuplicates(result)); } } //still need to copy the result to prevent tampering with the cache IBuildConfigReference[] result = (IBuildConfigReference[]) cachedRefs.get(configId); return makeCopy ? (IBuildConfigReference[]) result.clone() : result; } /* (non-Javadoc) * @see IProjectDescription#getReferencedConfigs(String) */ public IBuildConfigReference[] getReferencedProjectConfigs(String configId) { return getReferencedProjectConfigs(configId, true); } public IBuildConfigReference[] getReferencedProjectConfigs(String configId, boolean makeCopy) { if (!hasBuildConfig(configId) || !staticRefs.containsKey(configId)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfigReference[] result = (IBuildConfigReference[]) staticRefs.get(configId); return makeCopy ? (IBuildConfigReference[]) result.clone() : result; } /* (non-Javadoc) * @see IProjectDescription#setReferencedConfigs(String, IBuildConfigReference[]) */ public void setReferencedProjectConfigs(String configId, IBuildConfigReference[] references) { Assert.isLegal(references != null); if (!hasBuildConfig(configId)) return; staticRefs.put(configId, copyAndRemoveDuplicates(references)); clearCachedReferences(configId); } /* (non-Javadoc) * @see IProjectDescription#getDynamicConfigReferences(String) */ public IBuildConfigReference[] getDynamicConfigReferences(String configId) { return getDynamicConfigReferences(configId, true); } public IBuildConfigReference[] getDynamicConfigReferences(String configId, boolean makeCopy) { if (!hasBuildConfig(configId) || !dynamicRefs.containsKey(configId)) return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; IBuildConfigReference[] result = (IBuildConfigReference[]) dynamicRefs.get(configId); return makeCopy ? (IBuildConfigReference[]) result.clone() : result; } /* (non-Javadoc) * @see IProjectDescription#setDynamicConfigReferences(String, IBuildConfigReference[]) */ public void setDynamicConfigReferences(String configId, IBuildConfigReference[] references) { Assert.isLegal(references != null); if (!hasBuildConfig(configId)) return; dynamicRefs.put(configId, copyAndRemoveDuplicates(references)); clearCachedReferences(configId); } /* (non-Javadoc) * @see IProjectDescription#newBuildConfiguration(String) */ public IBuildConfiguration newBuildConfiguration(String buildConfigId) { return new BuildConfiguration(buildConfigId); } /* (non-Javadoc) * @see IProjectDescription#setBuildConfigurations(IBuildConfiguration[]) */ public void setBuildConfigurations(IBuildConfiguration[] value) { if (value == null || value.length == 0) buildConfigs = DEFAULT_BUILD_CONFIGS; else { // Filter out duplicates Set filtered = new LinkedHashSet(value.length); for (int i = 0; i < value.length; i++) { BuildConfiguration config = (BuildConfiguration)((BuildConfiguration) value[i]).clone(); // Ensure the project is not set config.clearProject(); Assert.isTrue(config.internalGetProject() == null); filtered.add(config); } if (filtered.isEmpty()) buildConfigs = DEFAULT_BUILD_CONFIGS; else { buildConfigs = new BuildConfiguration[filtered.size()]; filtered.toArray(buildConfigs); } } // Remove references for deleted buildConfigs buildConfigIds = new HashSet(buildConfigs.length); for (int i = 0; i < buildConfigs.length; i++) buildConfigIds.add(buildConfigs[i].getConfigurationId()); boolean modified = false; modified |= staticRefs.keySet().retainAll(buildConfigIds); modified |= dynamicRefs.keySet().retainAll(buildConfigIds); if (modified) clearCachedReferences(); } /** * Used by Project to get the buildConfigs on the description */ public IBuildConfiguration[] internalGetBuildConfigs(boolean makeCopy) { if (buildConfigs == null || buildConfigs.length == 0) buildConfigs = DEFAULT_BUILD_CONFIGS; for (int i = 0; i < buildConfigs.length; i++) Assert.isTrue(buildConfigs[i].internalGetProject() == null); return makeCopy ? copyBuildConfigs(buildConfigs) : buildConfigs; } private IBuildConfiguration[] copyBuildConfigs(BuildConfiguration[] pvars) { IBuildConfiguration[] result = new BuildConfiguration[buildConfigs.length]; for (int i = 0; i < buildConfigs.length; i++) result[i] = (BuildConfiguration) buildConfigs[i].clone(); return result; } /** * Internal method to check if the description has a given build configuration. */ private boolean hasBuildConfig(String buildConfigId) { if (buildConfigId == null) return false; for (int i = 0; i < buildConfigs.length; i++) if (buildConfigs[i].getConfigurationId().equals(buildConfigId)) return true; return false; } /** * Clear all cached references for the given build configuration * @param configId the configuration Id to clear cached references for */ private void clearCachedReferences(String configId) { cachedRefs.remove(configId); cachedProjectRefs = null; cachedStaticProjectRefs = null; cachedDynamicProjectRefs = null; } /** * Clear all cached references for all buildConfigs */ private void clearCachedReferences() { cachedRefs = new HashMap(); cachedProjectRefs = null; cachedStaticProjectRefs = null; cachedDynamicProjectRefs = null; } /** * Returns a copy of the given array of build configs with all duplicates removed */ private IBuildConfigReference[] copyAndRemoveDuplicates(IBuildConfigReference[] values) { Set set = new LinkedHashSet(); set.addAll(Arrays.asList(values)); return (IBuildConfigReference[]) set.toArray(new IBuildConfigReference[set.size()]); } /** * Returns the union of the description's static and dynamic project references, * with duplicates omitted. The calculation is optimized by caching the result * @see #getAllBuildConfigReferences(String, boolean) */ public IProject[] getAllReferences(boolean makeCopy) { if (cachedProjectRefs == null) { IProject[] statik = getReferencedProjects(false); IProject[] dynamic = getDynamicReferences(false); if (dynamic.length == 0) { cachedProjectRefs = statik; } else if (statik.length == 0) { cachedProjectRefs = dynamic; } else { Set set = new LinkedHashSet(); set.addAll(Arrays.asList(statik)); set.addAll(Arrays.asList(dynamic)); cachedProjectRefs = (IProject[]) set.toArray(new IProject[set.size()]); } } //still need to copy the result to prevent tampering with the cache return makeCopy ? (IProject[]) cachedProjectRefs.clone() : cachedProjectRefs; } /* (non-Javadoc) * @see IProjectDescription#getReferencedProjects() */ public IProject[] getReferencedProjects() { return getReferencedProjects(true); } public IProject[] getReferencedProjects(boolean makeCopy) { if (staticRefs == null) return EMPTY_PROJECT_ARRAY; // Generate project references from build configs references if (cachedStaticProjectRefs == null) { cachedStaticProjectRefs = getProjectsFromBuildConfigReferences(staticRefs); } //still need to copy the result to prevent tampering with the cache return makeCopy ? (IProject[]) cachedStaticProjectRefs.clone() : cachedStaticProjectRefs; } /* (non-Javadoc) * @see IProjectDescription#setReferencedProjects(IProject[]) */ public void setReferencedProjects(IProject[] projects) { Assert.isLegal(projects != null); // Add all buildConfigs in each of the projects as a reference for (int i = 0; i < buildConfigs.length; i++) { + // To interact with users of the old API, we just add references to the active configuration (null configId) + // to the set of existing non-active build configuration references Set configRefs = new LinkedHashSet(); configRefs.addAll(getBuildConfigReferencesFromProjects(projects)); - configRefs.addAll(Arrays.asList(getReferencedProjectConfigs(buildConfigs[i].getConfigurationId(), false))); + // Iterate over the existing refs. Re-add any which aren't to the 'default' configuration + IBuildConfigReference[] oldRefs = getReferencedProjectConfigs(buildConfigs[i].getConfigurationId(), false); + for (int j = 0; j < oldRefs.length; j++) + if (oldRefs[j].getConfigurationId() != null) + configRefs.add(oldRefs[j]); setReferencedProjectConfigs(buildConfigs[i].getConfigurationId(), (IBuildConfigReference[])configRefs.toArray(new IBuildConfigReference[configRefs.size()])); } } /* (non-Javadoc) * @see IProjectDescription#getDynamicReferences() */ public IProject[] getDynamicReferences() { return getDynamicReferences(true); } public IProject[] getDynamicReferences(boolean makeCopy) { if (dynamicRefs == null) return EMPTY_PROJECT_ARRAY; // Generate dynamic project references from dynamic build configs references if (cachedDynamicProjectRefs == null) { cachedDynamicProjectRefs = getProjectsFromBuildConfigReferences(dynamicRefs); } return makeCopy ? (IProject[]) cachedDynamicProjectRefs.clone() : cachedDynamicProjectRefs; } /* (non-Javadoc) * @see IProjectDescription#setDynamicReferences(IProject[]) */ public void setDynamicReferences(IProject[] projects) { Assert.isLegal(projects != null); for (int i = 0; i < buildConfigs.length; i++) { - // To interact with users of the old API, we just add references to the active configuration - // To the set of existing build configuration references + // To interact with users of the old API, we just add references to the active configuration (null configId) + // to the set of existing non-active build configuration references Set configRefs = new LinkedHashSet(); configRefs.addAll(getBuildConfigReferencesFromProjects(projects)); - configRefs.addAll(Arrays.asList(getDynamicConfigReferences(buildConfigs[i].getConfigurationId(), false))); + // Iterate over the existing dynamic refs. Re-add any which aren't to the 'default' configuration + IBuildConfigReference[] oldRefs = getDynamicConfigReferences(buildConfigs[i].getConfigurationId(), false); + for (int j = 0; j < oldRefs.length; j++) + if (oldRefs[j].getConfigurationId() != null) + configRefs.add(oldRefs[j]); setDynamicConfigReferences(buildConfigs[i].getConfigurationId(), (IBuildConfigReference[])configRefs.toArray(new IBuildConfigReference[configRefs.size()])); } } /** * Get a list of projects, without duplicates, from a list of build config references. * Order is preserved, and is according to the first occurrence of a project in the * array of build configs. * @param refsMap map containing the build config references to get the projects from * @return list of projects */ private IProject[] getProjectsFromBuildConfigReferences(Map/*<String, IBuildConfigReference[]>*/ refsMap) { Set projects = new LinkedHashSet(); Iterator i = refsMap.values().iterator(); while (i.hasNext()) { IBuildConfigReference[] refs = (IBuildConfigReference[]) i.next(); for (int j = 0; j < refs.length; j++) { projects.add(refs[j].getProject()); } } return (IProject[]) projects.toArray(new Project[projects.size()]); } /** * Turns an array of projects into an array of {@link IBuildConfigReference} to the * projects' active configuration * Order is preserved - the buildConfigs appear for each project in the order * that the projects were specified. * @param projects projects to get the active configuration from * @return list of build config references */ private List getBuildConfigReferencesFromProjects(IProject[] projects) { List refs = new ArrayList(); for (int i = 0; i < projects.length; i++) { IProject project = projects[i]; refs.add(new BuildConfigReference(project)); } return refs; } }
false
false
null
null
diff --git a/src/org/linphone/LinphoneService.java b/src/org/linphone/LinphoneService.java index b06b660..7e82ea5 100644 --- a/src/org/linphone/LinphoneService.java +++ b/src/org/linphone/LinphoneService.java @@ -1,333 +1,343 @@ /* LinphoneService.java Copyright (C) 2010 Belledonne Communications, Grenoble, France This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.linphone; import java.io.IOException; import org.linphone.LinphoneManager.LinphoneServiceListener; import org.linphone.LinphoneManager.NewOutgoingCallUiListener; import org.linphone.core.LinphoneCall; +import org.linphone.core.LinphoneCoreFactoryImpl; import org.linphone.core.Log; import org.linphone.core.OnlineStatus; import org.linphone.core.LinphoneCall.State; import org.linphone.core.LinphoneCore.GlobalState; import org.linphone.core.LinphoneCore.RegistrationState; import org.linphone.mediastream.Version; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; /*** * * Linphone service, reacting to Incoming calls, ...<br /> * * Roles include:<ul> * <li>Initializing LinphoneManager</li> * <li>Starting C libLinphone through LinphoneManager</li> * <li>Reacting to LinphoneManager state changes</li> * <li>Delegating GUI state change actions to GUI listener</li> * * * @author Guillaume Beraudo * */ public final class LinphoneService extends Service implements LinphoneServiceListener { /* Listener needs to be implemented in the Service as it calls * setLatestEventInfo and startActivity() which needs a context. */ private Handler mHandler = new Handler(); private static LinphoneService instance; static boolean isReady() { return (instance!=null); } /** * @throws RuntimeException service not instantiated */ static LinphoneService instance() { if (isReady()) return instance; throw new RuntimeException("LinphoneService not instantiated yet"); } private NotificationManager mNotificationMgr; private final static int NOTIF_ID=1; private Notification mNotif; private PendingIntent mNotifContentIntent; private String notificationTitle; private static final int IC_LEVEL_ORANGE=0; /*private static final int IC_LEVEL_GREEN=1; private static final int IC_LEVEL_RED=2;*/ private static final int IC_LEVEL_OFFLINE=3; @Override public void onCreate() { super.onCreate(); // In case restart after a crash. Main in LinphoneActivity LinphonePreferenceManager.getInstance(this); // Set default preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, true); notificationTitle = getString(R.string.app_name); // Dump some debugging information to the logs Log.i(START_LINPHONE_LOGS); dumpDeviceInformation(); dumpInstalledLinphoneInformation(); mNotificationMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); mNotif = new Notification(R.drawable.status_level, "", System.currentTimeMillis()); mNotif.iconLevel=IC_LEVEL_ORANGE; mNotif.flags |= Notification.FLAG_ONGOING_EVENT; Intent notifIntent = new Intent(this, LinphoneActivity.class); mNotifContentIntent = PendingIntent.getActivity(this, 0, notifIntent, 0); mNotif.setLatestEventInfo(this, notificationTitle,"", mNotifContentIntent); mNotificationMgr.notify(NOTIF_ID, mNotif); LinphoneManager.createAndStart(this, this); LinphoneManager.getLc().setPresenceInfo(0, null, OnlineStatus.Online); instance = this; // instance is ready once linphone manager has been created } public static final String START_LINPHONE_LOGS = " ==== Phone information dump ===="; private void dumpDeviceInformation() { StringBuilder sb = new StringBuilder(); sb.append("DEVICE=").append(Build.DEVICE).append("\n"); sb.append("MODEL=").append(Build.MODEL).append("\n"); //MANUFACTURER doesn't exist in android 1.5. //sb.append("MANUFACTURER=").append(Build.MANUFACTURER).append("\n"); sb.append("SDK=").append(Build.VERSION.SDK); Log.i(sb.toString()); } private void dumpInstalledLinphoneInformation() { PackageInfo info = null; try { info = getPackageManager().getPackageInfo(getPackageName(),0); } catch (NameNotFoundException nnfe) {} if (info != null) { Log.i("Linphone version is ", info.versionCode); } else { Log.i("Linphone version is unknown"); } } private void sendNotification(int level, int textId) { mNotif.iconLevel = level; mNotif.when=System.currentTimeMillis(); String text = getString(textId); if (text.contains("%s")) { String id = LinphoneManager.getLc().getDefaultProxyConfig().getIdentity(); text = String.format(text, id); } mNotif.setLatestEventInfo(this, notificationTitle, text, mNotifContentIntent); mNotificationMgr.notify(NOTIF_ID, mNotif); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); LinphoneManager.getLcIfManagerNotDestroyedOrNull().setPresenceInfo(0, null, OnlineStatus.Offline); LinphoneManager.destroy(this); mNotificationMgr.cancel(NOTIF_ID); instance=null; } private static final LinphoneGuiListener guiListener() { return DialerActivity.instance(); } public void onDisplayStatus(final String message) { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onDisplayStatus(message); } }); } public void onGlobalStateChanged(final GlobalState state, final String message) { if (state == GlobalState.GlobalOn) { sendNotification(IC_LEVEL_OFFLINE, R.string.notification_started); mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onGlobalStateChangedToOn(message); } }); } } public void onRegistrationStateChanged(final RegistrationState state, final String message) { if (state == RegistrationState.RegistrationOk && LinphoneManager.getLc().getDefaultProxyConfig().isRegistered()) { sendNotification(IC_LEVEL_ORANGE, R.string.notification_registered); } if (state == RegistrationState.RegistrationFailed) { sendNotification(IC_LEVEL_OFFLINE, R.string.notification_register_failure); } if (state == RegistrationState.RegistrationOk || state == RegistrationState.RegistrationFailed) { mHandler.post(new Runnable() { public void run() { if (LinphoneActivity.isInstanciated()) LinphoneActivity.instance().onRegistrationStateChanged(state, message); } }); } } public void onCallStateChanged(final LinphoneCall call, final State state, final String message) { if (state == LinphoneCall.State.IncomingReceived) { //wakeup linphone startActivity(new Intent() .setClass(this, LinphoneActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } else if (state == LinphoneCall.State.StreamsRunning) { if (Version.isVideoCapable() && getResources().getBoolean(R.bool.use_video_activity) && !VideoCallActivity.launched && LinphoneActivity.isInstanciated() && call.getCurrentParamsCopy().getVideoEnabled()) { // Do not call if video activity already launched as it would cause a pause() of the launched one // and a race condition with capture surfaceview leading to a crash LinphoneActivity.instance().startVideoActivity(); } + else if (VideoCallActivity.launched && LinphoneActivity.isInstanciated() + && !call.getCurrentParamsCopy().getVideoEnabled()) { + LinphoneActivity.instance().finishVideoActivity(); + } + } else if (state == LinphoneCall.State.CallUpdatedByRemote) { + if (VideoCallActivity.launched && LinphoneActivity.isInstanciated() + && !call.getCurrentParamsCopy().getVideoEnabled()) { + LinphoneActivity.instance().finishVideoActivity(); + } } mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onCallStateChanged(call, state, message); } }); } public interface LinphoneGuiListener extends NewOutgoingCallUiListener { void onDisplayStatus(String message); void onGlobalStateChangedToOn(String message); // void onRegistrationStateChanged(RegistrationState state, String message); void onCallStateChanged(LinphoneCall call, State state, String message); void onCallEncryptionChanged(LinphoneCall call, boolean encrypted, String authenticationToken); } public void onRingerPlayerCreated(MediaPlayer mRingerPlayer) { final Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); try { mRingerPlayer.setDataSource(getApplicationContext(), ringtoneUri); } catch (IOException e) { Log.e(e, "cannot set ringtone"); } } public void tryingNewOutgoingCallButAlreadyInCall() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onAlreadyInCall(); } }); } public void tryingNewOutgoingCallButCannotGetCallParameters() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onCannotGetCallParameters(); } }); } public void tryingNewOutgoingCallButWrongDestinationAddress() { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onWrongDestinationAddress(); } }); } public void onAlreadyInVideoCall() { LinphoneActivity.instance().startVideoActivity(); } public void onCallEncryptionChanged(final LinphoneCall call, final boolean encrypted, final String authenticationToken) { mHandler.post(new Runnable() { public void run() { if (guiListener() != null) guiListener().onCallEncryptionChanged(call, encrypted, authenticationToken); } }); } }
false
false
null
null
diff --git a/cadpage/src/net/anei/cadpage/parsers/SC/SCOconeeCountyParser.java b/cadpage/src/net/anei/cadpage/parsers/SC/SCOconeeCountyParser.java index 907be8f74..6405d2cc7 100644 --- a/cadpage/src/net/anei/cadpage/parsers/SC/SCOconeeCountyParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/SC/SCOconeeCountyParser.java @@ -1,145 +1,149 @@ package net.anei.cadpage.parsers.SC; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.parsers.FieldProgramParser; import net.anei.cadpage.parsers.MsgInfo.Data; /* Oconee County, SC Contact: William Rochester <william.rocheste Sender: 911@oconeelaw.com System: Aegis [911 Message] S80 - CORONARY PROBLEM 1280 N STHY 11 XStreet: SPRINGDALE DR / SCENIC HEIGHTS RD, FOWLER RD WEST UNION 2011-00000815 09/26/11 22:27 Narr: S [911 Message] S80 - CORONARY PROBLEM 206 S TUGALOO ST XStreet: W MAULDIN ST / BOOKER DR WALHALLA 2011-00000809 09/25/11 06:49 Narr: PATIENT IS HER FATHER [911 Message] S46 - ALTERED MENTAL STATUS 308 N LAUREL ST XStreet: ARDASHIR LN / WALHALLA GARDENS CIR WALHALLA 2011-00000777 09/16/11 12:24 Narr: 76 YOA (911 Message) S4 - DIABETIC REACTION 100 PINE MANOR CIR APT 3 XStreet: STOUDEMIRE ST / STOUDEMIRE ST WALHALLA COUNTRY RIDGE APTS 2011-00000872 10/26/11 19:21 (911 Message) LIFT ASSISTANCE 313 MANOR LN XStreet: INDUSTRIAL PARK PL / DEAD END SENECA 12/02/11 01:06 Narr: COME TO THE BACK DOOR NEEDS HELP GETTING UP (911 Message) S86 - CHEST PAIN 3440 BLUE RIDGE BLVD XStreet: MISTY DR, THE OLE HOME PLACE LN / TRAVELLERS BLVD WEST UNION EDWARDS AUTO SALES 2011-00000946 11/ (911 Message) LIFT ASSISTANCE 313 MANOR LN XStreet: INDUSTRIAL PARK PL / DEAD END SENECA 12/02/11 01:06 Narr: COME TO THE BACK DOOR NEEDS HELP GETTING UP Contact: support@active911.com (911 Message) S74 - RESPIRATORY DISTRESS 502 VERA DR XStreet: HOBSON ST / DEAD END WESTMINSTER 2012-00000025 01/14/12 01:28 Narr: TONED RQ5 DOES HAVE HEART PROBLEMS HEART PT HAVING TROUBLE BREATHING E911 Info - Class of Service: RESD Special Response Info: WESTMINSTER CITY PD WESTMINSTER CITY FIRE EMS ER-5 ER-3 +(911 Message) 70S - STRUCTURE FIRE 10941 CLEMSON BLVD XStreet: PRESSLEY PL / SONNYS DR SENECA BQS #5 CLEMSON BLVD 01/16/12 17:44 Narr: IN NEIGHBORHOOD BEHIND THE ROAD RUNNER SOMEWHERE ACROSS STREET E911 Info - Class of Service: BUSN Special Response Info: SHERIFF DEPT SENECA CORINTH-SHILOH FIRE #3 EMS ER-1 ER-2 +(911 Message) LIFT ASSISTANCE 1407 W LITTLE RIVER DR XStreet: AZURE COVE CT / KEOWEE LAKESHORE DR SENECA 01/15/12 20:43 Narr: NO 10-52 RESPONDING UNLESS NEEDED HE HAS FALLEN NEEDS HELP LIFTING SOMEONE OUT OF THE FLOOR E911 Info - Class of Service: RESD Special Response Info: SHERIFF DEPT SENECA CORINTH-SHILOH FIRE #3 EMS ER-1 ER-2 +(911 Message) S32 - SPINAL INJURY 105 GLORIA LN XStreet: SHILOH RD / DEAD END SENECA 2012-00000009 01/13/12 17:35 Narr: CANT MOVE HIS LEG HUSBAND FELL BATHROOM FLOOR + */ public class SCOconeeCountyParser extends FieldProgramParser { private static final Pattern ID_PTN = Pattern.compile(" (\\d{4}-\\d{8}) "); - private static final Pattern DATE_TIME_MARK = Pattern.compile(" (\\d\\d/\\d\\d/\\d\\d) (\\d\\d:\\d\\d)\\b"); + private static final Pattern DATE_TIME_MARK = Pattern.compile(" +(\\d\\d/\\d\\d/\\d\\d) (\\d\\d:\\d\\d)\\b"); private static final Pattern DATE_TIME_MARK2 = Pattern.compile("^(\\d\\d/\\d\\d/\\d\\d) (\\d\\d:\\d\\d)\\b"); private static final String DATE_TIME_MARK3 = "NN/NN/NN NN:NN"; public SCOconeeCountyParser() { super(CITY_LIST, "OCONEE COUNTY", "SC", "BASE! Narr:INFO E911_Info_-_Class_of_Service:SKIP Special_Response_Info:SKIP"); } @Override public String getFilter() { return "911@oconeelaw.com"; } @Override public boolean parseMsg(String subject, String body, Data data) { if (!subject.equals("911 Message")) return false; return super.parseMsg(body, data); } private class BaseField extends Field { @Override public void parse(String body, Data data) { // Look for an ID marker String sLeader = null; String sTrailer = null; do { Matcher match = ID_PTN.matcher(body); if (match.find()) { // Found it, get the ID and identify leading portion data.strCallId = match.group(1); sLeader = body.substring(0,match.start()).trim(); sTrailer = body.substring(match.end()).trim(); // This should be followed by a date and time match = DATE_TIME_MARK2.matcher(sTrailer); if (match.find()) { data.strDate = match.group(1); data.strTime = match.group(2); sTrailer = sTrailer.substring(match.end()).trim(); break; } // If it isn't, see if it is a truncated Date/time String sCheck = sTrailer.replaceAll("\\d", "N"); if (! DATE_TIME_MARK3.startsWith(sCheck)) abort(); sTrailer = ""; break; } match = DATE_TIME_MARK.matcher(body); if (match.find()) { data.strDate = match.group(1); data.strTime = match.group(2); sLeader = body.substring(0,match.start()).trim(); sTrailer = body.substring(match.end()).trim(); break; } abort(); } while (false); int pt = sLeader.indexOf(" "); if (pt < 0) abort(); data.strCall = sLeader.substring(0,pt); String sAddr = sLeader.substring(pt+2).trim(); sAddr = sAddr.replace(" XStreet:", " XS:"); parseAddress(StartType.START_ADDR, FLAG_START_FLD_REQ, sAddr, data); data.strPlace = getLeft(); } @Override public String getFieldNames() { return "CALL ADDR X CITY ID DATE TIME"; } } private class MyUnitField extends UnitField { @Override public void parse(String field, Data data) { int pt = field.indexOf(" "); if (pt >= 0) field = field.substring(pt+2).trim(); super.parse(field, data); } } @Override protected Field getField(String name) { if (name.equals("BASE")) return new BaseField(); if (name.equals("UNIT")) return new MyUnitField(); return super.getField(name); } private static final String[] CITY_LIST = new String[]{ "SALEM", "SENECA", "WALHALLA", "WEST UNION", "WESTMINSTER", "FAIR PLAY", "LONG CREEK", "MOUNTAIN REST", "NEWRY", "OAKWAY", "RICHLAND", "TAMASSEE", "TOWNVILLE", "UTICA" }; }
false
false
null
null
diff --git a/src/net/sf/freecol/server/ai/AIColony.java b/src/net/sf/freecol/server/ai/AIColony.java index d041779a8..b9269ebab 100644 --- a/src/net/sf/freecol/server/ai/AIColony.java +++ b/src/net/sf/freecol/server/ai/AIColony.java @@ -1,1584 +1,1595 @@ /** * Copyright (C) 2002-2011 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.ai; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.common.model.AbstractGoods; import net.sf.freecol.common.model.BuildableType; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.EquipmentType; import net.sf.freecol.common.model.ExportData; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.Location; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TileImprovement; import net.sf.freecol.common.model.TileImprovementType; import net.sf.freecol.common.model.TypeCountMap; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.model.UnitTypeChange; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.model.UnitTypeChange.ChangeType; import net.sf.freecol.common.networking.Connection; import net.sf.freecol.common.networking.Message; import net.sf.freecol.server.ai.AIMessage; import net.sf.freecol.server.ai.AIPlayer; import net.sf.freecol.server.ai.mission.PioneeringMission; import net.sf.freecol.server.ai.mission.TransportMission; import net.sf.freecol.server.ai.mission.WorkInsideColonyMission; import org.w3c.dom.Element; /** * Objects of this class contains AI-information for a single {@link Colony}. */ public class AIColony extends AIObject implements PropertyChangeListener { private static final Logger logger = Logger.getLogger(AIColony.class.getName()); private static enum ExperienceUpgrade { NONE, SOME, EXPERT } /** * The FreeColGameObject this AIObject contains AI-information for. */ private Colony colony; private ColonyPlan colonyPlan; private ArrayList<AIGoods> aiGoods = new ArrayList<AIGoods>(); private ArrayList<Wish> wishes = new ArrayList<Wish>(); private ArrayList<TileImprovementPlan> tileImprovementPlans = new ArrayList<TileImprovementPlan>(); /** * Records whether the workers in this Colony need to be * rearranged. */ private boolean rearrangeWorkers = false; /** * Creates a new <code>AIColony</code>. * * @param aiMain The main AI-object. * @param colony The colony to make an {@link AIObject} for. */ public AIColony(AIMain aiMain, Colony colony) { super(aiMain, colony.getId()); this.colony = colony; colonyPlan = new ColonyPlan(aiMain, colony); colony.addPropertyChangeListener(Colony.REARRANGE_WORKERS, this); } /** * Creates a new <code>AIColony</code>. * * @param aiMain The main AI-object. * @param element An <code>Element</code> containing an XML-representation * of this object. */ public AIColony(AIMain aiMain, Element element) { super(aiMain, element.getAttribute("ID")); readFromXMLElement(element); } /** * Creates a new <code>AIColony</code>. * * @param aiMain The main AI-object. * @param in The input stream containing the XML. * @throws XMLStreamException if a problem was encountered during parsing. */ public AIColony(AIMain aiMain, XMLStreamReader in) throws XMLStreamException { super(aiMain, in.getAttributeValue(null, "ID")); readFromXML(in); } protected AIUnit getAIUnit(Unit unit) { return (AIUnit) getAIMain().getAIObject(unit); } protected AIPlayer getAIOwner() { return (AIPlayer) getAIMain().getAIObject(colony.getOwner()); } protected Connection getConnection() { return getAIOwner().getConnection(); } /** * Creates a new <code>AIColony</code>. * * @param aiMain The main AI-object. * @param id */ public AIColony(AIMain aiMain, String id) { this(aiMain, (Colony) aiMain.getGame().getFreeColGameObject(id)); } /** * Gets the <code>Colony</code> this <code>AIColony</code> controls. * * @return The <code>Colony</code>. */ public Colony getColony() { return colony; } /** * Disposes this <code>AIColony</code>. */ public void dispose() { List<AIObject> disposeList = new ArrayList<AIObject>(); for (AIGoods ag : aiGoods) { if (ag.getGoods().getLocation() == colony) { disposeList.add(ag); } } for(Wish w : wishes) { disposeList.add(w); } for(TileImprovementPlan ti : tileImprovementPlans) { disposeList.add(ti); } for(AIObject o : disposeList) { o.dispose(); } super.dispose(); } /** * Returns an <code>Iterator</code> of the goods to be shipped from this * colony. The item with the highest * {@link Transportable#getTransportPriority transport priority} gets * returned first by this <code>Iterator</code>. * * @return The <code>Iterator</code>. */ public Iterator<AIGoods> getAIGoodsIterator() { Iterator<AIGoods> agi = aiGoods.iterator(); // TODO: Remove the following code and replace by throw RuntimeException while (agi.hasNext()) { AIGoods ag = agi.next(); if (ag.getGoods().getLocation() != colony) { agi.remove(); } } return aiGoods.iterator(); } /** * Gets an <code>Iterator</code> for every <code>Wish</code> the * <code>Colony</code> has. * * @return The <code>Iterator</code>. The items with the * {@link Wish#getValue highest value} appears first in the * <code>Iterator</code> * @see Wish */ public Iterator<Wish> getWishIterator() { return wishes.iterator(); } /** * Creates a list of the <code>Tile</code>-improvements which will * increase the production by this <code>Colony</code>. * * @see TileImprovementPlan */ public void createTileImprovementPlans() { Map<Tile, TileImprovementPlan> plans = new HashMap<Tile, TileImprovementPlan>(); for (TileImprovementPlan plan : tileImprovementPlans) { plans.put(plan.getTarget(), plan); } for (WorkLocationPlan wlp : colonyPlan.getWorkLocationPlans()) { if (wlp.getWorkLocation() instanceof ColonyTile) { ColonyTile colonyTile = (ColonyTile) wlp.getWorkLocation(); Tile target = colonyTile.getWorkTile(); boolean others = target.getOwningSettlement() != colony && target.getOwner() == colony.getOwner(); TileImprovementPlan plan = plans.get(target); if (plan == null) { if (others) continue; // owned by another of our colonies plan = wlp.createTileImprovementPlan(); if (plan != null) { int value = plan.getValue(); if (colonyTile.getUnit() != null) value *= 2; value -= colony.getOwner().getLandPrice(target); plan.setValue(value); tileImprovementPlans.add(plan); plans.put(target, plan); } } else if (wlp.updateTileImprovementPlan(plan) == null || others) { tileImprovementPlans.remove(plan); plan.dispose(); } } } Tile centerTile = colony.getTile(); TileImprovementPlan centerPlan = plans.get(centerTile); TileImprovementType type = TileImprovement .findBestTileImprovementType(centerTile, colony.getSpecification() .getGoodsType("model.goods.grain")); if (type == null) { if (centerPlan != null) { tileImprovementPlans.remove(centerPlan); } } else { if (centerPlan == null) { centerPlan = new TileImprovementPlan(getAIMain(), colony.getTile(), type, 30); tileImprovementPlans.add(0, centerPlan); } else { centerPlan.setType(type); } } Collections.sort(tileImprovementPlans); } /** * Returns an <code>Iterator</code> over all the * <code>TileImprovementPlan</code>s needed by this colony. * * @return The <code>Iterator</code>. * @see TileImprovementPlan */ public Iterator<TileImprovementPlan> getTileImprovementPlanIterator() { return tileImprovementPlans.iterator(); } /** * Removes a <code>TileImprovementPlan</code> from the list * @return True if it was successfully deleted, false otherwise */ public boolean removeTileImprovementPlan(TileImprovementPlan plan){ return tileImprovementPlans.remove(plan); } /** * Creates the wishes for the <code>Colony</code>. */ private void createWishes() { wishes.clear(); int expertValue = 100; int goodsWishValue = 50; // for every non-expert, request expert replacement for (Unit unit : colony.getUnitList()) { if (unit.getWorkType() != null && unit.getWorkType() != unit.getType().getExpertProduction()) { UnitType expert = colony.getSpecification().getExpertForProducing(unit.getWorkType()); wishes.add(new WorkerWish(getAIMain(), colony, expertValue, expert, true)); } } // request population increase if (wishes.isEmpty()) { int newPopulation = colony.getUnitCount() + 1; if (colony.governmentChange(newPopulation) >= 0) { // population increase incurs no penalty boolean needFood = colony.getFoodProduction() <= colony.getFoodConsumption() + colony.getOwner().getMaximumFoodConsumption(); // choose expert for best work location plan UnitType expert = getNextExpert(needFood); wishes.add(new WorkerWish(getAIMain(), colony, expertValue / 5, expert, false)); } } // TODO: check for students // increase defense value boolean badlyDefended = isBadlyDefended(); if (badlyDefended) { UnitType bestDefender = null; for (UnitType unitType : colony.getSpecification().getUnitTypeList()) { if ((bestDefender == null || bestDefender.getDefence() < unitType.getDefence()) && !unitType.hasAbility("model.ability.navalUnit") && unitType.isAvailableTo(colony.getOwner())) { bestDefender = unitType; } } if (bestDefender != null) { wishes.add(new WorkerWish(getAIMain(), colony, expertValue, bestDefender, true)); } } // request goods // TODO: improve heuristics TypeCountMap<GoodsType> requiredGoods = new TypeCountMap<GoodsType>(); // add building materials if (colony.getCurrentlyBuilding() != null) { for (AbstractGoods goods : colony.getCurrentlyBuilding().getGoodsRequired()) { if (colony.getProductionNetOf(goods.getType()) == 0) { requiredGoods.incrementCount(goods.getType(), goods.getAmount()); } } } // add materials required to improve tiles for (TileImprovementPlan plan : tileImprovementPlans) { for (AbstractGoods goods : plan.getType().getExpendedEquipmentType() .getGoodsRequired()) { requiredGoods.incrementCount(goods.getType(), goods.getAmount()); } } // add raw materials for buildings for (WorkLocation workLocation : colony.getWorkLocations()) { if (workLocation instanceof Building) { Building building = (Building) workLocation; GoodsType inputType = building.getGoodsInputType(); if (inputType != null && colony.getProductionNetOf(inputType) < building.getMaximumGoodsInput()) { requiredGoods.incrementCount(inputType, 100); } } } // add breedable goods for (GoodsType goodsType : colony.getSpecification().getGoodsTypeList()) { if (goodsType.isBreedable()) { requiredGoods.incrementCount(goodsType, goodsType.getBreedingNumber()); } } // add materials required to build military equipment if (badlyDefended) { for (EquipmentType type : colony.getSpecification().getEquipmentTypeList()) { if (type.isMilitaryEquipment()) { for (Unit unit : colony.getUnitList()) { if (unit.canBeEquippedWith(type)) { for (AbstractGoods goods : type.getGoodsRequired()) { requiredGoods.incrementCount(goods.getType(), goods.getAmount()); } break; } } } } } for (GoodsType type : requiredGoods.keySet()) { GoodsType requiredType = type; while (requiredType != null && !requiredType.isStorable()) { requiredType = requiredType.getRawMaterial(); } if (requiredType != null) { int amount = Math.min((requiredGoods.getCount(requiredType) - colony.getGoodsCount(requiredType)), colony.getWarehouseCapacity()); if (amount > 0) { int value = colonyCouldProduce(requiredType) ? goodsWishValue / 10 : goodsWishValue; wishes.add(new GoodsWish(getAIMain(), colony, value, amount, requiredType)); } } } Collections.sort(wishes); } private boolean colonyCouldProduce(GoodsType goodsType) { if (goodsType.isBreedable()) { return colony.getGoodsCount(goodsType) >= goodsType.getBreedingNumber(); } else if (goodsType.isFarmed()) { for (ColonyTile colonyTile : colony.getColonyTiles()) { if (colonyTile.getWorkTile().potential(goodsType, null) > 0) { return true; } } } else { if (!colony.getBuildingsForProducing(goodsType).isEmpty()) { if (goodsType.getRawMaterial() == null) { return true; } else { return colonyCouldProduce(goodsType.getRawMaterial()); } } } return false; } private UnitType getNextExpert(boolean onlyFood) { // some type should be returned, not null UnitType bestType = colony.getSpecification().getUnitType("model.unit.freeColonist"); for (WorkLocationPlan plan : colonyPlan.getSortedWorkLocationPlans()) { if (plan.getGoodsType().isFoodType() || !onlyFood) { WorkLocation location = plan.getWorkLocation(); if (location instanceof ColonyTile) { ColonyTile colonyTile = (ColonyTile) location; if (colonyTile.getUnit() == null && (colonyTile.getWorkTile().isLand() || colony.hasAbility("model.ability.produceInWater"))) { bestType = colony.getSpecification() .getExpertForProducing(plan.getGoodsType()); break; } } else if (location instanceof Building) { Building building = (Building) location; if (building.getUnitCount() < building.getMaxUnits()) { bestType = building.getExpertUnitType(); break; } } } } return bestType; } private int getToolsRequired(BuildableType buildableType) { int toolsRequiredForBuilding = 0; if (buildableType != null) { for (AbstractGoods goodsRequired : buildableType.getGoodsRequired()) { if (goodsRequired.getType() == colony.getSpecification().getGoodsType("model.goods.tools")) { toolsRequiredForBuilding = goodsRequired.getAmount(); break; } } } return toolsRequiredForBuilding; } private int getHammersRequired(BuildableType buildableType) { int hammersRequiredForBuilding = 0; if (buildableType != null) { for (AbstractGoods goodsRequired : buildableType.getGoodsRequired()) { if (goodsRequired.getType() == colony.getSpecification().getGoodsType("model.goods.hammers")) { hammersRequiredForBuilding = goodsRequired.getAmount(); break; } } } return hammersRequiredForBuilding; } public boolean isBadlyDefended() { int defence = 0; for (Unit unit : colony.getTile().getUnitList()) { // TODO: better algorithm to determine defence // should be located in combat model? defence += unit.getType().getDefence(); if (unit.isArmed()) { defence += 1; } if (unit.isMounted()) { defence += 1; } } // TODO: is this heuristic suitable? return defence < 3 * colony.getUnitCount(); } public void removeWish(Wish w) { wishes.remove(w); } /** * Add a <code>GoodsWish</code> to the wish list. * * @param gw The <code>GoodsWish</code> to be added. */ public void addGoodsWish(GoodsWish gw) { wishes.add(gw); } /** * Removes the given <code>AIGoods</code> from this colony's list. The * <code>AIGoods</code>-object is not disposed as part of this operation. * Use that method instead to remove the object completely (this method * would then be called indirectly). * * @param ag The <code>AIGoods</code> to be removed. * @see AIGoods#dispose() */ public void removeAIGoods(AIGoods ag) { while (aiGoods.remove(ag)) { /* Do nothing here */ } } /** * Creates a list of the goods which should be shipped out of this colony. * This is the list {@link #getAIGoodsIterator} returns the * <code>Iterator</code> for. */ public void createAIGoods() { int capacity = colony.getWarehouseCapacity(); if (colony.hasAbility("model.ability.export")) { for (GoodsType goodsType : colony.getSpecification().getGoodsTypeList()) { if (goodsType.isTradeGoods()) { // can only be produced in Europe colony.setExportData(new ExportData(goodsType, false, 0)); } else if (!goodsType.isStorable()) { // abstract goods such as hammers colony.setExportData(new ExportData(goodsType, false, 0)); } else if (goodsType.isBreedable()) { colony.setExportData(new ExportData(goodsType, true, capacity - 20)); } else if (goodsType.isMilitaryGoods()) { colony.setExportData(new ExportData(goodsType, true, capacity - 50)); } else if (goodsType.isBuildingMaterial()) { colony.setExportData(new ExportData(goodsType, true, Math.min(capacity, 250))); } else if (goodsType.isFoodType()) { colony.setExportData(new ExportData(goodsType, false, 0)); } else if (goodsType.isNewWorldGoodsType() || goodsType.isRefined()) { colony.setExportData(new ExportData(goodsType, true, 0)); } else { colony.setExportData(new ExportData(goodsType, false, 0)); } } aiGoods.clear(); } else { ArrayList<AIGoods> newAIGoods = new ArrayList<AIGoods>(); List<GoodsType> goodsList = colony.getSpecification().getGoodsTypeList(); loop: for (GoodsType goodsType : goodsList) { // Never export food and lumber if (goodsType.isFoodType() || goodsType == colony.getSpecification().getGoodsType("model.goods.lumber")) { continue; } // Never export unstorable goods if (!goodsType.isStorable()) { continue; } // Only export military goods if we do not have room for them: if (goodsType.isMilitaryGoods() && (colony.getProductionOf(goodsType) == 0 || (colony.getGoodsCount(goodsType) < capacity - colony.getProductionOf(goodsType)))) { continue; } // don't export stuff we need for (Wish wish : wishes) { if (wish instanceof GoodsWish && ((GoodsWish) wish).getGoodsType() == goodsType) { continue loop; } } Building consumer = colony.getBuildingForConsuming(goodsType); if (consumer != null && colony.getProductionOf(goodsType) < consumer.getGoodsInput()) { continue; } /* * Only export tools if we are producing it in this colony and have * sufficient amounts in warehouse: */ // TODO: make this more generic if (goodsType == colony.getSpecification().getGoodsType("model.goods.tools") && colony.getGoodsCount(colony.getSpecification().getGoodsType("model.goods.tools")) > 0) { if (colony.getProductionNetOf(colony.getSpecification().getGoodsType("model.goods.tools")) > 0) { final BuildableType currentlyBuilding = colony.getCurrentlyBuilding(); int requiredTools = getToolsRequired(currentlyBuilding); int requiredHammers = getHammersRequired(currentlyBuilding); int buildTurns = (requiredHammers - colony.getGoodsCount(colony.getSpecification().getGoodsType("model.goods.hammers"))) / (colony.getProductionOf(colony.getSpecification().getGoodsType("model.goods.hammers")) + 1); if (requiredTools > 0) { if (colony.getWarehouseCapacity() > 100) { requiredTools += 100; } int toolsProductionTurns = requiredTools / colony.getProductionNetOf(colony.getSpecification().getGoodsType("model.goods.tools")); if (buildTurns <= toolsProductionTurns + 1) { continue; } } else if (colony.getWarehouseCapacity() > 100 && colony.getGoodsCount(colony.getSpecification().getGoodsType("model.goods.tools")) <= 100) { continue; } } else { continue; } } if (colony.getGoodsCount(goodsType) > 0) { List<AIGoods> alreadyAdded = new ArrayList<AIGoods>(); for (int j = 0; j < aiGoods.size(); j++) { AIGoods ag = aiGoods.get(j); if (ag == null) { logger.warning("aiGoods == null"); } else if (ag.getGoods() == null) { logger.warning("aiGoods.getGoods() == null"); if (ag.isUninitialized()) { logger.warning("AIGoods uninitialized: " + ag.getId()); } } if (ag != null && ag.getGoods() != null && ag.getGoods().getType() == goodsType && ag.getGoods().getLocation() == colony) { alreadyAdded.add(ag); } } int amountRemaining = colony.getGoodsCount(goodsType); for (int i = 0; i < alreadyAdded.size(); i++) { AIGoods oldGoods = alreadyAdded.get(i); if (oldGoods.getGoods().getLocation() != colony) { continue; } if (oldGoods.getGoods().getAmount() < 100 && oldGoods.getGoods().getAmount() < amountRemaining) { int goodsAmount = Math.min(100, amountRemaining); oldGoods.getGoods().setAmount(goodsAmount); if (amountRemaining >= colony.getWarehouseCapacity() && oldGoods.getTransportPriority() < AIGoods.IMPORTANT_DELIVERY) { oldGoods.setTransportPriority(AIGoods.IMPORTANT_DELIVERY); } else if (goodsAmount == 100 && oldGoods.getTransportPriority() < AIGoods.FULL_DELIVERY) { oldGoods.setTransportPriority(AIGoods.FULL_DELIVERY); } amountRemaining -= goodsAmount; newAIGoods.add(oldGoods); } else if (oldGoods.getGoods().getAmount() > amountRemaining) { if (amountRemaining == 0) { if (oldGoods.getTransport() != null && oldGoods.getTransport().getMission() instanceof TransportMission) { ((TransportMission) oldGoods.getTransport().getMission()) .removeFromTransportList(oldGoods); } oldGoods.dispose(); } else { oldGoods.getGoods().setAmount(amountRemaining); newAIGoods.add(oldGoods); amountRemaining = 0; } } else { newAIGoods.add(oldGoods); amountRemaining -= oldGoods.getGoods().getAmount(); } } while (amountRemaining > 0) { if (amountRemaining >= 100) { AIGoods newGoods = new AIGoods(getAIMain(), colony, goodsType, 100, getColony().getOwner() .getEurope()); if (amountRemaining >= colony.getWarehouseCapacity()) { newGoods.setTransportPriority(AIGoods.IMPORTANT_DELIVERY); } else { newGoods.setTransportPriority(AIGoods.FULL_DELIVERY); } newAIGoods.add(newGoods); amountRemaining -= 100; } else { AIGoods newGoods = new AIGoods(getAIMain(), colony, goodsType, amountRemaining, getColony() .getOwner().getEurope()); newAIGoods.add(newGoods); amountRemaining = 0; } } } } aiGoods.clear(); Iterator<AIGoods> nai = newAIGoods.iterator(); while (nai.hasNext()) { AIGoods ag = nai.next(); int i; for (i = 0; i < aiGoods.size() && aiGoods.get(i).getTransportPriority() > ag.getTransportPriority(); i++) ; aiGoods.add(i, ag); } } } /** * Returns the available amount of the GoodsType given. * * @return The amount of tools not needed for the next thing we are * building. */ public int getAvailableGoods(GoodsType goodsType) { int materialsRequiredForBuilding = 0; if (colony.getCurrentlyBuilding() != null) { for (AbstractGoods materials : colony.getCurrentlyBuilding().getGoodsRequired()) { if (materials.getType() == goodsType) { materialsRequiredForBuilding = materials.getAmount(); break; } } } return Math.max(0, colony.getGoodsCount(goodsType) - materialsRequiredForBuilding); } /** * Returns <code>true</code> if this AIColony can build the given * type of equipment. Unlike the method of the Colony, this takes * goods "reserved" for building or breeding purposes into account. * * @param equipmentType an <code>EquipmentType</code> value * @return a <code>boolean</code> value * @see Colony#canBuildEquipment(EquipmentType equipmentType) */ public boolean canBuildEquipment(EquipmentType equipmentType) { if (getColony().canBuildEquipment(equipmentType)) { for (AbstractGoods goods : equipmentType.getGoodsRequired()) { int breedingNumber = goods.getType().getBreedingNumber(); if (breedingNumber != GoodsType.INFINITY && getColony().getGoodsCount(goods.getType()) < goods.getAmount() + breedingNumber) { return false; } if (getAvailableGoods(goods.getType()) < goods.getAmount()) { return false; } } return true; } else { return false; } } + /** + * Try to use a tile. Steal it if necessary. + * + * @param tile The <code>Tile</code> to use. + * @return True if the tile can be used. + */ + private boolean tryUseTile(Tile tile) { + if (tile.getOwningSettlement() == colony) return true; + return colony.getOwner().canClaimForSettlement(tile) + && AIMessage.askClaimLand(getConnection(), tile, colony, 0) + && tile.getOwningSettlement() == colony; + } /** * Find a colony's best tile to put a unit to produce a type of * goods. Steals land from other settlements only when it is * free. * * @param unit The <code>Unit</code> to work the tile. * @param goodsType The type of goods to produce. * @return The best choice of available vacant colony tiles, or * null if nothing suitable. */ private ColonyTile getBestVacantTile(Unit unit, GoodsType goodsType) { ColonyTile colonyTile = colony.getVacantColonyTileFor(unit, true, goodsType); if (colonyTile == null) return null; // Check if the tile needs to be claimed from another settlement. Tile tile = colonyTile.getWorkTile(); - if (tile.getOwningSettlement() != colony) { - if (!AIMessage.askClaimLand(getConnection(), tile, colony, 0) - || tile.getOwningSettlement() != colony) { - return null; // Claim failed. - } - } - return colonyTile; + return (tryUseTile(tile)) ? colonyTile : null; } /** * Rearranges the workers within this colony. This is done according to the * {@link ColonyPlan}, although minor adjustments can be done to increase * production. * * @param connection The <code>Connection</code> to be used when * communicating with the server. */ public boolean rearrangeWorkers(Connection connection) { colonyPlan.create(); if (!rearrangeWorkers) { logger.fine("No need to rearrange workers in " + colony.getName() + "."); return false; } // TODO: Detect a siege and move the workers temporarily around. checkForUnequippedExpertPioneer(); checkForUnarmedExpertSoldier(); List<Unit> units = new ArrayList<Unit>(); List<WorkLocationPlan> workLocationPlans = colonyPlan.getWorkLocationPlans(); Collections.sort(workLocationPlans); // Remove all colonists from the colony: Iterator<Unit> ui = colony.getUnitIterator(); while (ui.hasNext()) { Unit unit = ui.next(); units.add(unit); //don't set location to null, but to the tile of the colony this //unit is being removed from! unit.putOutsideColony(); } // Place the experts: placeExpertsInWorkPlaces(units, workLocationPlans); boolean workerAdded = true; GoodsType foodType = colony.getSpecification().getGoodsType("model.goods.grain"); while (workerAdded) { workerAdded = false; // Use a food production plan if necessary: int food = colony.getFoodProduction() - colony.getFoodConsumption(); for (int i = 0; i < workLocationPlans.size() && food < 2; i++) { WorkLocationPlan wlp = workLocationPlans.get(i); WorkLocation wl = wlp.getWorkLocation(); if (wlp.getGoodsType() == foodType && (((ColonyTile) wl).getWorkTile().isLand() || colony.hasAbility("model.ability.produceInWater"))) { Unit bestUnit = null; int bestProduction = 0; Iterator<Unit> unitIterator = units.iterator(); while (unitIterator.hasNext()) { Unit unit = unitIterator.next(); int production = ((ColonyTile) wlp.getWorkLocation()).getProductionOf(unit, foodType); if (production > 1 && (bestUnit == null || production > bestProduction || production == bestProduction && unit.getSkillLevel() < bestUnit.getSkillLevel())) { bestUnit = unit; bestProduction = production; } } if (bestUnit != null && wlp.getWorkLocation().canAdd(bestUnit) && AIMessage.askWork(getAIUnit(bestUnit), wlp.getWorkLocation())) { AIMessage.askChangeWorkType(getAIUnit(bestUnit), wlp.getGoodsType()); units.remove(bestUnit); workLocationPlans.remove(wlp); workerAdded = true; food = colony.getFoodProduction() - colony.getFoodConsumption(); } } } // Use the next non-food plan: if (food >= 2) { for (int i = 0; i < workLocationPlans.size(); i++) { WorkLocationPlan wlp = workLocationPlans.get(i); if (wlp.getGoodsType() != foodType) { Unit bestUnit = null; int bestProduction = 0; Iterator<Unit> unitIterator = units.iterator(); while (unitIterator.hasNext()) { Unit unit = unitIterator.next(); int production = 0; WorkLocation location = wlp.getWorkLocation(); if (location instanceof ColonyTile) { production = ((ColonyTile) wlp.getWorkLocation()).getProductionOf(unit, wlp.getGoodsType()); } else if (location instanceof Building) { production = ((Building) location).getUnitProductivity(unit); } if (bestUnit == null || production > bestProduction || production == bestProduction && unit.getSkillLevel() < bestUnit.getSkillLevel()) { bestUnit = unit; bestProduction = production; } } if (bestUnit != null && wlp.getWorkLocation().canAdd(bestUnit) && AIMessage.askWork(getAIUnit(bestUnit), wlp.getWorkLocation())) { AIMessage.askChangeWorkType(getAIUnit(bestUnit), wlp.getGoodsType()); units.remove(bestUnit); workLocationPlans.remove(wlp); workerAdded = true; food = colony.getFoodProduction() - colony.getFoodConsumption(); } } } } } // Ensure that we have enough food: int food = colony.getFoodProduction() - colony.getFoodConsumption(); while (food < 0 && colony.getGoodsCount(foodType) + food * 3 < 0) { WorkLocation bestPick = null; for (WorkLocation wl : colony.getWorkLocations()) { if (wl.getUnitCount() > 0) { if (wl instanceof ColonyTile) { ColonyTile ct = (ColonyTile) wl; Unit u = ct.getUnit(); if (ct.getUnit().getWorkType() != foodType) { int uProduction = ct.getProductionOf(u, foodType); if (uProduction > 1) { if (bestPick == null || bestPick instanceof Building) { bestPick = wl; } else { ColonyTile bpct = (ColonyTile) bestPick; int bestPickProduction = bpct.getProductionOf(bpct.getUnit(), foodType); if (uProduction > bestPickProduction || (uProduction == bestPickProduction && u.getSkillLevel() < bpct.getUnit() .getSkillLevel())) { bestPick = wl; } } } else { if (bestPick == null) { bestPick = wl; } // else - TODO: This might be the best pick // sometimes: } } } else { // wl instanceof Building if (bestPick == null || (bestPick instanceof Building && ((Building) wl).getProduction() < ((Building) bestPick) .getProduction())) { bestPick = wl; } } } } if (bestPick == null) { break; } if (bestPick instanceof ColonyTile) { ColonyTile ct = (ColonyTile) bestPick; Unit u = ct.getUnit(); if (ct.getProductionOf(u, foodType) > 1) { AIMessage.askChangeWorkType(getAIUnit(u), foodType); } else { u.putOutsideColony(); AIUnit au = getAIUnit(u); if (au.getMission() instanceof WorkInsideColonyMission) { au.setMission(null); } } } else { // bestPick instanceof Building Building b = (Building) bestPick; Iterator<Unit> unitIterator = b.getUnitIterator(); Unit bestUnit = unitIterator.next(); while (unitIterator.hasNext()) { Unit u = unitIterator.next(); if (u.getType().getExpertProduction() != u.getWorkType()) { bestUnit = u; break; } } bestUnit.putOutsideColony(); AIUnit au = getAIUnit(bestUnit); if (au.getMission() instanceof WorkInsideColonyMission) { au.setMission(null); } } food = colony.getFoodProduction() - colony.getFoodConsumption(); } // Move any workers not producing anything to a temporary location. for (WorkLocation wl : colony.getWorkLocations()) { while (wl.getUnitCount() > 0 && wl instanceof Building && ((Building) wl).getProductionNextTurn() <= 0) { Iterator<Unit> unitIterator = wl.getUnitIterator(); Unit bestPick = unitIterator.next(); while (unitIterator.hasNext()) { Unit u = unitIterator.next(); if (u.getType().getExpertProduction() != u.getWorkType()) { bestPick = u; break; } } GoodsType type = bestPick.getWorkType().getRawMaterial(); WorkLocation w = (type == null) ? null : getBestVacantTile(bestPick, type); if (w == null) { type = colony.getSpecification() .getGoodsType("model.goods.bells"); w = colony.getBuildingForProducing(type); } if (w == null) { w = getBestVacantTile(bestPick, foodType); type = foodType; } if (w != null) { if (AIMessage.askWork(getAIUnit(bestPick), w) && bestPick.getLocation() == w) { AIMessage.askChangeWorkType(getAIUnit(bestPick), type); break; } } else { bestPick.putOutsideColony(); } if (w == wl) break; } } // TODO: Move workers to temporarily improve the production. // Changes the production type of workers producing a cargo there // is no room for. List<GoodsType> goodsList = colony.getSpecification().getGoodsTypeList(); for (GoodsType goodsType : goodsList) { int production = colony.getProductionNetOf(goodsType); int in_stock = colony.getGoodsCount(goodsType); if (foodType != goodsType && goodsType.isStorable() && production + in_stock > colony.getWarehouseCapacity()) { Iterator<Unit> unitIterator = colony.getUnitIterator(); int waste = production + in_stock - colony.getWarehouseCapacity(); while (unitIterator.hasNext() && waste > 0){ Unit unit = unitIterator.next(); if (unit.getWorkType() == goodsType) { final Location oldLocation = unit.getLocation(); unit.putOutsideColony(); boolean working = false; waste = colony.getGoodsCount(goodsType) + colony.getProductionNetOf(goodsType) - colony.getWarehouseCapacity(); int best = 0; for (GoodsType goodsType2 : goodsList) { if (!goodsType2.isFarmed()) continue; ColonyTile bestTile = getBestVacantTile(unit, goodsType2); int production2 = (bestTile == null ? 0 : bestTile.getProductionOf(unit, goodsType2)); if (production2 > best && production2 + colony.getGoodsCount(goodsType2) + colony.getProductionNetOf(goodsType2) < colony.getWarehouseCapacity()){ if (working){ unit.putOutsideColony(); } if (AIMessage.askWork(getAIUnit(unit), bestTile)) { AIMessage.askChangeWorkType(getAIUnit(unit), goodsType2); best = production2; working = true; } } } if (!working){ //units.add(unit); /* * Keep the unit inside the colony. Units outside * colonies are assigned Missions. */ // TODO: Create a Mission for units temporarily moved outside colonies. //Assuming that unit already has the correct UnitState here. //If not, this will be fixed by setLocation(), //resulting in a logger warning. unit.setLocation(oldLocation); } } } } } // Use any remaining food plans: for (int i = 0; i < workLocationPlans.size(); i++) { WorkLocationPlan wlp = workLocationPlans.get(i); WorkLocation wl = wlp.getWorkLocation(); if (wlp.getGoodsType() == foodType && (((ColonyTile) wl).getWorkTile().isLand() || colony.hasAbility("model.ability.produceInWater"))) { Unit bestUnit = null; int bestProduction = 0; Iterator<Unit> unitIterator = units.iterator(); while (unitIterator.hasNext()) { Unit unit = unitIterator.next(); int production = ((ColonyTile) wlp.getWorkLocation()).getProductionOf(unit, foodType); if (production > 1 && (bestUnit == null || production > bestProduction || production == bestProduction && unit.getSkillLevel() < bestUnit.getSkillLevel())) { bestUnit = unit; bestProduction = production; } } if (bestUnit != null && wlp.getWorkLocation().canAdd(bestUnit)) { if (AIMessage.askWork(getAIUnit(bestUnit), wlp.getWorkLocation())) { AIMessage.askChangeWorkType(getAIUnit(bestUnit), wlp.getGoodsType()); units.remove(bestUnit); workLocationPlans.remove(wlp); } } } } // Put any remaining workers outside the colony: Iterator<Unit> ui6 = units.iterator(); while (ui6.hasNext()) { Unit u = ui6.next(); u.putOutsideColony(); AIUnit au = getAIUnit(u); if (au.getMission() instanceof WorkInsideColonyMission) { au.setMission(null); } } // FIXME: should be executed just once, when the custom house is built /*if (colony.hasAbility("model.ability.export")) { colony.setExports(Goods.SILVER, true); colony.setExports(Goods.RUM, true); colony.setExports(Goods.CIGARS, true); colony.setExports(Goods.CLOTH, true); colony.setExports(Goods.COATS, true); }*/ decideBuildable(connection); createTileImprovementPlans(); createWishes(); colonyPlan.adjustProductionAndManufacture(); checkConditionsForHorseBreed(); if (this.colony.getUnitCount()<=0) { // Something bad happened, there is no remaining unit // working in the colony. // // Throwing an exception stalls the AI and wrecks the // colony in a weird way. Try to recover by hopefully // finding a unit outside the colony and stuffing it into // the town hall. if (colony.getTile().getUnitCount() > 0) { logger.warning("Colony " + colony.getName() + " autodestruct averted."); Unit u = colony.getTile().getFirstUnit(); GoodsType bells = colony.getSpecification() .getGoodsType("model.goods.bells"); AIMessage.askWork(getAIUnit(u), colony.getBuildingForProducing(bells)); getAIUnit(u).setMission(null); } else { throw new IllegalStateException("Colony " + colony.getName() + " contains no units!"); } } // no need to rearrange workers again immediately rearrangeWorkers = false; return true; } private void checkForUnequippedExpertPioneer() { if (colony.getUnitCount() < 2) { return; } for(Unit unit : colony.getUnitList()){ if(!unit.hasAbility("model.ability.expertPioneer")){ continue; } AIUnit aiu = getAIUnit(unit); if( aiu == null){ continue; } //if its not valid for this unit, is not valid for any other, no need to continue if(!PioneeringMission.isValid(aiu)){ return; } unit.putOutsideColony(); aiu.setMission(new PioneeringMission(getAIMain(), aiu)); return; } } public static Unit bestUnitForWorkLocation(Collection<Unit> units, WorkLocation workLocation, GoodsType goodsType) { if (units == null || units.isEmpty() || workLocation == null || (workLocation instanceof ColonyTile && goodsType == null) || (workLocation instanceof Building && ((Building) workLocation).getUnitCount() >= ((Building) workLocation).getMaxUnits())) { return null; } else { Tile tile = null; Building building = null; UnitType expert = null; if (workLocation instanceof ColonyTile) { tile = ((ColonyTile) workLocation).getWorkTile(); expert = goodsType.getSpecification().getExpertForProducing(goodsType); } else if (workLocation instanceof Building) { building = (Building) workLocation; expert = building.getExpertUnitType(); } else { return null; } Unit bestUnit = null; int production = 0; int bestProduction = 0; int experience = 0; int wastedExperience = 0; ExperienceUpgrade canBeUpgraded = ExperienceUpgrade.NONE; for (Unit unit : units) { if (unit.getType() == expert) { // can't get any better than this return unit; } else { if (tile != null) { production = unit.getProductionOf(goodsType, tile.potential(goodsType, unit.getType())); } else if (building != null) { production = building.getUnitProductivity(unit); } if (production > bestProduction) { // production is better bestUnit = unit; bestProduction = production; canBeUpgraded = getExperienceUpgrade(unit, expert); if (canBeUpgraded == ExperienceUpgrade.NONE) { experience = 0; wastedExperience = 0; } else { if (unit.getWorkType() == goodsType) { experience = unit.getExperience(); wastedExperience = 0; } else { experience = 0; wastedExperience = unit.getExperience(); } } } else if (production == bestProduction) { ExperienceUpgrade upgradeable = getExperienceUpgrade(unit, expert); if ((upgradeable == ExperienceUpgrade.EXPERT && (canBeUpgraded != ExperienceUpgrade.EXPERT || (unit.getWorkType() == goodsType && unit.getExperience() > experience) || (unit.getWorkType() != goodsType && unit.getExperience() < wastedExperience))) || (upgradeable == ExperienceUpgrade.NONE && canBeUpgraded == ExperienceUpgrade.SOME)) { // production is equal, but unit is better // from an education perspective bestUnit = unit; canBeUpgraded = upgradeable; if (unit.getWorkType() == goodsType) { experience = unit.getExperience(); wastedExperience = 0; } else { experience = 0; wastedExperience = unit.getExperience(); } } } } } if (bestProduction == 0) { return null; } else { return bestUnit; } } } private static ExperienceUpgrade getExperienceUpgrade(Unit unit, UnitType expert) { ExperienceUpgrade result = ExperienceUpgrade.NONE; for (UnitTypeChange change : unit.getType().getTypeChanges()) { if (change.asResultOf(ChangeType.EXPERIENCE)) { if (expert == change.getNewUnitType()) { return ExperienceUpgrade.EXPERT; } else { result = ExperienceUpgrade.SOME; } } } return result; } /** * Checks if the colony has an unarmed expert soldier inside * If there are conditions to arm it, put it outside for later equip */ private void checkForUnarmedExpertSoldier() { EquipmentType musketsEqType = colony.getSpecification().getEquipmentType("model.equipment.muskets"); for(Unit unit : colony.getUnitList()){ if(colony.getUnitCount() == 1){ return; } if(!unit.hasAbility("model.ability.expertSoldier")){ continue; } // check if colony has goods to equip unit if(colony.canBuildEquipment(musketsEqType)){ unit.putOutsideColony(); continue; } // check for armed non-expert unit for(Unit outsideUnit : colony.getTile().getUnitList()){ if(outsideUnit.isArmed() && !outsideUnit.hasAbility("model.ability.expertSoldier")){ unit.putOutsideColony(); break; } } } } /** * Verifies if the <code>Colony</code> has conditions for breeding horses, *and un-mounts a mounted <code>Unit</code> if available, to have horses to breed. */ void checkConditionsForHorseBreed() { GoodsType horsesType = colony.getSpecification().getGoodsType("model.goods.horses"); EquipmentType horsesEqType = colony.getSpecification().getEquipmentType("model.equipment.horses"); GoodsType reqGoodsType = horsesType.getRawMaterial(); // Colony already is breeding horses if(colony.getGoodsCount(horsesType) >= horsesType.getBreedingNumber()){ return; } //int foodProdAvail = colony.getProductionOf(reqGoodsType) - colony.getConsumptionOf(reqGoodsType); int foodProdAvail = colony.getFoodProduction() - colony.getConsumptionOf(reqGoodsType); // no food production available for breeding anyway if(foodProdAvail <= 0){ return; } // we will now look for any mounted unit that can be temporarily dismounted for(Unit u : colony.getTile().getUnitList()){ int amount = u.getEquipmentCount(horsesEqType); if (amount > 0 && AIMessage.askEquipUnit(getAIUnit(u), horsesEqType, -amount)) { if (colony.getGoodsCount(horsesType) >= horsesType.getBreedingNumber()) { return; } } } } private void placeExpertsInWorkPlaces(List<Unit> units, List<WorkLocationPlan> workLocationPlans) { boolean canProduceInWater = colony.hasAbility("model.ability.produceInWater"); // Since we will change the original list, we need to make a copy to iterate from Iterator<Unit> uit = new ArrayList<Unit>(units).iterator(); while (uit.hasNext()) { Unit unit = uit.next(); GoodsType expertProd = unit.getType().getExpertProduction(); // not an expert if(expertProd == null){ continue; } WorkLocationPlan bestWorkPlan = null; int bestProduction = 0; Iterator<WorkLocationPlan> wlpIterator = workLocationPlans.iterator(); while (wlpIterator.hasNext()) { WorkLocationPlan wlp = wlpIterator.next(); WorkLocation wl = wlp.getWorkLocation(); GoodsType locGoods = wlp.getGoodsType(); boolean isColonyTile = wl instanceof ColonyTile; + + // Sanity check. Make sure the tile is usable by this colony. + if (isColonyTile + && !tryUseTile(((ColonyTile)wl).getTile())) continue; + boolean isLand = true; if(isColonyTile){ isLand = ((ColonyTile) wl).getWorkTile().isLand(); } //Colony cannot get fish yet if(isColonyTile && !isLand && !canProduceInWater){ continue; } // not a fit if(expertProd != locGoods){ continue; } // no need to look any further, only one place to work in if(!isColonyTile){ bestWorkPlan = wlp; break; } int planProd = wlp.getProductionOf(expertProd); if(bestWorkPlan == null || bestProduction < planProd){ bestWorkPlan = wlp; bestProduction = planProd; } } if (bestWorkPlan != null && AIMessage.askWork(getAIUnit(unit), bestWorkPlan.getWorkLocation())) { AIMessage.askChangeWorkType(getAIUnit(unit), bestWorkPlan.getGoodsType()); workLocationPlans.remove(bestWorkPlan); units.remove(unit); } } } /** * Decides what to build in the <code>Colony</code>. * * @param connection The connection to use when communicating with the * server. */ private void decideBuildable(Connection connection) { Iterator<BuildableType> bi = colonyPlan.getBuildable(); BuildableType buildable = (bi.hasNext()) ? bi.next() : null; if (buildable != null && colony.canBuild(buildable) && buildable != colony.getCurrentlyBuilding()) { List<BuildableType> queue = new ArrayList<BuildableType>(); queue.add(buildable); AIMessage.askSetBuildQueue(this, queue); } } public void propertyChange(PropertyChangeEvent event) { logger.finest("Property change REARRANGE_WORKERS fired."); rearrangeWorkers = true; } /** * Writes this object to an XML stream. * * @param out The target stream. * @throws XMLStreamException if there are any problems writing to the * stream. */ protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException { out.writeStartElement(getXMLElementTagName()); out.writeAttribute("ID", getId()); Iterator<AIGoods> aiGoodsIterator = aiGoods.iterator(); while (aiGoodsIterator.hasNext()) { AIGoods ag = aiGoodsIterator.next(); if (ag == null) { logger.warning("ag == null"); continue; } if (ag.getId() == null) { logger.warning("ag.getId() == null"); continue; } out.writeStartElement(AIGoods.getXMLElementTagName() + "ListElement"); out.writeAttribute("ID", ag.getId()); out.writeEndElement(); } Iterator<Wish> wishesIterator = wishes.iterator(); while (wishesIterator.hasNext()) { Wish w = wishesIterator.next(); if (!w.shouldBeStored()) { continue; } if (w instanceof WorkerWish) { out.writeStartElement(WorkerWish.getXMLElementTagName() + "WishListElement"); } else if (w instanceof GoodsWish) { out.writeStartElement(GoodsWish.getXMLElementTagName() + "WishListElement"); } else { logger.warning("Unknown type of wish."); continue; } out.writeAttribute("ID", w.getId()); out.writeEndElement(); } Iterator<TileImprovementPlan> TileImprovementPlanIterator = tileImprovementPlans.iterator(); while (TileImprovementPlanIterator.hasNext()) { TileImprovementPlan ti = TileImprovementPlanIterator.next(); out.writeStartElement(TileImprovementPlan.getXMLElementTagName() + "ListElement"); out.writeAttribute("ID", ti.getId()); out.writeEndElement(); } out.writeEndElement(); } /** * Reads information for this object from an XML stream. * * @param in The input stream with the XML. * @throws XMLStreamException if there are any problems reading from the * stream. */ protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { colony = (Colony) getAIMain().getFreeColGameObject(in.getAttributeValue(null, "ID")); if (colony == null) { throw new NullPointerException("Could not find Colony with ID: " + in.getAttributeValue(null, "ID")); } aiGoods.clear(); wishes.clear(); colonyPlan = new ColonyPlan(getAIMain(), colony); colonyPlan.create(); while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(AIGoods.getXMLElementTagName() + "ListElement")) { AIGoods ag = (AIGoods) getAIMain().getAIObject(in.getAttributeValue(null, "ID")); if (ag == null) { ag = new AIGoods(getAIMain(), in.getAttributeValue(null, "ID")); } aiGoods.add(ag); in.nextTag(); } else if (in.getLocalName().equals(WorkerWish.getXMLElementTagName() + "WishListElement")) { Wish w = (Wish) getAIMain().getAIObject(in.getAttributeValue(null, "ID")); if (w == null) { w = new WorkerWish(getAIMain(), in.getAttributeValue(null, "ID")); } wishes.add(w); in.nextTag(); } else if (in.getLocalName().equals(GoodsWish.getXMLElementTagName() + "WishListElement")) { Wish w = (Wish) getAIMain().getAIObject(in.getAttributeValue(null, "ID")); if (w == null) { w = new GoodsWish(getAIMain(), in.getAttributeValue(null, "ID")); } wishes.add(w); in.nextTag(); } else if (in.getLocalName().equals(TileImprovementPlan.getXMLElementTagName() + "ListElement")) { TileImprovementPlan ti = (TileImprovementPlan) getAIMain().getAIObject(in.getAttributeValue(null, "ID")); if (ti == null) { ti = new TileImprovementPlan(getAIMain(), in.getAttributeValue(null, "ID")); } tileImprovementPlans.add(ti); in.nextTag(); } else { logger.warning("Unknown tag name: " + in.getLocalName()); } } if (!in.getLocalName().equals(getXMLElementTagName())) { logger.warning("Expected end tag, received: " + in.getLocalName()); } } public ColonyPlan getColonyPlan() { return colonyPlan; } /** * Returns the tag name of the root element representing this object. * * @return "aiColony" */ public static String getXMLElementTagName() { return "aiColony"; } }
false
false
null
null
diff --git a/src/main/java/kniemkiewicz/jqblocks/ingame/action/AbstractActionController.java b/src/main/java/kniemkiewicz/jqblocks/ingame/action/AbstractActionController.java index 099817a..c5244ec 100644 --- a/src/main/java/kniemkiewicz/jqblocks/ingame/action/AbstractActionController.java +++ b/src/main/java/kniemkiewicz/jqblocks/ingame/action/AbstractActionController.java @@ -1,182 +1,186 @@ package kniemkiewicz.jqblocks.ingame.action; import kniemkiewicz.jqblocks.ingame.Sizes; import kniemkiewicz.jqblocks.ingame.UpdateQueue; import kniemkiewicz.jqblocks.ingame.event.Event; import kniemkiewicz.jqblocks.ingame.event.EventListener; import kniemkiewicz.jqblocks.ingame.event.input.InputEvent; import kniemkiewicz.jqblocks.ingame.event.input.mouse.Button; import kniemkiewicz.jqblocks.ingame.event.input.mouse.MouseDraggedEvent; import kniemkiewicz.jqblocks.ingame.event.input.mouse.MousePressedEvent; import kniemkiewicz.jqblocks.ingame.event.input.mouse.MouseReleasedEvent; import kniemkiewicz.jqblocks.ingame.event.screen.ScreenMovedEvent; import kniemkiewicz.jqblocks.ingame.input.InputContainer; import kniemkiewicz.jqblocks.ingame.content.player.Player; import kniemkiewicz.jqblocks.ingame.content.player.PlayerController; import kniemkiewicz.jqblocks.util.Collections3; import org.newdawn.slick.geom.Rectangle; import org.springframework.beans.factory.annotation.Autowired; import java.util.Arrays; import java.util.List; /** * User: qba * Date: 12.08.12 */ public abstract class AbstractActionController implements EventListener { public static final int RANGE = 16 * Sizes.BLOCK; @Autowired protected UpdateQueue updateQueue; @Autowired protected PlayerController playerController; @Autowired protected InputContainer inputContainer; protected Rectangle affectedRectangle; abstract protected boolean canPerformAction(int x, int y); abstract protected Rectangle getAffectedRectangle(int x, int y); abstract protected void startAction(); abstract protected void stopAction(); abstract protected void updateAction(int delta); abstract protected boolean isActionCompleted(); abstract protected void onAction(); + public Button getActionButton() { + return Button.LEFT; + } + public boolean canPerformAction() { int x = Sizes.roundToBlockSizeX(affectedRectangle.getX()); int y = Sizes.roundToBlockSizeY(affectedRectangle.getY()); return canPerformAction(x, y); } @Override public void listen(List<Event> events) { List<MousePressedEvent> mousePressedEvents = Collections3.collect(events, MousePressedEvent.class); if (!mousePressedEvents.isEmpty()) { for (MousePressedEvent e : mousePressedEvents) { handleMousePressedEvent(e); } } List<MouseDraggedEvent> mouseDraggedEvents = Collections3.collect(events, MouseDraggedEvent.class); if (!mouseDraggedEvents.isEmpty()) { for (MouseDraggedEvent e : mouseDraggedEvents) { handleMouseDraggedEvent(e); } } List<MouseReleasedEvent> mouseReleasedEvents = Collections3.collect(events, MouseReleasedEvent.class); if (!mouseReleasedEvents.isEmpty()) { for (MouseReleasedEvent e : mouseReleasedEvents) { handleMouseReleasedEvent(e); } } List<ScreenMovedEvent> screenMovedEvents = Collections3.collect(events, ScreenMovedEvent.class); if (!screenMovedEvents.isEmpty()) { for (ScreenMovedEvent e : screenMovedEvents) { handleScreenMovedEvent(e); } } } public void handleMousePressedEvent(MousePressedEvent event) { int x = Sizes.roundToBlockSizeX(event.getLevelX()); int y = Sizes.roundToBlockSizeY(event.getLevelY()); - if (isInRange(x, y) && event.getButton() == Button.LEFT) { + if (isInRange(x, y) && event.getButton().equals(getActionButton())) { if (canPerformAction(x, y)) { affectedRectangle = getAffectedRectangle(x, y); startAction(); event.consume(); } } } public void handleMouseDraggedEvent(MouseDraggedEvent event) { - if (event.getButton() != Button.LEFT) return; + if (!event.getButton().equals(getActionButton())) return; int x = Sizes.roundToBlockSizeX(event.getNewLevelX()); int y = Sizes.roundToBlockSizeY(event.getNewLevelY()); handleMouseCoordChange(x, y); if (affectedRectangle != null) event.consume(); } public void handleScreenMovedEvent(ScreenMovedEvent event) { if (!inputContainer.getInput().isMouseButtonDown(0)) { return; } int x = Sizes.roundToBlockSizeX(inputContainer.getInput().getMouseX() + event.getNewShiftX()); int y = Sizes.roundToBlockSizeY(inputContainer.getInput().getMouseY() + event.getNewShiftY()); handleMouseCoordChange(x, y); if (affectedRectangle != null) event.consume(); } private void handleMouseCoordChange(int x, int y) { Rectangle rect = new Rectangle(x, y, 1, 1); if (affectedRectangle != null && (!affectedRectangle.intersects(rect) || !isInRange(x, y))) { stopAction(); affectedRectangle = null; } if (!isInRange(x, y)) { return; } if (affectedRectangle == null && canPerformAction(x, y)) { affectedRectangle = getAffectedRectangle(x, y); startAction(); } } public void handleMouseReleasedEvent(MouseReleasedEvent event) { if (affectedRectangle == null) { return; } - if (event.getButton() != Button.LEFT) return; + if (!event.getButton().equals(getActionButton())) return; int x = Sizes.roundToBlockSizeX(event.getLevelX()); int y = Sizes.roundToBlockSizeY(event.getLevelY()); if (!isInRange(x, y)) { return; } stopAction(); affectedRectangle = null; } public static boolean isInRange(int x, int y, Player player, int range) { float px = player.getXYMovement().getX(); float py = player.getXYMovement().getY(); return (px - x) * (px - x) + (py - y) * (py - y) < range * range; } public boolean isInRange(int x, int y) { return isInRange(x, y, playerController.getPlayer(), RANGE); } public void update(int delta) { if (affectedRectangle == null) { return; } updateAction(delta); if (isActionCompleted()) { if (canPerformAction()) { onAction(); } stopAction(); affectedRectangle = null; } } @Override public List<Class> getEventTypesOfInterest() { return Arrays.asList((Class) InputEvent.class, (Class) ScreenMovedEvent.class); } } diff --git a/src/main/java/kniemkiewicz/jqblocks/ingame/content/item/bow/BowItemController.java b/src/main/java/kniemkiewicz/jqblocks/ingame/content/item/bow/BowItemController.java index 20d73b6..6ec8652 100644 --- a/src/main/java/kniemkiewicz/jqblocks/ingame/content/item/bow/BowItemController.java +++ b/src/main/java/kniemkiewicz/jqblocks/ingame/content/item/bow/BowItemController.java @@ -1,112 +1,118 @@ package kniemkiewicz.jqblocks.ingame.content.item.bow; import kniemkiewicz.jqblocks.ingame.PointOfView; import kniemkiewicz.jqblocks.ingame.Sizes; import kniemkiewicz.jqblocks.ingame.content.item.arrow.Arrow; import kniemkiewicz.jqblocks.ingame.content.item.arrow.ArrowController; import kniemkiewicz.jqblocks.ingame.content.player.PlayerController; import kniemkiewicz.jqblocks.ingame.controller.ItemController; import kniemkiewicz.jqblocks.ingame.event.Event; import kniemkiewicz.jqblocks.ingame.event.EventBus; +import kniemkiewicz.jqblocks.ingame.event.input.mouse.Button; import kniemkiewicz.jqblocks.ingame.event.input.mouse.MousePressedEvent; import kniemkiewicz.jqblocks.ingame.object.DroppableObject; import kniemkiewicz.jqblocks.util.Collections3; import kniemkiewicz.jqblocks.util.Pair; import org.newdawn.slick.geom.Rectangle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * User: knie * Date: 7/21/12 */ @Component public class BowItemController implements ItemController<BowItem> { @Autowired PlayerController playerController; @Autowired ArrowController arrowController; @Autowired PointOfView pointOfView; @Autowired EventBus eventBus; private static float SPEED = Sizes.MAX_FALL_SPEED / 1.5f; @Override public void listen(BowItem bowItem, List<Event> events) { List<MousePressedEvent> pressedEvents = Collections3.collect(events, MousePressedEvent.class); if (!pressedEvents.isEmpty()) { handlePressedEvent(pressedEvents); } } @Override public DroppableObject getObject(BowItem item, int centerX, int centerY) { return null; } private void handlePressedEvent(List<MousePressedEvent> pressedEvents) { assert pressedEvents.size() > 0; - shotArrow(); + for (MousePressedEvent event : pressedEvents) { + if (event.getButton().equals(Button.LEFT)) { + shotArrow(); + return; + } + } } // Returns pair dx,dy of vector with given radius, pointing where the bow should be pointed. public Pair<Float, Float> getCurrentDirection(float radius) { boolean leftFaced = playerController.getPlayer().isLeftFaced(); Pair<Float, Float> pos = getScreenBowPosition(); float x0 = pos.getFirst(); float y0 = pos.getSecond(); float mouseX = eventBus.getLatestMouseMovedEvent().getNewScreenX(); float mouseY = eventBus.getLatestMouseMovedEvent().getNewScreenY(); float dist = (float) Math.sqrt((mouseX - x0) * (mouseX - x0) + (mouseY - y0) * (mouseY - y0)); float dx; float dy; if (dist == 0) { dx = leftFaced ? - radius : radius; dy = 0; } else { dx = radius * (mouseX - x0) / dist; dy = radius * (mouseY - y0) / dist; } if (((dx > 0) && leftFaced) || (dx < 0 && !leftFaced)) { if (dy > 0) { dx = 0; dy = radius; } else { dx = 0; dy = - radius; } } return Pair.newInstance(dx, dy); } public Pair<Float, Float> getLevelBowPosition() { Rectangle shape = playerController.getPlayer().getShape(); float dx = -Sizes.BLOCK / 2; if (playerController.getPlayer().isLeftFaced()) { dx *= -1; } return Pair.newInstance(shape.getCenterX() + dx, shape.getCenterY() - Sizes.BLOCK / 2); } public Pair<Float, Float> getScreenBowPosition() { float dx = -Sizes.BLOCK / 2; if (playerController.getPlayer().isLeftFaced()) { dx *= -1; } return Pair.newInstance((float)pointOfView.getWindowWidth()/ 2 + dx, (float)pointOfView.getWindowHeight() / 2 - Sizes.BLOCK / 2); } private void shotArrow() { Pair<Float, Float> pos = getLevelBowPosition(); Pair<Float, Float> speed = getCurrentDirection(SPEED); arrowController.add(new Arrow(pos.getFirst(), pos.getSecond(), playerController.getPlayer(), speed.getFirst(), speed.getSecond())); } } diff --git a/src/main/java/kniemkiewicz/jqblocks/ingame/production/action/ProductionActionController.java b/src/main/java/kniemkiewicz/jqblocks/ingame/production/action/ProductionActionController.java index 3e318db..effdd20 100644 --- a/src/main/java/kniemkiewicz/jqblocks/ingame/production/action/ProductionActionController.java +++ b/src/main/java/kniemkiewicz/jqblocks/ingame/production/action/ProductionActionController.java @@ -1,134 +1,140 @@ package kniemkiewicz.jqblocks.ingame.production.action; import com.google.common.base.Optional; import kniemkiewicz.jqblocks.ingame.Sizes; import kniemkiewicz.jqblocks.ingame.action.AbstractActionController; import kniemkiewicz.jqblocks.ingame.content.player.PlayerController; import kniemkiewicz.jqblocks.ingame.controller.KeyboardUtils; import kniemkiewicz.jqblocks.ingame.event.Event; import kniemkiewicz.jqblocks.ingame.event.EventBus; import kniemkiewicz.jqblocks.ingame.event.input.keyboard.KeyPressedEvent; +import kniemkiewicz.jqblocks.ingame.event.input.mouse.Button; import kniemkiewicz.jqblocks.ingame.event.production.ProductionCompleteEvent; import kniemkiewicz.jqblocks.ingame.object.background.WorkplaceBackgroundElement; import kniemkiewicz.jqblocks.ingame.production.CanProduce; import kniemkiewicz.jqblocks.ingame.production.ProductionAssignment; import kniemkiewicz.jqblocks.ingame.production.ProductionAssignmentController; import kniemkiewicz.jqblocks.ingame.workplace.WorkplaceController; import kniemkiewicz.jqblocks.util.Collections3; import kniemkiewicz.jqblocks.util.GeometryUtils; import org.newdawn.slick.geom.Rectangle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; /** * User: qba * Date: 01.09.12 */ public abstract class ProductionActionController extends AbstractActionController { @Autowired ProductionAssignmentController productionAssignmentController; @Autowired EventBus eventBus; public abstract CanProduce getProductionPlace(Rectangle rectangle); @Override protected boolean canPerformAction(int x, int y) { Rectangle rectangle = new Rectangle(x, y, Sizes.BLOCK, Sizes.BLOCK); CanProduce productionPlace = getProductionPlace(rectangle); if (productionPlace == null) return false; return productionAssignmentController.hasAssigment(productionPlace); } @Override protected Rectangle getAffectedRectangle(int x, int y) { Rectangle rectangle = new Rectangle(x, y, Sizes.BLOCK, Sizes.BLOCK); CanProduce productionPlace = getProductionPlace(rectangle); return GeometryUtils.getBoundingRectangle(checkNotNull(productionPlace).getShape()); } @Override protected void startAction() { } @Override protected void stopAction() { } @Override protected void updateAction(int delta) { CanProduce productionPlace = getProductionPlace(affectedRectangle); Optional<ProductionAssignment> assignment = productionAssignmentController.getActiveAssignment(checkNotNull(productionPlace)); if (assignment.isPresent()) { assignment.get().update(delta); } } @Override protected boolean isActionCompleted() { CanProduce productionPlace = getProductionPlace(affectedRectangle); Optional<ProductionAssignment> assignment = productionAssignmentController.getActiveAssignment(checkNotNull(productionPlace)); return assignment.isPresent() && assignment.get().isCompleted(); } @Override protected void onAction() { if (affectedRectangle != null) { CanProduce productionPlace = getProductionPlace(affectedRectangle); Optional<ProductionAssignment> assignment = productionAssignmentController.getActiveAssignment(checkNotNull(productionPlace)); if (assignment.isPresent() && assignment.get().isCompleted()) { productionAssignmentController.removeActiveAssigment(productionPlace); eventBus.broadcast(new ProductionCompleteEvent(productionPlace, assignment.get())); } } } @Override + public Button getActionButton() { + return Button.RIGHT; + } + + @Override public void listen(List<Event> events) { List<KeyPressedEvent> keyPressedEvents = Collections3.collect(events, KeyPressedEvent.class); if (!keyPressedEvents.isEmpty()) { for (KeyPressedEvent e : keyPressedEvents) { handleKeyPressedEvent(e); } } super.listen(events); } private void handleKeyPressedEvent(KeyPressedEvent event) { if (KeyboardUtils.isInteractKey(event.getKey())) { int playerX = Sizes.roundToBlockSizeX(playerController.getPlayer().getShape().getCenterX()); int playerY = Sizes.roundToBlockSizeY(playerController.getPlayer().getShape().getCenterY()); if (affectedRectangle != null) { Rectangle rect = new Rectangle(playerX, playerY, 1, 1); if (affectedRectangle != null && (!affectedRectangle.intersects(rect))) { stopAction(); affectedRectangle = null; } event.consume(); } if (affectedRectangle == null && canPerformAction(playerX, playerY)) { affectedRectangle = getAffectedRectangle(playerX, playerY); startAction(); event.consume(); } } } @Override public List<Class> getEventTypesOfInterest() { List<Class> eventTypesOfInterest = new ArrayList<Class>(super.getEventTypesOfInterest()); if (!eventTypesOfInterest.contains(KeyPressedEvent.class)) { eventTypesOfInterest.add(KeyPressedEvent.class); } return eventTypesOfInterest; } }
false
false
null
null
diff --git a/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java b/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java index 3bff22908..f8bb123fa 100644 --- a/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java +++ b/javasrc/src/org/ccnx/ccn/profiles/nameenum/EnumeratedNameList.java @@ -1,474 +1,478 @@ /** * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.profiles.nameenum; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import org.bouncycastle.util.Arrays; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.config.ConfigurationException; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; /** * Blocking and background interface to name enumeration. This allows a caller to specify a prefix * under which to enumerate available children, and name enumeration to proceed in the background * for as long as desired, providing updates whenever new data is published. * Currently implemented as a wrapper around CCNNameEnumerator, will likely directly aggregate * name enumeration responses in the future. * * @see CCNNameEnumerator * @see BasicNameEnumeratorListener */ public class EnumeratedNameList implements BasicNameEnumeratorListener { protected static final long CHILD_WAIT_INTERVAL = 1000; protected ContentName _namePrefix; protected CCNNameEnumerator _enumerator; protected BasicNameEnumeratorListener callback; // make these contain something other than content names when the enumerator has better data types protected SortedSet<ContentName> _children = new TreeSet<ContentName>(); protected SortedSet<ContentName> _newChildren = null; protected Object _childLock = new Object(); protected CCNTime _lastUpdate = null; /** * Creates an EnumeratedNameList object * * This constructor creates a new EnumeratedNameList object that will begin enumerating * the children of the specified prefix. The new EnumeratedNameList will use the CCNHandle passed * in to the constructor, or create a new one using CCNHandle#open() if it is null. * * @param namePrefix the ContentName whose children we wish to list. * @param handle the CCNHandle object for sending interests and receiving content object responses. */ public EnumeratedNameList(ContentName namePrefix, CCNHandle handle) throws IOException { if (null == namePrefix) { throw new IllegalArgumentException("namePrefix cannot be null!"); } if (null == handle) { try { handle = CCNHandle.open(); } catch (ConfigurationException e) { throw new IOException("ConfigurationException attempting to open a handle: " + e.getMessage()); } } _namePrefix = namePrefix; _enumerator = new CCNNameEnumerator(namePrefix, handle, this); } /** * Method to return the ContentName used for enumeration. * * @return ContentName returns the prefix under which we are enumerating children. */ public ContentName getName() { return _namePrefix; } /** * Cancels ongoing name enumeration. Previously-accumulated information about * children of this name are still stored and available for use. * * @return void * */ public void stopEnumerating() { _enumerator.cancelPrefix(_namePrefix); } /** * First-come first-served interface to retrieve only new data from * enumeration responses as it arrives. This method blocks and * waits for data, but grabs the new data for processing * (thus removing it from every other listener), in effect handing the * new children to the first consumer to wake up and makes the other * ones go around again. Useful for assigning work to a thread pool, * somewhat dangerous in other contexts -- if there is more than * one waiter, many waiters can wait forever. * * @param timeout maximum amount of time to wait, 0 to wait forever. * @return SortedSet<ContentName> Returns the array of single-component * content name children that are new to us, or null if we reached the * timeout before new data arrived */ public SortedSet<ContentName> getNewData(long timeout) { SortedSet<ContentName> childArray = null; synchronized(_childLock) { // reentrant? while ((null == _children) || _children.size() == 0) { waitForNewChildren(timeout); if (timeout != SystemConfiguration.NO_TIMEOUT) break; } Log.info("Waiting for new data on prefix: " + _namePrefix + " got " + ((null == _newChildren) ? 0 : _newChildren.size()) + "."); if (null != _newChildren) { childArray = _newChildren; _newChildren = null; } } return childArray; } /** * Block and wait as long as it takes for new data to appear. See #getNewData(long). * @return SortedSet<ContentName> Returns the array of single-component * content name children that are new to us, or null if we reached the * timeout before new data arrived */ public SortedSet<ContentName> getNewData() { return getNewData(SystemConfiguration.NO_TIMEOUT); } /** * Returns single-component ContentName objects containing the name components of the children. * @return SortedSet<ContentName> Returns the array of single-component * content name children that have been retrieved so far, or null if no responses * have yet been received. The latter may indicate either that no children of this prefix * are known to any responders, or that they have not had time to respond. */ public SortedSet<ContentName> getChildren() { if (!hasChildren()) return null; return _children; } /** * Returns true if the prefix has new names that have not been handled by the calling application. * @return true if there are new children available to process */ public boolean hasNewData() { return ((null != _newChildren) && (_newChildren.size() > 0)); } /** * Returns true if we have received any responses listing available child names. * If no names have yet been received, this may mean either that responses * have not had time to arrive, or there are know children known to available * responders. * * @return true if we have child names received from enumeration responses */ public boolean hasChildren() { return ((null != _children) && (_children.size() > 0)); } /** * Returns true if we know the prefix has a child matching the given name component. * * @param childComponent name component to check for in the stored child names. * @return true if that child is in our list of known children */ public boolean hasChild(byte [] childComponent) { for (ContentName child : _children) { if (Arrays.areEqual(childComponent, child.component(0))) { return true; } } return false; } /** * Returns whether a child is present in the list of known children. * <p> * * @param childName String version of a child name to look for * @return boolean Returns true if the name is present in the list of known children. * */ public boolean hasChild(String childName) { return hasChild(ContentName.componentParseNative(childName)); } /** * Wait for new children to arrive. * * @param timeout Maximum time to wait for new data. * @return a boolean value that indicates whether new data was found. */ public boolean waitForNewChildren(long timeout) { boolean foundNewData = false; synchronized(_childLock) { CCNTime lastUpdate = _lastUpdate; long timeRemaining = timeout; long startTime = System.currentTimeMillis(); while (((null == _lastUpdate) || ((null != lastUpdate) && !_lastUpdate.after(lastUpdate))) && ((timeout == SystemConfiguration.NO_TIMEOUT) || (timeRemaining > 0))) { try { _childLock.wait((timeout != SystemConfiguration.NO_TIMEOUT) ? Math.min(timeRemaining, CHILD_WAIT_INTERVAL) : CHILD_WAIT_INTERVAL); if (timeout != SystemConfiguration.NO_TIMEOUT) { timeRemaining = timeout - (System.currentTimeMillis() - startTime); } } catch (InterruptedException e) { } Log.info("Waiting for new data on prefix: {0}, updated {1}, our update {2}, now have " + ((null == _children) ? 0 : _children.size()), _namePrefix + " new " + ((null == _newChildren) ? 0 : _newChildren.size()) + ".", _lastUpdate, lastUpdate); } if ((null != _lastUpdate) && ((null == lastUpdate) || (_lastUpdate.after(lastUpdate)))) foundNewData = true; } return foundNewData; } /** * Wait for new children to arrive. * This method does not have a timeout and will wait forever. * * @return void */ public void waitForNewChildren() { waitForNewChildren(SystemConfiguration.NO_TIMEOUT); } /** * Waits until there is any data at all. Right now, waits for the first response containing actual * children, not just a name enumeration response. That means it could block * forever if no children exist in a repository or there are not any applications responding to * name enumeration requests. Once we have an initial set of children, this method * returns immediately. * @param timeout Maximum amount of time to wait, if 0, waits forever. - * @return void + * @return a boolean value that indicates whether new data was found. */ - public void waitForChildren(long timeout) { + public boolean waitForChildren(long timeout) { + boolean foundNewData = false; + if ((null != _children) && (_children.size() > 0)) foundNewData = true; while ((null == _children) || _children.size() == 0) { - waitForNewChildren(timeout); + foundNewData = waitForNewChildren(timeout); if (timeout != SystemConfiguration.NO_TIMEOUT) break; } + return foundNewData; } /** * Wait (block) for initial data to arrive, possibly forever. See #waitForData(long). * * @return void */ public void waitForChildren() { waitForChildren(SystemConfiguration.NO_TIMEOUT); } /** * Wait for new children to arrive until there is a period of length timeout during which * no new child arrives. * @param timeout The maximum amount of time to wait between consecutive children arrivals. */ public void waitForUpdates(long timeout) { Log.info("Waiting for updates on prefix {0} with max timeout of {1} ms between consecutive children arrivals.", _namePrefix, timeout); long startTime = System.currentTimeMillis(); while (waitForNewChildren(timeout)) { Log.info("Child or children found on prefix {0}", _namePrefix); } Log.info("Quit waiting for updates on prefix {0} after waiting in total {1} ms.", _namePrefix, (System.currentTimeMillis() - startTime)); } /** * Handle responses from CCNNameEnumerator that give us a list of single-component child * names. Filter out the names new to us, add them to our list of known children, postprocess * them with processNewChildren(SortedSet<ContentName>), and signal waiters if we * have new data. * * @param prefix Prefix used for name enumeration. * @param names The list of names returned in this name enumeration response. * * @return int */ public int handleNameEnumerator(ContentName prefix, ArrayList<ContentName> names) { Log.info(names.size() + " new name enumeration results: our prefix: " + _namePrefix + " returned prefix: " + prefix); if (!prefix.equals(_namePrefix)) { Log.warning("Returned data doesn't match requested prefix!"); } Log.info("Handling Name Iteration " + prefix +" "); // the name enumerator hands off names to us, we own it now // DKS -- want to keep listed as new children we previously had synchronized (_childLock) { TreeSet<ContentName> thisRoundNew = new TreeSet<ContentName>(); thisRoundNew.addAll(names); Iterator<ContentName> it = thisRoundNew.iterator(); while (it.hasNext()) { ContentName name = it.next(); if (_children.contains(name)) { it.remove(); } } if (!thisRoundNew.isEmpty()) { if (null != _newChildren) { _newChildren.addAll(thisRoundNew); } else { _newChildren = thisRoundNew; } _children.addAll(thisRoundNew); _lastUpdate = new CCNTime(); Log.info("New children found: at {0} " + thisRoundNew.size() + " total children " + _children.size(), _lastUpdate); processNewChildren(thisRoundNew); _childLock.notifyAll(); } } return 0; } /** * Method to allow subclasses to do post-processing on incoming names * before handing them to customers. * Note that the set handed in here is not the set that will be handed * out; only the name objects are the same. * * @param newChildren SortedSet of children available for processing * * @return void */ protected void processNewChildren(SortedSet<ContentName> newChildren) { // default -- do nothing. } /** * If some or all of the children of this name are versions, returns the latest version * among them. * * @return ContentName The latest version component * */ public ContentName getLatestVersionChildName() { // of the available names in _children that are version components, // find the latest one (version-wise) // names are sorted, so the last one that is a version should be the latest version // ListIterator previous doesn't work unless you've somehow gotten it to point at the end... ContentName theName = null; ContentName latestName = null; CCNTime latestTimestamp = null; Iterator<ContentName> it = _children.iterator(); // TODO these are sorted -- we just need to iterate through them in reverse order. Having // trouble finding something like C++'s reverse iterators to do that (linked list iterators // can go backwards -- but you have to run them to the end first). while (it.hasNext()) { theName = it.next(); if (VersioningProfile.isVersionComponent(theName.component(0))) { if (null == latestName) { latestName = theName; latestTimestamp = VersioningProfile.getVersionComponentAsTimestamp(theName.component(0)); } else { CCNTime thisTimestamp = VersioningProfile.getVersionComponentAsTimestamp(theName.component(0)); if (thisTimestamp.after(latestTimestamp)) { latestName = theName; latestTimestamp = thisTimestamp; } } } } return latestName; } /** * Returns the latest version available under this prefix as a CCNTime object. * * @return CCNTime Latest child version as CCNTime */ public CCNTime getLatestVersionChildTime() { ContentName latestVersion = getLatestVersionChildName(); if (null != latestVersion) { return VersioningProfile.getVersionComponentAsTimestamp(latestVersion.component(0)); } return null; } /** * A static method that performs a one-shot call that returns the complete name of the latest * version of content with the given prefix. An alternative route to finding the name of the * latest version of a piece of content, rather than using methods in the VersioningProfile * to retrieve an arbitrary block of content under that version. Useful when the data under * a version is complex in structure. * * @param name ContentName to find the latest version of * @param handle CCNHandle to use for enumeration * @return ContentName The name supplied to the call with the latest version added. * @throws IOException */ public static ContentName getLatestVersionName(ContentName name, CCNHandle handle) throws IOException { EnumeratedNameList enl = new EnumeratedNameList(name, handle); enl.waitForChildren(); ContentName childLatestVersion = enl.getLatestVersionChildName(); enl.stopEnumerating(); if (null != childLatestVersion) { return new ContentName(name, childLatestVersion.component(0)); } return null; } /** * Static method that iterates down the namespace starting with the supplied prefix * as a ContentName (prefixKnownToExist) to a specific child (childName). The method * returns null if the name does not exist in a limited time iteration. If the child * is found, this method returns the EnumeratedNameList object for the parent of the * desired child in the namespace. The current implementation may time out before the * desired name is found. Additionally, the current implementation does not loop on * an enumeration attempt, so a child may be missed if it is not included in the first * enumeration response. * * TODO Add loop to enumerate under a name multiple times to avoid missing a child name * TODO Handle timeouts better to avoid missing children. (Note: We could modify the * name enumeration protocol to return empty responses if we query for an unknown name, * but that adds semantic complications.) * * @param childName ContentName for the child we are looking for under (does not have * to be directly under) a given prefix. * @param prefixKnownToExist ContentName prefix to enumerate to look for a given child. * @param handle CCNHandle for sending and receiving interests and content objects. * * @return EnumeratedNameList Returns the parent EnumeratedNameList for the desired child, * if one is found. Returns null if the child is not found. * * @throws IOException */ public static EnumeratedNameList exists(ContentName childName, ContentName prefixKnownToExist, CCNHandle handle) throws IOException { if ((null == prefixKnownToExist) || (null == childName) || (!prefixKnownToExist.isPrefixOf(childName))) { Log.info("Child " + childName + " must be prefixed by name " + prefixKnownToExist); throw new IllegalArgumentException("Child " + childName + " must be prefixed by name " + prefixKnownToExist); } if (childName.count() == prefixKnownToExist.count()) { // we're already there return new EnumeratedNameList(childName, handle); } ContentName parentName = prefixKnownToExist; int childIndex = parentName.count(); EnumeratedNameList parentEnumerator = null; while (childIndex < childName.count()) { - parentEnumerator = new EnumeratedNameList(parentName, handle); - parentEnumerator.waitForChildren(CHILD_WAIT_INTERVAL); // we're only getting the first round here... - // could wrap this bit in a loop if want to try harder byte[] childNameComponent = childName.component(childIndex); + parentEnumerator = new EnumeratedNameList(parentName, handle); + while (parentEnumerator.waitForChildren(CHILD_WAIT_INTERVAL)) { + if (parentEnumerator.hasChild(childNameComponent)) break; + } if (parentEnumerator.hasChild(childNameComponent)) { childIndex++; if (childIndex == childName.count()) { return parentEnumerator; } parentEnumerator.stopEnumerating(); parentName = new ContentName(parentName, childNameComponent); continue; } else { break; } } return null; } }
false
false
null
null
diff --git a/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java b/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java index dc98603e2..71b9f3eaf 100644 --- a/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java +++ b/source/oms/src/main/java/org/marketcetera/oms/OutgoingMessageHandler.java @@ -1,264 +1,265 @@ package org.marketcetera.oms; import org.marketcetera.core.*; import org.marketcetera.quickfix.*; import quickfix.*; import quickfix.field.*; import java.math.BigDecimal; import java.util.LinkedList; import java.util.List; /** * OutgoingMessageHandler is the "middle" stage that recieves an incoming order request * from JMS, does some operations on it in and sends it on to the FIX sender * * This is essentially the "OrderManager" stage: we send an immediate "ack" to an * incoming NewOrder, apply order modifiers and send it on. * * @author gmiller * $Id$ */ @ClassVersion("$Id$") public class OutgoingMessageHandler { private List<OrderModifier> orderModifiers; private OrderRouteManager routeMgr; private SessionID defaultSessionID; // used to store the SessionID so that FIX sender can find it private IQuickFIXSender quickFIXSender = new QuickFIXSender(); private IDFactory idFactory; private FIXMessageFactory msgFactory; private OrderLimits orderLimits; // this is temporary, until we have much better JMX visibility protected QuickFIXApplication qfApp; public OutgoingMessageHandler(SessionSettings settings, FIXMessageFactory inFactory, OrderLimits inLimits, QuickFIXApplication inQFApp) throws ConfigError, FieldConvertError, MarketceteraException { setOrderModifiers(new LinkedList<OrderModifier>()); setOrderRouteManager(new OrderRouteManager()); msgFactory = inFactory; idFactory = createDatabaseIDFactory(settings); orderLimits = inLimits; qfApp = inQFApp; try { idFactory.init(); } catch (Exception ex) { if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Error initializing the ID factory", ex, this); } // ignore the exception - should get the in-memory id factory instead } } public void setOrderRouteManager(OrderRouteManager inMgr) { routeMgr = inMgr; } public void setOrderModifiers(List<OrderModifier> mods){ orderModifiers = new LinkedList<OrderModifier>(); for (OrderModifier mod : mods) { orderModifiers.add(mod); } orderModifiers.add(new TransactionTimeInsertOrderModifier()); } public Message handleMessage(Message message) throws MarketceteraException { if(message == null) { LoggerAdapter.error(OMSMessageKey.ERROR_INCOMING_MSG_NULL.getLocalizedMessage(), this); return null; } if(!qfApp.isLoggedOn()) { return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_NO_DESTINATION_CONNECTION.getLocalizedMessage()), message); } try { String version = message.getHeader().getField(new BeginString()).getValue(); if(!msgFactory.getBeginString().equals(version)) { return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MISMATCHED_FIX_VERSION.getLocalizedMessage( msgFactory.getBeginString(), version)), message); } } catch (FieldNotFound fieldNotFound) { return createRejectionMessage(new MarketceteraException(OMSMessageKey.ERROR_MALFORMED_MESSAGE_NO_FIX_VERSION.getLocalizedMessage()), message); } Message returnVal = null; try { if(FIXMessageUtil.isOrderList(message)) { throw new MarketceteraException(OMSMessageKey.ERROR_ORDER_LIST_UNSUPPORTED.getLocalizedMessage()); } modifyOrder(message); orderLimits.verifyOrderLimits(message); // if single, pre-create an executionReport and send it back if (FIXMessageUtil.isOrderSingle(message)) { Message outReport = executionReportFromNewOrder(message); if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Sending immediate execReport: "+outReport, this); } returnVal = outReport; } routeMgr.modifyOrder(message, msgFactory.getMsgAugmentor()); if (defaultSessionID != null) quickFIXSender.sendToTarget(message, defaultSessionID); else quickFIXSender.sendToTarget(message); } catch (FieldNotFound fnfEx) { MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fnfEx); returnVal = createRejectionMessage(mfix, message); } catch(SessionNotFound snf) { MarketceteraException ex = new MarketceteraException(MessageKey.SESSION_NOT_FOUND.getLocalizedMessage(defaultSessionID), snf); returnVal = createRejectionMessage(ex, message); } catch (MarketceteraException e) { returnVal = createRejectionMessage(e, message); } catch(Exception ex) { returnVal = createRejectionMessage(ex, message); } return returnVal; } /** Creates a rejection message based on the message that causes the rejection * Currently, if it's an orderCancel then we send back an OrderCancelReject, * otherwise we always send back the ExecutionReport. * @param existingOrder * @return Corresponding rejection Message */ protected Message createRejectionMessage(Exception causeEx, Message existingOrder) { Message rejection = null; if(FIXMessageUtil.isCancelReplaceRequest(existingOrder) || FIXMessageUtil.isCancelRequest(existingOrder) ) { rejection = msgFactory.newOrderCancelReject(); } else { rejection = msgFactory.createMessage(MsgType.EXECUTION_REPORT); rejection.setField(getNextExecId()); rejection.setField(new AvgPx(0)); rejection.setField(new CumQty(0)); rejection.setField(new LastShares(0)); rejection.setField(new LastPx(0)); rejection.setField(new ExecTransType(ExecTransType.STATUS)); } rejection.setField(new OrdStatus(OrdStatus.REJECTED)); FIXMessageUtil.fillFieldsFromExistingMessage(rejection, existingOrder); String msg = (causeEx.getMessage() == null) ? causeEx.toString() : causeEx.getMessage(); LoggerAdapter.error(OMSMessageKey.MESSAGE_EXCEPTION.getLocalizedMessage(msg, existingOrder), this); if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug("Reason for above rejection: "+msg, causeEx, this); } rejection.setString(Text.FIELD, msg); // manually set the ClOrdID since it's not required in the dictionary but is for electronic orders try { rejection.setField(new ClOrdID(existingOrder.getString(ClOrdID.FIELD))); } catch(FieldNotFound ignored) { // don't set it if it's not there } try { msgFactory.getMsgAugmentor().executionReportAugment(rejection); } catch (FieldNotFound fieldNotFound) { MarketceteraFIXException mfix = MarketceteraFIXException.createFieldNotFoundException(fieldNotFound); if(LoggerAdapter.isDebugEnabled(this)) { LoggerAdapter.debug(mfix.getLocalizedMessage(), fieldNotFound, this); } // ignore the exception since we are already sending a reject } + rejection.getHeader().setField(new SendingTime()); return rejection; } protected Message executionReportFromNewOrder(Message newOrder) throws FieldNotFound { if (FIXMessageUtil.isOrderSingle(newOrder)){ String clOrdId = newOrder.getString(ClOrdID.FIELD); char side = newOrder.getChar(Side.FIELD); String symbol = newOrder.getString(Symbol.FIELD); BigDecimal orderQty = new BigDecimal(newOrder.getString(OrderQty.FIELD)); BigDecimal orderPrice = null; try { String strPrice = newOrder.getString(Price.FIELD); orderPrice = new BigDecimal(strPrice); } catch(FieldNotFound ex) { // leave as null } String inAccount = null; try { inAccount = newOrder.getString(Account.FIELD); } catch (FieldNotFound ex) { // only set the Account field if it's there } Message execReport = msgFactory.newExecutionReport( null, clOrdId, getNextExecId().getValue(), OrdStatus.NEW, side, orderQty, orderPrice, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, new MSymbol(symbol), inAccount); execReport.getHeader().setField(new SendingTime()); return execReport; } else { return null; } } /** Apply all the order modifiers to this message */ protected void modifyOrder(Message inOrder) throws MarketceteraException { for (OrderModifier oneModifier : orderModifiers) { oneModifier.modifyOrder(inOrder, msgFactory.getMsgAugmentor()); } } /** Sets the default session */ public void setDefaultSessionID(SessionID inSessionID) { defaultSessionID = inSessionID; } public SessionID getDefaultSessionID() { return defaultSessionID; } public IQuickFIXSender getQuickFIXSender() { return quickFIXSender; } public void setQuickFIXSender(IQuickFIXSender quickFIXSender) { this.quickFIXSender = quickFIXSender; } protected IDFactory createDatabaseIDFactory(SessionSettings settings) throws ConfigError, FieldConvertError { return new DatabaseIDFactory(settings.getString(JdbcSetting.SETTING_JDBC_CONNECTION_URL), settings.getString(JdbcSetting.SETTING_JDBC_DRIVER), settings.getString(JdbcSetting.SETTING_JDBC_USER), settings.getString(JdbcSetting.SETTING_JDBC_PASSWORD), DatabaseIDFactory.TABLE_NAME, DatabaseIDFactory.COL_NAME, DatabaseIDFactory.NUM_IDS_GRABBED); } /** Returns the next ExecID from the factory, or a hardcoded ZZ-internal if we have * problems creating an execID * @return */ private ExecID getNextExecId() { try { return new ExecID(idFactory.getNext()); } catch(NoMoreIDsException ex) { LoggerAdapter.error(OMSMessageKey.ERROR_GENERATING_EXEC_ID.getLocalizedMessage(ex.getMessage()), this); return new ExecID("ZZ-INTERNAL"); } } } diff --git a/source/oms/src/test/java/org/marketcetera/oms/OrderManagerTest.java b/source/oms/src/test/java/org/marketcetera/oms/OrderManagerTest.java index cc39c2591..9f24a797f 100644 --- a/source/oms/src/test/java/org/marketcetera/oms/OrderManagerTest.java +++ b/source/oms/src/test/java/org/marketcetera/oms/OrderManagerTest.java @@ -1,474 +1,475 @@ package org.marketcetera.oms; import junit.framework.Test; import org.marketcetera.core.*; import org.marketcetera.quickfix.*; import org.marketcetera.quickfix.DefaultOrderModifier.MessageFieldType; import quickfix.*; import quickfix.field.*; import java.math.BigDecimal; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.HashSet; /** * Tests the code coming out of {@link OutgoingMessageHandler} class * @author Toli Kuznets * @version $Id$ */ @ClassVersion("$Id$") public class OrderManagerTest extends FIXVersionedTestCase { /* a bunch of random made-up header/trailer/field values */ public static final String HEADER_57_VAL = "CERT"; public static final String HEADER_12_VAL = "12.24"; public static final String TRAILER_2_VAL = "2-trailer"; public static final String FIELDS_37_VAL = "37-regField"; public static final String FIELDS_14_VAL = "37"; public OrderManagerTest(String inName, FIXVersion version) { super(inName, version); } public static Test suite() { /* MarketceteraTestSuite suite = new MarketceteraTestSuite(); suite.addTest(new OrderManagerTest("testMessageRejectedLoggedOutOMS", FIXVersion.FIX41)); suite.init(new MessageBundleInfo[]{OrderManagementSystem.OMS_MESSAGE_BUNDLE_INFO}); return suite; /*/ return new FIXVersionTestSuite(OrderManagerTest.class, OrderManagementSystem.OMS_MESSAGE_BUNDLE_INFO, FIXVersionTestSuite.ALL_VERSIONS, new HashSet<String>(Arrays.asList("testIncompatibleFIXVersions")), new FIXVersion[]{FIXVersion.FIX40}); } public void testNewExecutionReportFromOrder() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); Message newOrder = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), TimeInForce.DAY, "bob"); Message execReport = handler.executionReportFromNewOrder(newOrder); // put an orderID in since immediate execReport doesn't have one and we need one for validation execReport.setField(new OrderID("fake-order-id")); verifyExecutionReport(execReport); // verify the acount id is present assertEquals("bob", execReport.getString(Account.FIELD)); assertTrue("sendingTime not set", execReport.getHeader().isSetField(SendingTime.FIELD)); // on a non-single order should get back null assertNull(handler.executionReportFromNewOrder(msgFactory.newCancel("bob", "bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), "counterparty"))); } // test one w/out incoming account public void testNewExecutionReportFromOrder_noAccount() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); Message newOrder = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), TimeInForce.DAY, "bob"); // remove account ID newOrder.removeField(Account.FIELD); final Message execReport = handler.executionReportFromNewOrder(newOrder); // put an orderID in since immediate execReport doesn't have one and we need one for validation execReport.setField(new OrderID("fake-order-id")); verifyExecutionReport(execReport); // verify the acount id is not present (new ExpectedTestFailure(FieldNotFound.class) { protected void execute() throws Exception { execReport.getString(Account.FIELD); } }).run(); } private void verifyExecutionReport(Message inExecReport) throws Exception { FIXMessageUtilTest.verifyExecutionReport(inExecReport, "100", "IBM", Side.BUY, msgFactory); } /** Create a few default fields and verify they get placed * into the message */ public void testInsertDefaultFields() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); handler.setOrderModifiers(getOrderModifiers()); NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); Message msg = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), TimeInForce.DAY, "bob"); Message response = handler.handleMessage(msg); assertNotNull(response); assertEquals(1, quickFIXSender.getCapturedMessages().size()); Message modifiedMessage = quickFIXSender.getCapturedMessages().get(0); // verify that all the default fields have been set assertEquals(HEADER_57_VAL, modifiedMessage.getHeader().getString(57)); assertEquals(HEADER_12_VAL, modifiedMessage.getHeader().getString(12)); assertEquals(TRAILER_2_VAL, modifiedMessage.getTrailer().getString(2)); assertEquals(FIELDS_37_VAL, modifiedMessage.getString(37)); assertEquals(FIELDS_14_VAL, modifiedMessage.getString(14)); if(msgFactory.getMsgAugmentor().needsTransactTime(modifiedMessage)) { // verify that transaction date is set as well, but it'd be set anyway b/c new order sets it assertNotNull(modifiedMessage.getString(TransactTime.FIELD)); } // field 14 and 37 doesn't really belong in NOS so get rid of it before verification, same with field 2 in trailer modifiedMessage.removeField(14); modifiedMessage.removeField(37); modifiedMessage.getTrailer().removeField(2); FIXDataDictionaryManager.getDictionary().validate(modifiedMessage); // put an orderID in since immediate execReport doesn't have one and we need one for validation response.setField(new OrderID("fake-order-id")); FIXDataDictionaryManager.getDictionary().validate(response); } /** Send a generic event and a single-order event. * Verify get an executionReport (not content of it) and that the msg come out * on the sink * * Should get 3 outputs: * execution report * original new order report * cancel report * @throws Exception */ @SuppressWarnings("unchecked") public void testHandleEvents() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); Message newOrder = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), TimeInForce.DAY, "bob"); Message cancelOrder = msgFactory.newCancel("bob", "bob", Side.SELL, new BigDecimal(7), new MSymbol("TOLI"), "redParty"); List<Message> orderList = Arrays.asList(newOrder, cancelOrder); List<Message> responses = new LinkedList<Message>(); for (Message message : orderList) { responses.add(handler.handleMessage(message)); } // verify that we have 2 orders on the mQF sink and 1 on the incomingJMS assertEquals("not enough events on the QF output", 2, quickFIXSender.getCapturedMessages().size()); assertEquals("first output should be outgoing execReport", MsgType.EXECUTION_REPORT, responses.get(0).getHeader().getString(MsgType.FIELD)); assertEquals("2nd event should be original buy order", newOrder, quickFIXSender.getCapturedMessages().get(0)); assertEquals("3rd event should be cancel order", cancelOrder, quickFIXSender.getCapturedMessages().get(1)); // put an orderID in since immediate execReport doesn't have one and we need one for validation responses.get(0).setField(new OrderID("fake-order-id")); verifyExecutionReport(responses.get(0)); } /** verify that sending a malformed buy order (ie missing Side) results in a reject exectuionReport */ public void testHandleMalformedEvent() throws Exception { Message buyOrder = FIXMessageUtilTest.createNOS("toli", 12.34, 234, Side.BUY, msgFactory); buyOrder.removeField(Side.FIELD); OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), fixVersion.getMessageFactory()); handler.setOrderRouteManager(new OrderRouteManager()); NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); final Message result = handler.handleMessage(buyOrder); assertNotNull(result); assertEquals(0, quickFIXSender.getCapturedMessages().size()); assertEquals("first output should be outgoing execReport", MsgType.EXECUTION_REPORT, result.getHeader().getString(MsgType.FIELD)); assertEquals("should be a reject execReport", OrdStatus.REJECTED, result.getChar(OrdStatus.FIELD)); assertTrue("Error message should say field Side was missing", result.getString(Text.FIELD).contains("field Side")); if(!msgFactory.getBeginString().equals(FIXVersion.FIX40.toString())) { assertEquals("execType should be a reject", ExecType.REJECTED, result.getChar(ExecType.FIELD)); } // validation will fail b/c we didn't send a side in to begin with new ExpectedTestFailure(RuntimeException.class, "field="+Side.FIELD) { protected void execute() throws Throwable { FIXDataDictionaryManager.getDictionary().validate(result); } }.run(); } /** Basically, this is a test for bug #15 where any error in the internal code * should result in a rejection being sent back. * @throws Exception */ public void testMalformedPrice() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), fixVersion.getMessageFactory()); handler.setOrderRouteManager(new OrderRouteManager()); NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); Message buyOrder = FIXMessageUtilTest.createNOS("toli", 12.34, 234, Side.BUY, msgFactory); buyOrder.setString(Price.FIELD, "23.23.3"); assertNotNull(buyOrder.getString(ClOrdID.FIELD)); Message result = handler.handleMessage(buyOrder); assertNotNull(result); assertEquals("first output should be outgoing execReport", MsgType.EXECUTION_REPORT, result.getHeader().getString(MsgType.FIELD)); assertEquals("should be a reject execReport", OrdStatus.REJECTED, result.getChar(OrdStatus.FIELD)); if(!msgFactory.getBeginString().equals(FIXVersion.FIX40.toString())) { assertEquals("execType should be a reject", ExecType.REJECTED, result.getChar(ExecType.FIELD)); } assertNotNull("rejectExecReport doesn't have a ClOrdID set", result.getString(ClOrdID.FIELD)); assertNotNull("no useful rejection message", result.getString(Text.FIELD)); } /** brain-dead: make sure that incoming orders just get placed on the sink */ @SuppressWarnings("unchecked") public void testHandleFIXMessages() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); Message newOrder = msgFactory.newCancelReplaceShares("bob", "orig", new BigDecimal(100)); newOrder.setField(new Symbol("ASDF")); Message cancelOrder = msgFactory.newCancel("bob", "bob", Side.SELL, new BigDecimal(7), new MSymbol("TOLI"), "redParty"); handler.handleMessage(newOrder); handler.handleMessage(cancelOrder); assertEquals("not enough events on the OM quickfix sink", 2, quickFIXSender.getCapturedMessages().size()); assertEquals("1st event should be original buy order", newOrder, quickFIXSender.getCapturedMessages().get(0)); assertEquals("2nd event should be cancel order", cancelOrder, quickFIXSender.getCapturedMessages().get(1)); FIXDataDictionaryManager.getDictionary().validate(quickFIXSender.getCapturedMessages().get(1)); } public void testInvalidSessionID() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); handler.setOrderRouteManager(new OrderRouteManager()); SessionID sessionID = new SessionID(msgFactory.getBeginString(), "no-sender", "no-target"); handler.setDefaultSessionID(sessionID); QuickFIXSender quickFIXSender = new QuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); Message newOrder = msgFactory.newMarketOrder("123", Side.BUY, new BigDecimal(100), new MSymbol("SUNW"), TimeInForce.DAY, "dummyaccount"); // verify we got an execReport that's a rejection with the sessionNotfound error message Message result = handler.handleMessage(newOrder); verifyRejection(result, msgFactory, MessageKey.SESSION_NOT_FOUND, sessionID); } /** Create props with a route manager entry, and make sure the FIX message is * modified but the other ones are not * @throws Exception */ public void testWithOrderRouteManager() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); OrderRouteManager orm = OrderRouteManagerTest.getORMWithOrderRouting(); handler.setOrderRouteManager(orm); final NullQuickFIXSender quickFIXSender = new NullQuickFIXSender(); handler.setQuickFIXSender(quickFIXSender); // 1. create a "incoming JMS buy" order and verify that it doesn't have routing in it final Message newOrder = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol("IBM"), TimeInForce.DAY, "bob"); // verify there's no route info new ExpectedTestFailure(FieldNotFound.class) { protected void execute() throws Throwable { newOrder.getField(new ExDestination()); } }.run(); Message result = handler.handleMessage(newOrder); assertNotNull(result); assertEquals(1, quickFIXSender.getCapturedMessages().size()); new ExpectedTestFailure(FieldNotFound.class) { protected void execute() throws Throwable { newOrder.getHeader().getString(100); quickFIXSender.getCapturedMessages().get(1).getField(new ExDestination()); }}.run(); // now send a FIX-related message through order manager and make sure routing does show up orderRouterTesterHelper(handler, "BRK/A", null, "A"); orderRouterTesterHelper(handler, "IFLI.IM", "Milan", null); orderRouterTesterHelper(handler, "BRK/A.N", "SIGMA", "A"); } public void testIncomingNullMessage() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); assertNull(handler.handleMessage(null)); } /** verify the OMS sends back a rejection when it receives a message of incompatible or unknown verison * this test is hardcoded with OMS at fix40 so exclude it from multi-version tests */ public void testIncompatibleFIXVersions() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), FIXVersion.FIX40.getMessageFactory()); Message msg = new quickfix.fix41.Message(); Message reject = handler.handleMessage(msg); assertEquals("didn't get an execution report", MsgType.EXECUTION_REPORT, reject.getHeader().getString(MsgType.FIELD)); assertEquals("didn't get a reject", OrdStatus.REJECTED+"", reject.getString(OrdStatus.FIELD)); assertEquals("didn't get a right reason", OMSMessageKey.ERROR_MISMATCHED_FIX_VERSION.getLocalizedMessage(FIXVersion.FIX40.toString(), FIXVersion.FIX41.toString()), reject.getString(Text.FIELD)); // now test it with no fix version at all reject = handler.handleMessage(new Message()); verifyRejection(reject, msgFactory, OMSMessageKey.ERROR_MALFORMED_MESSAGE_NO_FIX_VERSION); } /** we test the order limits in {@link OrderLimitsTest} so here we just need to verify * that having one limit be setup incorrectly will fail */ public void testOrderListNotSupported() throws Exception { OutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); Message orderList = msgFactory.createMessage(MsgType.ORDER_LIST); orderList.setField(new Symbol("TOLI")); Message reject = handler.handleMessage(orderList); verifyRejection(reject, msgFactory, OMSMessageKey.ERROR_ORDER_LIST_UNSUPPORTED); } /** verify that OMS rejects messages if it's not connected to a FIX destination */ public void testMessageRejectedLoggedOutOMS() throws Exception { MyOutgoingMessageHandler handler = new MyOutgoingMessageHandler(getDummySessionSettings(), msgFactory); NullQuickFIXSender sender = new NullQuickFIXSender(); handler.setQuickFIXSender(sender); Message execReport = handler.handleMessage(FIXMessageUtilTest.createNOS("TOLI", 23.33, 100, Side.BUY, msgFactory)); assertEquals(1, sender.capturedMessages.size()); assertEquals(MsgType.EXECUTION_REPORT, execReport.getHeader().getString(MsgType.FIELD)); assertEquals(OrdStatus.NEW, execReport.getChar(OrdStatus.FIELD)); // now set it to be logged out and verify a reject sender.capturedMessages.clear(); handler.getQFApp().onLogout(null); execReport = handler.handleMessage(FIXMessageUtilTest.createNOS("TOLI", 23.33, 100, Side.BUY, msgFactory)); assertEquals(0, sender.capturedMessages.size()); verifyRejection(execReport, msgFactory, OMSMessageKey.ERROR_NO_DESTINATION_CONNECTION); // verify goes through again after log on sender.capturedMessages.clear(); handler.getQFApp().onLogon(null); execReport = handler.handleMessage(FIXMessageUtilTest.createNOS("TOLI", 23.33, 100, Side.BUY, msgFactory)); assertEquals(1, sender.capturedMessages.size()); assertEquals(MsgType.EXECUTION_REPORT, execReport.getHeader().getString(MsgType.FIELD)); assertEquals(OrdStatus.NEW, execReport.getChar(OrdStatus.FIELD)); } /** Helper method that takes an OrderManager, the stock symbol and the expect exchange * and verifies that the route parsing comes back correct * @param symbol Symbol, can contain either a share class or an exchange (or both) * @param expectedExchange Exchange we expec (or null) * @param shareClass Share class (or null) */ private void orderRouterTesterHelper(OutgoingMessageHandler handler, String symbol, String expectedExchange, String shareClass) throws Exception { final Message qfMsg = msgFactory.newMarketOrder("bob", Side.BUY, new BigDecimal(100), new MSymbol(symbol), TimeInForce.DAY, "bob"); NullQuickFIXSender nullQuickFIXSender = ((NullQuickFIXSender)handler.getQuickFIXSender()); nullQuickFIXSender.getCapturedMessages().clear(); Message result = handler.handleMessage(qfMsg); assertNotNull(result); assertEquals(1,nullQuickFIXSender.getCapturedMessages().size()); Message incomingMsg = nullQuickFIXSender.getCapturedMessages().get(0); if(expectedExchange != null) { assertEquals(expectedExchange, incomingMsg.getString(ExDestination.FIELD)); } if(shareClass != null) { assertEquals(shareClass, incomingMsg.getString(SymbolSfx.FIELD)); } } /** Helper method for creating a set of properties with defaults to be reused */ public static List<OrderModifier> getOrderModifiers() { List<OrderModifier> orderModifiers = new LinkedList<OrderModifier>(); DefaultOrderModifier defaultOrderModifier = new DefaultOrderModifier(); defaultOrderModifier.addDefaultField(57, HEADER_57_VAL, MessageFieldType.HEADER); orderModifiers.add(defaultOrderModifier); defaultOrderModifier = new DefaultOrderModifier(); defaultOrderModifier.addDefaultField(12, HEADER_12_VAL, MessageFieldType.HEADER); orderModifiers.add(defaultOrderModifier); defaultOrderModifier = new DefaultOrderModifier(); defaultOrderModifier.addDefaultField(2, TRAILER_2_VAL, MessageFieldType.TRAILER); orderModifiers.add(defaultOrderModifier); defaultOrderModifier = new DefaultOrderModifier(); defaultOrderModifier.addDefaultField(37, FIELDS_37_VAL, MessageFieldType.MESSAGE); orderModifiers.add(defaultOrderModifier); defaultOrderModifier = new DefaultOrderModifier(); defaultOrderModifier.addDefaultField(14, FIELDS_14_VAL, MessageFieldType.MESSAGE); orderModifiers.add(defaultOrderModifier); return orderModifiers; } public static void verifyRejection(Message inMsg, FIXMessageFactory msgFactory, LocalizedMessage msgKey, Object ... args) throws Exception { assertEquals("didn't get an execution report", MsgType.EXECUTION_REPORT, inMsg.getHeader().getString(MsgType.FIELD)); assertEquals("didn't get a reject", OrdStatus.REJECTED+"", inMsg.getString(OrdStatus.FIELD)); if(!msgFactory.getBeginString().equals(FIXVersion.FIX40.toString())) { assertEquals("execType should be a reject", ExecType.REJECTED, inMsg.getChar(ExecType.FIELD)); } assertEquals("didn't get a right reason", msgKey.getLocalizedMessage(args), inMsg.getString(Text.FIELD)); + assertTrue("rejects should have sending time in them too", inMsg.getHeader().isSetField(SendingTime.FIELD)); } private SessionSettings getDummySessionSettings() { SessionSettings settings = new SessionSettings(); settings.setString(JdbcSetting.SETTING_JDBC_CONNECTION_URL, "jdbc:mysql://localhost/junit"); settings.setString(JdbcSetting.SETTING_JDBC_DRIVER, "com.mysql.jdbc.Driver"); settings.setString(JdbcSetting.SETTING_JDBC_USER, ""); settings.setString(JdbcSetting.SETTING_JDBC_PASSWORD, ""); return settings; } public static class MyOutgoingMessageHandler extends OutgoingMessageHandler { private static int factoryStart = (int) Math.round((Math.random() * 1000)); public MyOutgoingMessageHandler(SessionSettings settings, FIXMessageFactory inFactory) throws ConfigError, FieldConvertError, MarketceteraException { super(settings, inFactory, OrderLimitsTest.createBasicOrderLimits(), new QuickFIXApplication()); // simulate logon qfApp.onLogon(null); } public MyOutgoingMessageHandler(SessionSettings settings, FIXMessageFactory inFactory, OrderLimits limits) throws ConfigError, FieldConvertError, MarketceteraException { super(settings, inFactory, limits, new QuickFIXApplication()); // simulate logon qfApp.onLogon(null); } protected IDFactory createDatabaseIDFactory(SessionSettings settings) throws ConfigError, FieldConvertError { return new InMemoryIDFactory(factoryStart); } public QuickFIXApplication getQFApp() { return qfApp; } } }
false
false
null
null
diff --git a/src/org/eclipse/core/tests/internal/builders/ConfigurationBuilder.java b/src/org/eclipse/core/tests/internal/builders/ConfigurationBuilder.java index 7296db0..a28a171 100644 --- a/src/org/eclipse/core/tests/internal/builders/ConfigurationBuilder.java +++ b/src/org/eclipse/core/tests/internal/builders/ConfigurationBuilder.java @@ -1,76 +1,76 @@ /******************************************************************************* * Copyright (c) 2010 Broadcom Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Broadcom Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.tests.internal.builders; import java.util.*; import junit.framework.Assert; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; /** * A builder used that stores statistics, such as which target was built, per project build config. */ public class ConfigurationBuilder extends TestBuilder { public static final String BUILDER_NAME = "org.eclipse.core.tests.resources.configbuilder"; /** Stores IBuildConfiguration -> ConfigurationBuilder */ private static HashMap builders = new HashMap(); /** Order in which builders have been run */ static List buildOrder = new ArrayList(); // Per builder instance stats int triggerForLastBuild; IResourceDelta deltaForLastBuild; int buildCount; public ConfigurationBuilder() { } public static ConfigurationBuilder getBuilder(IBuildConfiguration config) { return (ConfigurationBuilder) builders.get(config); } public static void clearBuildOrder() { buildOrder = new ArrayList(); } public static void clearStats() { for (Iterator it = builders.values().iterator(); it.hasNext();) { ConfigurationBuilder builder = (ConfigurationBuilder) it.next(); builder.buildCount = 0; builder.triggerForLastBuild = 0; builder.deltaForLastBuild = null; } } protected void startupOnInitialize() { super.startupOnInitialize(); - builders.put(getBuildConfiguration(), this); + builders.put(getBuildConfig(), this); buildCount = 0; } protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException { buildCount++; triggerForLastBuild = kind; deltaForLastBuild = getDelta(getProject()); - buildOrder.add(getBuildConfiguration()); + buildOrder.add(getBuildConfig()); return super.build(kind, args, monitor); } protected void clean(IProgressMonitor monitor) throws CoreException { super.clean(monitor); IResourceDelta delta = getDelta(getProject()); Assert.assertNull(delta); buildCount++; triggerForLastBuild = IncrementalProjectBuilder.CLEAN_BUILD; } }
false
false
null
null
diff --git a/demos/about/src/java/org/xhtmlrenderer/demo/aboutbox/AboutBox.java b/demos/about/src/java/org/xhtmlrenderer/demo/aboutbox/AboutBox.java index 6b383718..cbe9d809 100755 --- a/demos/about/src/java/org/xhtmlrenderer/demo/aboutbox/AboutBox.java +++ b/demos/about/src/java/org/xhtmlrenderer/demo/aboutbox/AboutBox.java @@ -1,153 +1,160 @@ /* * {{{ header & license * Copyright (c) 2004 Joshua Marinacci * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * }}} */ -package org.joshy.html.app.aboutbox; +package org.xhtmlrenderer.demo.aboutbox; -import java.awt.event.*; -import javax.swing.*; -import java.awt.*; -import java.io.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.io.File; import java.net.URL; -import javax.xml.parsers.*; -import org.w3c.dom.*; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; -import org.joshy.html.*; -import org.joshy.u; -import org.joshy.html.app.browser.*; +import org.xhtmlrenderer.*; +import org.xhtmlrenderer.swing.*; +import org.xhtmlrenderer.util.u; public class AboutBox extends JDialog implements Runnable { JScrollPane scroll; JButton close_button; boolean go = false; public AboutBox(String text, String url) { super(); u.p("starting the about box"); setTitle(text); HTMLPanel panel = new HTMLPanel(); int w = 400; int h = 500; panel.setPreferredSize(new Dimension(w,h)); scroll = new JScrollPane(panel); scroll.setVerticalScrollBarPolicy(scroll.VERTICAL_SCROLLBAR_ALWAYS); scroll.setHorizontalScrollBarPolicy(scroll.HORIZONTAL_SCROLLBAR_NEVER); scroll.setPreferredSize(new Dimension(w,h)); - panel.setViewportComponent(scroll); - panel.setJScrollPane(scroll); + //panel.setViewportComponent(scroll); + //panel.setJScrollPane(scroll); getContentPane().add(scroll,"Center"); close_button = new JButton("Close"); getContentPane().add(close_button,"South"); close_button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { setVisible(false); go = false; } }); try { loadPage(url,panel); } catch (Exception ex) { u.p(ex); } pack(); setSize(w,h); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width-w)/2,(screen.height-h)/2); } public void loadPage(String url_text, HTMLPanel panel) throws Exception { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setValidating(true); DocumentBuilder builder = fact.newDocumentBuilder(); //builder.setErrorHandler(root.error_handler); Document doc = null; URL ref = null; if(url_text.startsWith("demo:")) { u.p("starts with demo"); DemoMarker marker = new DemoMarker(); u.p("url text = " + url_text); String short_url = url_text.substring(5); if(!short_url.startsWith("/")) { short_url = "/" + short_url; } u.p("short url = " + short_url); ref = marker.getClass().getResource(short_url); u.p("ref = " + ref); doc = builder.parse(marker.getClass().getResourceAsStream(short_url)); } else if(url_text.startsWith("http")) { doc = builder.parse(url_text); ref = new File(url_text).toURL(); } else { doc = builder.parse(url_text); ref = new File(url_text).toURL(); } u.p("ref = " + ref); u.p("url_text = " + url_text); panel.setDocument(doc,ref); } public void setVisible(boolean vis) { super.setVisible(vis); if(vis == true) { startScrolling(); } } Thread thread; public void startScrolling() { go = true; thread = new Thread(this); thread.start(); } public void run() { while(go) { try { Thread.currentThread().sleep(100); } catch (Exception ex) { u.p(ex); } JScrollBar sb = scroll.getVerticalScrollBar(); sb.setValue(sb.getValue()+1); } } public static void main(String[] args) { JFrame frame = new JFrame("About Box Test"); frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); JButton launch = new JButton("Show About Box"); frame.getContentPane().add(launch); frame.pack(); frame.setVisible(true); launch.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { - AboutBox ab = new AboutBox("About Flying Saucer","demo:demos/about/index.xhtml"); + AboutBox ab = new AboutBox("About Flying Saucer","demo:demos/index.xhtml"); ab.setVisible(true); } }); } }
false
false
null
null
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/JavaFile.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/JavaFile.java index d8346fa13c..8d55cac43a 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/JavaFile.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/resources/JavaFile.java @@ -1,315 +1,317 @@ /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.resources; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.sonar.api.scan.filesystem.PathResolver; import org.sonar.api.utils.WildcardPattern; import java.io.File; import java.util.List; /** * A class that represents a Java class. This class can either be a Test class or source class * * @since 1.10 */ public class JavaFile extends Resource { private static final String JAVA_SUFFIX = ".java"; private static final String JAV_SUFFIX = ".jav"; private String className; private String filename; private String fullyQualifiedName; private String packageFullyQualifiedName; private boolean unitTest; private JavaPackage parent; private JavaFile() { // Default constructor } /** * Creates a JavaFile that is not a class of test based on package and file names * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public JavaFile(String packageName, String className) { this(packageName, className, false); } /** * Creates a JavaFile that can be of any type based on package and file names * * @param unitTest whether it is a unit test file or a source file * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public JavaFile(String packageKey, String className, boolean unitTest) { if (className == null) { throw new IllegalArgumentException("Java filename can not be null"); } this.className = StringUtils.trim(className); String deprecatedKey; if (StringUtils.isBlank(packageKey)) { this.packageFullyQualifiedName = JavaPackage.DEFAULT_PACKAGE_NAME; this.fullyQualifiedName = this.className; deprecatedKey = new StringBuilder().append(this.packageFullyQualifiedName).append(".").append(this.className).toString(); } else { this.packageFullyQualifiedName = packageKey.trim(); deprecatedKey = new StringBuilder().append(this.packageFullyQualifiedName).append(".").append(this.className).toString(); this.fullyQualifiedName = deprecatedKey; } setDeprecatedKey(deprecatedKey); this.unitTest = unitTest; } /** * Creates a source file from its key * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public JavaFile(String key) { this(key, false); } /** * Creates any JavaFile from its key * * @param unitTest whether it is a unit test file or a source file * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public JavaFile(String key, boolean unitTest) { if (key == null) { throw new IllegalArgumentException("Java filename can not be null"); } String realKey = StringUtils.trim(key); this.unitTest = unitTest; if (realKey.contains(".")) { this.className = StringUtils.substringAfterLast(realKey, "."); this.packageFullyQualifiedName = StringUtils.substringBeforeLast(realKey, "."); this.fullyQualifiedName = realKey; } else { this.className = realKey; this.fullyQualifiedName = realKey; this.packageFullyQualifiedName = JavaPackage.DEFAULT_PACKAGE_NAME; realKey = new StringBuilder().append(JavaPackage.DEFAULT_PACKAGE_NAME).append(".").append(realKey).toString(); } setDeprecatedKey(realKey); } /** * {@inheritDoc} */ @Override public JavaPackage getParent() { if (parent == null) { parent = new JavaPackage(packageFullyQualifiedName); } return parent; } /** * @return null */ @Override public String getDescription() { return null; } /** * @return Java */ @Override public Language getLanguage() { return Java.INSTANCE; } /** * {@inheritDoc} */ @Override public String getName() { return StringUtils.isNotBlank(filename) ? filename : (className + JAVA_SUFFIX); } /** * {@inheritDoc} */ @Override public String getLongName() { return fullyQualifiedName; } /** * @return SCOPE_ENTITY */ @Override public String getScope() { return Scopes.FILE; } /** * @return QUALIFIER_UNIT_TEST_CLASS or QUALIFIER_FILE depending whether it is a unit test class */ @Override public String getQualifier() { return unitTest ? Qualifiers.UNIT_TEST_FILE : Qualifiers.FILE; } /** * @return whether the JavaFile is a unit test class or not */ public boolean isUnitTest() { return unitTest; } /** * {@inheritDoc} */ @Override public boolean matchFilePattern(String antPattern) { WildcardPattern matcher = WildcardPattern.create(antPattern, Directory.SEPARATOR); return matcher.match(getKey()); } /** * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public static JavaFile fromIOFile(File file, Project module, boolean unitTest) { if (file == null || !StringUtils.endsWithIgnoreCase(file.getName(), JAVA_SUFFIX)) { return null; } PathResolver.RelativePath relativePath = new PathResolver().relativePath( unitTest ? module.getFileSystem().getTestDirs() : module.getFileSystem().getSourceDirs(), file); if (relativePath != null) { JavaFile sonarFile = fromRelativePath(relativePath.path(), unitTest); sonarFile.setPath(new PathResolver().relativePath(module.getFileSystem().getBasedir(), file)); return sonarFile; } return null; } /** * For internal use only. */ public static JavaFile create(String relativePathFromBasedir) { JavaFile javaFile = new JavaFile(); String normalizedPath = normalize(relativePathFromBasedir); javaFile.setKey(normalizedPath); javaFile.setPath(normalizedPath); - String directoryKey = StringUtils.substringBeforeLast(normalizedPath, Directory.SEPARATOR); javaFile.parent = new Directory(); - javaFile.parent.setKey(directoryKey); + String directoryPath = StringUtils.substringBeforeLast(normalizedPath, Directory.SEPARATOR); + String normalizedParentPath = normalize(directoryPath); + javaFile.parent.setKey(normalizedParentPath); + javaFile.parent.setPath(normalizedParentPath); return javaFile; } public static JavaFile create(String relativePathFromBasedir, String relativePathFromSourceDir, boolean unitTest) { JavaFile javaFile = JavaFile.create(relativePathFromBasedir); if (relativePathFromSourceDir.contains(Directory.SEPARATOR)) { javaFile.packageFullyQualifiedName = StringUtils.substringBeforeLast(relativePathFromSourceDir, Directory.SEPARATOR); javaFile.packageFullyQualifiedName = StringUtils.replace(javaFile.packageFullyQualifiedName, Directory.SEPARATOR, "."); javaFile.filename = StringUtils.substringAfterLast(relativePathFromSourceDir, Directory.SEPARATOR); if (javaFile.filename.endsWith(JAVA_SUFFIX)) { javaFile.className = StringUtils.removeEndIgnoreCase(javaFile.filename, JAVA_SUFFIX); } else if (javaFile.filename.endsWith(JAV_SUFFIX)) { javaFile.className = StringUtils.removeEndIgnoreCase(javaFile.filename, JAV_SUFFIX); } javaFile.fullyQualifiedName = javaFile.packageFullyQualifiedName + "." + javaFile.className; javaFile.setDeprecatedKey(javaFile.fullyQualifiedName); javaFile.parent.setDeprecatedKey(Directory.parseKey(StringUtils.substringBeforeLast(relativePathFromSourceDir, Directory.SEPARATOR))); } else { javaFile.packageFullyQualifiedName = JavaPackage.DEFAULT_PACKAGE_NAME; javaFile.className = StringUtils.removeEndIgnoreCase(relativePathFromSourceDir, JAVA_SUFFIX); javaFile.fullyQualifiedName = javaFile.className; javaFile.setDeprecatedKey(JavaPackage.DEFAULT_PACKAGE_NAME + "." + javaFile.className); javaFile.parent.setDeprecatedKey(Directory.ROOT); } javaFile.unitTest = unitTest; return javaFile; } /** * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public static JavaFile fromRelativePath(String relativePath, boolean unitTest) { if (relativePath != null) { String pacname = null; String classname = relativePath; if (relativePath.indexOf('/') >= 0) { pacname = StringUtils.substringBeforeLast(relativePath, "/"); pacname = StringUtils.replace(pacname, "/", "."); classname = StringUtils.substringAfterLast(relativePath, "/"); } classname = StringUtils.substringBeforeLast(classname, "."); return new JavaFile(pacname, classname, unitTest); } return null; } /** * Creates a JavaFile from a file in the source directories * * @return the JavaFile created if exists, null otherwise * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public static JavaFile fromIOFile(File file, List<File> sourceDirs, boolean unitTest) { if (file == null || !StringUtils.endsWithIgnoreCase(file.getName(), JAVA_SUFFIX)) { return null; } PathResolver.RelativePath relativePath = new PathResolver().relativePath(sourceDirs, file); if (relativePath != null) { return fromRelativePath(relativePath.path(), unitTest); } return null; } /** * Shortcut to fromIOFile with an abolute path * @deprecated since 4.2 use {@link #create(String, String, boolean)} */ @Deprecated public static JavaFile fromAbsolutePath(String path, List<File> sourceDirs, boolean unitTest) { if (path == null) { return null; } return fromIOFile(new File(path), sourceDirs, unitTest); } @Override public String toString() { return new ToStringBuilder(this) .append("key", getKey()) .append("deprecatedKey", getDeprecatedKey()) .append("path", getPath()) .append("filename", className) .toString(); } } diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/JavaFileTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/JavaFileTest.java index 9dba526fb4..c5f158533e 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/JavaFileTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/resources/JavaFileTest.java @@ -1,262 +1,274 @@ /* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.resources; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.util.Arrays; import java.util.List; import static org.fest.assertions.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class JavaFileTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void testNewClass() { JavaFile javaClass = JavaFile.create("src/main/java/org/foo/bar/Hello.java", "org/foo/bar/Hello.java", false); assertThat(javaClass.getKey()).isEqualTo("/src/main/java/org/foo/bar/Hello.java"); assertThat(javaClass.getDeprecatedKey(), is("org.foo.bar.Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("org.foo.bar.Hello")); assertThat(javaClass.getParent().getKey(), is("/src/main/java/org/foo/bar")); assertThat(javaClass.getParent().getDeprecatedKey(), is("org/foo/bar")); } @Test public void testNewClassByDeprecatedKey() { JavaFile javaClass = new JavaFile("org.foo.bar.Hello", false); assertThat(javaClass.getDeprecatedKey(), is("org.foo.bar.Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("org.foo.bar.Hello")); assertThat(javaClass.getParent().getDeprecatedKey(), is("org/foo/bar")); } @Test public void testNewClassWithExplicitPackage() { JavaFile javaClass = new JavaFile("org.foo.bar", "Hello", false); assertThat(javaClass.getDeprecatedKey(), is("org.foo.bar.Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("org.foo.bar.Hello")); assertThat(javaClass.getParent().getDeprecatedKey(), is("org/foo/bar")); } @Test public void shouldAcceptFilenamesWithDollars() { // $ is not used only for inner classes !!! JavaFile javaFile = new JavaFile("org.foo.bar", "Hello$Bar"); assertThat(javaFile.getDeprecatedKey(), is("org.foo.bar.Hello$Bar")); } @Test public void testNewClassWithEmptyPackage() { JavaFile javaClass = JavaFile.create("src/main/java/Hello.java", "Hello.java", false); assertThat(javaClass.getKey()).isEqualTo("/src/main/java/Hello.java"); assertThat(javaClass.getDeprecatedKey(), is(JavaPackage.DEFAULT_PACKAGE_NAME + ".Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("Hello")); assertThat(javaClass.getParent().getKey()).isEqualTo("/src/main/java"); assertThat(javaClass.getParent().getDeprecatedKey()).isEqualTo(Directory.ROOT); assertThat(javaClass.getParent().isDefault()).isTrue(); } @Test + public void testNewClassInRootFolder() { + JavaFile javaClass = JavaFile.create("Hello.java", "Hello.java", false); + assertThat(javaClass.getKey()).isEqualTo("/Hello.java"); + assertThat(javaClass.getDeprecatedKey(), is(JavaPackage.DEFAULT_PACKAGE_NAME + ".Hello")); + assertThat(javaClass.getName(), is("Hello.java")); + assertThat(javaClass.getLongName(), is("Hello")); + assertThat(javaClass.getParent().getKey()).isEqualTo("/"); + assertThat(javaClass.getParent().getDeprecatedKey()).isEqualTo(Directory.ROOT); + assertThat(javaClass.getParent().isDefault()).isTrue(); + } + + @Test public void testNewClassWithEmptyPackageDeprecatedConstructor() { JavaFile javaClass = new JavaFile("", "Hello", false); assertThat(javaClass.getDeprecatedKey(), is(JavaPackage.DEFAULT_PACKAGE_NAME + ".Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("Hello")); assertThat(javaClass.getParent().isDefault(), is(true)); } @Test public void testNewClassWithNullPackageDeprecatedConstructor() { JavaFile javaClass = new JavaFile(null, "Hello", false); assertThat(javaClass.getDeprecatedKey(), is(JavaPackage.DEFAULT_PACKAGE_NAME + ".Hello")); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("Hello")); assertThat((javaClass.getParent()).isDefault(), is(true)); } @Test public void shouldBeDefaultPackageIfNoPackage() { JavaFile javaClass = new JavaFile("Hello", false); assertEquals(JavaPackage.DEFAULT_PACKAGE_NAME + ".Hello", javaClass.getDeprecatedKey()); assertThat(javaClass.getName(), is("Hello.java")); assertThat(javaClass.getLongName(), is("Hello")); assertThat(javaClass.getParent().isDefault(), is(true)); } @Test public void aClassShouldBeNamedJava() { JavaFile javaClass = new JavaFile("org.foo.bar.Java", false); assertThat(javaClass.getDeprecatedKey(), is("org.foo.bar.Java")); assertThat(javaClass.getLongName(), is("org.foo.bar.Java")); assertThat(javaClass.getName(), is("Java.java")); JavaPackage parent = javaClass.getParent(); assertEquals("org/foo/bar", parent.getDeprecatedKey()); } @Test public void shouldTrimClasses() { JavaFile clazz = new JavaFile(" org.foo.bar.Hello ", false); assertThat(clazz.getDeprecatedKey(), is("org.foo.bar.Hello")); assertThat(clazz.getLongName(), is("org.foo.bar.Hello")); assertThat(clazz.getName(), is("Hello.java")); JavaPackage parent = clazz.getParent(); assertThat(parent.getDeprecatedKey(), is("org/foo/bar")); } @Test public void testEqualsOnClasses() { JavaFile class1 = new JavaFile("foo.bar", "Hello", false); JavaFile class2 = new JavaFile("foo.bar.Hello", false); assertThat(class1).isEqualTo(class2); class1 = new JavaFile("NoPackage", false); class2 = new JavaFile("NoPackage", false); assertThat(class1).isEqualTo(class2); assertThat(class1).isEqualTo(class1); } @Test public void oneLevelPackage() { JavaFile clazz = new JavaFile("onelevel.MyFile"); assertEquals("onelevel.MyFile", clazz.getDeprecatedKey()); assertEquals("onelevel", clazz.getParent().getDeprecatedKey()); clazz = new JavaFile("onelevel", "MyFile"); assertEquals("onelevel.MyFile", clazz.getDeprecatedKey()); assertEquals("onelevel", clazz.getParent().getDeprecatedKey()); File sourceDir = newDir("sources"); List<File> sources = Arrays.asList(sourceDir); JavaFile javaFile = JavaFile.fromAbsolutePath(absPath(sourceDir, "onelevel/MyFile.java"), sources, false); assertEquals("onelevel.MyFile", javaFile.getDeprecatedKey()); assertEquals("MyFile.java", javaFile.getName()); assertEquals("onelevel", javaFile.getParent().getDeprecatedKey()); assertThat(javaFile.getParent().isDefault(), is(false)); } @Test public void shouldResolveClassFromAbsolutePath() { File sources1 = newDir("source1"); File sources2 = newDir("source2"); List<File> sources = Arrays.asList(sources1, sources2); JavaFile javaFile = JavaFile.fromAbsolutePath(absPath(sources2, "foo/bar/MyFile.java"), sources, false); assertThat("foo.bar.MyFile", is(javaFile.getDeprecatedKey())); assertThat(javaFile.getLongName(), is("foo.bar.MyFile")); assertThat(javaFile.getName(), is("MyFile.java")); assertThat(javaFile.getParent().getDeprecatedKey(), is("foo/bar")); } @Test public void shouldResolveFromAbsolutePathEvenIfDefaultPackage() { File source1 = newDir("source1"); File source2 = newDir("source2"); List<File> sources = Arrays.asList(source1, source2); JavaFile javaClass = JavaFile.fromAbsolutePath(absPath(source1, "MyClass.java"), sources, false); assertEquals(JavaPackage.DEFAULT_PACKAGE_NAME + ".MyClass", javaClass.getDeprecatedKey()); assertEquals("MyClass.java", javaClass.getName()); assertThat((javaClass.getParent()).isDefault()).isEqualTo(true); } @Test public void shouldResolveOnlyJavaFromAbsolutePath() { File source1 = newDir("source1"); List<File> sources = Arrays.asList(source1); assertThat(JavaFile.fromAbsolutePath(absPath(source1, "foo/bar/my_file.sql"), sources, false)).isNull(); } @Test public void shouldNotFailWhenResolvingUnknownClassFromAbsolutePath() { File source1 = newDir("source1"); List<File> sources = Arrays.asList(source1); assertThat(JavaFile.fromAbsolutePath("/home/other/src/main/java/foo/bar/MyClass.java", sources, false)).isNull(); } @Test public void shouldMatchFilePatterns() { JavaFile clazz = JavaFile.create("src/main/java/org/sonar/commons/Foo.java", "org/sonar/commons/Foo.java", false); assertThat(clazz.matchFilePattern("**/commons/**/*.java")).isTrue(); assertThat(clazz.matchFilePattern("/**/commons/**/*.java")).isTrue(); assertThat(clazz.matchFilePattern("/**/commons/**/*.*")).isTrue(); assertThat(clazz.matchFilePattern("/**/sonar/*.java")).isFalse(); assertThat(clazz.matchFilePattern("src/main/java/org/*/commons/**/*.java")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar/commons/*")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar/**/*.java")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar/*")).isFalse(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar*/*")).isFalse(); assertThat(clazz.matchFilePattern("src/main/java/org/**")).isTrue(); assertThat(clazz.matchFilePattern("*src/main/java/org/sona?/co??ons/**.*")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar/core/**")).isFalse(); assertThat(clazz.matchFilePattern("src/main/java/org/sonar/commons/Foo.java")).isTrue(); assertThat(clazz.matchFilePattern("**/*Foo.java")).isTrue(); assertThat(clazz.matchFilePattern("**/*Foo.*")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/*/*/Foo.java")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/org/**/**/Foo.java")).isTrue(); assertThat(clazz.matchFilePattern("**/commons/**/*")).isTrue(); assertThat(clazz.matchFilePattern("**/*")).isTrue(); } // SONAR-4397 @Test public void shouldMatchFilePatternsWhenNoPackage() { JavaFile clazz = JavaFile.create("src/main/java/Foo.java", "Foo.java", false); assertThat(clazz.matchFilePattern("**/*Foo.java")).isTrue(); assertThat(clazz.matchFilePattern("**/*Foo.*")).isTrue(); assertThat(clazz.matchFilePattern("**/*")).isTrue(); assertThat(clazz.matchFilePattern("src/main/java/Foo*.*")).isTrue(); } /** * See http://jira.codehaus.org/browse/SONAR-1449 */ @Test public void doNotMatchAPattern() { JavaFile file = JavaFile.create("src/main/java/org/sonar/commons/Foo.java", "org/sonar/commons/Foo.java", false); assertThat(file.matchFilePattern("**/*.aj")).isFalse(); assertThat(file.matchFilePattern("**/*.java")).isTrue(); } @Test public void should_exclude_test_files() { JavaFile unitTest = JavaFile.create("src/main/java/org/sonar/commons/Foo.java", "org/sonar/commons/Foo.java", true); assertThat(unitTest.matchFilePattern("**/*")).isTrue(); } private File newDir(String dirName) { return tempFolder.newFolder(dirName); } private String absPath(File dir, String filePath) { return new File(dir, filePath).getPath(); } }
false
false
null
null
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java index 85163668..6fb8e4c9 100644 --- a/src/com/android/launcher2/Launcher.java +++ b/src/com/android/launcher2/Launcher.java @@ -1,1971 +1,1976 @@ /* * 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.launcher2; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ISearchManager; import android.app.SearchManager; import android.app.StatusBarManager; import android.app.WallpaperInfo; import android.app.WallpaperManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.LabeledIntent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.os.Parcelable; import android.os.RemoteException; import android.os.ServiceManager; import android.provider.LiveFolders; import android.text.Selection; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.method.TextKeyListener; import static android.util.Log.*; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.View.OnLongClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.DataInputStream; /** * Default launcher application. */ public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks { static final String LOG_TAG = "Launcher"; static final String TAG = LOG_TAG; static final boolean LOGD = false; static final boolean PROFILE_STARTUP = false; static final boolean PROFILE_ROTATE = false; static final boolean DEBUG_USER_INTERFACE = false; private static final int WALLPAPER_SCREENS_SPAN = 2; private static final int MENU_GROUP_ADD = 1; private static final int MENU_ADD = Menu.FIRST + 1; private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1; private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1; private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1; private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1; private static final int REQUEST_CREATE_SHORTCUT = 1; private static final int REQUEST_CREATE_LIVE_FOLDER = 4; private static final int REQUEST_CREATE_APPWIDGET = 5; private static final int REQUEST_PICK_APPLICATION = 6; private static final int REQUEST_PICK_SHORTCUT = 7; private static final int REQUEST_PICK_LIVE_FOLDER = 8; private static final int REQUEST_PICK_APPWIDGET = 9; + private static final int REQUEST_PICK_WALLPAPER = 10; static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; static final String EXTRA_CUSTOM_WIDGET = "custom_widget"; static final String SEARCH_WIDGET = "search_widget"; static final int SCREEN_COUNT = 3; static final int DEFAULT_SCREN = 1; static final int NUMBER_CELLS_X = 4; static final int NUMBER_CELLS_Y = 4; static final int DIALOG_CREATE_SHORTCUT = 1; static final int DIALOG_RENAME_FOLDER = 2; private static final String PREFERENCES = "launcher.preferences"; // Type: int private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; // Type: boolean private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder"; // Type: long private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX"; // Type: int private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY"; // Type: int[] private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells"; // Type: boolean private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; // Type: long private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; static final int APPWIDGET_HOST_ID = 1024; private static final Object sLock = new Object(); private static int sScreen = DEFAULT_SCREN; private LayoutInflater mInflater; private DragController mDragController; private Workspace mWorkspace; private AppWidgetManager mAppWidgetManager; private LauncherAppWidgetHost mAppWidgetHost; private CellLayout.CellInfo mAddItemCellInfo; private CellLayout.CellInfo mMenuAddInfo; private final int[] mCellCoordinates = new int[2]; private FolderInfo mFolderInfo; private DeleteZone mDeleteZone; private HandleView mHandleView; private AllAppsView mAllAppsGrid; private Bundle mSavedState; private SpannableStringBuilder mDefaultKeySsb = null; private boolean mIsNewIntent; private boolean mWorkspaceLoading = true; private boolean mRestoring; private boolean mWaitingForResult; private boolean mLocaleChanged; private boolean mExitingBecauseOfLaunch; private boolean mHomeDown; private boolean mBackDown; private Bundle mSavedInstanceState; private LauncherModel mModel; private ArrayList<ItemInfo> mDesktopItems = new ArrayList(); private static HashMap<Long, FolderInfo> mFolders = new HashMap(); private ArrayList<ApplicationInfo> mAllAppsList = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mModel = ((LauncherApplication)getApplication()).setLauncher(this); mInflater = getLayoutInflater(); mAppWidgetManager = AppWidgetManager.getInstance(this); mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); mAppWidgetHost.startListening(); if (PROFILE_STARTUP) { android.os.Debug.startMethodTracing("/sdcard/launcher"); } checkForLocaleChange(); setWallpaperDimension(); setContentView(R.layout.launcher); setupViews(); lockAllApps(); mSavedState = savedInstanceState; restoreState(mSavedState); if (PROFILE_STARTUP) { android.os.Debug.stopMethodTracing(); } // We have a new AllAppsView, we need to re-bind everything, and it could have // changed in our absence. mModel.setAllAppsDirty(); mModel.setWorkspaceDirty(); if (!mRestoring) { mModel.startLoader(this, true); } // For handling default keys mDefaultKeySsb = new SpannableStringBuilder(); Selection.setSelection(mDefaultKeySsb, 0); } private void checkForLocaleChange() { final LocaleConfiguration localeConfiguration = new LocaleConfiguration(); readConfiguration(this, localeConfiguration); final Configuration configuration = getResources().getConfiguration(); final String previousLocale = localeConfiguration.locale; final String locale = configuration.locale.toString(); final int previousMcc = localeConfiguration.mcc; final int mcc = configuration.mcc; final int previousMnc = localeConfiguration.mnc; final int mnc = configuration.mnc; mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; if (mLocaleChanged) { localeConfiguration.locale = locale; localeConfiguration.mcc = mcc; localeConfiguration.mnc = mnc; writeConfiguration(this, localeConfiguration); AppInfoCache.flush(); } } private static class LocaleConfiguration { public String locale; public int mcc = -1; public int mnc = -1; } private static void readConfiguration(Context context, LocaleConfiguration configuration) { DataInputStream in = null; try { in = new DataInputStream(context.openFileInput(PREFERENCES)); configuration.locale = in.readUTF(); configuration.mcc = in.readInt(); configuration.mnc = in.readInt(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { // Ignore } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Ignore } } } } private static void writeConfiguration(Context context, LocaleConfiguration configuration) { DataOutputStream out = null; try { out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); out.writeUTF(configuration.locale); out.writeInt(configuration.mcc); out.writeInt(configuration.mnc); out.flush(); } catch (FileNotFoundException e) { // Ignore } catch (IOException e) { //noinspection ResultOfMethodCallIgnored context.getFileStreamPath(PREFERENCES).delete(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Ignore } } } } static int getScreen() { synchronized (sLock) { return sScreen; } } static void setScreen(int screen) { synchronized (sLock) { sScreen = screen; } } private void setWallpaperDimension() { WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE); Display display = getWindowManager().getDefaultDisplay(); boolean isPortrait = display.getWidth() < display.getHeight(); final int width = isPortrait ? display.getWidth() : display.getHeight(); final int height = isPortrait ? display.getHeight() : display.getWidth(); wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mWaitingForResult = false; // The pattern used here is that a user PICKs a specific application, // which, depending on the target, might need to CREATE the actual target. // For example, the user would PICK_SHORTCUT for "Music playlist", and we // launch over to the Music app to actually CREATE_SHORTCUT. if (resultCode == RESULT_OK && mAddItemCellInfo != null) { switch (requestCode) { case REQUEST_PICK_APPLICATION: completeAddApplication(this, data, mAddItemCellInfo); break; case REQUEST_PICK_SHORTCUT: processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT); break; case REQUEST_CREATE_SHORTCUT: completeAddShortcut(data, mAddItemCellInfo); break; case REQUEST_PICK_LIVE_FOLDER: addLiveFolder(data); break; case REQUEST_CREATE_LIVE_FOLDER: completeAddLiveFolder(data, mAddItemCellInfo); break; case REQUEST_PICK_APPWIDGET: addAppWidget(data); break; case REQUEST_CREATE_APPWIDGET: completeAddAppWidget(data, mAddItemCellInfo); break; + case REQUEST_PICK_WALLPAPER: + // We just wanted the activity result here so we can clear mWaitingForResult + break; } } else if (requestCode == REQUEST_PICK_APPWIDGET && resultCode == RESULT_CANCELED && data != null) { // Clean up the appWidgetId if we canceled int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); if (appWidgetId != -1) { mAppWidgetHost.deleteAppWidgetId(appWidgetId); } } } @Override protected void onResume() { super.onResume(); if (mRestoring) { mWorkspaceLoading = true; mModel.startLoader(this, true); mRestoring = false; } // If this was a new intent (i.e., the mIsNewIntent flag got set to true by // onNewIntent), then close the search dialog if needed, because it probably // came from the user pressing 'home' (rather than, for example, pressing 'back'). if (mIsNewIntent) { // Post to a handler so that this happens after the search dialog tries to open // itself again. mWorkspace.post(new Runnable() { public void run() { ISearchManager searchManagerService = ISearchManager.Stub.asInterface( ServiceManager.getService(Context.SEARCH_SERVICE)); try { searchManagerService.stopSearch(); } catch (RemoteException e) { e(LOG_TAG, "error stopping search", e); } } }); } mIsNewIntent = false; } @Override protected void onPause() { super.onPause(); if (mExitingBecauseOfLaunch) { mExitingBecauseOfLaunch = false; closeAllApps(false); } } @Override public Object onRetainNonConfigurationInstance() { // Flag the loader to stop early before switching mModel.stopLoader(); if (PROFILE_ROTATE) { android.os.Debug.startMethodTracing("/sdcard/launcher-rotate"); } return null; } private boolean acceptFilter() { final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); return !inputManager.isFullscreenMode(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { boolean handled = super.onKeyDown(keyCode, event); if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) { boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, keyCode, event); if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { // something usable has been typed - start a search // the typed text will be retrieved and cleared by // showSearchDialog() // If there are multiple keystrokes before the search dialog takes focus, // onSearchRequested() will be called for every keystroke, // but it is idempotent, so it's fine. return onSearchRequested(); } } return handled; } private String getTypedText() { return mDefaultKeySsb.toString(); } private void clearTypedText() { mDefaultKeySsb.clear(); mDefaultKeySsb.clearSpans(); Selection.setSelection(mDefaultKeySsb, 0); } /** * Restores the previous state, if it exists. * * @param savedState The previous state. */ private void restoreState(Bundle savedState) { if (savedState == null) { return; } final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); if (currentScreen > -1) { mWorkspace.setCurrentScreen(currentScreen); } final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); if (addScreen > -1) { mAddItemCellInfo = new CellLayout.CellInfo(); final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo; addItemCellInfo.valid = true; addItemCellInfo.screen = addScreen; addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X); addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y); addItemCellInfo.findVacantCellsFromOccupied( savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS), savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X), savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y)); mRestoring = true; } boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); if (renameFolder) { long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); mFolderInfo = mModel.getFolderById(this, mFolders, id); mRestoring = true; } } /** * Finds all the views we need and configure them properly. */ private void setupViews() { mDragController = new DragController(this); DragController dragController = mDragController; DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer); dragLayer.setDragController(dragController); mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view); mAllAppsGrid.setLauncher(this); mAllAppsGrid.setDragController(dragController); mAllAppsGrid.setWillNotDraw(false); // We don't want a hole punched in our window. // Manage focusability manually since this thing is always visible mAllAppsGrid.setFocusable(false); mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace); final Workspace workspace = mWorkspace; DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone); mDeleteZone = deleteZone; mHandleView = (HandleView) findViewById(R.id.all_apps_button); mHandleView.setLauncher(this); mHandleView.setOnClickListener(this); /* TODO TransitionDrawable handleIcon = (TransitionDrawable) mHandleView.getDrawable(); handleIocon.setCrossFadeEnabled(true); */ workspace.setOnLongClickListener(this); workspace.setDragController(dragController); workspace.setLauncher(this); deleteZone.setLauncher(this); deleteZone.setDragController(dragController); deleteZone.setHandle(mHandleView); dragController.setDragScoller(workspace); dragController.setDragListener(deleteZone); dragController.setScrollView(dragLayer); // The order here is bottom to top. dragController.addDropTarget(workspace); dragController.addDropTarget(deleteZone); } /** * Creates a view representing a shortcut. * * @param info The data structure describing the shortcut. * * @return A View inflated from R.layout.application. */ View createShortcut(ApplicationInfo info) { return createShortcut(R.layout.application, (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info); } /** * Creates a view representing a shortcut inflated from the specified resource. * * @param layoutResId The id of the XML layout used to create the shortcut. * @param parent The group the shortcut belongs to. * @param info The data structure describing the shortcut. * * @return A View inflated from layoutResId. */ View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) { TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false); if (info.icon == null) { info.icon = AppInfoCache.getIconDrawable(getPackageManager(), info); } if (!info.filtered) { info.icon = Utilities.createIconThumbnail(info.icon, this); info.filtered = true; } favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null); favorite.setText(info.title); favorite.setTag(info); favorite.setOnClickListener(this); return favorite; } /** * Add an application shortcut to the workspace. * * @param data The intent describing the application. * @param cellInfo The position on screen where to create the shortcut. */ void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) { cellInfo.screen = mWorkspace.getCurrentScreen(); if (!findSingleSlot(cellInfo)) return; final ApplicationInfo info = infoFromApplicationIntent(context, data); if (info != null) { mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked()); } } private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) { ComponentName component = data.getComponent(); PackageManager packageManager = context.getPackageManager(); ActivityInfo activityInfo = null; try { activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */); } catch (NameNotFoundException e) { e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e); } if (activityInfo != null) { ApplicationInfo itemInfo = new ApplicationInfo(); itemInfo.title = activityInfo.loadLabel(packageManager); if (itemInfo.title == null) { itemInfo.title = activityInfo.name; } itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); itemInfo.icon = activityInfo.loadIcon(packageManager); itemInfo.container = ItemInfo.NO_ID; return itemInfo; } return null; } /** * Add a shortcut to the workspace. * * @param data The intent describing the shortcut. * @param cellInfo The position on screen where to create the shortcut. */ private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) { cellInfo.screen = mWorkspace.getCurrentScreen(); if (!findSingleSlot(cellInfo)) return; final ApplicationInfo info = addShortcut(this, data, cellInfo, false); if (!mRestoring) { final View view = createShortcut(info); mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked()); } } /** * Add a widget to the workspace. * * @param data The intent describing the appWidgetId. * @param cellInfo The position on screen where to create the widget. */ private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) { Bundle extras = data.getExtras(); int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); d(LOG_TAG, "dumping extras content="+extras.toString()); AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); // Calculate the grid spans needed to fit this widget CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen); int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight); // Try finding open space on Launcher screen final int[] xy = mCellCoordinates; if (!findSlot(cellInfo, xy, spans[0], spans[1])) return; // Build Launcher-specific widget info and save to database LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId); launcherInfo.spanX = spans[0]; launcherInfo.spanY = spans[1]; LauncherModel.addItemToDatabase(this, launcherInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP, mWorkspace.getCurrentScreen(), xy[0], xy[1], false); if (!mRestoring) { mDesktopItems.add(launcherInfo); // Perform actual inflation because we're live launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); launcherInfo.hostView.setTag(launcherInfo); mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1], launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); } } public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { mDesktopItems.remove(launcherInfo); launcherInfo.hostView = null; } public LauncherAppWidgetHost getAppWidgetHost() { return mAppWidgetHost; } static ApplicationInfo addShortcut(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { final ApplicationInfo info = infoFromShortcutIntent(context, data); LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); return info; } private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); Drawable icon = null; boolean filtered = false; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null) { icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context)); filtered = true; customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = resources.getDrawable(id); } catch (Exception e) { w(LOG_TAG, "Could not load shortcut icon: " + extra); } } } if (icon == null) { icon = context.getPackageManager().getDefaultActivityIcon(); } final ApplicationInfo info = new ApplicationInfo(); info.icon = icon; info.filtered = filtered; info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // Close the menu if (Intent.ACTION_MAIN.equals(intent.getAction())) { getWindow().closeAllPanels(); // Whatever we were doing is hereby canceled. mWaitingForResult = false; // Set this flag so that onResume knows to close the search dialog if it's open, // because this was a new intent (thus a press of 'home' or some such) rather than // for example onResume being called when the user pressed the 'back' button. mIsNewIntent = true; try { dismissDialog(DIALOG_CREATE_SHORTCUT); // Unlock the workspace if the dialog was showing } catch (Exception e) { // An exception is thrown if the dialog is not visible, which is fine } try { dismissDialog(DIALOG_RENAME_FOLDER); // Unlock the workspace if the dialog was showing } catch (Exception e) { // An exception is thrown if the dialog is not visible, which is fine } if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) { if (!mWorkspace.isDefaultScreenShowing()) { mWorkspace.moveToDefaultScreen(); } closeAllApps(true); final View v = getWindow().peekDecorView(); if (v != null && v.getWindowToken() != null) { InputMethodManager imm = (InputMethodManager)getSystemService( INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } else { closeAllApps(false); } } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { // Do not call super here mSavedInstanceState = savedInstanceState; } @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen()); final ArrayList<Folder> folders = mWorkspace.getOpenFolders(); if (folders.size() > 0) { final int count = folders.size(); long[] ids = new long[count]; for (int i = 0; i < count; i++) { final FolderInfo info = folders.get(i).getInfo(); ids[i] = info.id; } outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids); } else { super.onSaveInstanceState(outState); } final boolean isConfigurationChange = getChangingConfigurations() != 0; // When the drawer is opened and we are saving the state because of a // configuration change // TODO should not do this if the drawer is currently closing. if (isAllAppsVisible() && isConfigurationChange) { outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true); } if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) { final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo; final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen); outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX); outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX); outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY); outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX()); outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY()); outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS, layout.getOccupiedCells()); } if (mFolderInfo != null && mWaitingForResult) { outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true); outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id); } } @Override public void onDestroy() { super.onDestroy(); try { mAppWidgetHost.stopListening(); } catch (NullPointerException ex) { w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex); } TextKeyListener.getInstance().release(); mModel.stopLoader(); unbindDesktopItems(); AppInfoCache.unbindDrawables(); } @Override public void startActivityForResult(Intent intent, int requestCode) { if (requestCode >= 0) mWaitingForResult = true; super.startActivityForResult(intent, requestCode); } @Override public void startSearch(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { closeAllApps(true); // Slide the search widget to the top, if it's on the current screen, // otherwise show the search dialog immediately. Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); if (searchWidget == null) { showSearchDialog(initialQuery, selectInitialQuery, appSearchData, globalSearch); } else { searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); // show the currently typed text in the search widget while sliding searchWidget.setQuery(getTypedText()); } } /** * Show the search dialog immediately, without changing the search widget. * * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean) */ void showSearchDialog(String initialQuery, boolean selectInitialQuery, Bundle appSearchData, boolean globalSearch) { if (initialQuery == null) { // Use any text typed in the launcher as the initial query initialQuery = getTypedText(); clearTypedText(); } if (appSearchData == null) { appSearchData = new Bundle(); appSearchData.putString(SearchManager.SOURCE, "launcher-search"); } final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); final Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); if (searchWidget != null) { // This gets called when the user leaves the search dialog to go back to // the Launcher. searchManager.setOnCancelListener(new SearchManager.OnCancelListener() { public void onCancel() { searchManager.setOnCancelListener(null); stopSearch(); } }); } searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), appSearchData, globalSearch); } /** * Cancel search dialog if it is open. */ void stopSearch() { // Close search dialog SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchManager.stopSearch(); // Restore search widget to its normal position Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); if (searchWidget != null) { searchWidget.stopSearch(false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (isWorkspaceLocked()) { return false; } super.onCreateOptionsMenu(menu); menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add) .setIcon(android.R.drawable.ic_menu_add) .setAlphabeticShortcut('A'); menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper) .setIcon(android.R.drawable.ic_menu_gallery) .setAlphabeticShortcut('W'); menu.add(0, MENU_SEARCH, 0, R.string.menu_search) .setIcon(android.R.drawable.ic_search_category_default) .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications) .setIcon(com.android.internal.R.drawable.ic_menu_notifications) .setAlphabeticShortcut('N'); final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS); settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings) .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P') .setIntent(settings); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); mMenuAddInfo = mWorkspace.findAllVacantCells(null); menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_ADD: addItems(); return true; case MENU_WALLPAPER_SETTINGS: startWallpaper(); return true; case MENU_SEARCH: onSearchRequested(); return true; case MENU_NOTIFICATIONS: showNotifications(); return true; } return super.onOptionsItemSelected(item); } /** * Indicates that we want global search for this activity by setting the globalSearch * argument for {@link #startSearch} to true. */ @Override public boolean onSearchRequested() { startSearch(null, false, null, true); return true; } public boolean isWorkspaceLocked() { return mWorkspaceLoading || mWaitingForResult; } private void addItems() { showAddDialog(mMenuAddInfo); } void addAppWidget(Intent data) { // TODO: catch bad widget exception when sent int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET); if (SEARCH_WIDGET.equals(customWidget)) { // We don't need this any more, since this isn't a real app widget. mAppWidgetHost.deleteAppWidgetId(appWidgetId); // add the search widget addSearch(); } else { AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId); if (appWidget.configure != null) { // Launch over to configure widget, if needed Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); intent.setComponent(appWidget.configure); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); } else { // Otherwise just add it onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data); } } } void addSearch() { final Widget info = Widget.makeSearch(); final CellLayout.CellInfo cellInfo = mAddItemCellInfo; final int[] xy = mCellCoordinates; final int spanX = info.spanX; final int spanY = info.spanY; if (!findSlot(cellInfo, xy, spanX, spanY)) return; LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, mWorkspace.getCurrentScreen(), xy[0], xy[1], false); final View view = mInflater.inflate(info.layoutResource, null); view.setTag(info); Search search = (Search) view.findViewById(R.id.widget_search); search.setLauncher(this); mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY); } void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) { // Handle case where user selected "Applications" String applicationName = getResources().getString(R.string.group_applications); String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); if (applicationName != null && applicationName.equals(shortcutName)) { Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); startActivityForResult(pickIntent, requestCodeApplication); } else { startActivityForResult(intent, requestCodeShortcut); } } void addLiveFolder(Intent intent) { // Handle case where user selected "Folder" String folderName = getResources().getString(R.string.group_folder); String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); if (folderName != null && folderName.equals(shortcutName)) { addFolder(); } else { startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER); } } void addFolder() { UserFolderInfo folderInfo = new UserFolderInfo(); folderInfo.title = getText(R.string.folder_name); CellLayout.CellInfo cellInfo = mAddItemCellInfo; cellInfo.screen = mWorkspace.getCurrentScreen(); if (!findSingleSlot(cellInfo)) return; // Update the model LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP, mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false); mFolders.put(folderInfo.id, folderInfo); // Create the view FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo); mWorkspace.addInCurrentScreen(newFolder, cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked()); } void removeFolder(FolderInfo folder) { mFolders.remove(folder.id); } private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) { cellInfo.screen = mWorkspace.getCurrentScreen(); if (!findSingleSlot(cellInfo)) return; final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false); if (!mRestoring) { final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this, (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info); mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked()); } } static LiveFolderInfo addLiveFolder(Context context, Intent data, CellLayout.CellInfo cellInfo, boolean notify) { Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT); String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME); Drawable icon = null; boolean filtered = false; Intent.ShortcutIconResource iconResource = null; Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON); if (extra != null && extra instanceof Intent.ShortcutIconResource) { try { iconResource = (Intent.ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = resources.getDrawable(id); } catch (Exception e) { w(LOG_TAG, "Could not load live folder icon: " + extra); } } if (icon == null) { icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); } final LiveFolderInfo info = new LiveFolderInfo(); info.icon = icon; info.filtered = filtered; info.title = name; info.iconResource = iconResource; info.uri = data.getData(); info.baseIntent = baseIntent; info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_GRID); LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); mFolders.put(info.id, info); return info; } private boolean findSingleSlot(CellLayout.CellInfo cellInfo) { final int[] xy = new int[2]; if (findSlot(cellInfo, xy, 1, 1)) { cellInfo.cellX = xy[0]; cellInfo.cellY = xy[1]; return true; } return false; } private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) { if (!cellInfo.findCellForSpan(xy, spanX, spanY)) { boolean[] occupied = mSavedState != null ? mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null; cellInfo = mWorkspace.findAllVacantCells(occupied); if (!cellInfo.findCellForSpan(xy, spanX, spanY)) { Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show(); return false; } } return true; } private void showNotifications() { final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE); if (statusBar != null) { statusBar.expand(); } } private void startWallpaper() { final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); Intent chooser = Intent.createChooser(pickWallpaper, getText(R.string.chooser_wallpaper)); WallpaperManager wm = (WallpaperManager) getSystemService(Context.WALLPAPER_SERVICE); WallpaperInfo wi = wm.getWallpaperInfo(); if (wi != null && wi.getSettingsActivity() != null) { LabeledIntent li = new LabeledIntent(getPackageName(), R.string.configure_wallpaper, 0); li.setClassName(wi.getPackageName(), wi.getSettingsActivity()); chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li }); } - startActivity(chooser); + startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (!hasFocus) { mBackDown = mHomeDown = false; } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: mBackDown = true; return true; case KeyEvent.KEYCODE_HOME: mHomeDown = true; return true; } } else if (event.getAction() == KeyEvent.ACTION_UP) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: if (!event.isCanceled()) { mWorkspace.dispatchKeyEvent(event); if (isAllAppsVisible()) { closeAllApps(true); } else { closeFolder(); } } mBackDown = false; return true; case KeyEvent.KEYCODE_HOME: mHomeDown = false; return true; } } return super.dispatchKeyEvent(event); } private void closeFolder() { Folder folder = mWorkspace.getOpenFolder(); if (folder != null) { closeFolder(folder); } } void closeFolder(Folder folder) { folder.getInfo().opened = false; ViewGroup parent = (ViewGroup) folder.getParent(); if (parent != null) { parent.removeView(folder); // TODO: this line crashes. //mDragController.removeDropTarget((DropTarget)folder); } folder.onClose(); } /** * Go through the and disconnect any of the callbacks in the drawables and the views or we * leak the previous Home screen on orientation change. */ private void unbindDesktopItems() { for (ItemInfo item: mDesktopItems) { item.unbind(); } } /** * Launches the intent referred by the clicked shortcut. * * @param v The view representing the clicked shortcut. */ public void onClick(View v) { Object tag = v.getTag(); if (tag instanceof ApplicationInfo) { // Open shortcut final Intent intent = ((ApplicationInfo) tag).intent; startActivitySafely(intent); mExitingBecauseOfLaunch = true; } else if (tag instanceof FolderInfo) { handleFolderClick((FolderInfo) tag); } else if (v == mHandleView) { Log.d(TAG, "onClick"); if (isAllAppsVisible()) { closeAllApps(true); } else { showAllApps(); } } } void startActivitySafely(Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); e(LOG_TAG, "Launcher does not have the permission to launch " + intent + ". Make sure to create a MAIN intent-filter for the corresponding activity " + "or use the exported attribute for this activity.", e); } } private void handleFolderClick(FolderInfo folderInfo) { if (!folderInfo.opened) { // Close any open folder closeFolder(); // Open the requested folder openFolder(folderInfo); } else { // Find the open folder... Folder openFolder = mWorkspace.getFolderForTag(folderInfo); int folderScreen; if (openFolder != null) { folderScreen = mWorkspace.getScreenForView(openFolder); // .. and close it closeFolder(openFolder); if (folderScreen != mWorkspace.getCurrentScreen()) { // Close any folder open on the current screen closeFolder(); // Pull the folder onto this screen openFolder(folderInfo); } } } } /** * Opens the user fodler described by the specified tag. The opening of the folder * is animated relative to the specified View. If the View is null, no animation * is played. * * @param folderInfo The FolderInfo describing the folder to open. */ private void openFolder(FolderInfo folderInfo) { Folder openFolder; if (folderInfo instanceof UserFolderInfo) { openFolder = UserFolder.fromXml(this); } else if (folderInfo instanceof LiveFolderInfo) { openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo); } else { return; } openFolder.setDragController(mDragController); openFolder.setLauncher(this); openFolder.bind(folderInfo); folderInfo.opened = true; mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4); openFolder.onOpen(); } public boolean onLongClick(View v) { if (isWorkspaceLocked()) { return false; } if (!(v instanceof CellLayout)) { v = (View) v.getParent(); } CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag(); // This happens when long clicking an item with the dpad/trackball if (cellInfo == null) { return true; } if (mWorkspace.allowLongPress()) { if (cellInfo.cell == null) { if (cellInfo.valid) { // User long pressed on empty space mWorkspace.setAllowLongPress(false); showAddDialog(cellInfo); } } else { if (!(cellInfo.cell instanceof Folder)) { // User long pressed on an item mWorkspace.startDrag(cellInfo); } } } return true; } View getDrawerHandle() { return mHandleView; } Workspace getWorkspace() { return mWorkspace; } /* TODO GridView getApplicationsGrid() { return mAllAppsGrid; } */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CREATE_SHORTCUT: return new CreateShortcut().createDialog(); case DIALOG_RENAME_FOLDER: return new RenameFolder().createDialog(); } return super.onCreateDialog(id); } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_CREATE_SHORTCUT: break; case DIALOG_RENAME_FOLDER: if (mFolderInfo != null) { EditText input = (EditText) dialog.findViewById(R.id.folder_name); final CharSequence text = mFolderInfo.title; input.setText(text); input.setSelection(0, text.length()); } break; } } void showRenameDialog(FolderInfo info) { mFolderInfo = info; mWaitingForResult = true; showDialog(DIALOG_RENAME_FOLDER); } private void showAddDialog(CellLayout.CellInfo cellInfo) { mAddItemCellInfo = cellInfo; mWaitingForResult = true; showDialog(DIALOG_CREATE_SHORTCUT); } private void pickShortcut(int requestCode, int title) { Bundle bundle = new Bundle(); ArrayList<String> shortcutNames = new ArrayList<String>(); shortcutNames.add(getString(R.string.group_applications)); bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>(); shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, R.drawable.ic_launcher_application)); bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT)); pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title)); pickIntent.putExtras(bundle); startActivityForResult(pickIntent, requestCode); } private class RenameFolder { private EditText mInput; Dialog createDialog() { mWaitingForResult = true; final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); mInput = (EditText) layout.findViewById(R.id.folder_name); AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); builder.setIcon(0); builder.setTitle(getString(R.string.rename_folder_title)); builder.setCancelable(true); builder.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { cleanup(); } }); builder.setNegativeButton(getString(R.string.cancel_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cleanup(); } } ); builder.setPositiveButton(getString(R.string.rename_action), new Dialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { changeFolderName(); } } ); builder.setView(layout); final AlertDialog dialog = builder.create(); dialog.setOnShowListener(new DialogInterface.OnShowListener() { public void onShow(DialogInterface dialog) { } }); return dialog; } private void changeFolderName() { final String name = mInput.getText().toString(); if (!TextUtils.isEmpty(name)) { // Make sure we have the right folder info mFolderInfo = mFolders.get(mFolderInfo.id); mFolderInfo.title = name; LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo); if (mWorkspaceLoading) { lockAllApps(); mModel.setWorkspaceDirty(); mModel.startLoader(Launcher.this, false); } else { final FolderIcon folderIcon = (FolderIcon) mWorkspace.getViewForTag(mFolderInfo); if (folderIcon != null) { folderIcon.setText(name); getWorkspace().requestLayout(); } else { lockAllApps(); mModel.setWorkspaceDirty(); mWorkspaceLoading = true; mModel.startLoader(Launcher.this, false); } } } cleanup(); } private void cleanup() { dismissDialog(DIALOG_RENAME_FOLDER); mWaitingForResult = false; mFolderInfo = null; } } boolean isAllAppsVisible() { return mAllAppsGrid.isVisible(); } void showAllApps() { mAllAppsGrid.zoom(1.0f); //mWorkspace.hide(); mAllAppsGrid.setFocusable(true); + mAllAppsGrid.requestFocus(); // TODO: fade these two too mDeleteZone.setVisibility(View.GONE); //mHandleView.setVisibility(View.GONE); } void closeAllApps(boolean animated) { if (mAllAppsGrid.isVisible()) { mAllAppsGrid.zoom(0.0f); mAllAppsGrid.setFocusable(false); mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); // TODO: fade these two too /* mDeleteZone.setVisibility(View.VISIBLE); mHandleView.setVisibility(View.VISIBLE); */ } } void lockAllApps() { // TODO } void unlockAllApps() { // TODO } /** * Displays the shortcut creation dialog and launches, if necessary, the * appropriate activity. */ private class CreateShortcut implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, DialogInterface.OnDismissListener, DialogInterface.OnShowListener { private AddAdapter mAdapter; Dialog createDialog() { mWaitingForResult = true; mAdapter = new AddAdapter(Launcher.this); final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); builder.setTitle(getString(R.string.menu_item_add_item)); builder.setAdapter(mAdapter, this); builder.setInverseBackgroundForced(true); AlertDialog dialog = builder.create(); dialog.setOnCancelListener(this); dialog.setOnDismissListener(this); dialog.setOnShowListener(this); return dialog; } public void onCancel(DialogInterface dialog) { mWaitingForResult = false; cleanup(); } public void onDismiss(DialogInterface dialog) { } private void cleanup() { dismissDialog(DIALOG_CREATE_SHORTCUT); } /** * Handle the action clicked in the "Add to home" dialog. */ public void onClick(DialogInterface dialog, int which) { Resources res = getResources(); cleanup(); switch (which) { case AddAdapter.ITEM_SHORTCUT: { // Insert extra item to handle picking application pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut); break; } case AddAdapter.ITEM_APPWIDGET: { int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId(); Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK); pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); // add the search widget ArrayList<AppWidgetProviderInfo> customInfo = new ArrayList<AppWidgetProviderInfo>(); AppWidgetProviderInfo info = new AppWidgetProviderInfo(); info.provider = new ComponentName(getPackageName(), "XXX.YYY"); info.label = getString(R.string.group_search); info.icon = R.drawable.ic_search_widget; customInfo.add(info); pickIntent.putParcelableArrayListExtra( AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo); ArrayList<Bundle> customExtras = new ArrayList<Bundle>(); Bundle b = new Bundle(); b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET); customExtras.add(b); pickIntent.putParcelableArrayListExtra( AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras); // start the pick activity startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); break; } case AddAdapter.ITEM_LIVE_FOLDER: { // Insert extra item to handle inserting folder Bundle bundle = new Bundle(); ArrayList<String> shortcutNames = new ArrayList<String>(); shortcutNames.add(res.getString(R.string.group_folder)); bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>(); shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, R.drawable.ic_launcher_folder)); bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER)); pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_live_folder)); pickIntent.putExtras(bundle); startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER); break; } case AddAdapter.ITEM_WALLPAPER: { startWallpaper(); break; } } } public void onShow(DialogInterface dialog) { } } /** * Implementation of the method from LauncherModel.Callbacks. */ public int getCurrentWorkspaceScreen() { return mWorkspace.getCurrentScreen(); } /** * Refreshes the shortcuts shown on the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void startBinding() { final Workspace workspace = mWorkspace; int count = workspace.getChildCount(); for (int i = 0; i < count; i++) { ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout(); } if (DEBUG_USER_INTERFACE) { android.widget.Button finishButton = new android.widget.Button(this); finishButton.setText("Finish"); workspace.addInScreen(finishButton, 1, 0, 0, 1, 1); finishButton.setOnClickListener(new android.widget.Button.OnClickListener() { public void onClick(View v) { finish(); } }); } } /** * Bind the items start-end from the list. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { final Workspace workspace = mWorkspace; for (int i=start; i<end; i++) { final ItemInfo item = shortcuts.get(i); mDesktopItems.add(item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: final View shortcut = createShortcut((ApplicationInfo) item); workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1, false); break; case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), (UserFolderInfo) item); workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1, false); break; case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: final FolderIcon newLiveFolder = LiveFolderIcon.fromXml( R.layout.live_folder_icon, this, (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), (LiveFolderInfo) item); workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1, false); break; case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: final int screen = workspace.getCurrentScreen(); final View view = mInflater.inflate(R.layout.widget_search, (ViewGroup) workspace.getChildAt(screen), false); Search search = (Search) view.findViewById(R.id.widget_search); search.setLauncher(this); final Widget widget = (Widget) item; view.setTag(widget); workspace.addWidget(view, widget, false); break; } } workspace.requestLayout(); } /** * Implementation of the method from LauncherModel.Callbacks. */ void bindFolders(HashMap<Long, FolderInfo> folders) { mFolders.putAll(folders); } /** * Add the views for a widget to the workspace. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAppWidget(LauncherAppWidgetInfo item) { final Workspace workspace = mWorkspace; final int appWidgetId = item.appWidgetId; final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); if (true) { Log.d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s", appWidgetId, appWidgetInfo)); } item.hostView.setAppWidget(appWidgetId, appWidgetInfo); item.hostView.setTag(item); workspace.addInScreen(item.hostView, item.screen, item.cellX, item.cellY, item.spanX, item.spanY, false); workspace.requestLayout(); mDesktopItems.add(item); } /** * Callback saying that there aren't any more items to bind. * * Implementation of the method from LauncherModel.Callbacks. */ public void finishBindingItems() { if (mSavedState != null) { if (!mWorkspace.hasFocus()) { mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); } final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS); if (userFolders != null) { for (long folderId : userFolders) { final FolderInfo info = mFolders.get(folderId); if (info != null) { openFolder(info); } } final Folder openFolder = mWorkspace.getOpenFolder(); if (openFolder != null) { openFolder.requestFocus(); } } final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false); if (allApps) { showAllApps(); } mSavedState = null; } if (mSavedInstanceState != null) { super.onRestoreInstanceState(mSavedInstanceState); mSavedInstanceState = null; } /* TODO if (mAllAppsVisible && !mDrawer.hasFocus()) { mDrawer.requestFocus(); } */ Log.d(TAG, "finishBindingItems done"); mWorkspaceLoading = false; } /** * Add the icons for all apps. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindAllApplications(ArrayList<ApplicationInfo> apps) { mAllAppsList = apps; mAllAppsGrid.setApps(mAllAppsList); } /** * A package was installed. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindPackageAdded(ArrayList<ApplicationInfo> apps) { removeDialog(DIALOG_CREATE_SHORTCUT); mAllAppsGrid.addApps(apps); } /** * A package was updated. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps) { removeDialog(DIALOG_CREATE_SHORTCUT); mWorkspace.updateShortcutsForPackage(packageName); } /** * A package was uninstalled. * * Implementation of the method from LauncherModel.Callbacks. */ public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps) { removeDialog(DIALOG_CREATE_SHORTCUT); mWorkspace.removeShortcutsForPackage(packageName); mAllAppsGrid.removeApps(apps); } }
false
false
null
null
diff --git a/php/sonar-php-plugin/src/test/java/org/sonar/plugins/php/pmd/PhpmdExecutorTest.java b/php/sonar-php-plugin/src/test/java/org/sonar/plugins/php/pmd/PhpmdExecutorTest.java index b04d1a326..b2f7ac687 100644 --- a/php/sonar-php-plugin/src/test/java/org/sonar/plugins/php/pmd/PhpmdExecutorTest.java +++ b/php/sonar-php-plugin/src/test/java/org/sonar/plugins/php/pmd/PhpmdExecutorTest.java @@ -1,213 +1,213 @@ /* * Sonar PHP Plugin * Copyright (C) 2010 Akram Ben Aissi * dev@sonar.codehaus.org * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.php.pmd; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.CoreProperties.PROJECT_EXCLUSIONS_PROPERTY; import static org.sonar.plugins.php.MockUtils.getFile; import static org.sonar.plugins.php.MockUtils.getMockProject; import static org.sonar.plugins.php.core.PhpPlugin.FILE_SUFFIXES_KEY; import static org.sonar.plugins.php.pmd.PhpmdConfiguration.PHPMD_DEFAULT_REPORT_FILE_NAME; import static org.sonar.plugins.php.pmd.PhpmdConfiguration.PHPMD_DEFAULT_REPORT_FILE_PATH; import static org.sonar.plugins.php.pmd.PhpmdConfiguration.PHPMD_IGNORE_ARGUMENT_KEY; import static org.sonar.plugins.php.pmd.PhpmdConfiguration.PHPMD_REPORT_FILE_NAME_PROPERTY_KEY; import static org.sonar.plugins.php.pmd.PhpmdConfiguration.PHPMD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY; import java.util.Arrays; import java.util.List; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.junit.Test; import org.sonar.api.resources.Project; public class PhpmdExecutorTest { /** * Test method for {@link org.sonar.plugins.php.codesniffer.PhpCodeSnifferExecutor#getCommandLine()} . */ @Test public void testGetCommandLine1() { Project project = getMockProject(); Configuration configuration = project.getConfiguration(); String[] extensions = new String[] { "php", "php3", "php4" }; when(configuration.getStringArray(FILE_SUFFIXES_KEY)).thenReturn(extensions); when(configuration.getString(PHPMD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_PATH)).thenReturn("/"); when(configuration.getString(PHPMD_REPORT_FILE_NAME_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_NAME)).thenReturn("pmd.xml"); PhpmdConfiguration c = getWindowsConfiguration(project); PhpmdProfileExporter e = mock(PhpmdProfileExporter.class); PhpmdExecutor executor = new PhpmdExecutor(c, e, null); List<String> commandLine = executor.getCommandLine(); - String f1 = getFile("C:/projets/PHP/Monkey/sources/main"); + String f1 = "C:/projets/PHP/Monkey/sources/main"; String f2 = getFile("C:/projets/PHP/Monkey/target/pmd.xml"); String[] expected = new String[] { "phpmd.bat", f1, "xml", "codesize,unusedcode,naming", "--reportfile", f2, "--extensions", StringUtils.join(extensions, ",") }; assertThat(commandLine).isEqualTo(Arrays.asList(expected)); } @Test public void testGetIgnoreDirsWithNotNullWithSonarExclusionNull() { Project project = getMockProject(); Configuration configuration = project.getConfiguration(); String[] extensions = new String[] { "php", "php3", "php4" }; when(configuration.getStringArray(FILE_SUFFIXES_KEY)).thenReturn(extensions); when(configuration.getString(PHPMD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_PATH)).thenReturn("/"); when(configuration.getString(PHPMD_REPORT_FILE_NAME_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_NAME)).thenReturn("pmd.xml"); PhpmdConfiguration c = getWindowsConfiguration(project); PhpmdProfileExporter e = mock(PhpmdProfileExporter.class); when(c.isStringPropertySet(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(true); String pdependExclusionPattern = "Math,Math3*"; when(configuration.getStringArray(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(new String[] { pdependExclusionPattern }); when(configuration.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(null); assertThat(c.getIgnoreList()).isEqualTo(pdependExclusionPattern); PhpmdExecutor executor = new PhpmdExecutor(c, e, null); List<String> commandLine = executor.getCommandLine(); - String f1 = getFile("C:/projets/PHP/Monkey/sources/main"); + String f1 = "C:/projets/PHP/Monkey/sources/main"; String f2 = getFile("C:/projets/PHP/Monkey/target/pmd.xml"); String[] expected = new String[] { "phpmd.bat", f1, "xml", "codesize,unusedcode,naming", "--reportfile", f2, "--extensions", StringUtils.join(extensions, ",") }; assertThat(commandLine).isEqualTo(Arrays.asList(expected)); } @Test public void testGetIgnoreDirsNullWithSonarExclusionNotNull() { Project project = getMockProject(); Configuration configuration = project.getConfiguration(); String[] extensions = new String[] { "php", "php3", "php4" }; when(configuration.getStringArray(FILE_SUFFIXES_KEY)).thenReturn(extensions); when(configuration.getString(PHPMD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_PATH)).thenReturn("/"); when(configuration.getString(PHPMD_REPORT_FILE_NAME_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_NAME)).thenReturn("pmd.xml"); PhpmdConfiguration c = getWindowsConfiguration(project); PhpmdProfileExporter e = mock(PhpmdProfileExporter.class); when(c.isStringPropertySet(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(false); when(configuration.getStringArray(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(null); when(c.isStringPropertySet(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(true); String[] sonarExclusionPattern = { "*test", "**/math" }; when(configuration.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(sonarExclusionPattern); PhpmdExecutor executor = new PhpmdExecutor(c, e, null); List<String> commandLine = executor.getCommandLine(); String s1 = "phpmd.bat"; - String s2 = getFile("C:/projets/PHP/Monkey/sources/main"); + String s2 = "C:/projets/PHP/Monkey/sources/main"; String s3 = "xml"; String s4 = "codesize,unusedcode,naming"; String s5 = "--reportfile"; String s6 = getFile("C:/projets/PHP/Monkey/target/pmd.xml"); String s7 = "--ignore"; String s8 = StringUtils.join(sonarExclusionPattern, ","); String s9 = "--extensions"; String s10 = "php,php3,php4"; List<String> expected = Arrays.asList(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10); assertThat(commandLine).isEqualTo(expected); } @Test public void testGetIgnoreDirsNotNullWithSonarExclusionNotNull() { Project project = getMockProject(); Configuration configuration = project.getConfiguration(); String[] extensions = new String[] { "php", "php3", "php4" }; when(configuration.getStringArray(FILE_SUFFIXES_KEY)).thenReturn(extensions); when(configuration.getString(PHPMD_REPORT_FILE_RELATIVE_PATH_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_PATH)).thenReturn("/"); when(configuration.getString(PHPMD_REPORT_FILE_NAME_PROPERTY_KEY, PHPMD_DEFAULT_REPORT_FILE_NAME)).thenReturn("pmd.xml"); PhpmdConfiguration c = getWindowsConfiguration(project); PhpmdProfileExporter e = mock(PhpmdProfileExporter.class); when(c.isStringPropertySet(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(true); String[] phpmdExclusionPattern = { "*Math5.php" }; when(configuration.getStringArray(PHPMD_IGNORE_ARGUMENT_KEY)).thenReturn(phpmdExclusionPattern); when(c.isStringPropertySet(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(true); String[] sonarExclusionPattern = { "sites/all/", "files", "*Math4.php" }; when(configuration.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(sonarExclusionPattern); PhpmdExecutor executor = new PhpmdExecutor(c, e, null); List<String> commandLine = executor.getCommandLine(); String s1 = "phpmd.bat"; - String s2 = getFile("C:/projets/PHP/Monkey/sources/main"); + String s2 = "C:/projets/PHP/Monkey/sources/main"; String s3 = "xml"; String s4 = "codesize,unusedcode,naming"; String s5 = "--reportfile"; String s6 = getFile("C:/projets/PHP/Monkey/target/pmd.xml"); String s7 = "--ignore"; String s8 = StringUtils.join(phpmdExclusionPattern, ","); s8 += "," + StringUtils.join(sonarExclusionPattern, ","); String s9 = "--extensions"; String s10 = "php,php3,php4"; List<String> expected = Arrays.asList(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10); assertThat(commandLine).isEqualTo(expected); assertThat(commandLine).isEqualTo(expected); } /** * Gets the windows configuration. * * @return the windows configuration */ private PhpmdConfiguration getWindowsConfiguration(Project project) { return getConfiguration(project, true, "aaa"); } /** * Gets the configuration. * * @param isOsWindows * the is os windows * @param path * the path * @return the configuration */ private PhpmdConfiguration getConfiguration(Project project, final boolean isOsWindows, final String path) { PhpmdConfiguration config = new PhpmdConfiguration(project) { @SuppressWarnings("unused") public String getCommandLinePath() { return path; } @Override public boolean isOsWindows() { return isOsWindows; } }; return config; } }
false
false
null
null
diff --git a/src/NFAGenerator.java b/src/NFAGenerator.java index 8be3733..f94c2c5 100644 --- a/src/NFAGenerator.java +++ b/src/NFAGenerator.java @@ -1,478 +1,476 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * * @author andrew * */ public class NFAGenerator { private final boolean DEBUG = true; private StateTable nfa; private int index; private Lexical lex; private String regex; private String token; private int entry_ind; private boolean toggleStar; private boolean togglePlus; private boolean toggleEpsilon; public NFAGenerator(Lexical l){ lex = l; index = 0; entry_ind = 0; nfa = new StateTable(); regex = new String(); token = new String(); toggleStar = false; toggleEpsilon = false; } public NFAGenerator(String r){ index = 0; entry_ind = 0; nfa = new StateTable(); regex = r; token = new String(); toggleStar = false; toggleEpsilon = false; } public StateTable genNFA(){ if(DEBUG)System.out.println("genNFA()"); populate("@"); int subnfa; for(TokenC t: lex.getTokens()){ subnfa = entry_ind; regex = t.getLegal().get(0); token = t.getTitle().substring(1); index = 0; if(DEBUG)System.out.println(token); if(DEBUG)System.out.println(regex); regex(); concat(1,subnfa); } // regex(); return nfa; } private boolean regex(){ if(DEBUG)System.out.println("regex()"); boolean result = rexp(); nfa.getTableRowArray(entry_ind-1).get(0).setAccept(true);//set the very last entry to accept nfa.getTableRowArray(entry_ind-1).get(0).setType(token); return result; /* if(rexp()){ return true; } else{ return false; }*/ } private boolean rexp(){ if(DEBUG)System.out.println("rexp()"); populate("@"); int epsilon = entry_ind-1; int state1 = entry_ind; if(rexp1()){//find rexp1 int state2=entry_ind; if(peekChar()=='|'){//if UNION if(rexpprime()){ union(epsilon,state1,state2); return true; } } else { concat(epsilon,state1); return true; } } return false; } private boolean rexpprime(){ if(DEBUG)System.out.println("rexpprime()"); populate("@"); if(index>=regex.length()||peekChar()==')'){//end of regex return true; } if(peekChar()=='|'){//if another UNION if(match('|')){ int epsilon = entry_ind-1; int state1 = entry_ind; if(rexp1()){//first subnfa - nfa.getTableRowArray(entry_ind-1).get(0).setAccept(true); - nfa.getTableRowArray(entry_ind-1).get(0).setType(token); int state2 = entry_ind; if(peekChar()=='|'){//yet another UNION rexpprime();//second subnfa; union(epsilon,state1,state2); return true; } } } else return false; } toggleEpsilon=true;; return true; } private boolean rexp1(){ if(DEBUG)System.out.println("rexp1()"); if(rexp2()){ if(toggleStar){ toggleStar=false; concat(entry_ind-4,entry_ind-3); } else{ concat(entry_ind-3,entry_ind-2); } if(rexp1prime()){ return true; } } return false; } private boolean rexp1prime(){ if(DEBUG)System.out.println("rexp1prime()"); if(index>=regex.length()||peekChar()==')'){ return true; } if(rexp2()){ if(toggleStar){ toggleStar=false; concat(entry_ind-4,entry_ind-3); } else if(togglePlus){ togglePlus=false; concat(entry_ind-3,entry_ind-2); } else{ concat(entry_ind-3,entry_ind-2); } if(!toggleEpsilon&&rexp1prime()){ toggleEpsilon = false; return true; } } toggleEpsilon=true; return true; } private boolean rexp2(){ if(DEBUG)System.out.println("rexp2()"); int state1 = entry_ind-1; if(peekChar()=='('){ if(match('(')&&rexp()&&match(')')){ int state2 = entry_ind-2; rexp2_tail(); if(toggleStar){ return true; } else if(togglePlus){ concat(entry_ind-1,state1); concat(state1,state1+1); return true; } else{ concat(state1,state1+1); toggleEpsilon=false; return true; } } } if(isRE_CHAR(peekChar())){ char temp = peekChar(); if(match(peekChar())){ populate(String.valueOf(temp)); int state2 = entry_ind-2; rexp2_tail(); if(toggleEpsilon){ toggleEpsilon = false; return true; } else if(toggleStar){ concat(state1,state2); toggleStar = false; return true; } else if(togglePlus){ concat(entry_ind-1,state1); togglePlus = false; return true; } } } if(rexp3()){ return true; } return false; } private boolean rexp2_tail(){ if(DEBUG)System.out.println("rexp2_tail()"); if(index>=regex.length()||peekChar()==')'){ return true; } if(peekChar()=='*'){ //System.out.println("Index at Star: "+entry_ind); match('*'); /* TableRow nextRow = new TableRow(new HashMap<String,ArrayList<TableRow>>(), Integer.toString(entry_ind), "Invalid Type"); nfa.add(nextRow, entry_ind); entry_ind++; concat(entry_ind-3,entry_ind-1); concat(entry_ind-2,entry_ind-3); concat(entry_ind-2,entry_ind-1); */ toggleStar=true; return true; } if(peekChar()=='+'){ match('+'); // concat(entry_ind-1,entry_ind-2); togglePlus=true; return true; } else{ toggleEpsilon = true; return true; } } private boolean rexp3(){ if(DEBUG)System.out.println("rexp3()"); if(index>=regex.length()||peekChar()==')'){ return true; } if(char_class()){ return true; } toggleEpsilon = true; if(DEBUG)System.out.println(toggleEpsilon); return true; } private boolean char_class(){ if(DEBUG)System.out.println("char_class()"); if(peekChar()=='.'){ match('.'); populate("."); return true; } if(peekChar()=='['){ if(match('[')&&char_class1()) return true; } String temp = defined_class(); if(temp!=null){ populate(temp); return true; } return false; } private boolean char_class1(){ if(DEBUG)System.out.println("char_class1()"); if(char_set_list()) return true; if(exclude_set()) return true; return false; } private boolean char_set_list(){ if(DEBUG)System.out.println("char_set_list()"); if(char_set()&&char_set_list()){ return true; } if(peekChar()==']'){ if(match(']')) return true; } return false; } private boolean char_set(){ if(DEBUG)System.out.println("char_set()"); if(isCLS_CHAR(peekChar())){ if(match(peekChar())&&char_set_tail()) return true; } return false; } private boolean char_set_tail(){ if(DEBUG)System.out.println("char_set_tail()"); if(index>=regex.length()||peekChar()==')'){ return true; } if(peekChar()=='-'){ if(match('-')&&isCLS_CHAR(peekChar())){ match(peekChar()); return true; } } toggleEpsilon = true; return true; } private boolean exclude_set(){ if(DEBUG)System.out.println("exclude_set()"); if(peekChar()=='^'){ if(match('^')&&char_set()&&match(']')&&match('I')&&match('N')&&exclude_set_tail()) return true; } return false; } private boolean exclude_set_tail(){ if(DEBUG)System.out.println("exclude_set_tail()"); if(peekChar()=='['){ if(match('[')&&char_set()&&match(']')) return true; } String temp = defined_class(); if(temp!=null){ return true; } return false; } private String defined_class(){ if(DEBUG)System.out.println("define_class()"); String token = ""; if(peekChar()=='$'){ token+='$'; match('$'); while(isUpper(peekChar())){ token+=peekChar(); match(peekChar()); } if(DEBUG)System.out.println(token); return token; } return null; } private char peekChar(){ if(index>=regex.length()) return '\0'; if(DEBUG)System.out.println(regex.charAt(index)); return regex.charAt(index); } private char getChar(){ char result = regex.charAt(index); index++; return result; } private boolean match(char c){ if(peekChar()==c){ if(DEBUG)System.out.printf("Consumed: %c\n",getChar()); else{ getChar(); } return true; } else{ System.out.printf("Error: Expected %c but found %c\n", c,peekChar()); return false; } } private boolean isRE_CHAR(char c){ if(c>=0x20&&c<=0x7E){ if(c!='\\'&&c!='*'&&c!='+'&&c!='?'&&c!='|'&&c!='['&&c!=']'&&c!='('&&c!=')'&&c!='.'&&c!='\''&&c!='\"'&&c!='$'&&c!='@'){ return true; } else if(c=='\\'){ match('\\'); char t = peekChar(); if(t==' '||t=='\\'||t=='*'||t=='+'||t=='?'||t=='|'||t=='['||t==']'||t=='('||t==')'||t=='.'||t=='\''||t=='\"'||t=='$'||t=='@'){ return true; } } } return false; } private boolean isCLS_CHAR(char c){ if(c>=0x20&&c<=0x7E){ if(c!='\\'&&c!='^'&&c!='-'&&c!='['&&c!=']'&&c!='@'){ return true; } else if(c=='\\'){ match('\\'); char t = peekChar(); if(t=='\\'||t=='^'||t=='-'||t=='['||t==']'||t=='@'){ return true; } } } return false; } private boolean isUpper(char c){ return c>='A'&&c<='Z'; } private void populate(String c){ Map<String,ArrayList<TableRow>> trans = new HashMap<String,ArrayList<TableRow>>(); TableRow nextRow = new TableRow(new HashMap<String,ArrayList<TableRow>>(), Integer.toString(entry_ind+1), "Invalid Type"); nfa.add(null, entry_ind); nfa.add(nextRow, entry_ind+1); trans.put(c, nfa.getTableRowArray(entry_ind+1)); nfa.addState(trans, Integer.toString(entry_ind), "Invalid Type", entry_ind, false); entry_ind+=2; } private void concat(int x, int y){ // if(entry_ind>2){ if(DEBUG)System.out.println("Concated: "+x+" & "+y); ArrayList<TableRow> curr = nfa.getTableRowArray(x); ArrayList<TableRow> next = nfa.getTableRowArray(y); Map<String,ArrayList<TableRow>> nextStates = curr.get(0).getSuccessorStates(); if(nextStates.get("@")!=null){ nextStates.get("@").add(next.get(0)); } else{ nextStates.put("@", next); } curr.get(0).setSuccessorStates(nextStates); // } } private void union(int epsilon, int state1, int state2){ if(DEBUG)System.out.println("United: "+state1+" & "+ state2); populate("@"); ArrayList<TableRow> first_next = nfa.getTableRowArray(state1); ArrayList<TableRow> second_next = nfa.getTableRowArray(state2); //glue to epsilon nfa.getTableRowArray(epsilon).get(0).getSuccessorStates().put("@",first_next); nfa.getTableRowArray(epsilon).get(0).getSuccessorStates().get("@").add(second_next.get(0)); //merge to epsilon concat(state2-1,entry_ind-2); concat(entry_ind-3,entry_ind-2); // if(first_next.get(0).getSuccessorStates().get("@")==null){ // first_next.get(0).getSuccessorStates().put("@",nfa.getTableRowArray(entry_ind-2)); // } // else{ // first_next.get(0).getSuccessorStates().get("@").add(nfa.getTableRowArray(entry_ind-2).get(0)); // } // if(second_next.get(0).getSuccessorStates().get("@")==null){ // second_next.get(0).getSuccessorStates().put("@",nfa.getTableRowArray(entry_ind-2)); // } // else{ // second_next.get(0).getSuccessorStates().get("@").add(nfa.getTableRowArray(entry_ind-2).get(0)); // } } }
true
false
null
null
diff --git a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/DomChangeListener.java b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/DomChangeListener.java index 5cc2d6630..ff0b1c8b4 100644 --- a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/DomChangeListener.java +++ b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/DomChangeListener.java @@ -1,62 +1,63 @@ /* * Copyright (c) 2002-2007 Gargoyle Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: * * "This product includes software developed by Gargoyle Software Inc. * (http://www.GargoyleSoftware.com/)." * * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * 4. The name "Gargoyle Software" must not be used to endorse or promote * products derived from this software without prior written permission. * For written permission, please contact info@GargoyleSoftware.com. * 5. Products derived from this software may not be called "HtmlUnit", nor may * "HtmlUnit" appear in their name, without prior written permission of * Gargoyle Software Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 GARGOYLE * SOFTWARE INC. OR ITS 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.gargoylesoftware.htmlunit.html; /** * Implementations of this interface receive notifications of changes to the DOM structure. * * @version $Revision$ * @author Ahmed Ashour * @see DomChangeEvent */ public interface DomChangeListener { /** * Notification that a new node was added. Called after the node is added. * * @param event The event. */ - void nodeAdded( DomChangeEvent event ); + void nodeAdded( final DomChangeEvent event ); /** * Notification that a new node was deleted. Called after the node is deleted. * * @param event The event. */ - void nodeDeleted( DomChangeEvent event ); + void nodeDeleted( final DomChangeEvent event ); + } diff --git a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HtmlAttributeChangeListener.java b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HtmlAttributeChangeListener.java index 6e4fe4f4e..fe41c484b 100644 --- a/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HtmlAttributeChangeListener.java +++ b/htmlunit/src/java/com/gargoylesoftware/htmlunit/html/HtmlAttributeChangeListener.java @@ -1,71 +1,72 @@ /* * Copyright (c) 2002-2007 Gargoyle Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: * * "This product includes software developed by Gargoyle Software Inc. * (http://www.GargoyleSoftware.com/)." * * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * 4. The name "Gargoyle Software" must not be used to endorse or promote * products derived from this software without prior written permission. * For written permission, please contact info@GargoyleSoftware.com. * 5. Products derived from this software may not be called "HtmlUnit", nor may * "HtmlUnit" appear in their name, without prior written permission of * Gargoyle Software Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 GARGOYLE * SOFTWARE INC. OR ITS 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.gargoylesoftware.htmlunit.html; /** * Implementations of this interface receive notifications of changes to the attribute * list on the HtmlElement. * * @version $Revision$ * @author Ahmed Ashour * @see HtmlAttributeChangeEvent */ public interface HtmlAttributeChangeListener { /** * Notification that a new attribute was added to the HtmlElement. Called after the attribute is added. * * @param event The event. */ - void attributeAdded( HtmlAttributeChangeEvent event ); + void attributeAdded( final HtmlAttributeChangeEvent event ); /** * Notification that an existing attribute has been removed from the HtmlElement. * Called after the attribute is removed. * * @param event The event. */ - void attributeRemoved( HtmlAttributeChangeEvent event ); + void attributeRemoved( final HtmlAttributeChangeEvent event ); /** * Notification that an attribute on the HtmlElement has been replaced. Called after the attribute is replaced. * * @param event The event. */ - void attributeReplaced( HtmlAttributeChangeEvent event ); + void attributeReplaced( final HtmlAttributeChangeEvent event ); + }
false
false
null
null
diff --git a/src/main/java/org/nees/rpi/vis/viewer3d/Viewer3DDisplayProxy.java b/src/main/java/org/nees/rpi/vis/viewer3d/Viewer3DDisplayProxy.java index b231651..7099e76 100644 --- a/src/main/java/org/nees/rpi/vis/viewer3d/Viewer3DDisplayProxy.java +++ b/src/main/java/org/nees/rpi/vis/viewer3d/Viewer3DDisplayProxy.java @@ -1,69 +1,72 @@ -/** +/* * Copyright (c) 2004-2007 Rensselaer Polytechnic Institute + * Copyright (c) 2010 Rensselaer Polytechnic Institute * Copyright (c) 2007 NEES Cyberinfrastructure Center * * 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 * * For more information: http://nees.rpi.edu/3dviewer/ */ package org.nees.rpi.vis.viewer3d; -//swing import javax.swing.JFrame; import javax.swing.JPanel; -import org.nees.rpi.vis.ui.*; -//Viewer3D import org.nees.rpi.vis.ui.XYChartPanelProxy; +import org.nees.rpi.vis.ui.*; + /** * This Interface is used by applications needing to use the GEO Viewer3D * in their display. It acts as a proxy for the various components used in the - * display of the 3D universe.<br> + * display of the 3D universe.<br><br> * * It is designed to create low coupling between the main application and the * 3D viewer. */ public interface Viewer3DDisplayProxy { /** * Returns the main application display frame. Used within the 3D panel * for modal and other dependant components. * @return * a JFrame pointing to the main application frame */ public JFrame getApplicationFrame(); + /** * Returns the main panel used to display the 3D universe. * @return * a JPanel pointing to the main 3D panel */ public JPanel getMain3DPanel(); + /** * Returns the helper panel used to display the orientation view. * @return * a JPanel pointing to the orientation 3D panel */ public JPanel getOrientation3DPanel(); + /** * Returns the XYChartPanelProxy used to display data series. * @return * an XYChartPanelProxy declared by the main app */ public XYChartPanelProxy getXYChartProxy(); public ShapeInfoPanel getShapeInfoPanel(); }
false
false
null
null
diff --git a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java index 222935c0a..5606a6186 100644 --- a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java +++ b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java @@ -1,2671 +1,2671 @@ package org.klomp.snark.web; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.text.Collator; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.DataHelper; import net.i2p.util.I2PAppThread; import net.i2p.util.Log; import org.klomp.snark.I2PSnarkUtil; import org.klomp.snark.MagnetURI; import org.klomp.snark.MetaInfo; import org.klomp.snark.Peer; import org.klomp.snark.Snark; import org.klomp.snark.SnarkManager; import org.klomp.snark.Storage; import org.klomp.snark.Tracker; import org.klomp.snark.TrackerClient; import org.klomp.snark.dht.DHT; /** * Refactored to eliminate Jetty dependencies. */ public class I2PSnarkServlet extends BasicServlet { /** generally "/i2psnark" */ private String _contextPath; /** generally "i2psnark" */ private String _contextName; private SnarkManager _manager; private static long _nonce; private String _themePath; private String _imgPath; private String _lastAnnounceURL; private static final String DEFAULT_NAME = "i2psnark"; public static final String PROP_CONFIG_FILE = "i2psnark.configFile"; public I2PSnarkServlet() { super(); } @Override public void init(ServletConfig cfg) throws ServletException { super.init(cfg); String cpath = getServletContext().getContextPath(); _contextPath = cpath == "" ? "/" : cpath; _contextName = cpath == "" ? DEFAULT_NAME : cpath.substring(1).replace("/", "_"); _nonce = _context.random().nextLong(); // limited protection against overwriting other config files or directories // in case you named your war "router.war" String configName = _contextName; if (!configName.equals(DEFAULT_NAME)) configName = DEFAULT_NAME + '_' + _contextName; _manager = new SnarkManager(_context, _contextPath, configName); String configFile = _context.getProperty(PROP_CONFIG_FILE); if ( (configFile == null) || (configFile.trim().length() <= 0) ) configFile = configName + ".config"; _manager.loadConfig(configFile); _manager.start(); loadMimeMap("org/klomp/snark/web/mime"); setResourceBase(_manager.getDataDir()); setWarBase("/.icons/"); } @Override public void destroy() { if (_manager != null) _manager.stop(); super.destroy(); } /** * We override this instead of passing a resource base to super(), because * if a resource base is set, super.getResource() always uses that base, * and we can't get any resources (like icons) out of the .war */ @Override public File getResource(String pathInContext) { if (pathInContext == null || pathInContext.equals("/") || pathInContext.equals("/index.jsp") || pathInContext.equals("/index.html") || pathInContext.startsWith("/.icons/")) return super.getResource(pathInContext); // files in the i2psnark/ directory return new File(_resourceBase, pathInContext); } /** * Handle what we can here, calling super.doGet() for the rest. * @since 0.8.3 */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGetAndPost(request, response); } /** * Handle what we can here, calling super.doPost() for the rest. * @since Jetty 7 */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGetAndPost(request, response); } /** * Handle what we can here, calling super.doGet() or super.doPost() for the rest. * * Some parts modified from: * <pre> // ======================================================================== // $Id: Default.java,v 1.51 2006/10/08 14:13:18 gregwilkins Exp $ // Copyright 199-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== * </pre> * */ private void doGetAndPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //if (_log.shouldLog(Log.DEBUG)) // _log.debug("Service " + req.getMethod() + " \"" + req.getContextPath() + "\" \"" + req.getServletPath() + "\" \"" + req.getPathInfo() + '"'); // since we are not overriding handle*(), do this here String method = req.getMethod(); _themePath = "/themes/snark/" + _manager.getTheme() + '/'; _imgPath = _themePath + "images/"; // this is the part after /i2psnark String path = req.getServletPath(); resp.setHeader("X-Frame-Options", "SAMEORIGIN"); String peerParam = req.getParameter("p"); String stParam = req.getParameter("st"); String peerString; if (peerParam == null || (!_manager.util().connected()) || peerParam.replaceAll("[a-zA-Z0-9~=-]", "").length() > 0) { // XSS peerString = ""; } else { peerString = "?p=" + peerParam; } if (stParam != null && !stParam.equals("0")) { if (peerString.length() > 0) peerString += "&amp;st=" + stParam; else peerString = "?st="+ stParam; } // AJAX for mainsection if ("/.ajax/xhr1.html".equals(path)) { resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); //if (_log.shouldLog(Log.DEBUG)) // _manager.addMessage((_context.clock().now() / 1000) + " xhr1 p=" + req.getParameter("p")); writeMessages(out, false, peerString); writeTorrents(out, req); return; } boolean isConfigure = "/configure".equals(path); // index.jsp doesn't work, it is grabbed by the war handler before here if (!(path == null || path.equals("/") || path.equals("/index.jsp") || path.equals("/index.html") || path.equals("/_post") || isConfigure)) { if (path.endsWith("/")) { // Listing of a torrent (torrent detail page) // bypass the horrid Resource.getListHTML() String pathInfo = req.getPathInfo(); String pathInContext = addPaths(path, pathInfo); req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); File resource = getResource(pathInContext); if (resource == null) { resp.sendError(404); } else { String base = addPaths(req.getRequestURI(), "/"); String listing = getListHTML(resource, base, true, method.equals("POST") ? req.getParameterMap() : null); if (method.equals("POST")) { // P-R-G sendRedirect(req, resp, ""); } else if (listing != null) { resp.getWriter().write(listing); } else { // shouldn't happen resp.sendError(404); } } } else { // local completed files in torrent directories if (method.equals("GET") || method.equals("HEAD")) super.doGet(req, resp); else if (method.equals("POST")) super.doPost(req, resp); else resp.sendError(405); } return; } // Either the main page or /configure req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html; charset=UTF-8"); String nonce = req.getParameter("nonce"); if (nonce != null) { if (nonce.equals(String.valueOf(_nonce))) processRequest(req); else // nonce is constant, shouldn't happen _manager.addMessage("Please retry form submission (bad nonce)"); // P-R-G (or G-R-G to hide the params from the address bar) sendRedirect(req, resp, peerString); return; } PrintWriter out = resp.getWriter(); out.write(DOCTYPE + "<html>\n" + "<head><link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">\n" + "<title>"); out.write(_("I2PSnark - Anonymous BitTorrent Client")); if ("2".equals(peerParam)) out.write(" | Debug Mode"); out.write("</title>\n"); // we want it to go to the base URI so we don't refresh with some funky action= value int delay = 0; if (!isConfigure) { delay = _manager.getRefreshDelaySeconds(); if (delay > 0) { //out.write("<meta http-equiv=\"refresh\" content=\"" + delay + ";/i2psnark/" + peerString + "\">\n"); out.write("<script src=\"/js/ajax.js\" type=\"text/javascript\"></script>\n" + "<script type=\"text/javascript\">\n" + "var failMessage = \"<div class=\\\"routerdown\\\"><b>" + _("Router is down") + "<\\/b><\\/div>\";\n" + "function requestAjax1() { ajax(\"" + _contextPath + "/.ajax/xhr1.html" + peerString.replace("&amp;", "&") + // don't html escape in js "\", \"mainsection\", " + (delay*1000) + "); }\n" + "function initAjax() { setTimeout(requestAjax1, " + (delay*1000) +"); }\n" + "</script>\n"); } } out.write(HEADER_A + _themePath + HEADER_B + "</head>\n"); if (isConfigure || delay <= 0) out.write("<body>"); else out.write("<body onload=\"initAjax()\">"); out.write("<center>"); List<Tracker> sortedTrackers = null; if (isConfigure) { out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + "/\" title=\""); out.write(_("Torrents")); out.write("\" class=\"snarkRefresh\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) out.write(_("I2PSnark")); else out.write(_contextName); out.write("</a>"); } else { out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + '/' + peerString + "\" title=\""); out.write(_("Refresh page")); out.write("\" class=\"snarkRefresh\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) out.write(_("I2PSnark")); else out.write(_contextName); out.write("</a> <a href=\"http://forum.i2p/viewforum.php?f=21\" class=\"snarkRefresh\" target=\"_blank\">"); out.write(_("Forum")); out.write("</a>\n"); sortedTrackers = _manager.getSortedTrackers(); for (Tracker t : sortedTrackers) { if (t.baseURL == null || !t.baseURL.startsWith("http")) continue; out.write(" <a href=\"" + t.baseURL + "\" class=\"snarkRefresh\" target=\"_blank\">" + t.name + "</a>"); } } out.write("</div>\n"); String newURL = req.getParameter("newURL"); if (newURL != null && newURL.trim().length() > 0 && req.getMethod().equals("GET")) _manager.addMessage(_("Click \"Add torrent\" button to fetch torrent")); out.write("<div class=\"page\"><div id=\"mainsection\" class=\"mainsection\">"); writeMessages(out, isConfigure, peerString); if (isConfigure) { // end of mainsection div out.write("<div class=\"logshim\"></div></div>\n"); writeConfigForm(out, req); writeTrackerForm(out, req); } else { boolean pageOne = writeTorrents(out, req); // end of mainsection div if (pageOne) { out.write("</div><div id=\"lowersection\">\n"); writeAddForm(out, req); writeSeedForm(out, req, sortedTrackers); writeConfigLink(out); // end of lowersection div } out.write("</div>\n"); } out.write(FOOTER); } private void writeMessages(PrintWriter out, boolean isConfigure, String peerString) throws IOException { List<String> msgs = _manager.getMessages(); if (!msgs.isEmpty()) { out.write("<div class=\"snarkMessages\">"); out.write("<a href=\"" + _contextPath + '/'); if (isConfigure) out.write("configure"); if (peerString.length() > 0) out.write(peerString + "&amp;"); else out.write("?"); out.write("action=Clear&amp;nonce=" + _nonce + "\">" + "<img src=\"" + _imgPath + "delete.png\" title=\"" + _("clear messages") + "\" alt=\"" + _("clear messages") + "\"></a>" + "<ul>"); for (int i = msgs.size()-1; i >= 0; i--) { String msg = msgs.get(i); out.write("<li>" + msg + "</li>\n"); } out.write("</ul></div>"); } } /** * @return true if on first page */ private boolean writeTorrents(PrintWriter out, HttpServletRequest req) throws IOException { /** dl, ul, down rate, up rate, peers, size */ final long stats[] = {0,0,0,0,0,0}; String peerParam = req.getParameter("p"); String stParam = req.getParameter("st"); List<Snark> snarks = getSortedSnarks(req); boolean isForm = _manager.util().connected() || !snarks.isEmpty(); if (isForm) { out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); // don't lose peer setting if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); // ...or st setting if (stParam != null) out.write("<input type=\"hidden\" name=\"st\" value=\"" + stParam + "\" >\n"); } out.write(TABLE_HEADER); // Opera and text-mode browsers: no &thinsp; and no input type=image values submitted // Using a unique name fixes Opera, except for the buttons with js confirms, see below String ua = req.getHeader("User-Agent"); boolean isDegraded = ua != null && (ua.startsWith("Lynx") || ua.startsWith("w3m") || ua.startsWith("ELinks") || ua.startsWith("Links") || ua.startsWith("Dillo")); boolean noThinsp = isDegraded || (ua != null && ua.startsWith("Opera")); // pages int start = 0; int total = snarks.size(); if (stParam != null) { try { start = Math.max(0, Math.min(total - 1, Integer.parseInt(stParam))); } catch (NumberFormatException nfe) {} } int pageSize = Math.max(_manager.getPageSize(), 5); out.write("<tr><th><img border=\"0\" src=\"" + _imgPath + "status.png\" title=\""); out.write(_("Status")); out.write("\" alt=\""); out.write(_("Status")); out.write("\"></th>\n<th>"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write(" <a href=\"" + _contextPath + '/'); if (peerParam != null) { if (stParam != null) { out.write("?st="); out.write(stParam); } out.write("\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "hidepeers.png\" title=\""); out.write(_("Hide Peers")); out.write("\" alt=\""); out.write(_("Hide Peers")); out.write("\">"); } else { out.write("?p=1"); if (stParam != null) { out.write("&amp;st="); out.write(stParam); } out.write("\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "showpeers.png\" title=\""); out.write(_("Show Peers")); out.write("\" alt=\""); out.write(_("Show Peers")); out.write("\">"); } out.write("</a><br>\n"); } out.write("</th>\n<th colspan=\"2\" align=\"left\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "torrent.png\" title=\""); out.write(_("Torrent")); out.write("\" alt=\""); out.write(_("Torrent")); out.write("\"></th>\n<th align=\"center\">"); if (total > 0 && (start > 0 || total > pageSize)) { writePageNav(out, start, pageSize, total, peerParam, noThinsp); } out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "eta.png\" title=\""); out.write(_("Estimated time remaining")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("ETA")); out.write("\">"); } out.write("</th>\n<th align=\"right\">"); out.write("<img border=\"0\" src=\"" + _imgPath + "head_rx.png\" title=\""); out.write(_("Downloaded")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("RX")); out.write("\">"); out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_tx.png\" title=\""); out.write(_("Uploaded")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("TX")); out.write("\">"); } out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_rxspeed.png\" title=\""); out.write(_("Down Rate")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("RX Rate")); out.write(" \">"); } out.write("</th>\n<th align=\"right\">"); if (_manager.util().connected() && !snarks.isEmpty()) { out.write("<img border=\"0\" src=\"" + _imgPath + "head_txspeed.png\" title=\""); out.write(_("Up Rate")); out.write("\" alt=\""); // Translators: Please keep short or translate as " " out.write(_("TX Rate")); out.write(" \">"); } out.write("</th>\n<th align=\"center\">"); if (_manager.isStopping()) { out.write("&nbsp;"); } else if (_manager.util().connected()) { if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=StopAll&amp;nonce=" + _nonce + "\"><img title=\""); else { // http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name //out.write("<input type=\"image\" name=\"action\" value=\"StopAll\" title=\""); out.write("<input type=\"image\" name=\"action_StopAll\" value=\"foo\" title=\""); } out.write(_("Stop all torrents and the I2P tunnel")); out.write("\" src=\"" + _imgPath + "stop_all.png\" alt=\""); out.write(_("Stop All")); out.write("\">"); if (isDegraded) out.write("</a>"); for (Snark s : snarks) { if (s.isStopped()) { // show startall too out.write("<br>"); if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=StartAll&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_StartAll\" value=\"foo\" title=\""); out.write(_("Start all stopped torrents")); out.write("\" src=\"" + _imgPath + "start_all.png\" alt=\""); out.write(_("Start All")); out.write("\">"); if (isDegraded) out.write("</a>"); break; } } } else if ((!_manager.util().isConnecting()) && !snarks.isEmpty()) { if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=StartAll&amp;nonce=" + _nonce + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_StartAll\" value=\"foo\" title=\""); out.write(_("Start all torrents and the I2P tunnel")); out.write("\" src=\"" + _imgPath + "start_all.png\" alt=\""); out.write(_("Start All")); out.write("\">"); if (isDegraded) out.write("</a>"); } else { out.write("&nbsp;"); } out.write("</th></tr>\n"); out.write("</thead>\n"); String uri = _contextPath + '/'; boolean showDebug = "2".equals(peerParam); String stParamStr = stParam == null ? "" : "&amp;st=" + stParam; for (int i = 0; i < total; i++) { Snark snark = (Snark)snarks.get(i); boolean showPeers = showDebug || "1".equals(peerParam) || Base64.encode(snark.getInfoHash()).equals(peerParam); boolean hide = i < start || i >= start + pageSize; displaySnark(out, snark, uri, i, stats, showPeers, isDegraded, noThinsp, showDebug, hide, stParamStr); } if (total == 0) { out.write("<tr class=\"snarkTorrentNoneLoaded\">" + "<td class=\"snarkTorrentNoneLoaded\"" + " colspan=\"11\"><i>"); out.write(_("No torrents loaded.")); out.write("</i></td></tr>\n"); } else /** if (snarks.size() > 1) */ { out.write("<tfoot><tr>\n" + " <th align=\"left\" colspan=\"6\">"); out.write("&nbsp;"); out.write(_("Totals")); out.write(":&nbsp;"); out.write(ngettext("1 torrent", "{0} torrents", total)); out.write(", "); out.write(DataHelper.formatSize2(stats[5]) + "B"); if (_manager.util().connected() && total > 0) { out.write(", "); out.write(ngettext("1 connected peer", "{0} connected peers", (int) stats[4])); } DHT dht = _manager.util().getDHT(); if (dht != null) { int dhts = dht.size(); if (dhts > 0) { out.write(", "); out.write(ngettext("1 DHT peer", "{0} DHT peers", dhts)); } if (showDebug) out.write(dht.renderStatusHTML()); } out.write("</th>\n"); if (_manager.util().connected() && total > 0) { out.write(" <th align=\"right\">" + formatSize(stats[0]) + "</th>\n" + " <th align=\"right\">" + formatSize(stats[1]) + "</th>\n" + " <th align=\"right\">" + formatSize(stats[2]) + "ps</th>\n" + " <th align=\"right\">" + formatSize(stats[3]) + "ps</th>\n" + " <th></th>"); } else { out.write("<th colspan=\"5\"></th>"); } out.write("</tr></tfoot>\n"); } out.write("</table>"); if (isForm) out.write("</form>\n"); return start == 0; } /** * @since 0.9.6 */ private void writePageNav(PrintWriter out, int start, int pageSize, int total, String peerParam, boolean noThinsp) { // Page nav if (start > 0) { // First out.write("<a href=\"" + _contextPath); if (peerParam != null) out.write("?p=" + peerParam); out.write("\">" + "<img alt=\"" + _("First") + "\" title=\"" + _("First page") + "\" border=\"0\" src=\"" + _imgPath + "control_rewind_blue.png\">" + "</a>&nbsp;"); int prev = Math.max(0, start - pageSize); //if (prev > 0) { if (true) { // Back out.write("&nbsp;<a href=\"" + _contextPath + "?st=" + prev); if (peerParam != null) out.write("&amp;p=" + peerParam); out.write("\">" + "<img alt=\"" + _("Prev") + "\" title=\"" + _("Previous page") + "\" border=\"0\" src=\"" + _imgPath + "control_back_blue.png\">" + "</a>&nbsp;"); } } else { out.write( "<img alt=\"\" border=\"0\" class=\"disable\" src=\"" + _imgPath + "control_rewind_blue.png\">" + "&nbsp;" + "<img alt=\"\" border=\"0\" class=\"disable\" src=\"" + _imgPath + "control_back_blue.png\">" + "&nbsp;"); } // Page count int pages = 1 + ((total - 1) / pageSize); if (pages == 1 && start > 0) pages = 2; if (pages > 1) { int page; if (start + pageSize >= total) page = pages; else page = 1 + (start / pageSize); //out.write("&nbsp;" + _("Page {0}", page) + thinsp(noThinsp) + pages + "&nbsp;"); out.write("&nbsp;&nbsp;" + page + thinsp(noThinsp) + pages + "&nbsp;&nbsp;"); } if (start + pageSize < total) { int next = start + pageSize; //if (next + pageSize < total) { if (true) { // Next out.write("&nbsp;<a href=\"" + _contextPath + "?st=" + next); if (peerParam != null) out.write("&amp;p=" + peerParam); out.write("\">" + "<img alt=\"" + _("Next") + "\" title=\"" + _("Next page") + "\" border=\"0\" src=\"" + _imgPath + "control_play_blue.png\">" + "</a>&nbsp;"); } // Last int last = ((total - 1) / pageSize) * pageSize; out.write("&nbsp;<a href=\"" + _contextPath + "?st=" + last); if (peerParam != null) out.write("&amp;p=" + peerParam); out.write("\">" + "<img alt=\"" + _("Last") + "\" title=\"" + _("Last page") + "\" border=\"0\" src=\"" + _imgPath + "control_fastforward_blue.png\">" + "</a>&nbsp;"); } else { out.write("&nbsp;" + "<img alt=\"\" border=\"0\" class=\"disable\" src=\"" + _imgPath + "control_play_blue.png\">" + "&nbsp;" + "<img alt=\"\" border=\"0\" class=\"disable\" src=\"" + _imgPath + "control_fastforward_blue.png\">"); } } /** * Do what they ask, adding messages to _manager.addMessage as necessary */ private void processRequest(HttpServletRequest req) { String action = req.getParameter("action"); if (action == null) { // http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name Map params = req.getParameterMap(); for (Object o : params.keySet()) { String key = (String) o; if (key.startsWith("action_") && key.endsWith(".x")) { action = key.substring(0, key.length() - 2).substring(7); break; } } if (action == null) { _manager.addMessage("No action specified"); return; } } // sadly, Opera doesn't send value with input type=image, so we have to use GET there //if (!"POST".equals(req.getMethod())) { // _manager.addMessage("Action must be with POST"); // return; //} if ("Add".equals(action)) { String newURL = req.getParameter("newURL"); /****** // NOTE - newFile currently disabled in HTML form - see below File f = null; if ( (newFile != null) && (newFile.trim().length() > 0) ) f = new File(newFile.trim()); if ( (f != null) && (!f.exists()) ) { _manager.addMessage(_("Torrent file {0} does not exist", newFile)); } if ( (f != null) && (f.exists()) ) { // NOTE - All this is disabled - load from local file disabled File local = new File(_manager.getDataDir(), f.getName()); String canonical = null; try { canonical = local.getCanonicalPath(); if (local.exists()) { if (_manager.getTorrent(canonical) != null) _manager.addMessage(_("Torrent already running: {0}", newFile)); else _manager.addMessage(_("Torrent already in the queue: {0}", newFile)); } else { boolean ok = FileUtil.copy(f.getAbsolutePath(), local.getAbsolutePath(), true); if (ok) { _manager.addMessage(_("Copying torrent to {0}", local.getAbsolutePath())); _manager.addTorrent(canonical); } else { _manager.addMessage(_("Unable to copy the torrent to {0}", local.getAbsolutePath()) + ' ' + _("from {0}", f.getAbsolutePath())); } } } catch (IOException ioe) { _log.warn("hrm: " + local, ioe); } } else *****/ if (newURL != null) { if (newURL.startsWith("http://")) { FetchAndAdd fetch = new FetchAndAdd(_context, _manager, newURL); _manager.addDownloader(fetch); } else if (newURL.startsWith(MagnetURI.MAGNET) || newURL.startsWith(MagnetURI.MAGGOT)) { addMagnet(newURL); } else if (newURL.length() == 40 && newURL.replaceAll("[a-fA-F0-9]", "").length() == 0) { addMagnet(MagnetURI.MAGNET_FULL + newURL); } else { _manager.addMessage(_("Invalid URL: Must start with \"http://\", \"{0}\", or \"{1}\"", MagnetURI.MAGNET, MagnetURI.MAGGOT)); } } else { // no file or URL specified } } else if (action.startsWith("Stop_")) { String torrent = action.substring(5); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { _manager.stopTorrent(snark, false); break; } } } } } else if (action.startsWith("Start_")) { String torrent = action.substring(6); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 _manager.startTorrent(infoHash); } } } else if (action.startsWith("Remove_")) { String torrent = action.substring(7); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { MetaInfo meta = snark.getMetaInfo(); if (meta == null) { // magnet - remove and delete are the same thing // Remove not shown on UI so we shouldn't get here _manager.deleteMagnet(snark); _manager.addMessage(_("Magnet deleted: {0}", name)); return; } _manager.stopTorrent(snark, true); // should we delete the torrent file? // yeah, need to, otherwise it'll get autoadded again (at the moment File f = new File(name); f.delete(); _manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath())); break; } } } } } else if (action.startsWith("Delete_")) { String torrent = action.substring(7); if (torrent != null) { byte infoHash[] = Base64.decode(torrent); if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1 for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) { String name = (String)iter.next(); Snark snark = _manager.getTorrent(name); if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) { MetaInfo meta = snark.getMetaInfo(); if (meta == null) { // magnet - remove and delete are the same thing _manager.deleteMagnet(snark); if (snark instanceof FetchAndAdd) _manager.addMessage(_("Download deleted: {0}", name)); else _manager.addMessage(_("Magnet deleted: {0}", name)); return; } _manager.stopTorrent(snark, true); File f = new File(name); f.delete(); _manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath())); List<List<String>> files = meta.getFiles(); String dataFile = snark.getBaseName(); f = new File(_manager.getDataDir(), dataFile); if (files == null) { // single file torrent if (f.delete()) _manager.addMessage(_("Data file deleted: {0}", f.getAbsolutePath())); else _manager.addMessage(_("Data file could not be deleted: {0}", f.getAbsolutePath())); break; } // step 1 delete files for (int i = 0; i < files.size(); i++) { // multifile torrents have the getFiles() return lists of lists of filenames, but // each of those lists just contain a single file afaict... File df = Storage.getFileFromNames(f, files.get(i)); if (df.delete()) { //_manager.addMessage(_("Data file deleted: {0}", df.getAbsolutePath())); } else { _manager.addMessage(_("Data file could not be deleted: {0}", df.getAbsolutePath())); } } // step 2 make Set of dirs with reverse sort Set<File> dirs = new TreeSet(Collections.reverseOrder()); for (List<String> list : files) { for (int i = 1; i < list.size(); i++) { dirs.add(Storage.getFileFromNames(f, list.subList(0, i))); } } // step 3 delete dirs bottom-up for (File df : dirs) { if (df.delete()) { //_manager.addMessage(_("Data dir deleted: {0}", df.getAbsolutePath())); } else { _manager.addMessage(_("Directory could not be deleted: {0}", df.getAbsolutePath())); if (_log.shouldLog(Log.WARN)) _log.warn("Could not delete dir " + df); } } // step 4 delete base if (f.delete()) { _manager.addMessage(_("Directory deleted: {0}", f.getAbsolutePath())); } else { _manager.addMessage(_("Directory could not be deleted: {0}", f.getAbsolutePath())); if (_log.shouldLog(Log.WARN)) _log.warn("Could not delete dir " + f); } break; } } } } } else if ("Save".equals(action)) { String dataDir = req.getParameter("dataDir"); boolean filesPublic = req.getParameter("filesPublic") != null; boolean autoStart = req.getParameter("autoStart") != null; String seedPct = req.getParameter("seedPct"); String eepHost = req.getParameter("eepHost"); String eepPort = req.getParameter("eepPort"); String i2cpHost = req.getParameter("i2cpHost"); String i2cpPort = req.getParameter("i2cpPort"); String i2cpOpts = buildI2CPOpts(req); String upLimit = req.getParameter("upLimit"); String upBW = req.getParameter("upBW"); String refreshDel = req.getParameter("refreshDelay"); String startupDel = req.getParameter("startupDelay"); String pageSize = req.getParameter("pageSize"); boolean useOpenTrackers = req.getParameter("useOpenTrackers") != null; boolean useDHT = req.getParameter("useDHT") != null; //String openTrackers = req.getParameter("openTrackers"); String theme = req.getParameter("theme"); _manager.updateConfig(dataDir, filesPublic, autoStart, refreshDel, startupDel, pageSize, seedPct, eepHost, eepPort, i2cpHost, i2cpPort, i2cpOpts, upLimit, upBW, useOpenTrackers, useDHT, theme); // update servlet try { setResourceBase(_manager.getDataDir()); } catch (ServletException se) {} } else if ("Save2".equals(action)) { String taction = req.getParameter("taction"); if (taction != null) processTrackerForm(taction, req); } else if ("Create".equals(action)) { String baseData = req.getParameter("baseFile"); if (baseData != null && baseData.trim().length() > 0) { File baseFile = new File(_manager.getDataDir(), baseData); String announceURL = req.getParameter("announceURL"); // make the user add a tracker on the config form now //String announceURLOther = req.getParameter("announceURLOther"); //if ( (announceURLOther != null) && (announceURLOther.trim().length() > "http://.i2p/announce".length()) ) // announceURL = announceURLOther; if (baseFile.exists()) { if (announceURL.equals("none")) announceURL = null; _lastAnnounceURL = announceURL; List<String> backupURLs = new ArrayList(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (!(o instanceof String)) continue; String k = (String) o; if (k.startsWith("backup_")) { String url = k.substring(7); if (!url.equals(announceURL)) backupURLs.add(url); } } List<List<String>> announceList = null; if (!backupURLs.isEmpty()) { // BEP 12 - Put primary first, then the others, each as the sole entry in their own list if (announceURL == null) { _manager.addMessage(_("Error - Cannot include alternate trackers without a primary tracker")); return; } backupURLs.add(0, announceURL); boolean hasPrivate = false; boolean hasPublic = false; for (String url : backupURLs) { - if (_manager.getPrivateTrackers().contains(announceURL)) + if (_manager.getPrivateTrackers().contains(url)) hasPrivate = true; else hasPublic = true; } if (hasPrivate && hasPublic) { _manager.addMessage(_("Error - Cannot mix private and public trackers in a torrent")); return; } announceList = new ArrayList(backupURLs.size()); for (String url : backupURLs) { announceList.add(Collections.singletonList(url)); } } try { // This may take a long time to check the storage, but since it already exists, // it shouldn't be THAT bad, so keep it in this thread. // TODO thread it for big torrents, perhaps a la FetchAndAdd boolean isPrivate = _manager.getPrivateTrackers().contains(announceURL); Storage s = new Storage(_manager.util(), baseFile, announceURL, announceList, isPrivate, null); s.close(); // close the files... maybe need a way to pass this Storage to addTorrent rather than starting over MetaInfo info = s.getMetaInfo(); File torrentFile = new File(_manager.getDataDir(), s.getBaseName() + ".torrent"); // FIXME is the storage going to stay around thanks to the info reference? // now add it, but don't automatically start it _manager.addTorrent(info, s.getBitField(), torrentFile.getAbsolutePath(), true); _manager.addMessage(_("Torrent created for \"{0}\"", baseFile.getName()) + ": " + torrentFile.getAbsolutePath()); if (announceURL != null && !_manager.util().getOpenTrackers().contains(announceURL)) _manager.addMessage(_("Many I2P trackers require you to register new torrents before seeding - please do so before starting \"{0}\"", baseFile.getName())); } catch (IOException ioe) { _manager.addMessage(_("Error creating a torrent for \"{0}\"", baseFile.getAbsolutePath()) + ": " + ioe); _log.error("Error creating a torrent", ioe); } } else { _manager.addMessage(_("Cannot create a torrent for the nonexistent data: {0}", baseFile.getAbsolutePath())); } } else { _manager.addMessage(_("Error creating torrent - you must enter a file or directory")); } } else if ("StopAll".equals(action)) { _manager.stopAllTorrents(false); } else if ("StartAll".equals(action)) { _manager.startAllTorrents(); } else if ("Clear".equals(action)) { _manager.clearMessages(); } else { _manager.addMessage("Unknown POST action: \"" + action + '\"'); } } /** * Redirect a POST to a GET (P-R-G), preserving the peer string * @since 0.9.5 */ private void sendRedirect(HttpServletRequest req, HttpServletResponse resp, String p) throws IOException { String url = req.getRequestURL().toString(); StringBuilder buf = new StringBuilder(128); if (url.endsWith("_post")) url = url.substring(0, url.length() - 5); buf.append(url); if (p.length() > 0) buf.append(p.replace("&amp;", "&")); // no you don't html escape the redirect header resp.setHeader("Location", buf.toString()); resp.sendError(302, "Moved"); } /** @since 0.9 */ private void processTrackerForm(String action, HttpServletRequest req) { if (action.equals(_("Delete selected")) || action.equals(_("Save tracker configuration"))) { boolean changed = false; Map<String, Tracker> trackers = _manager.getTrackerMap(); List<String> removed = new ArrayList(); List<String> open = new ArrayList(); List<String> priv = new ArrayList(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { Object o = e.nextElement(); if (!(o instanceof String)) continue; String k = (String) o; if (k.startsWith("delete_")) { k = k.substring(7); Tracker t; if ((t = trackers.remove(k)) != null) { removed.add(t.announceURL); _manager.addMessage(_("Removed") + ": " + k); changed = true; } } else if (k.startsWith("open_")) { open.add(k.substring(5)); } else if (k.startsWith("private_")) { priv.add(k.substring(8)); } } if (changed) { _manager.saveTrackerMap(); } open.removeAll(removed); List<String> oldOpen = new ArrayList(_manager.util().getOpenTrackers()); Collections.sort(oldOpen); Collections.sort(open); if (!open.equals(oldOpen)) _manager.saveOpenTrackers(open); priv.removeAll(removed); // open trumps private priv.removeAll(open); List<String> oldPriv = new ArrayList(_manager.getPrivateTrackers()); Collections.sort(oldPriv); Collections.sort(priv); if (!priv.equals(oldPriv)) _manager.savePrivateTrackers(priv); } else if (action.equals(_("Add tracker"))) { String name = req.getParameter("tname"); String hurl = req.getParameter("thurl"); String aurl = req.getParameter("taurl"); if (name != null && hurl != null && aurl != null) { name = name.trim(); hurl = hurl.trim(); aurl = aurl.trim().replace("=", "&#61;"); if (name.length() > 0 && hurl.startsWith("http://") && TrackerClient.isValidAnnounce(aurl)) { Map<String, Tracker> trackers = _manager.getTrackerMap(); trackers.put(name, new Tracker(name, aurl, hurl)); _manager.saveTrackerMap(); // open trumps private if (req.getParameter("_add_open_") != null) { List newOpen = new ArrayList(_manager.util().getOpenTrackers()); newOpen.add(aurl); _manager.saveOpenTrackers(newOpen); } else if (req.getParameter("_add_private_") != null) { List newPriv = new ArrayList(_manager.getPrivateTrackers()); newPriv.add(aurl); _manager.savePrivateTrackers(newPriv); } } else { _manager.addMessage(_("Enter valid tracker name and URLs")); } } else { _manager.addMessage(_("Enter valid tracker name and URLs")); } } else if (action.equals(_("Restore defaults"))) { _manager.setDefaultTrackerMap(); _manager.saveOpenTrackers(null); _manager.addMessage(_("Restored default trackers")); } else { _manager.addMessage("Unknown POST action: \"" + action + '\"'); } } private static final String iopts[] = {"inbound.length", "inbound.quantity", "outbound.length", "outbound.quantity" }; /** put the individual i2cp selections into the option string */ private static String buildI2CPOpts(HttpServletRequest req) { StringBuilder buf = new StringBuilder(128); String p = req.getParameter("i2cpOpts"); if (p != null) buf.append(p); for (int i = 0; i < iopts.length; i++) { p = req.getParameter(iopts[i]); if (p != null) buf.append(' ').append(iopts[i]).append('=').append(p); } return buf.toString(); } /** * Sort alphabetically in current locale, ignore case, ignore leading "the " * (I guess this is worth it, a lot of torrents start with "The " * @since 0.7.14 */ private static class TorrentNameComparator implements Comparator<Snark> { private final Comparator collator = Collator.getInstance(); public int compare(Snark l, Snark r) { // put downloads and magnets first if (l.getStorage() == null && r.getStorage() != null) return -1; if (l.getStorage() != null && r.getStorage() == null) return 1; String ls = l.getBaseName(); String llc = ls.toLowerCase(Locale.US); if (llc.startsWith("the ") || llc.startsWith("the.") || llc.startsWith("the_")) ls = ls.substring(4); String rs = r.getBaseName(); String rlc = rs.toLowerCase(Locale.US); if (rlc.startsWith("the ") || rlc.startsWith("the.") || rlc.startsWith("the_")) rs = rs.substring(4); return collator.compare(ls, rs); } } private List<Snark> getSortedSnarks(HttpServletRequest req) { ArrayList<Snark> rv = new ArrayList(_manager.getTorrents()); Collections.sort(rv, new TorrentNameComparator()); return rv; } private static final int MAX_DISPLAYED_FILENAME_LENGTH = 50; private static final int MAX_DISPLAYED_ERROR_LENGTH = 43; /** * Display one snark (one line in table, unless showPeers is true) * * @param stats in/out param (totals) * @param statsOnly if true, output nothing, update stats only * @param stParam non null; empty or e.g. &amp;st=10 */ private void displaySnark(PrintWriter out, Snark snark, String uri, int row, long stats[], boolean showPeers, boolean isDegraded, boolean noThinsp, boolean showDebug, boolean statsOnly, String stParam) throws IOException { // stats long uploaded = snark.getUploaded(); stats[0] += snark.getDownloaded(); stats[1] += uploaded; long downBps = snark.getDownloadRate(); long upBps = snark.getUploadRate(); boolean isRunning = !snark.isStopped(); if (isRunning) { stats[2] += downBps; stats[3] += upBps; } int curPeers = snark.getPeerCount(); stats[4] += curPeers; long total = snark.getTotalLength(); if (total > 0) stats[5] += total; if (statsOnly) return; String basename = snark.getBaseName(); String fullBasename = basename; if (basename.length() > MAX_DISPLAYED_FILENAME_LENGTH) { String start = basename.substring(0, MAX_DISPLAYED_FILENAME_LENGTH); if (start.indexOf(" ") < 0 && start.indexOf("-") < 0) { // browser has nowhere to break it basename = start + "&hellip;"; } } // includes skipped files, -1 for magnet mode long remaining = snark.getRemainingLength(); if (remaining > total) remaining = total; // does not include skipped files, -1 for magnet mode or when not running. long needed = snark.getNeededLength(); if (needed > total) needed = total; long remainingSeconds; if (downBps > 0 && needed > 0) remainingSeconds = needed / downBps; else remainingSeconds = -1; MetaInfo meta = snark.getMetaInfo(); // isValid means isNotMagnet boolean isValid = meta != null; boolean isMultiFile = isValid && meta.getFiles() != null; String err = snark.getTrackerProblems(); int knownPeers = Math.max(curPeers, snark.getTrackerSeenPeers()); String rowClass = (row % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd"); String statusString; if (snark.isChecking()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Checking") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Checking"); } else if (snark.isAllocating()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Allocating") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Allocating"); } else if (err != null && curPeers == 0) { // Also don't show if seeding... but then we won't see the not-registered error // && remaining != 0 && needed != 0) { // let's only show this if we have no peers, otherwise PEX and DHT should bail us out, user doesn't care //if (isRunning && curPeers > 0 && !showPeers) // statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + // "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") + // ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" + // curPeers + thinsp(noThinsp) + // ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; //else if (isRunning) if (isRunning) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Tracker Error") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else { if (err.length() > MAX_DISPLAYED_ERROR_LENGTH) err = err.substring(0, MAX_DISPLAYED_ERROR_LENGTH) + "&hellip;"; statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Tracker Error"); } } else if (snark.isStarting()) { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Starting") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Starting"); } else if (remaining == 0 || needed == 0) { // < 0 means no meta size yet // partial complete or seeding if (isRunning) { String img; String txt; if (remaining == 0) { img = "seeding"; txt = _("Seeding"); } else { // partial img = "complete"; txt = _("Complete"); } if (curPeers > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + txt + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + txt + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); } else { statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "complete.png\" title=\"" + _("Complete") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Complete"); } } else { if (isRunning && curPeers > 0 && downBps > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("OK") + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else if (isRunning && curPeers > 0 && downBps > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("OK") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else if (isRunning && curPeers > 0 && !showPeers) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Stalled") + ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers) + "</a>"; else if (isRunning && curPeers > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Stalled") + ": " + curPeers + thinsp(noThinsp) + ngettext("1 peer", "{0} peers", knownPeers); else if (isRunning && knownPeers > 0) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("No Peers") + ": 0" + thinsp(noThinsp) + knownPeers ; else if (isRunning) statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("No Peers"); else statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stopped.png\" title=\"" + _("Stopped") + "\"></td>" + "<td class=\"snarkTorrentStatus\">" + _("Stopped"); } out.write("<tr class=\"" + rowClass + "\">"); out.write("<td class=\"center\">"); out.write(statusString + "</td>\n\t"); // (i) icon column out.write("<td>"); if (isValid && meta.getAnnounce() != null) { // Link to local details page - note that trailing slash on a single-file torrent // gets us to the details page instead of the file. //StringBuilder buf = new StringBuilder(128); //buf.append("<a href=\"").append(snark.getBaseName()) // .append("/\" title=\"").append(_("Torrent details")) // .append("\"><img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"") // .append(_imgPath).append("details.png\"></a>"); //out.write(buf.toString()); // Link to tracker details page String trackerLink = getTrackerLink(meta.getAnnounce(), snark.getInfoHash()); if (trackerLink != null) out.write(trackerLink); } String encodedBaseName = urlEncode(fullBasename); // File type icon column out.write("</td>\n<td>"); if (isValid) { // Link to local details page - note that trailing slash on a single-file torrent // gets us to the details page instead of the file. StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(encodedBaseName) .append("/\" title=\"").append(_("Torrent details")) .append("\">"); out.write(buf.toString()); } String icon; if (isMultiFile) icon = "folder"; else if (isValid) icon = toIcon(meta.getName()); else if (snark instanceof FetchAndAdd) icon = "basket_put"; else icon = "magnet"; if (isValid) { out.write(toImg(icon)); out.write("</a>"); } else { out.write(toImg(icon)); } // Torrent name column out.write("</td><td class=\"snarkTorrentName\">"); if (remaining == 0 || isMultiFile) { StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(encodedBaseName); if (isMultiFile) buf.append('/'); buf.append("\" title=\""); if (isMultiFile) buf.append(_("View files")); else buf.append(_("Open file")); buf.append("\">"); out.write(buf.toString()); } out.write(basename); if (remaining == 0 || isMultiFile) out.write("</a>"); out.write("<td align=\"right\" class=\"snarkTorrentETA\">"); if(isRunning && remainingSeconds > 0 && !snark.isChecking()) out.write(DataHelper.formatDuration2(Math.max(remainingSeconds, 10) * 1000)); // (eta 6h) out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentDownloaded\">"); if (remaining > 0) out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total)); else if (remaining == 0) out.write(formatSize(total)); // 3GB //else // out.write("??"); // no meta size yet out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentUploaded\">"); if(isRunning && isValid) out.write(formatSize(uploaded)); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentRateDown\">"); if(isRunning && needed > 0) out.write(formatSize(downBps) + "ps"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentRateUp\">"); if(isRunning && isValid) out.write(formatSize(upBps) + "ps"); out.write("</td>\n\t"); out.write("<td align=\"center\" class=\"snarkTorrentAction\">"); String b64 = Base64.encode(snark.getInfoHash()); if (snark.isChecking()) { // show no buttons } else if (isRunning) { // Stop Button if (isDegraded) out.write("<a href=\"" + _contextPath + "/?action=Stop_" + b64 + "&amp;nonce=" + _nonce + stParam + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Stop_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Stop the torrent")); out.write("\" src=\"" + _imgPath + "stop.png\" alt=\""); out.write(_("Stop")); out.write("\">"); if (isDegraded) out.write("</a>"); } else if (!snark.isStarting()) { if (!_manager.isStopping()) { // Start Button // This works in Opera but it's displayed a little differently, so use noThinsp here too so all 3 icons are consistent if (noThinsp) out.write("<a href=\"" + _contextPath + "/?action=Start_" + b64 + "&amp;nonce=" + _nonce + stParam + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Start_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Start the torrent")); out.write("\" src=\"" + _imgPath + "start.png\" alt=\""); out.write(_("Start")); out.write("\">"); if (isDegraded) out.write("</a>"); } if (isValid) { // Remove Button // Doesnt work with Opera so use noThinsp instead of isDegraded if (noThinsp) out.write("<a href=\"" + _contextPath + "/?action=Remove_" + b64 + "&amp;nonce=" + _nonce + stParam + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Remove_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Remove the torrent from the active list, deleting the .torrent file")); out.write("\" onclick=\"if (!confirm('"); // Can't figure out how to escape double quotes inside the onclick string. // Single quotes in translate strings with parameters must be doubled. // Then the remaining single quote must be escaped out.write(_("Are you sure you want to delete the file \\''{0}\\'' (downloaded data will not be deleted) ?", snark.getName())); out.write("')) { return false; }\""); out.write(" src=\"" + _imgPath + "remove.png\" alt=\""); out.write(_("Remove")); out.write("\">"); if (isDegraded) out.write("</a>"); } // Delete Button // Doesnt work with Opera so use noThinsp instead of isDegraded if (noThinsp) out.write("<a href=\"" + _contextPath + "/?action=Delete_" + b64 + "&amp;nonce=" + _nonce + stParam + "\"><img title=\""); else out.write("<input type=\"image\" name=\"action_Delete_" + b64 + "\" value=\"foo\" title=\""); out.write(_("Delete the .torrent file and the associated data file(s)")); out.write("\" onclick=\"if (!confirm('"); // Can't figure out how to escape double quotes inside the onclick string. // Single quotes in translate strings with parameters must be doubled. // Then the remaining single quote must be escaped out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", fullBasename)); out.write("')) { return false; }\""); out.write(" src=\"" + _imgPath + "delete.png\" alt=\""); out.write(_("Delete")); out.write("\">"); if (isDegraded) out.write("</a>"); } out.write("</td>\n</tr>\n"); if(showPeers && isRunning && curPeers > 0) { List<Peer> peers = snark.getPeerList(); if (!showDebug) Collections.sort(peers, new PeerComparator()); for (Peer peer : peers) { if (!peer.isConnected()) continue; out.write("<tr class=\"" + rowClass + "\"><td></td>"); out.write("<td colspan=\"4\" align=\"right\">"); String ch = peer.toString().substring(0, 4); String client; if ("AwMD".equals(ch)) client = _("I2PSnark"); else if ("BFJT".equals(ch)) client = "I2PRufus"; else if ("TTMt".equals(ch)) client = "I2P-BT"; else if ("LUFa".equals(ch)) client = "Azureus"; else if ("CwsL".equals(ch)) client = "I2PSnarkXL"; else if ("ZV".equals(ch.substring(2,4)) || "VUZP".equals(ch)) client = "Robert"; else if (ch.startsWith("LV")) // LVCS 1.0.2?; LVRS 1.0.4 client = "Transmission"; else if ("LUtU".equals(ch)) client = "KTorrent"; else client = _("Unknown") + " (" + ch + ')'; out.write(client + "&nbsp;&nbsp;<tt>" + peer.toString().substring(5, 9)+ "</tt>"); if (showDebug) out.write(" inactive " + (peer.getInactiveTime() / 1000) + "s"); out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus\">"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus\">"); float pct; if (isValid) { pct = (float) (100.0 * peer.completed() / meta.getPieces()); if (pct >= 100.0) out.write(_("Seed")); else { String ps = String.valueOf(pct); if (ps.length() > 5) ps = ps.substring(0, 5); out.write(ps + "%"); } } else { pct = (float) 101.0; // until we get the metainfo we don't know how many pieces there are //out.write("??"); } out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus\">"); out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus\">"); if (needed > 0) { if (peer.isInteresting() && !peer.isChoked()) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</span>"); } else { out.write("<span class=\"choked\"><a title=\""); if (!peer.isInteresting()) out.write(_("Uninteresting (The peer has no pieces we need)")); else out.write(_("Choked (The peer is not allowing us to request pieces)")); out.write("\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</a></span>"); } } else if (!isValid) { //if (peer supports metadata extension) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getDownloadRate()) + "ps</span>"); //} else { //} } out.write("</td>\n\t"); out.write("<td align=\"right\" class=\"snarkTorrentStatus\">"); if (isValid && pct < 100.0) { if (peer.isInterested() && !peer.isChoking()) { out.write("<span class=\"unchoked\">"); out.write(formatSize(peer.getUploadRate()) + "ps</span>"); } else { out.write("<span class=\"choked\"><a title=\""); if (!peer.isInterested()) out.write(_("Uninterested (We have no pieces the peer needs)")); else out.write(_("Choking (We are not allowing the peer to request pieces)")); out.write("\">"); out.write(formatSize(peer.getUploadRate()) + "ps</a></span>"); } } out.write("</td>\n\t"); out.write("<td class=\"snarkTorrentStatus\">"); out.write("</td></tr>\n\t"); if (showDebug) out.write("<tr class=\"" + rowClass + "\"><td></td><td colspan=\"10\" align=\"right\">" + peer.getSocket() + "</td></tr>"); } } } /** @since 0.8.2 */ private static String thinsp(boolean disable) { if (disable) return " / "; return ("&thinsp;/&thinsp;"); } /** * Sort by completeness (seeds first), then by ID * @since 0.8.1 */ private static class PeerComparator implements Comparator<Peer> { public int compare(Peer l, Peer r) { int diff = r.completed() - l.completed(); // reverse if (diff != 0) return diff; return l.toString().substring(5, 9).compareTo(r.toString().substring(5, 9)); } } /** * Start of anchor only, caller must add anchor text or img and close anchor * @return string or null * @since 0.8.4 */ private String getTrackerLinkUrl(String announce, byte[] infohash) { // temporarily hardcoded for postman* and anonymity, requires bytemonsoon patch for lookup by info_hash if (announce != null && (announce.startsWith("http://YRgrgTLG") || announce.startsWith("http://8EoJZIKr") || announce.startsWith("http://lnQ6yoBT") || announce.startsWith("http://tracker2.postman.i2p/") || announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/"))) { for (Tracker t : _manager.getTrackers()) { String aURL = t.announceURL; if (!(aURL.startsWith(announce) || // vvv hack for non-b64 announce in list vvv (announce.startsWith("http://lnQ6yoBT") && aURL.startsWith("http://tracker2.postman.i2p/")) || (announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/") && aURL.startsWith("http://tracker2.postman.i2p/")))) continue; String baseURL = t.baseURL; String name = t.name; StringBuilder buf = new StringBuilder(128); buf.append("<a href=\"").append(baseURL).append("details.php?dllist=1&amp;filelist=1&amp;info_hash=") .append(TrackerClient.urlencode(infohash)) .append("\" title=\"").append(_("Details at {0} tracker", name)).append("\" target=\"_blank\">"); return buf.toString(); } } return null; } /** * Full anchor with img * @return string or null * @since 0.8.4 */ private String getTrackerLink(String announce, byte[] infohash) { String linkUrl = getTrackerLinkUrl(announce, infohash); if (linkUrl != null) { StringBuilder buf = new StringBuilder(128); buf.append(linkUrl) .append("<img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"></a>"); return buf.toString(); } return null; } /** * Full anchor with shortened URL as anchor text * @return string, non-null * @since 0.9.5 */ private String getShortTrackerLink(String announce, byte[] infohash) { StringBuilder buf = new StringBuilder(128); String trackerLinkUrl = getTrackerLinkUrl(announce, infohash); if (trackerLinkUrl != null) buf.append(trackerLinkUrl); if (announce.startsWith("http://")) announce = announce.substring(7); int slsh = announce.indexOf('/'); if (slsh > 0) announce = announce.substring(0, slsh); if (announce.length() > 67) announce = announce.substring(0, 40) + "&hellip;" + announce.substring(announce.length() - 8); buf.append(announce); if (trackerLinkUrl != null) buf.append("</a>"); return buf.toString(); } private void writeAddForm(PrintWriter out, HttpServletRequest req) throws IOException { // display incoming parameter if a GET so links will work String newURL = req.getParameter("newURL"); if (newURL == null || newURL.trim().length() <= 0 || req.getMethod().equals("POST")) newURL = ""; else newURL = DataHelper.stripHTML(newURL); // XSS //String newFile = req.getParameter("newFile"); //if ( (newFile == null) || (newFile.trim().length() <= 0) ) newFile = ""; out.write("<div class=\"snarkNewTorrent\">\n"); // *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); out.write("<input type=\"hidden\" name=\"action\" value=\"Add\" >\n"); // don't lose peer setting String peerParam = req.getParameter("p"); if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); out.write("<div class=\"addtorrentsection\"><span class=\"snarkConfigTitle\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "add.png\"> "); out.write(_("Add Torrent")); out.write("</span><hr>\n<table border=\"0\"><tr><td>"); out.write(_("From URL")); out.write(":<td><input type=\"text\" name=\"newURL\" size=\"85\" value=\"" + newURL + "\" spellcheck=\"false\""); out.write(" title=\""); out.write(_("Enter the torrent file download URL (I2P only), magnet link, maggot link, or info hash")); out.write("\"> \n"); // not supporting from file at the moment, since the file name passed isn't always absolute (so it may not resolve) //out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>"); out.write("<input type=\"submit\" class=\"add\" value=\""); out.write(_("Add torrent")); out.write("\" name=\"foo\" ><br>\n"); out.write("<tr><td>&nbsp;<td><span class=\"snarkAddInfo\">"); out.write(_("You can also copy .torrent files to: {0}.", "<code>" + _manager.getDataDir().getAbsolutePath () + "</code>")); out.write("\n"); out.write(_("Removing a .torrent will cause it to stop.")); out.write("<br></span></table>\n"); out.write("</div></form></div>"); } private void writeSeedForm(PrintWriter out, HttpServletRequest req, List<Tracker> sortedTrackers) throws IOException { String baseFile = req.getParameter("baseFile"); if (baseFile == null || baseFile.trim().length() <= 0) baseFile = ""; else baseFile = DataHelper.stripHTML(baseFile); // XSS out.write("<a name=\"add\"></a><div class=\"newtorrentsection\"><div class=\"snarkNewTorrent\">\n"); // *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file out.write("<form action=\"_post\" method=\"POST\">\n"); out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n"); out.write("<input type=\"hidden\" name=\"action\" value=\"Create\" >\n"); // don't lose peer setting String peerParam = req.getParameter("p"); if (peerParam != null) out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n"); out.write("<span class=\"snarkConfigTitle\">"); out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "create.png\"> "); out.write(_("Create Torrent")); out.write("</span><hr>\n<table border=\"0\"><tr><td>"); //out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>\n"); out.write(_("Data to seed")); out.write(":<td><code>" + _manager.getDataDir().getAbsolutePath() + File.separatorChar + "</code><input type=\"text\" name=\"baseFile\" size=\"58\" value=\"" + baseFile + "\" spellcheck=\"false\" title=\""); out.write(_("File or directory to seed (must be within the specified path)")); out.write("\" ><tr><td>\n"); out.write(_("Trackers")); out.write(":<td><table style=\"width: 30%;\"><tr><td></td><td align=\"center\">"); out.write(_("Primary")); out.write("</td><td align=\"center\">"); out.write(_("Alternates")); out.write("</td><td rowspan=\"0\">" + " <input type=\"submit\" class=\"create\" value=\""); out.write(_("Create torrent")); out.write("\" name=\"foo\" >" + "</td></tr>\n"); for (Tracker t : sortedTrackers) { String name = t.name; String announceURL = t.announceURL.replace("&#61;", "="); out.write("<tr><td>"); out.write(name); out.write("</td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\""); out.write(announceURL); out.write("\""); if (announceURL.equals(_lastAnnounceURL)) out.write(" checked"); out.write("></td><td align=\"center\"><input type=\"checkbox\" name=\"backup_"); out.write(announceURL); out.write("\" value=\"foo\"></td></tr>\n"); } out.write("<tr><td><i>"); out.write(_("none")); out.write("</i></td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\"none\""); if (_lastAnnounceURL == null) out.write(" checked"); out.write("></td><td></td></tr></table>\n"); // make the user add a tracker on the config form now //out.write(_("or")); //out.write("&nbsp;<input type=\"text\" name=\"announceURLOther\" size=\"57\" value=\"http://\" " + // "title=\""); //out.write(_("Specify custom tracker announce URL")); //out.write("\" > " + out.write("</td></tr>" + "</table>\n" + "</form></div></div>"); } private static final int[] times = { 5, 15, 30, 60, 2*60, 5*60, 10*60, 30*60, -1 }; private void writeConfigForm(PrintWriter out, HttpServletRequest req) throws IOException { String dataDir = _manager.getDataDir().getAbsolutePath(); boolean filesPublic = _manager.areFilesPublic(); boolean autoStart = _manager.shouldAutoStart(); boolean useOpenTrackers = _manager.util().shouldUseOpenTrackers(); //String openTrackers = _manager.util().getOpenTrackerString(); boolean useDHT = _manager.util().shouldUseDHT(); //int seedPct = 0; out.write("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" + "<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" + "<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" + "<input type=\"hidden\" name=\"action\" value=\"Save\" >\n" + "<span class=\"snarkConfigTitle\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); out.write(_("Configuration")); out.write("</span><hr>\n" + "<table border=\"0\"><tr><td>"); out.write(_("Data directory")); out.write(": <td><input name=\"dataDir\" size=\"80\" value=\"" + dataDir + "\" spellcheck=\"false\"></td>\n" + "<tr><td>"); out.write(_("Files readable by all")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"filesPublic\" value=\"true\" " + (filesPublic ? "checked " : "") + "title=\""); out.write(_("If checked, other users may access the downloaded files")); out.write("\" >" + "<tr><td>"); out.write(_("Auto start")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"autoStart\" value=\"true\" " + (autoStart ? "checked " : "") + "title=\""); out.write(_("If checked, automatically start torrents that are added")); out.write("\" >" + "<tr><td>"); out.write(_("Theme")); out.write(": <td><select name='theme'>"); String theme = _manager.getTheme(); String[] themes = _manager.getThemes(); for(int i = 0; i < themes.length; i++) { if(themes[i].equals(theme)) out.write("\n<OPTION value=\"" + themes[i] + "\" SELECTED>" + themes[i]); else out.write("\n<OPTION value=\"" + themes[i] + "\">" + themes[i]); } out.write("</select>\n" + "<tr><td>"); out.write(_("Refresh time")); out.write(": <td><select name=\"refreshDelay\">"); int delay = _manager.getRefreshDelaySeconds(); for (int i = 0; i < times.length; i++) { out.write("<option value=\""); out.write(Integer.toString(times[i])); out.write("\""); if (times[i] == delay) out.write(" selected=\"selected\""); out.write(">"); if (times[i] > 0) out.write(DataHelper.formatDuration2(times[i] * 1000)); else out.write(_("Never")); out.write("</option>\n"); } out.write("</select><br>" + "<tr><td>"); out.write(_("Startup delay")); out.write(": <td><input name=\"startupDelay\" size=\"4\" class=\"r\" value=\"" + _manager.util().getStartupDelay() + "\"> "); out.write(_("minutes")); out.write("<br>\n" + "<tr><td>"); out.write(_("Page size")); out.write(": <td><input name=\"pageSize\" size=\"4\" maxlength=\"6\" class=\"r\" value=\"" + _manager.getPageSize() + "\"> "); out.write(_("torrents")); out.write("<br>\n"); //Auto add: <input type="checkbox" name="autoAdd" value="true" title="If true, automatically add torrents that are found in the data directory" /> //Auto stop: <input type="checkbox" name="autoStop" value="true" title="If true, automatically stop torrents that are removed from the data directory" /> //out.write("<br>\n"); /* out.write("Seed percentage: <select name=\"seedPct\" disabled=\"true\" >\n\t"); if (seedPct <= 0) out.write("<option value=\"0\" selected=\"selected\">Unlimited</option>\n\t"); else out.write("<option value=\"0\">Unlimited</option>\n\t"); if (seedPct == 100) out.write("<option value=\"100\" selected=\"selected\">100%</option>\n\t"); else out.write("<option value=\"100\">100%</option>\n\t"); if (seedPct == 150) out.write("<option value=\"150\" selected=\"selected\">150%</option>\n\t"); else out.write("<option value=\"150\">150%</option>\n\t"); out.write("</select><br>\n"); */ out.write("<tr><td>"); out.write(_("Total uploader limit")); out.write(": <td><input type=\"text\" name=\"upLimit\" class=\"r\" value=\"" + _manager.util().getMaxUploaders() + "\" size=\"4\" maxlength=\"3\" > "); out.write(_("peers")); out.write("<br>\n" + "<tr><td>"); out.write(_("Up bandwidth limit")); out.write(": <td><input type=\"text\" name=\"upBW\" class=\"r\" value=\"" + _manager.util().getMaxUpBW() + "\" size=\"4\" maxlength=\"4\" > KBps <i>"); out.write(_("Half available bandwidth recommended.")); out.write(" [<a href=\"/config.jsp\" target=\"blank\">"); out.write(_("View or change router bandwidth")); out.write("</a>]</i><br>\n" + "<tr><td>"); out.write(_("Use open trackers also")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useOpenTrackers\" value=\"true\" " + (useOpenTrackers ? "checked " : "") + "title=\""); out.write(_("If checked, announce torrents to open trackers as well as the tracker listed in the torrent file")); out.write("\" ></td></tr>\n" + "<tr><td>"); out.write(_("Enable DHT")); out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useDHT\" value=\"true\" " + (useDHT ? "checked " : "") + "title=\""); out.write(_("If checked, use DHT")); out.write("\" ></td></tr>\n"); // "<tr><td>"); //out.write(_("Open tracker announce URLs")); //out.write(": <td><input type=\"text\" name=\"openTrackers\" value=\"" // + openTrackers + "\" size=\"50\" ><br>\n"); //out.write("\n"); //out.write("EepProxy host: <input type=\"text\" name=\"eepHost\" value=\"" // + _manager.util().getEepProxyHost() + "\" size=\"15\" /> "); //out.write("port: <input type=\"text\" name=\"eepPort\" value=\"" // + _manager.util().getEepProxyPort() + "\" size=\"5\" maxlength=\"5\" /><br>\n"); Map<String, String> options = new TreeMap(_manager.util().getI2CPOptions()); out.write("<tr><td>"); out.write(_("Inbound Settings")); out.write(":<td>"); out.write(renderOptions(1, 6, options.remove("inbound.quantity"), "inbound.quantity", TUNNEL)); out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.write(renderOptions(0, 4, options.remove("inbound.length"), "inbound.length", HOP)); out.write("<tr><td>"); out.write(_("Outbound Settings")); out.write(":<td>"); out.write(renderOptions(1, 6, options.remove("outbound.quantity"), "outbound.quantity", TUNNEL)); out.write("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); out.write(renderOptions(0, 4, options.remove("outbound.length"), "outbound.length", HOP)); if (!_context.isRouterContext()) { out.write("<tr><td>"); out.write(_("I2CP host")); out.write(": <td><input type=\"text\" name=\"i2cpHost\" value=\"" + _manager.util().getI2CPHost() + "\" size=\"15\" > " + "<tr><td>"); out.write(_("I2CP port")); out.write(": <td><input type=\"text\" name=\"i2cpPort\" class=\"r\" value=\"" + + _manager.util().getI2CPPort() + "\" size=\"5\" maxlength=\"5\" > <br>\n"); } options.remove(I2PSnarkUtil.PROP_MAX_BW); // was accidentally in the I2CP options prior to 0.8.9 so it will be in old config files options.remove(SnarkManager.PROP_OPENTRACKERS); StringBuilder opts = new StringBuilder(64); for (Map.Entry<String, String> e : options.entrySet()) { String key = e.getKey(); String val = e.getValue(); opts.append(key).append('=').append(val).append(' '); } out.write("<tr><td>"); out.write(_("I2CP options")); out.write(": <td><textarea name=\"i2cpOpts\" cols=\"60\" rows=\"1\" wrap=\"off\" spellcheck=\"false\" >" + opts.toString() + "</textarea><br>\n" + "<tr><td colspan=\"2\">&nbsp;\n" + // spacer "<tr><td>&nbsp;<td><input type=\"submit\" class=\"accept\" value=\""); out.write(_("Save configuration")); out.write("\" name=\"foo\" >\n" + "<tr><td colspan=\"2\">&nbsp;\n" + // spacer "</table></div></div></form>"); } /** @since 0.9 */ private void writeTrackerForm(PrintWriter out, HttpServletRequest req) throws IOException { StringBuilder buf = new StringBuilder(1024); buf.append("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" + "<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" + "<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" + "<input type=\"hidden\" name=\"action\" value=\"Save2\" >\n" + "<span class=\"snarkConfigTitle\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); buf.append(_("Trackers")); buf.append("</span><hr>\n" + "<table class=\"trackerconfig\"><tr><th>") //.append(_("Remove")) .append("</th><th>") .append(_("Name")) .append("</th><th>") .append(_("Website URL")) .append("</th><th>") .append(_("Open")) .append("</th><th>") .append(_("Private")) .append("</th><th>") .append(_("Announce URL")) .append("</th></tr>\n"); List<String> openTrackers = _manager.util().getOpenTrackers(); List<String> privateTrackers = _manager.getPrivateTrackers(); for (Tracker t : _manager.getSortedTrackers()) { String name = t.name; String homeURL = t.baseURL; String announceURL = t.announceURL.replace("&#61;", "="); buf.append("<tr><td><input type=\"checkbox\" class=\"optbox\" name=\"delete_") .append(name).append("\" title=\"").append(_("Delete")).append("\">" + "</td><td>").append(name) .append("</td><td>").append(urlify(homeURL, 35)) .append("</td><td><input type=\"checkbox\" class=\"optbox\" name=\"open_") .append(announceURL).append("\""); if (openTrackers.contains(t.announceURL)) buf.append(" checked=\"checked\""); buf.append(">" + "</td><td><input type=\"checkbox\" class=\"optbox\" name=\"private_") .append(announceURL).append("\""); if (privateTrackers.contains(t.announceURL)) { buf.append(" checked=\"checked\""); } else { for (int i = 1; i < SnarkManager.DEFAULT_TRACKERS.length; i += 2) { if (SnarkManager.DEFAULT_TRACKERS[i].contains(t.announceURL)) { buf.append(" disabled=\"disabled\""); break; } } } buf.append(">" + "</td><td>").append(urlify(announceURL, 35)) .append("</td></tr>\n"); } buf.append("<tr><td><b>") .append(_("Add")).append(":</b></td>" + "<td><input type=\"text\" class=\"trackername\" name=\"tname\" spellcheck=\"false\"></td>" + "<td><input type=\"text\" class=\"trackerhome\" name=\"thurl\" spellcheck=\"false\"></td>" + "<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_open_\"></td>" + "<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_private_\"></td>" + "<td><input type=\"text\" class=\"trackerannounce\" name=\"taurl\" spellcheck=\"false\"></td></tr>\n" + "<tr><td colspan=\"6\">&nbsp;</td></tr>\n" + // spacer "<tr><td colspan=\"2\"></td><td colspan=\"4\">\n" + "<input type=\"submit\" name=\"taction\" class=\"default\" value=\"").append(_("Add tracker")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"delete\" value=\"").append(_("Delete selected")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"accept\" value=\"").append(_("Save tracker configuration")).append("\">\n" + // "<input type=\"reset\" class=\"cancel\" value=\"").append(_("Cancel")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"reload\" value=\"").append(_("Restore defaults")).append("\">\n" + "<input type=\"submit\" name=\"taction\" class=\"add\" value=\"").append(_("Add tracker")).append("\">\n" + "</td></tr>" + "<tr><td colspan=\"6\">&nbsp;</td></tr>\n" + // spacer "</table></div></div></form>\n"); out.write(buf.toString()); } private void writeConfigLink(PrintWriter out) throws IOException { out.write("<div class=\"configsection\"><span class=\"snarkConfig\">\n" + "<span class=\"snarkConfigTitle\"><a href=\"configure\">" + "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> "); out.write(_("Configuration")); out.write("</a></span></span></div>\n"); } /** * @param url in base32 or hex * @since 0.8.4 */ private void addMagnet(String url) { try { MagnetURI magnet = new MagnetURI(_manager.util(), url); String name = magnet.getName(); byte[] ih = magnet.getInfoHash(); String trackerURL = magnet.getTrackerURL(); _manager.addMagnet(name, ih, trackerURL, true); } catch (IllegalArgumentException iae) { _manager.addMessage(_("Invalid magnet URL {0}", url)); } } /** copied from ConfigTunnelsHelper */ private static final String HOP = "hop"; private static final String TUNNEL = "tunnel"; /** dummies for translation */ private static final String HOPS = ngettext("1 hop", "{0} hops"); private static final String TUNNELS = ngettext("1 tunnel", "{0} tunnels"); /** prevents the ngettext line below from getting tagged */ private static final String DUMMY0 = "{0} "; private static final String DUMMY1 = "1 "; /** modded from ConfigTunnelsHelper @since 0.7.14 */ private String renderOptions(int min, int max, String strNow, String selName, String name) { int now = 2; try { now = Integer.parseInt(strNow); } catch (Throwable t) {} StringBuilder buf = new StringBuilder(128); buf.append("<select name=\"").append(selName).append("\">\n"); for (int i = min; i <= max; i++) { buf.append("<option value=\"").append(i).append("\" "); if (i == now) buf.append("selected=\"selected\" "); // constants to prevent tagging buf.append(">").append(ngettext(DUMMY1 + name, DUMMY0 + name + 's', i)); buf.append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); } /** translate */ private String _(String s) { return _manager.util().getString(s); } /** translate */ private String _(String s, Object o) { return _manager.util().getString(s, o); } /** translate */ private String _(String s, Object o, Object o2) { return _manager.util().getString(s, o, o2); } /** translate (ngettext) @since 0.7.14 */ private String ngettext(String s, String p, int n) { return _manager.util().getString(n, s, p); } /** dummy for tagging */ private static String ngettext(String s, String p) { return null; } // rounding makes us look faster :) private static String formatSize(long bytes) { if (bytes < 5000) return bytes + "&nbsp;B"; else if (bytes < 5*1024*1024) return ((bytes + 512)/1024) + "&nbsp;KB"; else if (bytes < 10*1024*1024*1024l) return ((bytes + 512*1024)/(1024*1024)) + "&nbsp;MB"; else return ((bytes + 512*1024*1024)/(1024*1024*1024)) + "&nbsp;GB"; } /** @since 0.7.14 */ static String urlify(String s) { return urlify(s, 100); } /** @since 0.9 */ private static String urlify(String s, int max) { StringBuilder buf = new StringBuilder(256); // browsers seem to work without doing this but let's be strict String link = urlEncode(s); String display; if (s.length() <= max) display = link; else display = urlEncode(s.substring(0, max)) + "&hellip;"; buf.append("<a href=\"").append(link).append("\">").append(display).append("</a>"); return buf.toString(); } /** @since 0.8.13 */ private static String urlEncode(String s) { return s.replace(";", "%3B").replace("&", "&amp;").replace(" ", "%20") .replace("[", "%5B").replace("]", "%5D"); } private static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"; private static final String HEADER_A = "<link href=\""; private static final String HEADER_B = "snark.css\" rel=\"stylesheet\" type=\"text/css\" >"; private static final String TABLE_HEADER = "<table border=\"0\" class=\"snarkTorrents\" width=\"100%\" >\n" + "<thead>\n"; private static final String FOOTER = "</div></center></body></html>"; /** * Sort alphabetically in current locale, ignore case, * directories first * @since 0.9.6 */ private static class ListingComparator implements Comparator<File> { private final Comparator collator = Collator.getInstance(); public int compare(File l, File r) { if (l.isDirectory() && !r.isDirectory()) return -1; if (r.isDirectory() && !l.isDirectory()) return 1; return collator.compare(l.getName(), r.getName()); } } /** * Modded heavily from the Jetty version in Resource.java, * pass Resource as 1st param * All the xxxResource constructors are package local so we can't extend them. * * <pre> // ======================================================================== // $Id: Resource.java,v 1.32 2009/05/16 01:53:36 gregwilkins Exp $ // Copyright 1996-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== * </pre> * * Get the resource list as a HTML directory listing. * @param r The Resource * @param base The base URL * @param parent True if the parent directory should be included * @param postParams map of POST parameters or null if not a POST * @return String of HTML or null if postParams != null * @since 0.7.14 */ private String getListHTML(File r, String base, boolean parent, Map postParams) throws IOException { File[] ls = null; if (r.isDirectory()) { ls = r.listFiles(); Arrays.sort(ls, new ListingComparator()); } // if r is not a directory, we are only showing torrent info section String title = decodePath(base); String cpath = _contextPath + '/'; if (title.startsWith(cpath)) title = title.substring(cpath.length()); // Get the snark associated with this directory String torrentName; int slash = title.indexOf('/'); if (slash > 0) torrentName = title.substring(0, slash); else torrentName = title; Snark snark = _manager.getTorrentByBaseName(torrentName); if (snark != null && postParams != null) { // caller must P-R-G savePriorities(snark, postParams); return null; } StringBuilder buf=new StringBuilder(4096); buf.append(DOCTYPE).append("<HTML><HEAD><TITLE>"); if (title.endsWith("/")) title = title.substring(0, title.length() - 1); String directory = title; title = _("Torrent") + ": " + title; buf.append(title); buf.append("</TITLE>").append(HEADER_A).append(_themePath).append(HEADER_B).append("<link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">" + "</HEAD><BODY>\n<center><div class=\"snarknavbar\"><a href=\"").append(_contextPath).append("/\" title=\"Torrents\""); buf.append(" class=\"snarkRefresh\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\">&nbsp;&nbsp;"); if (_contextName.equals(DEFAULT_NAME)) buf.append(_("I2PSnark")); else buf.append(_contextName); buf.append("</a></div></center>\n"); if (parent) // always true buf.append("<div class=\"page\"><div class=\"mainsection\">"); boolean showPriority = ls != null && snark != null && snark.getStorage() != null && !snark.getStorage().complete(); if (showPriority) buf.append("<form action=\"").append(base).append("\" method=\"POST\">\n"); if (snark != null) { // first table - torrent info buf.append("<table class=\"snarkTorrentInfo\">\n"); buf.append("<tr><th><b>") .append(_("Torrent")) .append(":</b> ") .append(snark.getBaseName()) .append("</th></tr>\n"); String fullPath = snark.getName(); String baseName = urlEncode((new File(fullPath)).getName()); buf.append("<tr><td>") .append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Torrent file")) .append(":</b> <a href=\"").append(_contextPath).append('/').append(baseName).append("\">") .append(fullPath) .append("</a></td></tr>\n"); MetaInfo meta = snark.getMetaInfo(); if (meta != null) { String announce = meta.getAnnounce(); if (announce != null) { buf.append("<tr><td>"); String trackerLink = getTrackerLink(announce, snark.getInfoHash()); if (trackerLink != null) buf.append(trackerLink).append(' '); buf.append("<b>").append(_("Primary Tracker")).append(":</b> "); buf.append(getShortTrackerLink(announce, snark.getInfoHash())); buf.append("</td></tr>"); } List<List<String>> alist = meta.getAnnounceList(); if (alist != null) { buf.append("<tr><td>" + "<img alt=\"\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"> <b>"); buf.append(_("Tracker List")).append(":</b> "); for (List<String> alist2 : alist) { buf.append('['); boolean more = false; for (String s : alist2) { if (more) buf.append(' '); else more = true; buf.append(getShortTrackerLink(s, snark.getInfoHash())); } buf.append("] "); } buf.append("</td></tr>"); } } if (meta != null) { String com = meta.getComment(); if (com != null) { if (com.length() > 1024) com = com.substring(0, 1024); buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"> <b>") .append(_("Comment")).append(":</b> ") .append(DataHelper.stripHTML(com)) .append("</td></tr>\n"); } long dat = meta.getCreationDate(); if (dat > 0) { String date = (new SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date(dat)); buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"> <b>") .append(_("Created")).append(":</b> ") .append(date).append(" UTC") .append("</td></tr>\n"); } String cby = meta.getCreatedBy(); if (cby != null) { if (cby.length() > 128) cby = com.substring(0, 128); buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"") .append(_imgPath).append("details.png\"> <b>") .append(_("Created By")).append(":</b> ") .append(DataHelper.stripHTML(cby)) .append("</td></tr>\n"); } } String hex = I2PSnarkUtil.toHex(snark.getInfoHash()); if (meta == null || !meta.isPrivate()) { buf.append("<tr><td><a href=\"") .append(MagnetURI.MAGNET_FULL).append(hex).append("\">") .append(toImg("magnet", _("Magnet link"))) .append("</a> <b>Magnet:</b> <a href=\"") .append(MagnetURI.MAGNET_FULL).append(hex).append("\">") .append(MagnetURI.MAGNET_FULL).append(hex).append("</a>") .append("</td></tr>\n"); } else { buf.append("<tr><td>") .append(_("Private torrent")) .append("</td></tr>\n"); } // We don't have the hash of the torrent file //buf.append("<tr><td>").append(_("Maggot link")).append(": <a href=\"").append(MAGGOT).append(hex).append(':').append(hex).append("\">") // .append(MAGGOT).append(hex).append(':').append(hex).append("</a></td></tr>"); buf.append("<tr><td>") .append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "size.png\" >&nbsp;<b>") .append(_("Size")) .append(":</b> ") .append(formatSize(snark.getTotalLength())); int pieces = snark.getPieces(); double completion = (pieces - snark.getNeeded()) / (double) pieces; if (completion < 1.0) buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;<b>") .append(_("Completion")) .append(":</b> ") .append((new DecimalFormat("0.00%")).format(completion)); else buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;") .append(_("Complete")); // else unknown long needed = snark.getNeededLength(); if (needed > 0) buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" >&nbsp;<b>") .append(_("Remaining")) .append(":</b> ") .append(formatSize(needed)); if (meta != null) { List files = meta.getFiles(); int fileCount = files != null ? files.size() : 1; buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Files")) .append(":</b> ") .append(fileCount); } buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Pieces")) .append(":</b> ") .append(pieces); buf.append("&nbsp;<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" >&nbsp;<b>") .append(_("Piece size")) .append(":</b> ") .append(formatSize(snark.getPieceLength(0))) .append("</td></tr>\n"); } else { // shouldn't happen buf.append("<tr><th>Not found<br>resource=\"").append(r.toString()) .append("\"<br>base=\"").append(base) .append("\"<br>torrent=\"").append(torrentName) .append("\"</th></tr>\n"); } buf.append("</table>\n"); if (ls == null) { // We are only showing the torrent info section buf.append("</div></div></BODY></HTML>"); return buf.toString(); } // second table - dir info buf.append("<table class=\"snarkDirInfo\"><thead>\n"); buf.append("<tr>\n") .append("<th colspan=2>") .append("<img border=\"0\" src=\"" + _imgPath + "file.png\" title=\"") .append(_("Directory")) .append(": ") .append(directory) .append("\" alt=\"") .append(_("Directory")) .append("\"></th>\n"); buf.append("<th align=\"right\">") .append("<img border=\"0\" src=\"" + _imgPath + "size.png\" title=\"") .append(_("Size")) .append("\" alt=\"") .append(_("Size")) .append("\"></th>\n"); buf.append("<th class=\"headerstatus\">") .append("<img border=\"0\" src=\"" + _imgPath + "status.png\" title=\"") .append(_("Status")) .append("\" alt=\"") .append(_("Status")) .append("\"></th>\n"); if (showPriority) buf.append("<th class=\"headerpriority\">") .append("<img border=\"0\" src=\"" + _imgPath + "priority.png\" title=\"") .append(_("Priority")) .append("\" alt=\"") .append(_("Priority")) .append("\"></th>\n"); buf.append("</tr>\n</thead>\n"); buf.append("<tr><td colspan=\"" + (showPriority ? '5' : '4') + "\" class=\"ParentDir\"><A HREF=\""); buf.append(addPaths(base,"../")); buf.append("\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "up.png\"> ") .append(_("Up to higher level directory")) .append("</A></td></tr>\n"); //DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM, // DateFormat.MEDIUM); boolean showSaveButton = false; for (int i=0 ; i< ls.length ; i++) { String encoded = encodePath(ls[i].getName()); // bugfix for I2P - Backport from Jetty 6 (zero file lengths and last-modified times) // http://jira.codehaus.org/browse/JETTY-361?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel#issue-tabs // See resource.diff attachment //Resource item = addPath(encoded); File item = ls[i]; String rowClass = (i % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd"); buf.append("<TR class=\"").append(rowClass).append("\">"); // Get completeness and status string boolean complete = false; String status = ""; long length = item.length(); if (item.isDirectory()) { complete = true; //status = toImg("tick") + ' ' + _("Directory"); } else { if (snark == null || snark.getStorage() == null) { // Assume complete, perhaps he removed a completed torrent but kept a bookmark complete = true; status = toImg("cancel") + ' ' + _("Torrent not found?"); } else { Storage storage = snark.getStorage(); try { File f = item; long remaining = storage.remaining(f.getCanonicalPath()); if (remaining < 0) { complete = true; status = toImg("cancel") + ' ' + _("File not found in torrent?"); } else if (remaining == 0 || length <= 0) { complete = true; status = toImg("tick") + ' ' + _("Complete"); } else { int priority = storage.getPriority(f.getCanonicalPath()); if (priority < 0) status = toImg("cancel"); else if (priority == 0) status = toImg("clock"); else status = toImg("clock_red"); status += " " + (100 * (length - remaining) / length) + "% " + _("complete") + " (" + DataHelper.formatSize2(remaining) + "B " + _("remaining") + ")"; } } catch (IOException ioe) { status = "Not a file? " + ioe; } } } String path=addPaths(base,encoded); if (item.isDirectory() && !path.endsWith("/")) path=addPaths(path,"/"); String icon = toIcon(item); buf.append("<TD class=\"snarkFileIcon\">"); if (complete) { buf.append("<a href=\"").append(path).append("\">"); // thumbnail ? String plc = item.toString().toLowerCase(Locale.US); if (plc.endsWith(".jpg") || plc.endsWith(".jpeg") || plc.endsWith(".png") || plc.endsWith(".gif") || plc.endsWith(".ico")) { buf.append("<img alt=\"\" border=\"0\" class=\"thumb\" src=\"") .append(path).append("\"></a>"); } else { buf.append(toImg(icon, _("Open"))).append("</a>"); } } else { buf.append(toImg(icon)); } buf.append("</TD><TD class=\"snarkFileName\">"); if (complete) buf.append("<a href=\"").append(path).append("\">"); buf.append(item.getName()); if (complete) buf.append("</a>"); buf.append("</TD><TD ALIGN=right class=\"snarkFileSize\">"); if (!item.isDirectory()) buf.append(DataHelper.formatSize2(length)).append('B'); buf.append("</TD><TD class=\"snarkFileStatus\">"); //buf.append(dfmt.format(new Date(item.lastModified()))); buf.append(status); buf.append("</TD>"); if (showPriority) { buf.append("<td class=\"priority\">"); File f = item; if ((!complete) && (!item.isDirectory())) { int pri = snark.getStorage().getPriority(f.getCanonicalPath()); buf.append("<input type=\"radio\" value=\"5\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri > 0) buf.append("checked=\"true\""); buf.append('>').append(_("High")); buf.append("<input type=\"radio\" value=\"0\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri == 0) buf.append("checked=\"true\""); buf.append('>').append(_("Normal")); buf.append("<input type=\"radio\" value=\"-9\" name=\"pri.").append(f.getCanonicalPath()).append("\" "); if (pri < 0) buf.append("checked=\"true\""); buf.append('>').append(_("Skip")); showSaveButton = true; } buf.append("</td>"); } buf.append("</TR>\n"); } if (showSaveButton) { buf.append("<thead><tr><th colspan=\"4\">&nbsp;</th><th class=\"headerpriority\"><input type=\"submit\" value=\""); buf.append(_("Save priorities")); buf.append("\" name=\"foo\" ></th></tr></thead>\n"); } buf.append("</table>\n"); if (showPriority) buf.append("</form>"); buf.append("</div></div></BODY></HTML>\n"); return buf.toString(); } /** @since 0.7.14 */ private String toIcon(File item) { if (item.isDirectory()) return "folder"; return toIcon(item.toString()); } /** * Pick an icon; try to catch the common types in an i2p environment * @return file name not including ".png" * @since 0.7.14 */ private String toIcon(String path) { String icon; // Note that for this to work well, our custom mime.properties file must be loaded. String plc = path.toLowerCase(Locale.US); String mime = getMimeType(path); if (mime == null) mime = ""; if (mime.equals("text/html")) icon = "html"; else if (mime.equals("text/plain") || mime.equals("text/x-sfv") || mime.equals("application/rtf") || mime.equals("application/epub+zip") || mime.equals("application/x-mobipocket-ebook")) icon = "page"; else if (mime.equals("application/java-archive") || plc.endsWith(".deb")) icon = "package"; else if (plc.endsWith(".xpi2p")) icon = "plugin"; else if (mime.equals("application/pdf")) icon = "page_white_acrobat"; else if (mime.startsWith("image/")) icon = "photo"; else if (mime.startsWith("audio/") || mime.equals("application/ogg")) icon = "music"; else if (mime.startsWith("video/")) icon = "film"; else if (mime.equals("application/zip") || mime.equals("application/x-gtar") || mime.equals("application/compress") || mime.equals("application/gzip") || mime.equals("application/x-7z-compressed") || mime.equals("application/x-rar-compressed") || mime.equals("application/x-tar") || mime.equals("application/x-bzip2")) icon = "compress"; else if (plc.endsWith(".exe")) icon = "application"; else if (plc.endsWith(".iso")) icon = "cd"; else icon = "page_white"; return icon; } /** @since 0.7.14 */ private String toImg(String icon) { return "<img alt=\"\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">"; } /** @since 0.8.2 */ private String toImg(String icon, String altText) { return "<img alt=\"" + altText + "\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">"; } /** @since 0.8.1 */ private void savePriorities(Snark snark, Map postParams) { Storage storage = snark.getStorage(); if (storage == null) return; Set<Map.Entry> entries = postParams.entrySet(); for (Map.Entry entry : entries) { String key = (String)entry.getKey(); if (key.startsWith("pri.")) { try { String file = key.substring(4); String val = ((String[])entry.getValue())[0]; // jetty arrays int pri = Integer.parseInt(val); storage.setPriority(file, pri); //System.err.println("Priority now " + pri + " for " + file); } catch (Throwable t) { t.printStackTrace(); } } } snark.updatePiecePriorities(); _manager.saveTorrentStatus(snark.getMetaInfo(), storage.getBitField(), storage.getFilePriorities()); } } diff --git a/router/java/src/net/i2p/router/RouterVersion.java b/router/java/src/net/i2p/router/RouterVersion.java index fc03273f8..b76ab6863 100644 --- a/router/java/src/net/i2p/router/RouterVersion.java +++ b/router/java/src/net/i2p/router/RouterVersion.java @@ -1,32 +1,32 @@ package net.i2p.router; /* * free (adj.): unencumbered; not under the control of others * Written by jrandom in 2003 and released into the public domain * with no warranty of any kind, either expressed or implied. * It probably won't make your computer catch on fire, or eat * your children, but it might. Use at your own risk. * */ import net.i2p.CoreVersion; /** * Expose a version string * */ public class RouterVersion { /** deprecated */ public final static String ID = "Monotone"; public final static String VERSION = CoreVersion.VERSION; - public final static long BUILD = 33; + public final static long BUILD = 34; /** for example "-test" */ public final static String EXTRA = "-rc"; public final static String FULL_VERSION = VERSION + "-" + BUILD + EXTRA; public static void main(String args[]) { System.out.println("I2P Router version: " + FULL_VERSION); System.out.println("Router ID: " + RouterVersion.ID); System.out.println("I2P Core version: " + CoreVersion.VERSION); System.out.println("Core ID: " + CoreVersion.ID); } }
false
false
null
null
diff --git a/src/java/com/sun/facelets/util/FacesAPI.java b/src/java/com/sun/facelets/util/FacesAPI.java index 3eb0057..19e5097 100644 --- a/src/java/com/sun/facelets/util/FacesAPI.java +++ b/src/java/com/sun/facelets/util/FacesAPI.java @@ -1,50 +1,50 @@ /** * Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.com/cddl/ * * 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.sun.facelets.util; import javax.faces.application.Application; import javax.faces.component.UIComponent; import javax.faces.component.UIComponentBase; public final class FacesAPI { private static final int version = specifyVersion(); private static final Class[] UIC_SIG = new Class[] { String.class }; private FacesAPI() { super(); } private final static int specifyVersion() { try { Application.class.getMethod("getExpressionFactory", null); } catch (NoSuchMethodException e) { return 11; } return 12; } public final static int getVersion() { return version; } public final static int getComponentVersion(UIComponent c) { - return (version >= 12 && c instanceof UIComponentBase) ? 12 : 11; + return version; } public final static int getComponentVersion(Class c) { - return (version >= 12 && UIComponentBase.class.isAssignableFrom(c)) ? 12 : 11; + return version; } }
false
false
null
null
diff --git a/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java b/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java index ec40131ae..e418d7b2a 100644 --- a/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java +++ b/src/contributions/resources/timeline/src/java/edu/mit/simile/yanel/impl/resources/timeline/TimelineResource.java @@ -1,187 +1,187 @@ /* * Copyright 2007 Wyona */ package edu.mit.simile.yanel.impl.resources.timeline; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.api.attributes.IntrospectableV1; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.PathUtil; import org.apache.log4j.Category; /** * */ public class TimelineResource extends Resource implements ViewableV2, IntrospectableV1 { private static Category log = Category.getInstance(TimelineResource.class); /** * */ public TimelineResource() { } /** * */ public boolean exists() { log.warn("Not really implemented yet! Needs to check if events XML exists."); return true; } /** * */ public String getMimeType(String viewId) { if (viewId != null) { if (viewId.equals("xml")) return "application/xml"; } return "application/xhtml+xml"; } /** * */ public long getSize() { log.warn("Not implemented yet!"); return -1; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("xml"); vd[1].setMimeType(getMimeType("xml")); return vd; } /** * */ public View getView(String viewId) { View view = new View(); try { view.setInputStream(new java.io.StringBufferInputStream(getXHTML().toString())); //view.setInputStream(getRealm().getRepository().getNode("/timeline.xhtml").getInputStream()); view.setMimeType(getMimeType(null)); } catch (Exception e) { log.error(e.getMessage(), e); } return view; } /** * */ private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); - sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); + sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPathURLencoded(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; } /** * Get introspection for Introspectable interface */ public String getIntrospection() throws Exception { String name = PathUtil.getName(getPath()); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<introspection xmlns=\"http://www.wyona.org/neutron/2.0\">"); sb.append("<navigation>"); sb.append(" <sitetree href=\"./\" method=\"PROPFIND\"/>"); sb.append("</navigation>"); sb.append("<resource name=\"" + name + "\">"); sb.append("<edit mime-type=\"application/xml\">"); sb.append("<checkout url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=checkout\" method=\"GET\"/>"); sb.append("<checkin url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=checkin\" method=\"PUT\"/>"); sb.append("<release-lock url=\"" + getResourceConfigProperty("href") + "?yanel.resource.usecase=release-lock\" method=\"GET\"/>"); sb.append("</edit>"); sb.append("</resource>"); sb.append("</introspection>"); return sb.toString(); } }
true
true
private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; }
private StringBuffer getXHTML() throws Exception { //java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy hh:mm:ss z"); //String todaysDate = sdf.format(new java.util.Date()); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MMM dd yyyy"); String todaysDate = sdf.format(new java.util.Date()) + " 00:00:00 GMT"; StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); if (getResourceConfigProperty("introspection-url") != null) { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"" + getResourceConfigProperty("introspection-url") + "\"/>"); } else { sb.append("<link rel=\"neutron-introspection\" type=\"application/neutron+xml\" href=\"?yanel.resource.usecase=introspection\"/>"); } //sb.append("<script src=\"http://simile.mit.edu/timeline/api/timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPathURLencoded(this) + "timeline-api.js\" type=\"text/javascript\"></script>"); sb.append("<script type=\"text/javascript\">"); sb.append("var tl;"); sb.append("var resizeTimerID = null;"); sb.append("function onResize() {"); sb.append(" if (resizeTimerID == null) {"); sb.append(" resizeTimerID = window.setTimeout(function() {"); sb.append(" resizeTimerID = null;"); sb.append(" tl.layout();"); sb.append(" }, 500);"); sb.append(" }"); sb.append("}"); sb.append("function onLoad() {"); sb.append(" var eventSource = new Timeline.DefaultEventSource();"); sb.append(" var bandInfos = ["); sb.append(" Timeline.createBandInfo({"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"70%\","); sb.append(" intervalUnit: Timeline.DateTime.MONTH,"); sb.append(" intervalPixels: 100"); sb.append(" }),"); sb.append(" Timeline.createBandInfo({"); sb.append("showEventText: false,"); sb.append(" trackHeight: 0.5,"); sb.append(" trackGap: 0.2,"); sb.append(" eventSource: eventSource,"); sb.append(" date: \"" + todaysDate + "\","); sb.append(" width: \"30%\","); sb.append(" intervalUnit: Timeline.DateTime.YEAR,"); sb.append(" intervalPixels: 200"); sb.append(" })"); sb.append(" ];"); sb.append(" bandInfos[1].syncWith = 0;"); sb.append(" bandInfos[1].highlight = true;"); sb.append(" tl = Timeline.create(document.getElementById(\"my-timeline\"), bandInfos);"); // TODO: Check first if a query string already exists! sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "?do-not-cache-timestamp=" + new java.util.Date().getTime() + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); //sb.append(" Timeline.loadXML(\"" + getResourceConfigProperty("href") + "\", function(xml, url) { eventSource.loadXML(xml, url); });"); sb.append("}"); sb.append("</script>"); sb.append("<title>" + getResourceConfigProperty("title") + "</title>"); sb.append("</head>"); sb.append("<body onload=\"onLoad();\" onresize=\"onResize();\">"); sb.append("<h3>" + getResourceConfigProperty("title") + "</h3>"); sb.append("<p>Today's Date (server time): " + todaysDate + "</p>"); sb.append("<p>XML: <a href=\"" + getResourceConfigProperty("href") + "\">" + getResourceConfigProperty("href") + "</a></p>"); String height = getResourceConfigProperty("height"); if (height == null) height = "250px"; sb.append("<div id=\"my-timeline\" style=\"height: " + height + "; border: 1px solid #aaa\"></div>"); sb.append("</body>"); sb.append("</html>"); return sb; }
diff --git a/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java b/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java index 219735d67..d16a8ffb1 100644 --- a/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java +++ b/proxy/src/test/java/org/fedoraproject/candlepin/pinsetter/tasks/MigrateOwnerJobTest.java @@ -1,176 +1,176 @@ /** * Copyright (c) 2009 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.fedoraproject.candlepin.pinsetter.tasks; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.fedoraproject.candlepin.client.CandlepinConnection; import org.fedoraproject.candlepin.client.OwnerClient; import org.fedoraproject.candlepin.config.Config; import org.fedoraproject.candlepin.config.ConfigProperties; import org.fedoraproject.candlepin.exceptions.BadRequestException; import org.fedoraproject.candlepin.exceptions.NotFoundException; import org.fedoraproject.candlepin.model.Owner; import org.fedoraproject.candlepin.model.OwnerCurator; import org.apache.commons.httpclient.Credentials; import org.jboss.resteasy.client.ClientResponse; import org.junit.Before; import org.junit.Test; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.spi.TriggerFiredBundle; import java.util.HashMap; /** * MigrateOwnerJobTest */ public class MigrateOwnerJobTest { private OwnerCurator ownerCurator; private CandlepinConnection conn; private MigrateOwnerJob moj; private Config config; @Before public void init() { config = new ConfigForTesting(); ownerCurator = mock(OwnerCurator.class); conn = mock(CandlepinConnection.class); moj = new MigrateOwnerJob(ownerCurator, conn, config); } @Test public void testMigrateOwner() { JobDetail jd = moj.migrateOwner("admin", "http://foo.example.com/candlepin"); assertNotNull(jd); assertNotNull(jd.getJobDataMap()); assertEquals("admin", jd.getJobDataMap().get("owner_key")); assertEquals("http://foo.example.com/candlepin", jd.getJobDataMap().get("uri")); } @Test(expected = Exception.class) public void nullOwner() { moj.migrateOwner(null, "http://foo.example.com/candlepin"); } @Test(expected = BadRequestException.class) public void nullUrl() { moj.migrateOwner("admin", null); } @Test(expected = BadRequestException.class) public void inavlidUrlFormat() { moj.migrateOwner("admin", "foo"); } // used by execute tests private JobExecutionContext buildContext(JobDataMap map) { Scheduler s = mock(Scheduler.class); TriggerFiredBundle bundle = mock(TriggerFiredBundle.class); JobDetail detail = mock(JobDetail.class); Trigger trig = mock(Trigger.class); when(detail.getJobDataMap()).thenReturn(map); when(bundle.getJobDetail()).thenReturn(detail); when(bundle.getTrigger()).thenReturn(trig); when(trig.getJobDataMap()).thenReturn(new JobDataMap()); return new JobExecutionContext(s, bundle, null); } @Test @SuppressWarnings("unchecked") public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); - verify(ownerCurator, atLeastOnce()).merge(any(Owner.class)); + verify(ownerCurator, atLeastOnce()).importOwner(any(Owner.class)); } @Test(expected = Exception.class) public void executeInvalidKey() throws JobExecutionException { JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("badurikey", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); } @Test(expected = BadRequestException.class) public void executeBadValues() throws JobExecutionException { JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", ""); moj.execute(buildContext(map)); } @Test(expected = NotFoundException.class) @SuppressWarnings("unchecked") public void executeNonExistentOwner() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("doesnotexist"))).thenReturn(resp); when(resp.getStatus()).thenReturn(404); JobDataMap map = new JobDataMap(); map.put("owner_key", "doesnotexist"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); } private static class ConfigForTesting extends Config { public ConfigForTesting() { super(new HashMap<String, String>() { private static final long serialVersionUID = 1L; { this.put(ConfigProperties.SHARD_USERNAME, "admin"); this.put(ConfigProperties.SHARD_PASSWORD, "admin"); this.put(ConfigProperties.SHARD_WEBAPP, "candlepin"); } }); } } }
true
true
public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); verify(ownerCurator, atLeastOnce()).merge(any(Owner.class)); }
public void execute() throws JobExecutionException { OwnerClient client = mock(OwnerClient.class); when(conn.connect(any(Credentials.class), any(String.class))).thenReturn(client); ClientResponse<Owner> resp = mock(ClientResponse.class); when(client.exportOwner(eq("admin"))).thenReturn(resp); when(resp.getStatus()).thenReturn(200); JobDataMap map = new JobDataMap(); map.put("owner_key", "admin"); map.put("uri", "http://foo.example.com/candlepin"); moj.execute(buildContext(map)); verify(conn).connect(any(Credentials.class), eq("http://foo.example.com/candlepin")); verify(ownerCurator, atLeastOnce()).importOwner(any(Owner.class)); }
diff --git a/src/java/org/jivesoftware/sparkimpl/profile/VCardManager.java b/src/java/org/jivesoftware/sparkimpl/profile/VCardManager.java index 096acdcc..1030c509 100644 --- a/src/java/org/jivesoftware/sparkimpl/profile/VCardManager.java +++ b/src/java/org/jivesoftware/sparkimpl/profile/VCardManager.java @@ -1,747 +1,748 @@ /** * $RCSfile: ,v $ * $Revision: $ * $Date: $ * * Copyright (C) 2004-2010 Jive Software. 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. */ package org.jivesoftware.sparkimpl.profile; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.PacketInterceptor; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.packet.XMPPError; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.smackx.provider.VCardProvider; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.util.Base64; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.ResourceUtils; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.manager.Enterprise; import org.jivesoftware.sparkimpl.profile.ext.JabberAvatarExtension; import org.jivesoftware.sparkimpl.profile.ext.VCardUpdateExtension; import org.xmlpull.mxp1.MXParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.LinkedBlockingQueue; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; /** * VCardManager handles all VCard loading/caching within Spark. * * @author Derek DeMoro */ public class VCardManager { private VCard personalVCard; private Map<String, VCard> vcards = new HashMap<String, VCard>(); private boolean vcardLoaded; private File imageFile; private final VCardEditor editor; private File vcardStorageDirectory; final MXParser parser; private LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(); private File contactsDir; private List<VCardListener> listeners = new ArrayList<VCardListener>(); /** * Initialize VCardManager. */ public VCardManager() { // Initialize parser parser = new MXParser(); try { parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); } catch (XmlPullParserException e) { Log.error(e); } imageFile = new File(SparkManager.getUserDirectory(), "personal.png"); // Initialize vCard. personalVCard = new VCard(); // Set VCard Storage vcardStorageDirectory = new File(SparkManager.getUserDirectory(), "vcards"); vcardStorageDirectory.mkdirs(); // Set the current user directory. contactsDir = new File(SparkManager.getUserDirectory(), "contacts"); contactsDir.mkdirs(); initializeUI(); // Intercept all presence packets being sent and append vcard information. PacketFilter presenceFilter = new PacketTypeFilter(Presence.class); SparkManager.getConnection().addPacketInterceptor(new PacketInterceptor() { public void interceptPacket(Packet packet) { Presence newPresence = (Presence)packet; VCardUpdateExtension update = new VCardUpdateExtension(); JabberAvatarExtension jax = new JabberAvatarExtension(); PacketExtension updateExt = newPresence.getExtension(update.getElementName(), update.getNamespace()); PacketExtension jabberExt = newPresence.getExtension(jax.getElementName(), jax.getNamespace()); if (updateExt != null) { newPresence.removeExtension(updateExt); } if (jabberExt != null) { newPresence.removeExtension(jabberExt); } if (personalVCard != null) { byte[] bytes = personalVCard.getAvatar(); if (bytes != null && bytes.length > 0) { update.setPhotoHash(personalVCard.getAvatarHash()); jax.setPhotoHash(personalVCard.getAvatarHash()); newPresence.addExtension(update); newPresence.addExtension(jax); } } } }, presenceFilter); editor = new VCardEditor(); // Start Listener startQueueListener(); } /** * Listens for new VCards to lookup in a queue. */ private void startQueueListener() { final Runnable queueListener = new Runnable() { public void run() { while (true) { try { String jid = queue.take(); reloadVCard(jid); } catch (InterruptedException e) { e.printStackTrace(); break; } } } }; TaskEngine.getInstance().submit(queueListener); } /** * Adds a jid to lookup vCard. * * @param jid the jid to lookup. */ public void addToQueue(String jid) { if (!queue.contains(jid)) { queue.add(jid); } } /** * Adds VCard capabilities to menus and other components in Spark. */ private void initializeUI() { boolean enabled = Enterprise.containsFeature(Enterprise.VCARD_FEATURE); if (!enabled) { return; } // Add Actions Menu final JMenu contactsMenu = SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.contacts")); final JMenu communicatorMenu = SparkManager.getMainWindow().getJMenuBar().getMenu(0); JMenuItem editProfileMenu = new JMenuItem(SparkRes.getImageIcon(SparkRes.SMALL_BUSINESS_MAN_VIEW)); ResourceUtils.resButton(editProfileMenu, Res.getString("menuitem.edit.my.profile")); int size = contactsMenu.getMenuComponentCount(); communicatorMenu.insert(editProfileMenu, 1); editProfileMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SwingWorker vcardLoaderWorker = new SwingWorker() { public Object construct() { try { personalVCard.load(SparkManager.getConnection()); } catch (XMPPException e) { Log.error("Error loading vcard information.", e); } return true; } public void finished() { editor.editProfile(personalVCard, SparkManager.getWorkspace()); } }; vcardLoaderWorker.start(); } }); JMenuItem viewProfileMenu = new JMenuItem("", SparkRes.getImageIcon(SparkRes.FIND_TEXT_IMAGE)); ResourceUtils.resButton(viewProfileMenu, Res.getString("menuitem.lookup.profile")); contactsMenu.insert(viewProfileMenu, size > 0 ? size - 1 : 0); viewProfileMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String jidToView = JOptionPane.showInputDialog(SparkManager.getMainWindow(), Res.getString("message.enter.jabber.id") + ":", Res.getString("title.lookup.profile"), JOptionPane.QUESTION_MESSAGE); if (ModelUtil.hasLength(jidToView) && jidToView.indexOf("@") != -1 && ModelUtil.hasLength(StringUtils.parseServer(jidToView))) { viewProfile(jidToView, SparkManager.getWorkspace()); } else if (ModelUtil.hasLength(jidToView)) { JOptionPane.showMessageDialog(SparkManager.getMainWindow(), Res.getString("message.invalid.jabber.id"), Res.getString("title.error"), JOptionPane.ERROR_MESSAGE); } } }); } /** * Displays <code>VCardViewer</code> for a particular JID. * * @param jid the jid of the user to display. * @param parent the parent component to use for displaying dialog. */ public void viewProfile(final String jid, final JComponent parent) { final SwingWorker vcardThread = new SwingWorker() { VCard vcard = new VCard(); public Object construct() { vcard = getVCard(jid); return vcard; } public void finished() { if (vcard.getError() != null || vcard == null) { // Show vcard not found JOptionPane.showMessageDialog(parent, Res.getString("message.unable.to.load.profile", jid), Res.getString("title.profile.not.found"), JOptionPane.ERROR_MESSAGE); } else { editor.displayProfile(jid, vcard, parent); } } }; vcardThread.start(); } /** * Displays the full profile for a particular JID. * * @param jid the jid of the user to display. * @param parent the parent component to use for displaying dialog. */ public void viewFullProfile(final String jid, final JComponent parent) { final SwingWorker vcardThread = new SwingWorker() { VCard vcard = new VCard(); public Object construct() { vcard = getVCard(jid); return vcard; } public void finished() { if (vcard.getError() != null || vcard == null) { // Show vcard not found JOptionPane.showMessageDialog(parent, Res.getString("message.unable.to.load.profile", jid), Res.getString("title.profile.not.found"), JOptionPane.ERROR_MESSAGE); } else { editor.viewFullProfile(vcard, parent); } } }; vcardThread.start(); } /** * Returns the VCard for this Spark user. This information will be cached after loading. * * @return this users VCard. */ public VCard getVCard() { if (!vcardLoaded) { try { personalVCard.load(SparkManager.getConnection()); // If VCard is loaded, then save the avatar to the personal folder. byte[] bytes = personalVCard.getAvatar(); if (bytes != null && bytes.length > 0) { ImageIcon icon = new ImageIcon(bytes); icon = VCardManager.scale(icon); if (icon != null && icon.getIconWidth() != -1) { BufferedImage image = GraphicUtils.convert(icon.getImage()); ImageIO.write(image, "PNG", imageFile); } } } catch (Exception e) { Log.error(e); } vcardLoaded = true; } return personalVCard; } /** * Returns the Avatar in the form of an <code>ImageIcon</code>. * * @param vcard the vCard containing the avatar. * @return the ImageIcon or null if no avatar was present. */ public static ImageIcon getAvatarIcon(VCard vcard) { // Set avatar byte[] bytes = vcard.getAvatar(); if (bytes != null && bytes.length > 0) { ImageIcon icon = new ImageIcon(bytes); return GraphicUtils.scaleImageIcon(icon, 40, 40); } return null; } /** * Returns the VCard. Will first look in VCard cache and only do a network * operation if no vcard is found. * * @param jid the users jid. * @return the VCard. */ public VCard getVCard(String jid) { return getVCard(jid, true); } /** * Loads the vCard from memory. If no vCard is found in memory, * will add it to a loading queue for future loading. Users of this method * should only use it if the correct vCard is not important the first time around. * * @param jid the users jid. * @return the users VCard or an empty VCard. */ public VCard getVCardFromMemory(String jid) { // Check in memory first. if (vcards.containsKey(jid)) { return vcards.get(jid); } // if not in memory VCard vcard = loadFromFileSystem(jid); if (vcard == null) { addToQueue(jid); // Create temp vcard. vcard = new VCard(); vcard.setJabberId(jid); } return vcard; } /** * Returns the VCard. * * @param jid the users jid. * @param useCache true to check in cache, otherwise false will do a new network vcard operation. * @return the VCard. */ public VCard getVCard(String jid, boolean useCache) { jid = StringUtils.parseBareAddress(jid); if (!vcards.containsKey(jid) || !useCache) { VCard vcard = new VCard(); try { // Check File system first VCard localVCard = loadFromFileSystem(jid); if (localVCard != null) { localVCard.setJabberId(jid); vcards.put(jid, localVCard); return localVCard; } // Otherwise retrieve vCard from server and persist back out. vcard.load(SparkManager.getConnection(), jid); vcard.setJabberId(jid); if (vcard.getNickName() != null && vcard.getNickName().length() > 0) { // update nickname. - ContactItem item = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid); - item.setNickname(vcard.getNickName()); + //if the conract isn't on your list + ContactItem item = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid); + if (item!= null)item.setNickname(vcard.getNickName()); // TODO: this doesn't work if someone removes his nickname. If we remove it in that case, it will cause problems with people using another way to manage their nicknames. } vcards.put(jid, vcard); } catch (XMPPException e) { vcard.setJabberId(jid); //Log.warning("Unable to load vcard for " + jid, e); vcard.setError(new XMPPError(XMPPError.Condition.conflict)); vcards.put(jid, vcard); } // Persist XML persistVCard(jid, vcard); } return vcards.get(jid); } /** * Forces a reload of a <code>VCard</code>. * * @param jid the jid of the user. * @return the new VCard. */ public VCard reloadVCard(String jid) { jid = StringUtils.parseBareAddress(jid); VCard vcard = new VCard(); try { vcard.load(SparkManager.getConnection(), jid); vcard.setJabberId(jid); if (vcard.getNickName() != null && vcard.getNickName().length() > 0) { // update nickname. ContactItem item = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid); item.setNickname(vcard.getNickName()); // TODO: this doesn't work if someone removes his nickname. If we remove it in that case, it will cause problems with people using another way to manage their nicknames. } vcards.put(jid, vcard); } catch (XMPPException e) { vcard.setError(new XMPPError(XMPPError.Condition.conflict)); vcards.put(jid, vcard); } // Persist XML persistVCard(jid, vcard); return vcards.get(jid); } /** * Adds a new vCard to the cache. * * @param jid the jid of the user. * @param vcard the users vcard to cache. */ public void addVCard(String jid, VCard vcard) { vcard.setJabberId(jid); vcards.put(jid, vcard); } /** * Scales an image to the preferred avatar size. * * @param icon the icon to scale. * @return the scaled version of the image. */ public static ImageIcon scale(ImageIcon icon) { Image avatarImage = icon.getImage(); if (icon.getIconHeight() > 64 || icon.getIconWidth() > 64) { avatarImage = avatarImage.getScaledInstance(-1, 64, Image.SCALE_SMOOTH); } return new ImageIcon(avatarImage); } /** * Returns the URL of the avatar image associated with the users JID. * * @param jid the jid of the user. * @return the URL of the image. If not image is found, a default avatar is returned. */ public URL getAvatar(String jid) { // Handle own avatar file. if (jid != null && StringUtils.parseBareAddress(SparkManager.getSessionManager().getJID()).equals(StringUtils.parseBareAddress(jid))) { if (imageFile.exists()) { try { return imageFile.toURI().toURL(); } catch (MalformedURLException e) { Log.error(e); } } else { return SparkRes.getURL(SparkRes.DUMMY_CONTACT_IMAGE); } } // Handle other users JID ContactItem item = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid); URL avatarURL = null; if (item != null) { try { avatarURL = item.getAvatarURL(); } catch (MalformedURLException e) { Log.error(e); } } if (avatarURL == null) { return SparkRes.getURL(SparkRes.DUMMY_CONTACT_IMAGE); } return avatarURL; } /** * Searches all vCards for a specified phone number. * * @param phoneNumber the phoneNumber. * @return the vCard which contains the phone number. */ public VCard searchPhoneNumber(String phoneNumber) { for (VCard vcard : vcards.values()) { String homePhone = getNumbersFromPhone(vcard.getPhoneHome("VOICE")); String workPhone = getNumbersFromPhone(vcard.getPhoneWork("VOICE")); String cellPhone = getNumbersFromPhone(vcard.getPhoneWork("CELL")); String query = getNumbersFromPhone(phoneNumber); if ((homePhone != null && homePhone.endsWith(query)) || (workPhone != null && workPhone.endsWith(query)) || (cellPhone != null && cellPhone.endsWith(query))) { return vcard; } } return null; } /** * Parses out the numbers only from a phone number. * * @param number the full phone number. * @return the phone number only (5551212) */ public static String getNumbersFromPhone(String number) { if (number == null) { return null; } number = number.replace("-", ""); number = number.replace("(", ""); number = number.replace(")", ""); number = number.replace(" ", ""); if (number.startsWith("1")) { number = number.substring(1); } return number; } /** * Sets the personal vcard of the user. * * @param vcard the users vCard. */ public void setPersonalVCard(VCard vcard) { this.personalVCard = vcard; } public URL getAvatarURL(String jid) { VCard vcard = getVCard(jid, true); if (vcard != null) { String hash = vcard.getAvatarHash(); if (!ModelUtil.hasLength(hash)) { return null; } final File avatarFile = new File(contactsDir, hash); try { return avatarFile.toURI().toURL(); } catch (MalformedURLException e) { Log.error(e); } } return null; } /** * Persist vCard information out for caching. * * @param jid the users jid. * @param vcard the users vcard. */ private void persistVCard(String jid, VCard vcard) { String fileName = Base64.encodeBytes(jid.getBytes()); byte[] bytes = vcard.getAvatar(); if (bytes != null && bytes.length > 0) { vcard.setAvatar(bytes); try { String hash = vcard.getAvatarHash(); final File avatarFile = new File(contactsDir, hash); ImageIcon icon = new ImageIcon(bytes); icon = VCardManager.scale(icon); if (icon != null && icon.getIconWidth() != -1) { BufferedImage image = GraphicUtils.convert(icon.getImage()); if (image == null) { Log.warning("Unable to write out avatar for " + jid); } else { ImageIO.write(image, "PNG", avatarFile); } } } catch (Exception e) { Log.error("Unable to update avatar in Contact Item.", e); } } // Set timestamp vcard.setField("timestamp", Long.toString(System.currentTimeMillis())); final String xml = vcard.toString(); File vcardFile = new File(vcardStorageDirectory, fileName); // write xml to file try { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(vcardFile), "UTF-8")); out.write(xml); out.close(); } catch (IOException e) { Log.error(e); } } /** * Attempts to load * * @param jid the jid of the user. * @return the VCard if found, otherwise null. */ private VCard loadFromFileSystem(String jid) { // Unescape JID String fileName = Base64.encodeBytes(jid.getBytes()); final File vcardFile = new File(vcardStorageDirectory, fileName); if (!vcardFile.exists()) { return null; } try { // Otherwise load from file system. BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(vcardFile), "UTF-8")); VCardProvider provider = new VCardProvider(); parser.setInput(in); VCard vcard = (VCard)provider.parseIQ(parser); // Check to see if the file is older 10 minutes. If so, reload. String timestamp = vcard.getField("timestamp"); if (timestamp != null) { long time = Long.parseLong(timestamp); long now = System.currentTimeMillis(); long hour = (1000 * 60) * 60; if (now - time > hour) { addToQueue(jid); } } vcard.setJabberId(jid); vcards.put(jid, vcard); return vcard; } catch (Exception e) { Log.warning("Unable to load vCard for " + jid, e); } return null; } /** * Add <code>VCardListener</code>. * * @param listener the listener to add. */ public void addVCardListener(VCardListener listener) { listeners.add(listener); } /** * Remove <code>VCardListener</code>. * * @param listener the listener to remove. */ public void removeVCardListener(VCardListener listener) { listeners.remove(listener); } /** * Notify all <code>VCardListener</code> implementations. */ protected void notifyVCardListeners() { for (VCardListener listener : listeners) { listener.vcardChanged(personalVCard); } } }
true
false
null
null
diff --git a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java index 7e61695d0..23a23626f 100644 --- a/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java +++ b/dspace-api/src/main/java/org/dspace/content/packager/AbstractMETSDisseminator.java @@ -1,1533 +1,1539 @@ /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.content.packager; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import edu.harvard.hul.ois.mets.AmdSec; import edu.harvard.hul.ois.mets.BinData; import edu.harvard.hul.ois.mets.Checksumtype; import edu.harvard.hul.ois.mets.Div; import edu.harvard.hul.ois.mets.DmdSec; import edu.harvard.hul.ois.mets.MdRef; import edu.harvard.hul.ois.mets.FLocat; import edu.harvard.hul.ois.mets.FileGrp; import edu.harvard.hul.ois.mets.FileSec; import edu.harvard.hul.ois.mets.Fptr; import edu.harvard.hul.ois.mets.Mptr; import edu.harvard.hul.ois.mets.Loctype; import edu.harvard.hul.ois.mets.MdWrap; import edu.harvard.hul.ois.mets.Mdtype; import edu.harvard.hul.ois.mets.Mets; import edu.harvard.hul.ois.mets.MetsHdr; import edu.harvard.hul.ois.mets.StructMap; import edu.harvard.hul.ois.mets.TechMD; import edu.harvard.hul.ois.mets.SourceMD; import edu.harvard.hul.ois.mets.DigiprovMD; import edu.harvard.hul.ois.mets.RightsMD; import edu.harvard.hul.ois.mets.helper.MdSec; import edu.harvard.hul.ois.mets.XmlData; import edu.harvard.hul.ois.mets.helper.Base64; import edu.harvard.hul.ois.mets.helper.MetsElement; import edu.harvard.hul.ois.mets.helper.MetsException; import edu.harvard.hul.ois.mets.helper.MetsValidator; import edu.harvard.hul.ois.mets.helper.MetsWriter; import edu.harvard.hul.ois.mets.helper.PreformedXML; import java.io.File; import java.io.FileOutputStream; import org.apache.log4j.Logger; import org.dspace.app.util.Util; import org.dspace.authorize.AuthorizeException; import org.dspace.authorize.AuthorizeManager; import org.dspace.content.Bitstream; import org.dspace.content.Bundle; import org.dspace.content.Community; import org.dspace.content.Collection; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.content.ItemIterator; import org.dspace.content.crosswalk.AbstractPackagerWrappingCrosswalk; import org.dspace.content.crosswalk.CrosswalkException; import org.dspace.content.crosswalk.CrosswalkObjectNotSupported; import org.dspace.content.crosswalk.DisseminationCrosswalk; import org.dspace.content.crosswalk.StreamDisseminationCrosswalk; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.core.PluginManager; import org.dspace.core.Utils; import org.dspace.license.CreativeCommons; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * Base class for disseminator of * METS (Metadata Encoding & Transmission Standard) Package.<br> * See <a href="http://www.loc.gov/standards/mets/">http://www.loc.gov/standards/mets/</a> * <p> * This is a generic packager framework intended to be subclassed to create * packagers for more specific METS "profiles". METS is an * abstract and flexible framework that can encompass many * different kinds of metadata and inner package structures. * <p> * <b>Package Parameters:</b><br> * <ul> * <li><code>manifestOnly</code> -- if true, generate a standalone XML * document of the METS manifest instead of a complete package. Any * other metadata (such as licenses) will be encoded inline. * Default is <code>false</code>.</li> * * <li><code>unauthorized</code> -- this determines what is done when the * packager encounters a Bundle or Bitstream it is not authorized to * read. By default, it just quits with an AuthorizeException. * If this option is present, it must be one of the following values: * <ul> * <li><code>skip</code> -- simply exclude unreadable content from package.</li> * <li><code>zero</code> -- include unreadable bitstreams as 0-length files; * unreadable Bundles will still cause authorize errors.</li></ul></li> * </ul> * * @author Larry Stone * @author Robert Tansley * @author Tim Donohue * @version $Revision$ */ public abstract class AbstractMETSDisseminator extends AbstractPackageDisseminator { /** log4j category */ private static Logger log = Logger.getLogger(AbstractMETSDisseminator.class); // JDOM xml output writer - indented format for readability. private static XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); // for gensym() private int idCounter = 1; /** * Default date/time (in milliseconds since epoch) to set for Zip Entries * for DSpace Objects which don't have a Last Modified date. If we don't * set our own date/time, then it will default to current system date/time. * This is less than ideal, as it causes the md5 checksum of Zip file to * change whenever Zip is regenerated (even if compressed files are unchanged) * 1036368000 seconds * 1000 = Nov 4, 2002 GMT (the date DSpace 1.0 was released) */ private static final int DEFAULT_MODIFIED_DATE = 1036368000 * 1000; /** * Wrapper for a table of streams to add to the package, such as * mdRef'd metadata. Key is relative pathname of file, value is * <code>InputStream</code> with contents to put in it. Some * superclasses will put streams in this table when adding an mdRef * element to e.g. a rightsMD segment. */ protected static class MdStreamCache { private Map<MdRef,InputStream> extraFiles = new HashMap<MdRef,InputStream>(); public void addStream(MdRef key, InputStream md) { extraFiles.put(key, md); } public Map<MdRef,InputStream> getMap() { return extraFiles; } public void close() throws IOException { for (InputStream is : extraFiles.values()) { is.close(); } } } /** * Make a new unique ID symbol with specified prefix. * @param prefix the prefix of the identifier, constrained to XML ID schema * @return a new string identifier unique in this session (instance). */ protected synchronized String gensym(String prefix) { return prefix + "_" + String.valueOf(idCounter++); } @Override public String getMIMEType(PackageParameters params) { return (params != null && (params.getBooleanProperty("manifestOnly", false))) ? "text/xml" : "application/zip"; } /** * Export the object (Item, Collection, or Community) as a * "package" on the indicated OutputStream. Package is any serialized * representation of the item, at the discretion of the implementing * class. It does not have to include content bitstreams. * <p> * Use the <code>params</code> parameter list to adjust the way the * package is made, e.g. including a "<code>metadataOnly</code>" * parameter might make the package a bare manifest in XML * instead of a Zip file including manifest and contents. * <p> * Throws an exception of the chosen object is not acceptable or there is * a failure creating the package. * * @param context DSpace context. * @param object DSpace object (item, collection, etc) * @param params Properties-style list of options specific to this packager * @param pkgFile File where export package should be written * @throws PackageValidationException if package cannot be created or there is * a fatal error in creating it. */ @Override public void disseminate(Context context, DSpaceObject dso, PackageParameters params, File pkgFile) throws PackageValidationException, CrosswalkException, AuthorizeException, SQLException, IOException { FileOutputStream outStream = null; try { //Make sure our package file exists if(!pkgFile.exists()) { PackageUtils.createFile(pkgFile); } //Open up an output stream to write to package file outStream = new FileOutputStream(pkgFile); // Generate a true manifest-only "package", no external files/data & no need to zip up if (params != null && params.getBooleanProperty("manifestOnly", false)) { Mets manifest = makeManifest(context, dso, params, null); manifest.validate(new MetsValidator()); manifest.write(new MetsWriter(outStream)); } else { // make a Zip-based package writeZipPackage(context, dso, params, outStream); }//end if/else }//end try catch (MetsException e) { + String errorMsg = "Error exporting METS for DSpace Object, type=" + + Constants.typeText[dso.getType()] + ", handle=" + + dso.getHandle() + ", dbID=" + + String.valueOf(dso.getID()); + // We don't pass up a MetsException, so callers don't need to // know the details of the METS toolkit - log.error("METS error: ",e); - throw new PackageValidationException(e); + log.error(errorMsg,e); + throw new PackageValidationException(errorMsg, e); } finally { //Close stream / stop writing to file if (outStream != null) { outStream.close(); } } } /** * Make a Zipped up METS package for the given DSpace Object * * @param context DSpace Context * @param dso The DSpace Object * @param params Parameters to the Packager script * @param pkg Package output stream * @throws PackageValidationException * @throws AuthorizeException * @throws SQLException * @throws IOException */ protected void writeZipPackage(Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg) throws PackageValidationException, CrosswalkException, MetsException, AuthorizeException, SQLException, IOException { long lmTime = 0; if (dso.getType() == Constants.ITEM) { lmTime = ((Item) dso).getLastModified().getTime(); } // map of extra streams to put in Zip (these are located during makeManifest()) MdStreamCache extraStreams = new MdStreamCache(); ZipOutputStream zip = new ZipOutputStream(pkg); zip.setComment("METS archive created by DSpace " + Util.getSourceVersion()); Mets manifest = makeManifest(context, dso, params, extraStreams); // copy extra (metadata, license, etc) bitstreams into zip, update manifest if (extraStreams != null) { for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet()) { MdRef ref = ment.getKey(); // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be // included in our Package (if their bundles are already included in the <filSec> section of manifest). // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>. // (this ensures that we don't accidentally add the same License file to our package twice) linkLicenseRefsToBitstreams(context, params, dso, ref); //If this 'mdRef' is NOT already linked up to a file in the package, // then its file must be missing. So, we are going to add a new // file to the Zip package. if(ref.getXlinkHref()==null || ref.getXlinkHref().isEmpty()) { InputStream is = ment.getValue(); // create a hopefully unique filename within the Zip String fname = gensym("metadata"); // link up this 'mdRef' to point to that file ref.setXlinkHref(fname); if (log.isDebugEnabled()) { log.debug("Writing EXTRA stream to Zip: " + fname); } //actually add the file to the Zip package ZipEntry ze = new ZipEntry(fname); if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } zip.putNextEntry(ze); Utils.copy(is, zip); zip.closeEntry(); is.close(); } } } // write manifest after metadata. ZipEntry me = new ZipEntry(METSManifest.MANIFEST_FILE); if (lmTime != 0) { me.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { me.setTime(DEFAULT_MODIFIED_DATE); } zip.putNextEntry(me); // can only validate now after fixing up extraStreams manifest.validate(new MetsValidator()); manifest.write(new MetsWriter(zip)); zip.closeEntry(); //write any bitstreams associated with DSpace object to zip package addBitstreamsToZip(context, dso, params, zip); zip.close(); } /** * Add Bitstreams associated with a given DSpace Object into an * existing ZipOutputStream * @param context DSpace Context * @param dso The DSpace Object * @param params Parameters to the Packager script * @param zip Zip output */ protected void addBitstreamsToZip(Context context, DSpaceObject dso, PackageParameters params, ZipOutputStream zip) throws PackageValidationException, AuthorizeException, SQLException, IOException { // how to handle unauthorized bundle/bitstream: String unauth = (params == null) ? null : params.getProperty("unauthorized"); // copy all non-meta bitstreams into zip if (dso.getType() == Constants.ITEM) { Item item = (Item)dso; //get last modified time long lmTime = ((Item)dso).getLastModified().getTime(); Bundle bundles[] = item.getBundles(); for (int i = 0; i < bundles.length; i++) { if (includeBundle(bundles[i])) { // unauthorized bundle? if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) { if (unauth != null && (unauth.equalsIgnoreCase("skip"))) { log.warn("Skipping Bundle[\""+bundles[i].getName()+"\"] because you are not authorized to read it."); continue; } else { throw new AuthorizeException("Not authorized to read Bundle named \"" + bundles[i].getName() + "\""); } } Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int k = 0; k < bitstreams.length; k++) { boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[k], Constants.READ); if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) { String zname = makeBitstreamURL(bitstreams[k], params); ZipEntry ze = new ZipEntry(zname); if (log.isDebugEnabled()) { log.debug(new StringBuilder().append("Writing CONTENT stream of bitstream(").append(bitstreams[k].getID()).append(") to Zip: ").append(zname).append(", size=").append(bitstreams[k].getSize()).toString()); } if (lmTime != 0) { ze.setTime(lmTime); } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged { ze.setTime(DEFAULT_MODIFIED_DATE); } ze.setSize(auth ? bitstreams[k].getSize() : 0); zip.putNextEntry(ze); if (auth) { Utils.copy(bitstreams[k].retrieve(), zip); } else { log.warn("Adding zero-length file for Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID()) + ", not authorized for READ."); } zip.closeEntry(); } else if (unauth != null && unauth.equalsIgnoreCase("skip")) { log.warn("Skipping Bitstream, SID="+String.valueOf(bitstreams[k].getSequenceID())+", not authorized for READ."); } else { throw new AuthorizeException("Not authorized to read Bitstream, SID="+String.valueOf(bitstreams[k].getSequenceID())); } } } } } // Coll, Comm just add logo bitstream to content if there is one else if (dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY) { Bitstream logoBs = dso.getType() == Constants.COLLECTION ? ((Collection)dso).getLogo() : ((Community)dso).getLogo(); if (logoBs != null) { String zname = makeBitstreamURL(logoBs, params); ZipEntry ze = new ZipEntry(zname); if (log.isDebugEnabled()) { log.debug("Writing CONTENT stream of bitstream(" + String.valueOf(logoBs.getID()) + ") to Zip: " + zname + ", size=" + String.valueOf(logoBs.getSize())); } ze.setSize(logoBs.getSize()); //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged ze.setTime(DEFAULT_MODIFIED_DATE); zip.putNextEntry(ze); Utils.copy(logoBs.retrieve(), zip); zip.closeEntry(); } } } // set metadata type - if Mdtype.parse() gets exception, // that means it's not in the MDTYPE vocabulary, so use OTHER. protected void setMdType(MdWrap mdWrap, String mdtype) { try { mdWrap.setMDTYPE(Mdtype.parse(mdtype)); } catch (MetsException e) { mdWrap.setMDTYPE(Mdtype.OTHER); mdWrap.setOTHERMDTYPE(mdtype); } } // set metadata type - if Mdtype.parse() gets exception, // that means it's not in the MDTYPE vocabulary, so use OTHER. protected void setMdType(MdRef mdRef, String mdtype) { try { mdRef.setMDTYPE(Mdtype.parse(mdtype)); } catch (MetsException e) { mdRef.setMDTYPE(Mdtype.OTHER); mdRef.setOTHERMDTYPE(mdtype); } } /** * Create an element wrapped around a metadata reference (either mdWrap * or mdRef); i.e. dmdSec, techMd, sourceMd, etc. Checks for * XML-DOM oriented crosswalk first, then if not found looks for * stream crosswalk of the same name. * * @param context DSpace Context * @param dso DSpace Object we are generating METS manifest for * @param mdSecClass class of mdSec (TechMD, RightsMD, DigiProvMD, etc) * @param typeSpec Type of metadata going into this mdSec (e.g. MODS, DC, PREMIS, etc) * @param params the PackageParameters * @param extraStreams list of extra files which need to be added to final dissemination package * * @return mdSec element or null if xwalk returns empty results. * * @throws SQLException * @throws PackageValidationException * @throws CrosswalkException * @throws IOException * @throws AuthorizeException */ protected MdSec makeMdSec(Context context, DSpaceObject dso, Class mdSecClass, String typeSpec, PackageParameters params, MdStreamCache extraStreams) throws SQLException, PackageValidationException, CrosswalkException, IOException, AuthorizeException { try { //create our metadata element (dmdSec, techMd, sourceMd, rightsMD etc.) MdSec mdSec = (MdSec) mdSecClass.newInstance(); mdSec.setID(gensym(mdSec.getLocalName())); String parts[] = typeSpec.split(":", 2); String xwalkName, metsName; //determine the name of the crosswalk to use to generate metadata // for dmdSecs this is the part *after* the colon in the 'type' (see getDmdTypes()) // for all other mdSecs this is usually just corresponds to type name. if (parts.length > 1) { metsName = parts[0]; xwalkName = parts[1]; } else { metsName = typeSpec; xwalkName = typeSpec; } // First, check to see if the crosswalk we are using is a normal DisseminationCrosswalk boolean xwalkFound = PluginManager.hasNamedPlugin(DisseminationCrosswalk.class, xwalkName); if(xwalkFound) { // Find the crosswalk we will be using to generate the metadata for this mdSec DisseminationCrosswalk xwalk = (DisseminationCrosswalk) PluginManager.getNamedPlugin(DisseminationCrosswalk.class, xwalkName); if (xwalk.canDisseminate(dso)) { // Check if our Crosswalk actually wraps another Packager Plugin if(xwalk instanceof AbstractPackagerWrappingCrosswalk) { // If this crosswalk wraps another Packager Plugin, we can pass it our Packaging Parameters // (which essentially allow us to customize the output of the crosswalk) AbstractPackagerWrappingCrosswalk wrapper = (AbstractPackagerWrappingCrosswalk) xwalk; wrapper.setPackagingParameters(params); } //For a normal DisseminationCrosswalk, we will be expecting an XML (DOM) based result. // So, we are going to wrap this XML result in an <mdWrap> element MdWrap mdWrap = new MdWrap(); setMdType(mdWrap, metsName); XmlData xmlData = new XmlData(); if (crosswalkToMetsElement(xwalk, dso, xmlData) != null) { mdWrap.getContent().add(xmlData); mdSec.getContent().add(mdWrap); return mdSec; } else { return null; } } else { return null; } } // If we didn't find the correct crosswalk, we will check to see if this is // a StreamDisseminationCrosswalk -- a Stream crosswalk disseminates to an OutputStream else { StreamDisseminationCrosswalk sxwalk = (StreamDisseminationCrosswalk) PluginManager.getNamedPlugin(StreamDisseminationCrosswalk.class, xwalkName); if (sxwalk != null) { if (sxwalk.canDisseminate(context, dso)) { // Check if our Crosswalk actually wraps another Packager Plugin if(sxwalk instanceof AbstractPackagerWrappingCrosswalk) { // If this crosswalk wraps another Packager Plugin, we can pass it our Packaging Parameters // (which essentially allow us to customize the output of the crosswalk) AbstractPackagerWrappingCrosswalk wrapper = (AbstractPackagerWrappingCrosswalk) sxwalk; wrapper.setPackagingParameters(params); } // Disseminate crosswalk output to an outputstream ByteArrayOutputStream disseminateOutput = new ByteArrayOutputStream(); sxwalk.disseminate(context, dso, disseminateOutput); // Convert output to an inputstream, so we can write to manifest or Zip file ByteArrayInputStream crosswalkedStream = new ByteArrayInputStream(disseminateOutput.toByteArray()); //If we are capturing extra files to put into a Zip package if(extraStreams!=null) { //Create an <mdRef> -- we'll just reference the file by name in Zip package MdRef mdRef = new MdRef(); //add the crosswalked Stream to list of files to add to Zip package later extraStreams.addStream(mdRef, crosswalkedStream); //set properties on <mdRef> // Note, filename will get set on this <mdRef> later, // when we process all the 'extraStreams' mdRef.setMIMETYPE(sxwalk.getMIMEType()); setMdType(mdRef, metsName); mdRef.setLOCTYPE(Loctype.URL); mdSec.getContent().add(mdRef); } else { //If we are *not* capturing extra streams to add to Zip package later, // that means we are likely only generating a METS manifest // (i.e. manifestOnly = true) // In this case, the best we can do is take the crosswalked // Stream, base64 encode it, and add in an <mdWrap> field // First, create our <mdWrap> MdWrap mdWrap = new MdWrap(); mdWrap.setMIMETYPE(sxwalk.getMIMEType()); setMdType(mdWrap, metsName); // Now, create our <binData> and add base64 encoded contents to it. BinData binData = new BinData(); Base64 base64 = new Base64(crosswalkedStream); binData.getContent().add(base64); mdWrap.getContent().add(binData); mdSec.getContent().add(mdWrap); } return mdSec; } else { return null; } } else { throw new PackageValidationException("Cannot find " + xwalkName + " crosswalk plugin, either DisseminationCrosswalk or StreamDisseminationCrosswalk"); } } } catch (InstantiationException e) { throw new PackageValidationException("Error instantiating Mdsec object: "+ e.toString(), e); } catch (IllegalAccessException e) { throw new PackageValidationException("Error instantiating Mdsec object: "+ e.toString(), e); } } // add either a techMd or sourceMd element to amdSec. // mdSecClass determines which type. // mdTypes[] is array of "[metsName:]PluginName" strings, maybe empty. protected void addToAmdSec(AmdSec fAmdSec, String mdTypes[], Class mdSecClass, Context context, DSpaceObject dso, PackageParameters params, MdStreamCache extraStreams) throws SQLException, PackageValidationException, CrosswalkException, IOException, AuthorizeException { for (int i = 0; i < mdTypes.length; ++i) { MdSec md = makeMdSec(context, dso, mdSecClass, mdTypes[i], params, extraStreams); if (md != null) { fAmdSec.getContent().add(md); } } } // Create amdSec for any tech md's, return its ID attribute. protected String addAmdSec(Context context, DSpaceObject dso, PackageParameters params, Mets mets, MdStreamCache extraStreams) throws SQLException, PackageValidationException, CrosswalkException, IOException, AuthorizeException { String techMdTypes[] = getTechMdTypes(context, dso, params); String rightsMdTypes[] = getRightsMdTypes(context, dso, params); String sourceMdTypes[] = getSourceMdTypes(context, dso, params); String digiprovMdTypes[] = getDigiprovMdTypes(context, dso, params); // only bother if there are any sections to add if ((techMdTypes.length+sourceMdTypes.length+ digiprovMdTypes.length+rightsMdTypes.length) > 0) { String result = gensym("amd"); AmdSec fAmdSec = new AmdSec(); fAmdSec.setID(result); addToAmdSec(fAmdSec, techMdTypes, TechMD.class, context, dso, params, extraStreams); addToAmdSec(fAmdSec, rightsMdTypes, RightsMD.class, context, dso, params, extraStreams); addToAmdSec(fAmdSec, sourceMdTypes, SourceMD.class, context, dso, params, extraStreams); addToAmdSec(fAmdSec, digiprovMdTypes, DigiprovMD.class, context, dso, params, extraStreams); mets.getContent().add(fAmdSec); return result; } else { return null; } } // make the most "persistent" identifier possible, preferably a URN // based on the Handle. protected String makePersistentID(DSpaceObject dso) { String handle = dso.getHandle(); // If no Handle, punt to much-less-satisfactory database ID and type.. if (handle == null) { return "DSpace_DB_" + Constants.typeText[dso.getType()] + "_" + String.valueOf(dso.getID()); } else { return getHandleURN(handle); } } /** * Write out a METS manifest. * Mostly lifted from Rob Tansley's METS exporter. */ protected Mets makeManifest(Context context, DSpaceObject dso, PackageParameters params, MdStreamCache extraStreams) throws MetsException, PackageValidationException, CrosswalkException, AuthorizeException, SQLException, IOException { // Create the METS manifest in memory Mets mets = new Mets(); String identifier = "DB-ID-" + dso.getID(); if(dso.getHandle()!=null) { identifier = dso.getHandle().replace('/', '-'); } // this ID should be globally unique (format: DSpace_[objType]_[handle with slash replaced with a dash]) mets.setID("DSpace_" + Constants.typeText[dso.getType()] + "_" + identifier); // identifies the object described by this document mets.setOBJID(makePersistentID(dso)); mets.setTYPE(getObjectTypeString(dso)); // this is the signature by which the ingester will recognize // a document it can expect to interpret. mets.setPROFILE(getProfile()); MetsHdr metsHdr = makeMetsHdr(context, dso, params); if (metsHdr != null) { mets.getContent().add(metsHdr); } // add DMD sections // Each type element MAY be either just a MODS-and-crosswalk name, OR // a combination "MODS-name:crosswalk-name" (e.g. "DC:qDC"). String dmdTypes[] = getDmdTypes(context, dso, params); // record of ID of each dmdsec to make DMDID in structmap. String dmdId[] = new String[dmdTypes.length]; for (int i = 0; i < dmdTypes.length; ++i) { MdSec dmdSec = makeMdSec(context, dso, DmdSec.class, dmdTypes[i], params, extraStreams); if (dmdSec != null) { mets.getContent().add(dmdSec); dmdId[i] = dmdSec.getID(); } } // add object-wide technical/source MD segments, get ID string: // Put that ID in ADMID of first div in structmap. String objectAMDID = addAmdSec(context, dso, params, mets, extraStreams); // Create simple structMap: initial div represents the Object's // contents, its children are e.g. Item bitstreams (content only), // Collection's members, or Community's members. StructMap structMap = new StructMap(); structMap.setID(gensym("struct")); structMap.setTYPE("LOGICAL"); structMap.setLABEL("DSpace Object"); Div div0 = new Div(); div0.setID(gensym("div")); div0.setTYPE("DSpace Object Contents"); structMap.getContent().add(div0); // fileSec is optional, let object type create it if needed. FileSec fileSec = null; // Item-specific manifest - license, bitstreams as Files, etc. if (dso.getType() == Constants.ITEM) { // this tags file ID and group identifiers for bitstreams. String bitstreamIDstart = "bitstream_"; Item item = (Item)dso; // how to handle unauthorized bundle/bitstream: String unauth = (params == null) ? null : params.getProperty("unauthorized"); // fileSec - all non-metadata bundles go into fileGrp, // and each bitstream therein into a file. // Create the bitstream-level techMd and div's for structmap // at the same time so we can connect the IDREFs to IDs. fileSec = new FileSec(); Bundle[] bundles = item.getBundles(); for (int i = 0; i < bundles.length; i++) { if (!includeBundle(bundles[i])) { continue; } // unauthorized bundle? // NOTE: This must match the logic in disseminate() if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) { if (unauth != null && (unauth.equalsIgnoreCase("skip"))) { continue; } else { throw new AuthorizeException("Not authorized to read Bundle named \"" + bundles[i].getName() + "\""); } } Bitstream[] bitstreams = bundles[i].getBitstreams(); // Create a fileGrp, USE = permuted Bundle name FileGrp fileGrp = new FileGrp(); String bName = bundles[i].getName(); if ((bName != null) && !bName.equals("")) { fileGrp.setUSE(bundleToFileGrp(bName)); } // add technical metadata for a bundle String techBundID = addAmdSec(context, bundles[i], params, mets, extraStreams); if (techBundID != null) { fileGrp.setADMID(techBundID); } // watch for primary bitstream int primaryBitstreamID = -1; boolean isContentBundle = false; if ((bName != null) && bName.equals("ORIGINAL")) { isContentBundle = true; primaryBitstreamID = bundles[i].getPrimaryBitstreamID(); } // For each bitstream, add to METS manifest for (int bits = 0; bits < bitstreams.length; bits++) { // Check for authorization. Handle unauthorized // bitstreams to match the logic in disseminate(), // i.e. "unauth=zero" means include a 0-length bitstream, // "unauth=skip" means to ignore it (and exclude from // manifest). boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[bits], Constants.READ); if (!auth) { if (unauth != null && unauth.equalsIgnoreCase("skip")) { continue; } else if (!(unauth != null && unauth.equalsIgnoreCase("zero"))) { throw new AuthorizeException("Not authorized to read Bitstream, SID=" + String.valueOf(bitstreams[bits].getSequenceID())); } } String sid = String.valueOf(bitstreams[bits].getSequenceID()); String fileID = bitstreamIDstart + sid; edu.harvard.hul.ois.mets.File file = new edu.harvard.hul.ois.mets.File(); file.setID(fileID); file.setSEQ(bitstreams[bits].getSequenceID()); fileGrp.getContent().add(file); // set primary bitstream in structMap if (bitstreams[bits].getID() == primaryBitstreamID) { Fptr fptr = new Fptr(); fptr.setFILEID(fileID); div0.getContent().add(0, fptr); } // if this is content, add to structmap too: if (isContentBundle) { div0.getContent().add(makeFileDiv(fileID, getObjectTypeString(bitstreams[bits]))); } /* * If we're in THUMBNAIL or TEXT bundles, the bitstream is * extracted text or a thumbnail, so we use the name to work * out which bitstream to be in the same group as */ String groupID = "GROUP_" + bitstreamIDstart + sid; if ((bundles[i].getName() != null) && (bundles[i].getName().equals("THUMBNAIL") || bundles[i].getName().startsWith("TEXT"))) { // Try and find the original bitstream, and chuck the // derived bitstream in the same group Bitstream original = findOriginalBitstream(item, bitstreams[bits]); if (original != null) { groupID = "GROUP_" + bitstreamIDstart + original.getSequenceID(); } } file.setGROUPID(groupID); file.setMIMETYPE(bitstreams[bits].getFormat().getMIMEType()); file.setSIZE(auth ? bitstreams[bits].getSize() : 0); // Translate checksum and type to METS String csType = bitstreams[bits].getChecksumAlgorithm(); String cs = bitstreams[bits].getChecksum(); if (auth && cs != null && csType != null) { try { file.setCHECKSUMTYPE(Checksumtype.parse(csType)); file.setCHECKSUM(cs); } catch (MetsException e) { log.warn("Cannot set bitstream checksum type="+csType+" in METS."); } } // FLocat: point to location of bitstream contents. FLocat flocat = new FLocat(); flocat.setLOCTYPE(Loctype.URL); flocat.setXlinkHref(makeBitstreamURL(bitstreams[bits], params)); file.getContent().add(flocat); // technical metadata for bitstream String techID = addAmdSec(context, bitstreams[bits], params, mets, extraStreams); if (techID != null) { file.setADMID(techID); } } fileSec.getContent().add(fileGrp); } } else if (dso.getType() == Constants.COLLECTION) { ItemIterator ii = ((Collection)dso).getItems(); while (ii.hasNext()) { //add a child <div> for each item in collection Item item = ii.next(); Div childDiv = makeChildDiv(getObjectTypeString(item), item, params); if(childDiv!=null) { div0.getContent().add(childDiv); } } Bitstream logoBs = ((Collection)dso).getLogo(); if (logoBs != null) { fileSec = new FileSec(); addLogoBitstream(logoBs, fileSec, div0, params); } } else if (dso.getType() == Constants.COMMUNITY) { // Subcommunities are directly under "DSpace Object Contents" <div>, // but are labeled as Communities. Community subcomms[] = ((Community)dso).getSubcommunities(); for (int i = 0; i < subcomms.length; ++i) { //add a child <div> for each subcommunity in this community Div childDiv = makeChildDiv(getObjectTypeString(subcomms[i]), subcomms[i], params); if(childDiv!=null) { div0.getContent().add(childDiv); } } // Collections are also directly under "DSpace Object Contents" <div>, // but are labeled as Collections. Collection colls[] = ((Community)dso).getCollections(); for (int i = 0; i < colls.length; ++i) { //add a child <div> for each collection in this community Div childDiv = makeChildDiv(getObjectTypeString(colls[i]), colls[i], params); if(childDiv!=null) { div0.getContent().add(childDiv); } } //add Community logo bitstream Bitstream logoBs = ((Community)dso).getLogo(); if (logoBs != null) { fileSec = new FileSec(); addLogoBitstream(logoBs, fileSec, div0, params); } } else if (dso.getType() == Constants.SITE) { // This is a site-wide <structMap>, which just lists the top-level // communities. Each top level community is referenced by a div. Community comms[] = Community.findAllTop(context); for (int i = 0; i < comms.length; ++i) { //add a child <div> for each top level community in this site Div childDiv = makeChildDiv(getObjectTypeString(comms[i]), comms[i], params); if(childDiv!=null) { div0.getContent().add(childDiv); } } } //Only add the <fileSec> to the METS file if it has content. A <fileSec> must have content. if (fileSec != null && fileSec.getContent()!=null && !fileSec.getContent().isEmpty()) { mets.getContent().add(fileSec); } mets.getContent().add(structMap); // set links to metadata for object -- after type-specific // code since that can add to the object metadata. StringBuilder dmdIds = new StringBuilder(); for (String currdmdId : dmdId) { dmdIds.append(" ").append(currdmdId); } div0.setDMDID(dmdIds.substring(1)); if (objectAMDID != null) { div0.setADMID(objectAMDID); } // Does subclass have something to add to structMap? addStructMap(context, dso, params, mets); return mets; } // Install logo bitstream into METS for Community, Collection. // Add a file element, and refer to it from an fptr in the first div // of the main structMap. protected void addLogoBitstream(Bitstream logoBs, FileSec fileSec, Div div0, PackageParameters params) { edu.harvard.hul.ois.mets.File file = new edu.harvard.hul.ois.mets.File(); String fileID = gensym("logo"); file.setID(fileID); file.setMIMETYPE(logoBs.getFormat().getMIMEType()); file.setSIZE(logoBs.getSize()); // Translate checksum and type to METS String csType = logoBs.getChecksumAlgorithm(); String cs = logoBs.getChecksum(); if (cs != null && csType != null) { try { file.setCHECKSUMTYPE(Checksumtype.parse(csType)); file.setCHECKSUM(cs); } catch (MetsException e) { log.warn("Cannot set bitstream checksum type="+csType+" in METS."); } } //Create <fileGroup USE="LOGO"> with a <FLocat> pointing at bitstream FLocat flocat = new FLocat(); flocat.setLOCTYPE(Loctype.URL); flocat.setXlinkHref(makeBitstreamURL(logoBs, params)); file.getContent().add(flocat); FileGrp fileGrp = new FileGrp(); fileGrp.setUSE("LOGO"); fileGrp.getContent().add(file); fileSec.getContent().add(fileGrp); // add fptr directly to div0 of structMap Fptr fptr = new Fptr(); fptr.setFILEID(fileID); div0.getContent().add(0, fptr); } // create <div> element pointing to a file protected Div makeFileDiv(String fileID, String type) { Div div = new Div(); div.setID(gensym("div")); div.setTYPE(type); Fptr fptr = new Fptr(); fptr.setFILEID(fileID); div.getContent().add(fptr); return div; } /** * Create a <div> element with <mptr> which references a child * object via its handle (and via a local file name, when recursively disseminating * all child objects). * @param type - type attr value for the <div> * @param dso - object for which to create the div * @param params * @return */ protected Div makeChildDiv(String type, DSpaceObject dso, PackageParameters params) { String handle = dso.getHandle(); //start <div> Div div = new Div(); div.setID(gensym("div")); div.setTYPE(type); boolean emptyDiv = true; //make sure we have a handle if (handle == null || handle.length()==0) { log.warn("METS Disseminator is skipping "+type+" without handle: " + dso.toString()); } else { //create <mptr> with handle reference Mptr mptr = new Mptr(); mptr.setID(gensym("mptr")); mptr.setLOCTYPE(Loctype.HANDLE); mptr.setXlinkHref(handle); div.getContent().add(mptr); emptyDiv=false; } // Check to see if this is a recursive dissemination (i.e. disseminating children METS packages) // if so, we want a direct reference to the eventual child METS file if(params.recursiveModeEnabled()) { //determine file extension of child references, //based on whether we are exporting just a manifest or a full Zip pkg String childFileExtension = (params.getBooleanProperty("manifestOnly", false)) ? "xml" : "zip"; //create <mptr> with file-name reference to child package Mptr mptr2 = new Mptr(); mptr2.setID(gensym("mptr")); mptr2.setLOCTYPE(Loctype.URL); //we get the name of the child package from the Packager -- as it is what will actually create this child pkg file mptr2.setXlinkHref(PackageUtils.getPackageName(dso, childFileExtension)); div.getContent().add(mptr2); emptyDiv=false; } if(emptyDiv) { return null; } else { return div; } } // put handle in canonical URN format -- note that HandleManager's // canonicalize currently returns HTTP URL format. protected String getHandleURN(String handle) { if (handle.startsWith("hdl:")) { return handle; } return "hdl:"+handle; } /** * For a bitstream that's a thumbnail or extracted text, find the * corresponding bitstream it was derived from, in the ORIGINAL bundle. * * @param item * the item we're dealing with * @param derived * the derived bitstream * * @return the corresponding original bitstream (or null) */ protected static Bitstream findOriginalBitstream(Item item, Bitstream derived) throws SQLException { Bundle[] bundles = item.getBundles(); // Filename of original will be filename of the derived bitstream // minus the extension (last 4 chars - .jpg or .txt) String originalFilename = derived.getName().substring(0, derived.getName().length() - 4); // First find "original" bundle for (int i = 0; i < bundles.length; i++) { if ((bundles[i].getName() != null) && bundles[i].getName().equals("ORIGINAL")) { // Now find the corresponding bitstream Bitstream[] bitstreams = bundles[i].getBitstreams(); for (int bsnum = 0; bsnum < bitstreams.length; bsnum++) { if (bitstreams[bsnum].getName().equals(originalFilename)) { return bitstreams[bsnum]; } } } } // Didn't find it return null; } // Get result from crosswalk plugin and add it to the document, // including namespaces and schema. // returns the new/modified element upon success. private MetsElement crosswalkToMetsElement(DisseminationCrosswalk xwalk, DSpaceObject dso, MetsElement me) throws CrosswalkException, IOException, SQLException, AuthorizeException { try { // add crosswalk's namespaces and schemaLocation to this element: String raw = xwalk.getSchemaLocation(); String sloc[] = raw == null ? null : raw.split("\\s+"); Namespace ns[] = xwalk.getNamespaces(); for (int i = 0; i < ns.length; ++i) { String uri = ns[i].getURI(); if (sloc != null && sloc.length > 1 && uri.equals(sloc[0])) { me.setSchema(ns[i].getPrefix(), uri, sloc[1]); } else { me.setSchema(ns[i].getPrefix(), uri); } } // add result of crosswalk PreformedXML pXML = null; if (xwalk.preferList()) { List<Element> res = xwalk.disseminateList(dso); if (!(res == null || res.isEmpty())) { pXML = new PreformedXML(outputter.outputString(res)); } } else { Element res = xwalk.disseminateElement(dso); if (res != null) { pXML = new PreformedXML(outputter.outputString(res)); } } if (pXML != null) { me.getContent().add(pXML); return me; } return null; } catch (CrosswalkObjectNotSupported e) { // ignore this xwalk if object is unsupported. if (log.isDebugEnabled()) { log.debug("Skipping MDsec because of CrosswalkObjectNotSupported: dso=" + dso.toString() + ", xwalk=" + xwalk.getClass().getName()); } return null; } } /** * Cleanup our license file reference links, as Deposit Licenses & CC Licenses can be * added two ways (and we only want to add them to zip package *once*): * (1) Added as a normal Bitstream (assuming LICENSE and CC_LICENSE bundles will be included in pkg) * (2) Added via a 'rightsMD' crosswalk (as they are rights information/metadata on an Item) * <p> * So, if they are being added by *both*, then we want to just link the rightsMD <mdRef> entry so * that it points to the Bitstream location. This implementation is a bit 'hackish', but it's * the best we can do, as the Harvard METS API doesn't allow us to go back and crawl an entire * METS file to look for these inconsistencies/duplications. * * @param context current DSpace Context * @param params current Packager Parameters * @param dso current DSpace Object * @param ref the rightsMD <mdRef> element * @throws SQLException * @throws IOException * @throws AuthorizeException */ protected void linkLicenseRefsToBitstreams(Context context, PackageParameters params, DSpaceObject dso, MdRef mdRef) throws SQLException, IOException, AuthorizeException { //If this <mdRef> is a reference to a DSpace Deposit License if(mdRef.getMDTYPE()!=null && mdRef.getMDTYPE()==Mdtype.OTHER && mdRef.getOTHERMDTYPE()!=null && mdRef.getOTHERMDTYPE().equals("DSpaceDepositLicense")) { //Locate the LICENSE bundle Item i = (Item)dso; Bundle license[] = i.getBundles(Constants.LICENSE_BUNDLE_NAME); //Are we already including the LICENSE bundle's bitstreams in this package? if(license!=null && license.length>0 && includeBundle(license[0])) { //Since we are including the LICENSE bitstreams, lets find our LICENSE bitstream path & link to it. Bitstream licenseBs = PackageUtils.findDepositLicense(context, (Item)dso); mdRef.setXlinkHref(makeBitstreamURL(licenseBs, params)); } } //If this <mdRef> is a reference to a Creative Commons Textual License else if(mdRef.getMDTYPE() != null && mdRef.getMDTYPE() == Mdtype.OTHER && mdRef.getOTHERMDTYPE()!=null && mdRef.getOTHERMDTYPE().equals("CreativeCommonsText")) { //Locate the CC-LICENSE bundle Item i = (Item)dso; Bundle license[] = i.getBundles(CreativeCommons.CC_BUNDLE_NAME); //Are we already including the CC-LICENSE bundle's bitstreams in this package? if(license!=null && license.length>0 && includeBundle(license[0])) { //Since we are including the CC-LICENSE bitstreams, lets find our CC-LICENSE (textual) bitstream path & link to it. Bitstream ccText = CreativeCommons.getLicenseTextBitstream(i); mdRef.setXlinkHref(makeBitstreamURL(ccText, params)); } } //If this <mdRef> is a reference to a Creative Commons RDF License else if(mdRef.getMDTYPE() != null && mdRef.getMDTYPE() == Mdtype.OTHER && mdRef.getOTHERMDTYPE()!=null && mdRef.getOTHERMDTYPE().equals("CreativeCommonsRDF")) { //Locate the CC-LICENSE bundle Item i = (Item)dso; Bundle license[] = i.getBundles(CreativeCommons.CC_BUNDLE_NAME); //Are we already including the CC-LICENSE bundle's bitstreams in this package? if(license!=null && license.length>0 && includeBundle(license[0])) { //Since we are including the CC-LICENSE bitstreams, lets find our CC-LICENSE (RDF) bitstream path & link to it. Bitstream ccRdf = CreativeCommons.getLicenseRdfBitstream(i); mdRef.setXlinkHref(makeBitstreamURL(ccRdf, params)); } } } /** * Build a string which will be used as the "Type" of this object in * the METS manifest. * <P> * Default format is "DSpace [Type-as-string]". * * @param dso DSpaceObject to create type-string for * @return a string which will represent this object Type in METS * @see org.dspace.core.Constants */ public String getObjectTypeString(DSpaceObject dso) { //Format: "DSpace <Type-as-string>" (e.g. "DSpace ITEM", "DSpace COLLECTION", etc) return "DSpace " + Constants.typeText[dso.getType()]; } /** * Returns a user help string which should describe the * additional valid command-line options that this packager * implementation will accept when using the <code>-o</code> or * <code>--option</code> flags with the Packager script. * * @return a string describing additional command-line options available * with this packager */ + @Override public String getParameterHelp() { return "* manifestOnly=[boolean] " + "If true, only export the METS manifest (mets.xml) and don't export content files (defaults to false)." + "\n\n" + "* unauthorized=[value] " + "If 'skip', skip over any files which the user doesn't have authorization to read. " + "If 'zero', create a zero-length file for any files the user doesn't have authorization to read. " + "By default, an AuthorizationException will be thrown for any files the user cannot read."; } /** * Return identifier for bitstream in an Item; when making a package, * this is the archive member name (e.g. in Zip file). In a bare * manifest, it might be an external URL. The name should be in URL * format ("file:" may be elided for in-archive filenames). It should * be deterministic, since this gets called twice for each bitstream * when building archive. */ public abstract String makeBitstreamURL(Bitstream bitstream, PackageParameters params); /** * Create metsHdr element - separate so subclasses can override. */ public abstract MetsHdr makeMetsHdr(Context context, DSpaceObject dso, PackageParameters params); /** * Returns name of METS profile to which this package conforms, e.g. * "DSpace METS DIP Profile 1.0" * @return string name of profile. */ public abstract String getProfile(); /** * Returns fileGrp's USE attribute value corresponding to a DSpace bundle name. * * @param bname name of DSpace bundle. * @return string name of fileGrp */ public abstract String bundleToFileGrp(String bname); /** * Get the types of Item-wide DMD to include in package. * Each element of the returned array is a String, which * MAY be just a simple name, naming both the Crosswalk Plugin and * the METS "MDTYPE", <em>or</em> a colon-separated pair consisting of * the METS name followed by a colon and the Crosswalk Plugin name. * E.g. the type string <code>"DC:qualifiedDublinCore"</code> tells it to * create a METS section with <code>MDTYPE="DC"</code> and use the plugin * named "qualifiedDublinCore" to obtain the data. * @param params the PackageParameters passed to the disseminator. * @return array of metadata type strings, never null. */ public abstract String [] getDmdTypes(Context context, DSpaceObject dso, PackageParameters params) throws SQLException, IOException, AuthorizeException; /** * Get the type string of the technical metadata to create for each * object and each Bitstream in an Item. The type string may be a * simple name or colon-separated compound as specified for * <code>getDmdTypes()</code> above. * @param params the PackageParameters passed to the disseminator. * @return array of metadata type strings, never null. */ public abstract String[] getTechMdTypes(Context context, DSpaceObject dso, PackageParameters params) throws SQLException, IOException, AuthorizeException; /** * Get the type string of the source metadata to create for each * object and each Bitstream in an Item. The type string may be a * simple name or colon-separated compound as specified for * <code>getDmdTypes()</code> above. * @param params the PackageParameters passed to the disseminator. * @return array of metadata type strings, never null. */ public abstract String[] getSourceMdTypes(Context context, DSpaceObject dso, PackageParameters params) throws SQLException, IOException, AuthorizeException; /** * Get the type string of the "digiprov" (digital provenance) * metadata to create for each object and each Bitstream in an Item. * The type string may be a simple name or colon-separated compound * as specified for <code>getDmdTypes()</code> above. * * @param params the PackageParameters passed to the disseminator. * @return array of metadata type strings, never null. */ public abstract String[] getDigiprovMdTypes(Context context, DSpaceObject dso, PackageParameters params) throws SQLException, IOException, AuthorizeException; /** * Get the type string of the "rights" (permission and/or license) * metadata to create for each object and each Bitstream in an Item. * The type string may be a simple name or colon-separated compound * as specified for <code>getDmdTypes()</code> above. * * @param params the PackageParameters passed to the disseminator. * @return array of metadata type strings, never null. */ public abstract String[] getRightsMdTypes(Context context, DSpaceObject dso, PackageParameters params) throws SQLException, IOException, AuthorizeException; /** * Add any additional <code>structMap</code> elements to the * METS document, as required by this subclass. A simple default * structure map which fulfills the minimal DSpace METS DIP/SIP * requirements is already present, so this does not need to do anything. * @param mets the METS document to which to add structMaps */ public abstract void addStructMap(Context context, DSpaceObject dso, PackageParameters params, Mets mets) throws SQLException, IOException, AuthorizeException, MetsException; /** * @return true when this bundle should be included as "content" * in the package.. e.g. DSpace SIP does not include metadata bundles. */ public abstract boolean includeBundle(Bundle bundle); }
false
false
null
null
diff --git a/src/Code/ChessTable.java b/src/Code/ChessTable.java index ca0883f..e790af9 100644 --- a/src/Code/ChessTable.java +++ b/src/Code/ChessTable.java @@ -1,750 +1,750 @@ package Code; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JPanel; public class ChessTable { private PieceLabel[] table; private String[] log; private PieceLabel[][] twoTable; public ChessTable() { this.table = new PieceLabel[64]; this.log = new String[2]; this.twoTable = new PieceLabel[8][8]; } public void updateTable(PieceLabel piece, int indeks) { table[indeks] = piece; } public void newTable(PieceLabel[] table2){ table = table2; } public PieceLabel[] getTable(){ return table; } public void testTwoTable() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (twoTable[i][j] instanceof PieceLabel) { System.out.println("i: " + i + " j: " + j + " " + twoTable[i][j].getPiece()); } } } } public void updateTwoTable() { int a = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { twoTable[i][j] = table[a]; a++; } } } public void updateLog(String log2, int indeks) { log[indeks] = log2; } public String getLog(int index) { return log[index]; } public Component getTable(int index) { if (table[index] instanceof PieceLabel) { return table[index]; } else { JPanel square = new JPanel(new BorderLayout()); square.setOpaque(false); return square; } } public void reset() { for (int i = 0; i < table.length; i++) { table[i] = null; } } public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { - table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassW.png"))); + table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolW.png"))); } if (table[i].getPiece() instanceof BishopB) { - table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassB.png"))); + table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } } public boolean checkW(int i) { if (checkBishopW(i)) { System.out.println("Bishop"); return true; } if (checkRookW(i)) { System.out.println("ROOK"); return true; } if (checkKnightW(i)) { System.out.println("KNIGHT"); return true; } if (checkPawnW(i)) { System.out.println("PAWN"); return true; } if (checkKingW(i)) { System.out.println("KING"); return true; } return false; } public boolean checkB(int i) { if (checkBishopB(i)) { System.out.println("Bishop"); return true; } if (checkRookB(i)) { System.out.println("ROOK"); return true; } if (checkKnightB(i)) { System.out.println("KNIGHT"); return true; } if (checkPawnB(i)) { System.out.println("PAWN"); return true; } if (checkKingB(i)) { System.out.println("KING"); return true; } return false; } public boolean checkKnightW(int i) { if ((i + 15) <= 63 && (i + 15) >= 0) { if (table[i + 15] instanceof PieceLabel) { if (table[i + 15].getPiece() instanceof KnightB) { return true; } } } if ((i + 6) <= 63 && (i + 6) >= 0) { if (table[i + 6] instanceof PieceLabel) { if (table[i + 6].getPiece() instanceof KnightB) { return true; } } } if ((i - 10) <= 63 && (i + -10) >= 0) { if (table[i - 10] instanceof PieceLabel) { if (table[i - 10].getPiece() instanceof KnightB) { return true; } } } if ((i - 17) <= 63 && (i - 17) >= 0) { if (table[i - 17] instanceof PieceLabel) { if (table[i - 17].getPiece() instanceof KnightB) { return true; } } } if ((i - 15) <= 63 && (i - 15) >= 0) { if (table[i - 15] instanceof PieceLabel) { if (table[i - 15].getPiece() instanceof KnightB) { return true; } } } if ((i + 10) <= 63 && (i + 10) >= 0) { if (table[i + 10] instanceof PieceLabel) { if (table[i + 10].getPiece() instanceof KnightB) { return true; } } } if ((i + 17) <= 63 && (i + 17) >= 0) { if (table[i + 17] instanceof PieceLabel) { if (table[i + 17].getPiece() instanceof KnightB) { return true; } } } if ((i - 6) <= 63 && (i - 6) >= 0) { if (table[i - 6] instanceof PieceLabel) { if (table[i - 6].getPiece() instanceof KnightB) { return true; } } } return false; } public boolean checkPawnW(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof PawnB) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof PawnB) { return true; } } } return false; } public boolean checkRookW(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } for (int j = b; j < 8; j++) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookB || twoTable[a][j].getPiece() instanceof QueenB) { return true; } if ((twoTable[a][j].getPiece() instanceof RookB) == false && (twoTable[a][j].getPiece() instanceof KingW) == false) { break; } } } for (int j = b; j >= 0; j--) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookB || twoTable[a][j].getPiece() instanceof QueenB) { return true; } if ((twoTable[a][j].getPiece() instanceof RookB) == false && (twoTable[a][j].getPiece() instanceof KingW) == false) { break; } } } for (int j = a; j < 8; j++) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookB || twoTable[j][b].getPiece() instanceof QueenB) { return true; } if ((twoTable[j][b].getPiece() instanceof RookB) == false && (twoTable[j][b].getPiece() instanceof KingW) == false) { break; } } } for (int j = a; j >= 0; j--) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookB || twoTable[j][b].getPiece() instanceof QueenB) { return true; } if ((twoTable[j][b].getPiece() instanceof RookB) == false && (twoTable[j][b].getPiece() instanceof KingW) == false) { break; } } } return false; } public boolean checkBishopW(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } int c = a; int d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c > 0 && d > 0) { c--; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c < 7 && d < 7) { c++; d++; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c < 7 && d > 0) { c++; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopB || twoTable[c][d].getPiece() instanceof QueenB) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopB) == false && (twoTable[c][d].getPiece() instanceof KingW) == false) { break; } } if (c > 0 && d < 7) { c--; d++; } } return false; } public boolean checkKingW(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof KingB) { return true; } } } if ((i - 8) <= 63 && (i - 8) >= 0) { if (table[i - 8] instanceof PieceLabel) { if (table[i - 8].getPiece() instanceof KingB) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof KingB) { return true; } } } if ((i - 1) <= 63 && (i - 1) >= 0) { if (table[i - 1] instanceof PieceLabel) { if (table[i - 1].getPiece() instanceof KingB) { return true; } } } if ((i + 1) <= 63 && (i + 1) >= 0) { if (table[i + 1] instanceof PieceLabel) { if (table[i + 1].getPiece() instanceof KingB) { return true; } } } if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof KingB) { return true; } } } if ((i + 8) <= 63 && (i + 8) >= 0) { if (table[i + 8] instanceof PieceLabel) { if (table[i + 8].getPiece() instanceof KingB) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof KingB) { return true; } } } return false; } public boolean checkKnightB(int i) { if ((i + 15) <= 63 && (i + 15) >= 0) { if (table[i + 15] instanceof PieceLabel) { if (table[i + 15].getPiece() instanceof KnightW) { return true; } } } if ((i + 6) <= 63 && (i + 6) >= 0) { if (table[i + 6] instanceof PieceLabel) { if (table[i + 6].getPiece() instanceof KnightW) { return true; } } } if ((i - 10) <= 63 && (i + -10) >= 0) { if (table[i - 10] instanceof PieceLabel) { if (table[i - 10].getPiece() instanceof KnightW) { return true; } } } if ((i - 17) <= 63 && (i - 17) >= 0) { if (table[i - 17] instanceof PieceLabel) { if (table[i - 17].getPiece() instanceof KnightW) { return true; } } } if ((i - 15) <= 63 && (i - 15) >= 0) { if (table[i - 15] instanceof PieceLabel) { if (table[i - 15].getPiece() instanceof KnightW) { return true; } } } if ((i + 10) <= 63 && (i + 10) >= 0) { if (table[i + 10] instanceof PieceLabel) { if (table[i + 10].getPiece() instanceof KnightW) { return true; } } } if ((i + 17) <= 63 && (i + 17) >= 0) { if (table[i + 17] instanceof PieceLabel) { if (table[i + 17].getPiece() instanceof KnightW) { return true; } } } if ((i - 6) <= 63 && (i - 6) >= 0) { if (table[i - 6] instanceof PieceLabel) { if (table[i - 6].getPiece() instanceof KnightW) { return true; } } } return false; } public boolean checkPawnB(int i) { if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof PawnW) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof PawnW) { return true; } } } return false; } public boolean checkRookB(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } for (int j = b; j < 8; j++) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookW || twoTable[a][j].getPiece() instanceof QueenW) { return true; } if ((twoTable[a][j].getPiece() instanceof RookW) == false && (twoTable[a][j].getPiece() instanceof KingB) == false) { break; } } } for (int j = b; j >= 0; j--) { if (twoTable[a][j] instanceof PieceLabel) { if (twoTable[a][j].getPiece() instanceof RookW || twoTable[a][j].getPiece() instanceof QueenW) { return true; } if ((twoTable[a][j].getPiece() instanceof RookW) == false && (twoTable[a][j].getPiece() instanceof KingB) == false) { break; } } } for (int j = a; j < 8; j++) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookW || twoTable[j][b].getPiece() instanceof QueenW) { return true; } if ((twoTable[j][b].getPiece() instanceof RookW) == false && (twoTable[j][b].getPiece() instanceof KingB) == false) { break; } } } for (int j = a; j >= 0; j--) { if (twoTable[j][b] instanceof PieceLabel) { if (twoTable[j][b].getPiece() instanceof RookW || twoTable[j][b].getPiece() instanceof QueenW) { return true; } if ((twoTable[j][b].getPiece() instanceof RookW) == false && (twoTable[j][b].getPiece() instanceof KingB) == false) { break; } } } return false; } public boolean checkBishopB(int i) { int a = 0; int b = 0; if (i > 7) { a = i / 8; b = i - (a * 8); } else { b = i; a = 0; } int c = a; int d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c > 0 && d > 0) { c--; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c < 7 && d < 7) { c++; d++; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c < 7 && d > 0) { c++; d--; } } c = a; d = b; for (int j = 0; j < 8; j++) { if (twoTable[c][d] instanceof PieceLabel) { if (twoTable[c][d].getPiece() instanceof BishopW || twoTable[c][d].getPiece() instanceof QueenW) { return true; } if ((twoTable[c][d].getPiece() instanceof BishopW) == false && (twoTable[c][d].getPiece() instanceof KingB) == false) { break; } } if (c > 0 && d < 7) { c--; d++; } } return false; } public boolean checkKingB(int i) { if ((i - 7) <= 63 && (i - 7) >= 0) { if (table[i - 7] instanceof PieceLabel) { if (table[i - 7].getPiece() instanceof KingW) { return true; } } } if ((i - 8) <= 63 && (i - 8) >= 0) { if (table[i - 8] instanceof PieceLabel) { if (table[i - 8].getPiece() instanceof KingW) { return true; } } } if ((i - 9) <= 63 && (i - 9) >= 0) { if (table[i - 9] instanceof PieceLabel) { if (table[i - 9].getPiece() instanceof KingW) { return true; } } } if ((i - 1) <= 63 && (i - 1) >= 0) { if (table[i - 1] instanceof PieceLabel) { if (table[i - 1].getPiece() instanceof KingW) { return true; } } } if ((i + 1) <= 63 && (i + 1) >= 0) { if (table[i + 1] instanceof PieceLabel) { if (table[i + 1].getPiece() instanceof KingW) { return true; } } } if ((i + 7) <= 63 && (i + 7) >= 0) { if (table[i + 7] instanceof PieceLabel) { if (table[i + 7].getPiece() instanceof KingW) { return true; } } } if ((i + 8) <= 63 && (i + 8) >= 0) { if (table[i + 8] instanceof PieceLabel) { if (table[i + 8].getPiece() instanceof KingW) { return true; } } } if ((i + 9) <= 63 && (i + 9) >= 0) { if (table[i + 9] instanceof PieceLabel) { if (table[i + 9].getPiece() instanceof KingW) { return true; } } } return false; } }
false
true
public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BadassB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } }
public void changeUI(int a) { switch (a) { case 1: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/OkayguyB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/FmercuryB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/TrollfaceB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/YaomingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/LolB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/MegustaB.png"))); } } } break; case 2: for (int i = 0; i < 64; i++) { if (table[i] instanceof PieceLabel) { if (table[i].getPiece() instanceof PawnW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnW.png"))); } if (table[i].getPiece() instanceof PawnB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/PawnB.png"))); } if (table[i].getPiece() instanceof QueenW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenW.png"))); } if (table[i].getPiece() instanceof QueenB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/QueenB.png"))); } if (table[i].getPiece() instanceof KnightW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightW.png"))); } if (table[i].getPiece() instanceof KnightB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KnightB.png"))); } if (table[i].getPiece() instanceof KingW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingW.png"))); } if (table[i].getPiece() instanceof KingB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/KingB.png"))); } if (table[i].getPiece() instanceof BishopW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopW.png"))); } if (table[i].getPiece() instanceof BishopB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/BishopB.png"))); } if (table[i].getPiece() instanceof RookW) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookW.png"))); } if (table[i].getPiece() instanceof RookB) { table[i].setIcon(new ImageIcon(getClass().getResource("/Pictures/RookB.png"))); } } } break; } }
diff --git a/src/com/neuron/trafikanten/tasks/SearchAddressTask.java b/src/com/neuron/trafikanten/tasks/SearchAddressTask.java index 1223548..4d0f517 100644 --- a/src/com/neuron/trafikanten/tasks/SearchAddressTask.java +++ b/src/com/neuron/trafikanten/tasks/SearchAddressTask.java @@ -1,178 +1,179 @@ package com.neuron.trafikanten.tasks; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Message; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.Toast; import com.neuron.trafikanten.R; import com.neuron.trafikanten.dataProviders.IRouteProvider; public class SearchAddressTask extends GenericTask { private static final String TAG = "Trafikanten-SearchAddressTask"; public static final int TASK_SEARCHADDRESS = 106; private static final int DIALOG_SEARCHADDRESS = Menu.FIRST; private List<Address> addresses; public static void StartTask(Activity activity) { final Intent intent = new Intent(activity, SearchAddressTask.class); StartGenericTask(activity, intent, TASK_SEARCHADDRESS); } @Override public int getlayoutId() { return R.layout.dialog_searchaddress; } /* * onCreate for searchAddressTask * Task shows a entry box for writing in an address, then does geo lookup to find the coordinates, and asks provider for data around that point. * @see com.neuron.trafikanten.tasks.GenericTask#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); message.setText(R.string.searchAddressTask); final EditText searchEdit = (EditText) findViewById(R.id.search); searchEdit.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } switch (keyCode) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: geoMap(searchEdit.getText().toString()); return true; } return false; } }); } @Override protected Dialog onCreateDialog(int id) { switch(id) { case DIALOG_SEARCHADDRESS: final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.searchAddressTask); /* * First take all addresses, convert them into strings and check for duplicates. */ ArrayList<String> addressStrings = new ArrayList<String>(); for(Address address : addresses) { Log.d(TAG,"Got address " + address.toString()); String result = address.getAddressLine(0); for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) { result = result + ", " + address.getAddressLine(i); } if (!addressStrings.contains(result)) { addressStrings.add(result); } } /* * Then convert it into the array setItems wants */ final String[] items = new String[addressStrings.size()]; addressStrings.toArray(items); /* * Then search for the address */ builder.setItems(items, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SearchAddressTask.this.foundLocation(addresses.get(which)); } }); AlertDialog dialog = builder.create(); dialog.setOnCancelListener(new OnCancelListener() { /* * OnCancel we should return to previous view. * @see android.content.DialogInterface.OnCancelListener#onCancel(android.content.DialogInterface) */ @Override public void onCancel(DialogInterface dialog) { SearchAddressTask.this.setResult(RESULT_CANCELED, new Intent()); SearchAddressTask.this.finish(); } }); return dialog; } return null; } /* * Do geo mapping. */ private void geoMap(String searchAddress) { setVisible(true); final Geocoder geocoder = new Geocoder(this); try { - addresses = geocoder.getFromLocationName(searchAddress, 10); + // NOTE : These coordinates do NOT cover all of norway. + addresses = geocoder.getFromLocationName(searchAddress, 10, 57, 3, 66, 16); switch(addresses.size()) { case 0: Toast.makeText(getApplicationContext(), R.string.failedToFindAddress, Toast.LENGTH_SHORT).show(); finish(); break; case 1: foundLocation(addresses.get(0)); break; default: showDialog(DIALOG_SEARCHADDRESS); break; } } catch (IOException e) { /* * Pass exceptions to parent */ final Message msg = handler.obtainMessage(IRouteProvider.MESSAGE_EXCEPTION); final Bundle bundle = new Bundle(); bundle.putString(IRouteProvider.KEY_EXCEPTION, e.toString()); msg.setData(bundle); handler.sendMessage(msg); } } private void foundLocation(Address location) { SearchStationTask.StartTask(this, location.getLatitude(), location.getLongitude()); setVisible(false); } /* * Direct passthrough * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { setResult(resultCode, data); finish(); } } diff --git a/src/com/neuron/trafikanten/tasks/SelectContactTask.java b/src/com/neuron/trafikanten/tasks/SelectContactTask.java index 73790d3..a4d58a5 100644 --- a/src/com/neuron/trafikanten/tasks/SelectContactTask.java +++ b/src/com/neuron/trafikanten/tasks/SelectContactTask.java @@ -1,180 +1,180 @@ /** * Copyright (C) 2009 Anders Aagaard <aagaande@gmail.com> * * 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.neuron.trafikanten.tasks; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.neuron.trafikanten.R; import com.neuron.trafikanten.dataProviders.IRouteProvider; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnCancelListener; import android.database.Cursor; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Message; import android.provider.Contacts; import android.util.Log; import android.view.Menu; import android.widget.Toast; public class SelectContactTask extends GenericTask { private static final String TAG = "Trafikanten-SelectContactTask"; public static final int TASK_SELECTCONTACT = 104; private static final int DIALOG_SELECTCONTACT = Menu.FIRST; public static final String KEY_ADDRESS = "address"; public static final String KEY_MESSAGE = "message"; public static void StartTask(Activity activity) { final Intent intent = new Intent(activity, SelectContactTask.class); StartGenericTask(activity, intent, TASK_SELECTCONTACT); } @Override public int getlayoutId() { return R.layout.dialog_progress; } /* * onCreate for selectContactTask. * Task shows contact list, allows user to select a contact, calculates geo position (with loading bar) and returns. * @see com.neuron.trafikanten.tasks.GenericTask#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); message.setText(R.string.searchStationTask); setVisible(false); showDialog(DIALOG_SELECTCONTACT); } private static final String FILTER_POSTAL = Contacts.ContactMethods.KIND + "=" + Contacts.KIND_POSTAL; private static final String[] CONTACTMETHODS_PROJECTION = new String[] { Contacts.People.NAME, Contacts.ContactMethods.DATA }; @Override protected Dialog onCreateDialog(int id) { switch(id) { case DIALOG_SELECTCONTACT: /* * Setup list of names with addresses */ ArrayList<String> nameList = new ArrayList<String>(); final Cursor cursor = managedQuery(Contacts.ContactMethods.CONTENT_URI, CONTACTMETHODS_PROJECTION, FILTER_POSTAL, null, null); while (cursor.moveToNext()) { nameList.add(cursor.getString(0)); } cursor.close(); /* * Setup select contact alert dialog */ final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.selectContact); final String[] items = new String[nameList.size()]; nameList.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { final Cursor cursor = managedQuery(Contacts.ContactMethods.CONTENT_URI, CONTACTMETHODS_PROJECTION, Contacts.People.NAME + " == ? AND " + FILTER_POSTAL, new String[] {items[item]}, null); if (!cursor.moveToNext()) { Log.w(TAG, "Couldn't lookup address for contact after contact selection : " + items[item]); Toast.makeText(SelectContactTask.this, "Failed to lookup contact, this is a bug, report!", Toast.LENGTH_SHORT).show(); return; } dialog.dismiss(); geoMap(cursor.getString(0), cursor.getString(1)); } }); AlertDialog dialog = builder.create(); dialog.setOnCancelListener(new OnCancelListener() { /* * OnCancel we should return to previous view. * @see android.content.DialogInterface.OnCancelListener#onCancel(android.content.DialogInterface) */ @Override public void onCancel(DialogInterface dialog) { SelectContactTask.this.setResult(RESULT_CANCELED, new Intent()); SelectContactTask.this.finish(); } }); return dialog; } return super.onCreateDialog(id); } /* * Do geo mapping. */ private void geoMap(String name, String address) { setVisible(true); final Geocoder geocoder = new Geocoder(this); try { - List<Address> addresses = geocoder.getFromLocationName(address, 2); + List<Address> addresses = geocoder.getFromLocationName(address, 2, 57, 3, 66, 16); switch(addresses.size()) { case 0: Toast.makeText(getApplicationContext(), R.string.failedToFindAddress, Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(getApplicationContext(), R.string.multipleAddressesFound, Toast.LENGTH_SHORT).show(); // Fallthrough default: foundLocation(addresses.get(0)); } } catch (IOException e) { /* * Pass exceptions to parent */ final Message msg = handler.obtainMessage(IRouteProvider.MESSAGE_EXCEPTION); final Bundle bundle = new Bundle(); bundle.putString(IRouteProvider.KEY_EXCEPTION, e.toString()); msg.setData(bundle); handler.sendMessage(msg); } } private void foundLocation(Address location) { setVisible(false); SearchStationTask.StartTask(this, location.getLatitude(), location.getLongitude()); } /* * Direct passthrough * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { setResult(resultCode, data); finish(); } }
false
false
null
null
diff --git a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Grid.java b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Grid.java index 749e5eb..27603a8 100644 --- a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Grid.java +++ b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Grid.java @@ -1,209 +1,209 @@ package com.sixtyfourbitsperminute.crushhour; import java.util.ArrayList; import java.util.HashMap; /** * @author Jonathan Thompson * @author Kelly Croswell * * This class represents the grid of the Rush Hour game, on which vehicles are * located and moved around. */ public class Grid { /** * A Map containing all of the vehicles on the grid and the character that * represents them visually. */ HashMap<Character, Vehicle> vehicles; /** * A list of any previous grids that directly led to the formation of the * current grid. */ ArrayList<Grid> previousGrids; /** * The length (or width, as grids are square) of the grid. */ int gridSize; /** * This is the constructor for this class. It takes in an initial list of * vehicles that are present on the grid, and the size of the grid. * * @param vehicles A HashMap containing the list of vehicles and their characters. * @param gridSize An integer containing the size of the grid. */ public Grid(HashMap<Character, Vehicle> vehicles, int gridSize) { this.vehicles = vehicles; this.gridSize = gridSize; } /** * * * @param object * @return */ public Grid executeMove(Object object) { return null; } /** * This method returns the size of the grid. * @return An int holding the size of the grid. */ public int getGridSize() { return gridSize; } /** * This method returns the map of vehicles on the grid. * @return A HashMap containing the vehicles. */ public HashMap<Character, Vehicle> getVehicles() { return vehicles; } /** * This method returns the list of previous grids associated with the current * grid. * @return An ArrayList of previous grids. */ public ArrayList<Grid> getPreviousGrids() { return previousGrids; } /** * This method sets the previous grids on a current grid. * @param previousGrids An ArrayList containing the previous grids. */ public void setPreviousGrids(ArrayList<Grid> previousGrids) { this.previousGrids = previousGrids; } /** * This method gets a list of all of the Coordinates on the grid that are * covered by one vehicle or another. * @return An ArrayList containing the covered coordinates. */ public ArrayList<Coordinate> getCoveredCoordinates() { ArrayList<Coordinate> coveredCoordinates = new ArrayList<Coordinate>(); for (Character key : getVehicles().keySet()) { coveredCoordinates.addAll(getVehicles().get(key).getCoveredCoordinates()); } return coveredCoordinates; } /** * This method gets a list of all of the Coordinates on the grid that are * covered with the exception of one particular vehicle on the grid. * @param v The vehicle to be excluded from the list of covered coordinates. * @return An ArrayList containing all of the covered coordinates save those * covered by vehicle v. */ public ArrayList<Coordinate> getCoveredCoordinatesExcludingVehicle(Vehicle v) { ArrayList<Coordinate> coveredCoordinates = new ArrayList<Coordinate>(); for (Character key : getVehicles().keySet()) { coveredCoordinates.addAll(getVehicles().get(key).getCoveredCoordinates()); } coveredCoordinates.removeAll(v.getCoveredCoordinates()); return coveredCoordinates; } /** * This is the overridden hash code method for the coordinate class. Implemented * so that .equals() works properly. * @return An integer containing the hash code. */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((previousGrids == null) ? 0 : previousGrids.hashCode()); result = prime * result + ((vehicles == null) ? 0 : vehicles.hashCode()); return result; } /** * This is the overridden equals method for the coordinate class. Implemented * so that two grids can be easily compared for the purpose of eliminating loops. * @return Whether or not two grids are equal. */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Grid other = (Grid) obj; if (previousGrids == null) { if (other.previousGrids != null) return false; } else if (!previousGrids.equals(other.previousGrids)) return false; if (vehicles == null) { if (other.vehicles != null) return false; } else if (!vehicles.equals(other.vehicles)) return false; return true; } /** * This method returns whether or not there is a clear path from the user car * on the grid to the exit spot on the grid, thereby finishing the game. * @return A boolean containing whether or not the path is clear. */ public boolean playerCanExit() { Car player = (Car) vehicles.get('A'); for (int i = player.position.x; i < gridSize; i++) { } return false; } /** * This method turns the list of vehicles associated with a grid into a String * complete with x's for empty spots so that the grid can be handed over to * the GUI for parsing. * @return A String containing the grid. */ public String gridToString () { char[][] result = {{'x', 'x', 'x', 'x', 'x', 'x'}, {'x', 'x', 'x', 'x', 'x', 'x'}, {'x', 'x', 'x', 'x', 'x', 'x'}, {'x', 'x', 'x', 'x', 'x', 'x'}, {'x', 'x', 'x', 'x', 'x', 'x'}, {'x', 'x', 'x', 'x', 'x', 'x'}}; for(char c : this.vehicles.keySet()){ Vehicle current = vehicles.get(c); - System.out.println(c); + //System.out.println(c); ArrayList<Coordinate> coveredPositions = current.getCoveredCoordinates(); - System.out.println("Position x: " + current.getPosition().x + ", Position y: " + current.getPosition().y); - System.out.println("Orientation: " + current.horizontal); + //System.out.println("Position x: " + current.getPosition().x + ", Position y: " + current.getPosition().y); + //System.out.println("Orientation: " + current.horizontal); for(int i = 0; i < coveredPositions.size(); i++){ Coordinate currentCoordinate = coveredPositions.get(i); - System.out.println("x: " + currentCoordinate.x + ", y: " + currentCoordinate.y); + //System.out.println("x: " + currentCoordinate.x + ", y: " + currentCoordinate.y); result[currentCoordinate.x][currentCoordinate.y] = c; } } String resultString = ""; for(int i = 0; i < 6; i++){ for(int j = 0; j < 6; j++){ resultString = resultString + result[j][i]; - System.out.println(resultString); + //System.out.println(resultString); } } return resultString; } } diff --git a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Main.java b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Main.java index 7206913..c7f636b 100644 --- a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Main.java +++ b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Main.java @@ -1,71 +1,72 @@ package com.sixtyfourbitsperminute.crushhour; import java.io.IOException; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Date; import com.illposed.osc.*; /** * @author Jonathan Thompson * @author Kelly Croswell * * This is the main method of the program, where the heavy lifting happens. */ public class Main { /** * @param args */ public static void main(String[] args) { //Communicator communicator = new Communicator(); // if(!communicator.portsAreValid()){ // System.exit(0); // } - String gridString = GridStrings.getGrid(1); + //String gridString = GridStrings.getGrid(1); + String gridString = "bxxcccZbxxdxeZAAxdfeZgggxfeZxxhxiiZjjhkkxZ"; Parser parser = new Parser(gridString); if(parser.fileCanCreateGrid()){ Grid grid = parser.createGrid(); System.out.println("Created grid"); System.out.println(grid.gridToString()); } //send test message // Object payload[] = new Object[1]; // payload[0] = "bbxxxcexxdxceAAdxcexxdxxfxxxggfxhhhx"; // OSCMessage mesg = new OSCMessage("/ch/grid", payload); // try { // sender.send(mesg); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // for(;;){ // try { // Thread.sleep(500); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } } } diff --git a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Parser.java b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Parser.java index 9bd37f9..5f1fd97 100644 --- a/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Parser.java +++ b/CrushHour/src/com/sixtyfourbitsperminute/crushhour/Parser.java @@ -1,411 +1,419 @@ package com.sixtyfourbitsperminute.crushhour; import java.util.HashMap; /** * @author Jonathan Thompson * @author Kelly Croswell * * This method parses a String of text that represents a grid and turns it into * a Grid object if the grid is valid. */ public class Parser { /** * A String containing the unparsed grid. */ String gridString; /** * An array of Strings containing each separated line of the grid. */ String[] gridLines; /** * An int containing the length of the grid. */ int gridSize; /** * A two dimensional array of chars containing the fully separated grid. */ char[][] grid; /** * A HashMap containing the list of potential vehicles on the grid. */ HashMap<Character, Vehicle> vehicleMap = new HashMap<Character, Vehicle>(); /** * This is the constructor for this class which takes in a String containing * a potenial grid and sets it on a global variable. * @param gridString A string containing the unparsed grid. */ public Parser (String gridString){ this.gridString = gridString; } /** * This method returns whether or not the grid is square because only square * grids are valid in this version of the game. * @return A boolean containing whether or not the grid is square. */ public boolean isSquareGrid(){ if(this.gridString.length() == 0){ return false; } String[] gridLines = this.gridString.split("Z"); //System.out.println(gridLines); for(int i = 0; i < gridLines.length; i++){ gridLines[i].trim(); } - if(gridLines[0].length() == gridLines.length){ + if(gridLines[0].length() == gridLines.length && + gridLines[1].length() == gridLines.length && + gridLines[2].length() == gridLines.length && + gridLines[3].length() == gridLines.length && + gridLines[4].length() == gridLines.length && + gridLines[4].length() == gridLines.length){ //System.out.println("Inside if statement in isSquareGrid."); this.gridLines = gridLines; this.gridSize = gridLines.length; readStringInto2DArray(); return true; } else { return false; } } /** * This method reads the previously lines of the grid into a two dimensional * char array, in the global variables. */ public void readStringInto2DArray(){ this.grid = new char[this.gridSize][this.gridSize]; for(int i = 0; i < this.gridSize; i++){ for(int j = 0; j < this.gridSize; j++){ char current = this.gridLines[i].charAt(j); this.grid[i][j] = current; } } } /** * This method checks through every character in the grid to see if it is * a non "empty space" character, then checks to see if that character is * attached to a legal car or truck, then checks to ensure that the vehicle * is not repeated anywhere else on the grid. If, at any point, one of these * conditions is false the method returns false, causing the parse to return * false, meaning the potential grid is invalid. * @return A boolean containing whether or not all of the potential vehicles * are legal. */ public boolean allVehiclesAreLegal(){ for(int row = 0; row < this.gridSize; row++){ for(int column = 0; column < this.gridSize; column++){ char current = this.grid[row][column]; //System.out.println("Current character: " + current + ", and current position: [" + row + ", " + column + "]"); int[] position = {row, column}; char[] neighbors = {'?', '?', '?', '?', '?', '?', '?', '?'}; neighbors = readInNeighbors(neighbors, row, column); //System.out.println(neighbors); if(current == 'x'){ continue; } else { if(isTruck(current, neighbors, position)){ //System.out.println("In Truck if statement"); boolean direction = getDirection(current, neighbors); addVehicleToMap(current, direction, position, 3); } else if(isCar(current, neighbors, position)){ //System.out.println("In car if statement"); boolean direction = getDirection(current, neighbors); addVehicleToMap(current, direction, position, 2); } else { return false; } } } } return true; } /** * This method returns whether the vehicle in question is horizontally placed * or vertically placed on the grid. Returning true is horizontal, false is * vertical. * @param current The character representation of the current vehicle. * @param neighbors The characters immediately surrounding the current char. * @return A boolean containing the vehicle's orientation. */ public boolean getDirection (char current, char[] neighbors){ if(current == neighbors[4] || current == neighbors[6]){ return true; } else { return false; } } /** * This method checks to see if the current character in the grid is part of * a truck on the grid, and whether or not it has a duplicate somewhere. * @param current The current character in the grid. * @param neighbors The characters immediately surrounding the current character. * @param position The position that the current character is at in the array. * @return A boolean containing whether or not the character is part of a truck. */ public boolean isTruck(char current, char[] neighbors, int[] position){ if(current == neighbors[0] && current == neighbors[1]){ int[] positionTwo = {(position[0]-1), position[1]}; int[] positionThree = {(position[0]-2), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 1"); return true; } else { return false; } } else if (current == neighbors[2] && current == neighbors[3]){ int[] positionTwo = {(position[0]+1), position[1]}; int[] positionThree = {(position[0]+2), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 2"); return true; } else { return false; } } else if (current == neighbors[0] && current == neighbors[2]){ int[] positionTwo = {(position[0]-1), position[1]}; int[] positionThree = {(position[0]+1), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 3"); return true; } else { return false; } } else if (current == neighbors[4] && current == neighbors[5]){ int[] positionTwo = {position[0], (position[1]-1)}; int[] positionThree = {position[0], (position[1]-2)}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 4"); return true; } else { return false; } } else if (current == neighbors[6] && current == neighbors[7]){ int[] positionTwo = {position[0], (position[1]+1)}; int[] positionThree = {position[0], (position[1]+2)}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 5"); return true; } else { return false; } } else if (current == neighbors[4] && current == neighbors[6]){ int[] positionTwo = {position[0], (position[1]-1)}; int[] positionThree = {position[0], (position[1]+1)}; if(!letterExistsElsewhere(current, position, positionTwo, positionThree)){ //System.out.println("truck position 6"); return true; } else { return false; } } else { return false; } } /** * This method checks to see if the current character in the grid is part of * a car on the grid, and whether or not it has a duplicate somewhere. * @param current The current character in the grid. * @param neighbors The characters immediately surrounding the current character. * @param position The position that the current character is at in the array. * @return A boolean containing whether or not the character is part of a car. */ public boolean isCar(char current, char[] neighbors, int[] position){ if(current == neighbors[0]){ int[] positionTwo = {(position[0]-1), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 1"); return true; } else { return false; } } else if (current == neighbors[2]){ int[] positionTwo = {(position[0]+1), position[1]}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 2"); return true; } else { return false; } } else if (current == neighbors[4]){ int[] positionTwo = {position[0], (position[1]-1)}; //System.out.println(positionTwo[0] + "," + positionTwo[1]); if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 3"); return true; } else { return false; } } else if (current == neighbors[6]){ int[] positionTwo = {position[0], (position[1]+1)}; if(!letterExistsElsewhere(current, position, positionTwo, null)){ //System.out.println("car position 4"); return true; } else { return false; } } else { return false; } } /** * This method checks to see if the current character exists anywhere else * in the grid except the locations that are part of the potenial vehicle. * If the character does occur elsewhere, then the vehicle is not legal, the * grid is invalid, and the method returns false. * @param current The current character in the grid. * @param positionOne The position that the current character is in on the grid. * @param positionTwo The position of a neighboring character that is part of a * potential car or truck. * @param positionThree The position of a neighboring character that is part of * a potential truck. * @return A boolean containing whether or not the character exists somewhere * else in the grid. */ public boolean letterExistsElsewhere(char current, int[] positionOne, int[] positionTwo, int[] positionThree){ for(int i = 0; i < this.grid.length; i++){ for(int j = 0; j < this.grid.length; j++){ if(positionThree == null){ if((i == positionOne[0] && j == positionOne[1]) || (i == positionTwo[0] && j == positionTwo[1])){ continue; + } else if (this.grid[i][j] == current){ + //System.out.println("Comparing current character to: " + this.grid[i][j]); + return true; } } else if ((i == positionOne[0] && j == positionOne[1]) || (i == positionTwo[0] && j == positionTwo[1]) || (i == positionThree[0] && j == positionThree[1])){ continue; } else { if (this.grid[i][j] == current){ //System.out.println("Comparing current character to: " + this.grid[i][j]); return true; } } } } return false; } /** * This method takes an array of characters set to question marks and fills * it, where they exist, with the neighboring characters of the current grid * position. * @param neighbors The array of characters that are neighbors to the current * position. * @param row An int holding the current row of the position. * @param column An int holding the current column of the position. * @return An array containing the neighbors of the current position. */ public char[] readInNeighbors(char[] neighbors, int row, int column){ if(row-1 >= 0){ neighbors[0] = this.grid[row-1][column]; } if(row-2 >= 0){ neighbors[1] = this.grid[row-2][column]; } if(row+1 < this.gridSize){ neighbors[2] = this.grid[row+1][column]; } if(row+2 < this.gridSize){ neighbors[3] = this.grid[row+2][column]; } if(column-1 >= 0){ neighbors[4] = this.grid[row][column-1]; } if(column-2 >= 0){ neighbors[5] = this.grid[row][column-2]; } if(column+1 < this.gridSize){ neighbors[6] = this.grid[row][column+1]; } if(column+2 < this.gridSize){ neighbors[7] = this.grid[row][column+2]; } return neighbors; } /** * This method adds the newly found vehicle on the grid to the list of vehicles * that have already been found, if it has not already been added. * @param current The current character in the grid. * @param direction The orientation of the newly found vehicle. * @param position The position of the newly found vehicle. * @param length The length of the newly found vehicle. */ public void addVehicleToMap(char current, boolean direction, int[] position, int length){ Vehicle vehicle; if(length == 3){ vehicle = new Truck(direction, position[1], position[0]); } else { vehicle = new Car(direction, position[1], position[0]); } if(!vehicleMap.containsKey(current)){ vehicleMap.put(current, vehicle); } } /** * This method returns the "user" car, or the car that must be escaped from * the grid. * @return A Vehicle containing the User Car. */ public Vehicle findUserCar(){ return vehicleMap.get('A'); } /** * This method checks to ensure that the potential grid has a "user" car, or * the car that must be escaped from the grid. If the grid does nto contain a * User Car, the method returns false and the grid is invalid. * @return A boolean containing whether or not a User Car exists. */ public boolean gridHasUserCar(){ if(vehicleMap.containsKey('A')){ return true; } else { return false; } } /** * This method systemically checks through the grid, using the other methods * in the class, to ensure that the potential grid can greate a valid, legal * Grid object. If any of the previous methods fail, this method fails and * the grid is invalid. * @return A boolean containing the validity of the potential grid. */ public boolean fileCanCreateGrid(){ if(isSquareGrid()){ System.out.println("is square"); if(allVehiclesAreLegal()){ System.out.println("all vehicles legal"); if(gridHasUserCar()){ System.out.println("has user car"); return true; } else { return false; } } else { return false; } } else { return false; } } /** * This method checks to ensure that a valid grid can be created and, if it * can, it creates the grid. * @return The newly created grid. */ public Grid createGrid(){ Grid grid = null; if(fileCanCreateGrid()){ grid = new Grid(this.vehicleMap, this.gridSize); } return grid; } }
false
false
null
null
diff --git a/sos/sos-platform/src/main/java/sorcer/util/exec/ExecUtils.java b/sos/sos-platform/src/main/java/sorcer/util/exec/ExecUtils.java index 520a2f33..9976aec4 100644 --- a/sos/sos-platform/src/main/java/sorcer/util/exec/ExecUtils.java +++ b/sos/sos-platform/src/main/java/sorcer/util/exec/ExecUtils.java @@ -1,457 +1,461 @@ /* * Written by Dawid Kurzyniec and released to the public domain, as explained * at http://creativecommons.org/licenses/publicdomain */ package sorcer.util.exec; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Utility methods to interact with and manage native processes started from * Java. * * @author Dawid Kurzyniec * @author updated for SORCER by Mike Sobolewski */ public class ExecUtils { private ExecUtils() { } /** * Execute specified command and return its results. Waits for the command * to complete and returns its completion status and data written to * standard output and error streams. The process' standard input is set to * EOF. Example: * * <pre> * System.out.println(ExecUtils.execCommand(&quot;/bin/ls&quot;).getOut()); * </pre> * * @param cmd * the command to execute * @return the results of the command execution * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before command completes */ public static CmdResult execCommand(String cmd) throws IOException, InterruptedException { - return execCommand(Runtime.getRuntime().exec(cmd)); + // A workaround to start commands on Windows in a separate cmd process + String os = System.getProperty("os.name"); + if (os.toLowerCase().contains("windows")) + cmd = "cmd /c start " + cmd; + return execCommand(Runtime.getRuntime().exec(cmd)); } /** * Added by E. D. Thompson AFRL/RZTT 20100827 Execute specified command and * it arguments and return its results. Waits for the command to complete * and returns its completion status and data written to standard output and * error streams. The process' standard input is set to EOF. Example: * * <pre> * String[] cmd = { &quot;/bin/ls&quot;, &quot;-lah&quot; }; * System.out.println(ExecUtils.execCommand(cmd).getOut()); * </pre> * * @param cmdarray * the command and arguments to execute * @return the results of the command execution * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before command completes */ public static CmdResult execCommand(String[] cmdarray) throws IOException, InterruptedException { return execCommand(Runtime.getRuntime().exec(cmdarray)); } /** * Attach to the specified process and return its results. Waits for the * process to complete and returns its completion status and data written to * standard output and error streams. The process' standard input is set to * EOF. Example: * * <pre> * Process p = runtime.exec(&quot;/bin/ls&quot;); * System.out.println(ExecUtils.execCommand(p).getOut()); * </pre> * * @param process * the process to attach to * @return the results of the process * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before process ends */ public static CmdResult execCommand(Process process) throws IOException, InterruptedException { return execCommand(process, new NullInputStream()); } /** * Added by E. D. Thompson AFRL/RZTT 20100827 Attach to the specified * process and return its results. Returns data written to standard output * and error streams. The process standard input is set to EOF. Example: * * <pre> * Process p = runtime.exec(&quot;/bin/ls&quot;); * System.out.println(ExecUtils.execCommand(p).getOut()); * </pre> * * @param process * the process to attach to * @return the results of the process * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before process ends */ public static CmdResult execCommandNoBlocking(Process process) throws IOException, InterruptedException { return execCommandNoBlocking(process, new NullInputStream()); } public static CmdResult execCommand(final Process process, final InputStream stdin) throws IOException, InterruptedException { return execCommand(process, stdin, false); } /** * Attach to the specified process, feed specified standard input, and * return process' results. Waits for the process to complete and returns * completion status and data written to standard output and error streams. * * @see #execCommand(Process) * * @param process * the process to attach to * @param stdin * the data to redirect to process' standard input * @return the results of the process * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before process ends */ public static CmdResult execCommand(final Process process, final InputStream stdin, boolean outLogged) throws IOException, InterruptedException { // concurrency to avoid stdio deadlocks Redir stdout = null; String out = null; if (!outLogged) { stdout = new Redir(process.getInputStream()); new Thread(stdout).start(); } Redir stderr = new Redir(process.getErrorStream()); new Thread(stderr).start(); // redirect input in the current thread if (stdin != null) { OutputStream pout = process.getOutputStream(); new RedirectingInputStream(stdin, true, true).redirectAll(pout); } process.waitFor(); int exitValue = process.exitValue(); if (stdout != null) { stdout.throwIfHadException(); out = new String(stdout.getResult()); } stderr.throwIfHadException(); String err = new String(stderr.getResult()); return new CmdResult(exitValue, out, err); } /** * Added by E. D. Thompson AFRL/RZTT 20100827 Attach to the specified * process, feed specified standard input, and return process' results. * returns data written to standard output and error streams. * * @see #execCommand(Process) * * @param process * the process to attach to * @param stdin * the data to redirect to process' standard input * @return the results of the process * @throws IOException * if an I/O error occurs * @throws InterruptedException * if thread is interrupted before process ends */ public static CmdResult execCommandNoBlocking(final Process process, final InputStream stdin) throws IOException, InterruptedException { // concurrency to avoid stdio deadlocks Redir stdout = new Redir(process.getInputStream()); Redir stderr = new Redir(process.getErrorStream()); new Thread(stdout).start(); new Thread(stderr).start(); // redirect input in the current thread if (stdin != null) { OutputStream pout = process.getOutputStream(); new RedirectingInputStream(stdin, true, true).redirectAll(pout); } stdout.throwIfHadException(); stderr.throwIfHadException(); String out = new String(stdout.getResult()); String err = new String(stderr.getResult()); return new CmdResult(-1, out, err); } /** * User-specified IO exception handler for exceptions during I/O * redirection. */ public static interface BrokenPipeHandler { /** * Invoked when pipe is broken, that is, when I/O error occurs while * reading from the source or writing to the sink * * @param e * the associated I/O exception * @param src * the source of the pipe * @param sink * the sink of the pipe */ void brokenPipe(IOException e, InputStream src, OutputStream sink); } /** * User-specified handler invoked when associated native process exits. */ public static interface ProcessExitHandler { /** * Invoked when associated process has exited. * * @param process * the process that exited. */ void processExited(Process process); } /** * Represents the result of a native command. Consists of the process exit * value together with stdout and stderr dumped to strings. * * @author Dawid Kurzyniec * @version 1.0 */ public static class CmdResult { final int exitValue; final String out; final String err; public CmdResult(int exitValue, String out, String err) { this.exitValue = exitValue; this.out = out; this.err = err; } public int getExitValue() { return exitValue; } public String getOut() { return out; } public String getErr() { return err; } @Override public String toString() { StringBuilder sb = new StringBuilder("Cmd result [out:\n"); sb.append(out).append("\nerr: ").append(err) .append("\nexitValue: ").append(exitValue).append("]"); return sb.toString(); } } public static void handleProcess(Process process, InputStream stdin, OutputStream stdout, OutputStream stderr) throws IOException { handleProcess(process, stdin, stdout, stderr, true, false, null, null); } public static void handleProcess(Process process, InputStream stdin, OutputStream stdout, OutputStream stderr, boolean autoFlush, boolean autoClose, BrokenPipeHandler brokenPipeHandler, ProcessExitHandler exitHandler) throws IOException { handleProcess(process, stdin, autoFlush, autoClose, brokenPipeHandler, stdout, autoFlush, autoClose, brokenPipeHandler, stderr, autoFlush, autoClose, brokenPipeHandler, exitHandler); } public static void handleProcess(Process process, InputStream stdin, boolean inAutoFlush, boolean inAutoClose, BrokenPipeHandler inBrokenHandler, OutputStream stdout, boolean outAutoFlush, boolean outAutoClose, BrokenPipeHandler outBrokenHandler, OutputStream stderr, boolean errAutoFlush, boolean errAutoClose, BrokenPipeHandler errBrokenHandler, ProcessExitHandler exitHandler) throws IOException { ProcessHandler ph = new ProcessHandler(process, stdin, inAutoFlush, inAutoClose, inBrokenHandler, stdout, outAutoFlush, outAutoClose, outBrokenHandler, stderr, errAutoFlush, errAutoClose, errBrokenHandler, exitHandler); ph.start(); } private static class Pipe implements Runnable { final InputStream src; final OutputStream sink; final boolean autoFlush; final boolean autoClose; final BrokenPipeHandler brokenPipeHandler; public Pipe(InputStream src, OutputStream sink, BrokenPipeHandler brokenPipeHandler) { this(src, sink, brokenPipeHandler, true, false); } public Pipe(InputStream src, OutputStream sink, BrokenPipeHandler brokenPipeHandler, boolean autoFlush, boolean autoClose) { this.src = src; this.sink = sink; this.brokenPipeHandler = brokenPipeHandler; this.autoFlush = autoFlush; this.autoClose = autoClose; } public void run() { RedirectingInputStream sd = new RedirectingInputStream(src, autoFlush, autoClose); try { sd.redirectAll(sink); } catch (IOException e) { if (brokenPipeHandler != null) { brokenPipeHandler.brokenPipe(e, src, sink); } } } } private static class Redir implements Runnable { final Pipe pipe; IOException ex; Redir(InputStream is) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); BrokenPipeHandler bph = new BrokenPipeHandler() { public void brokenPipe(IOException ex, InputStream src, OutputStream sink) { setException(ex); } }; this.pipe = new Pipe(is, bos, bph, true, true); } public void run() { pipe.run(); } synchronized void setException(IOException e) { this.ex = e; } synchronized void throwIfHadException() throws IOException { if (ex != null) throw ex; } public byte[] getResult() { return ((ByteArrayOutputStream) pipe.sink).toByteArray(); } } private static class ProcessHandler { final Process process; final Thread tstdin; final Thread tstdout; final Thread tstderr; final Thread texitHandler; ProcessHandler(final Process process, InputStream stdin, boolean inAutoFlush, boolean inAutoClose, BrokenPipeHandler inBrokenHandler, OutputStream stdout, boolean outAutoFlush, boolean outAutoClose, BrokenPipeHandler outBrokenHandler, OutputStream stderr, boolean errAutoFlush, boolean errAutoClose, BrokenPipeHandler errBrokenHandler, final ProcessExitHandler exitHandler) throws IOException { this.process = process; this.tstdin = createPipe(stdin, process.getOutputStream(), inBrokenHandler, inAutoFlush, inAutoClose); this.tstdout = createPipe(process.getInputStream(), stdout, outBrokenHandler, outAutoFlush, outAutoClose); this.tstderr = createPipe(process.getErrorStream(), stderr, errBrokenHandler, errAutoFlush, errAutoClose); if (exitHandler != null) { this.texitHandler = new Thread(new ExitHandler(process, exitHandler)); } else { texitHandler = null; } } void start() { if (tstdin != null) tstdin.start(); if (tstdout != null) tstdout.start(); if (tstderr != null) tstderr.start(); if (texitHandler != null) texitHandler.start(); } private static class ExitHandler implements Runnable { final Process process; final ProcessExitHandler exitHandler; ExitHandler(Process process, ProcessExitHandler exitHandler) { this.process = process; this.exitHandler = exitHandler; } public void run() { try { process.waitFor(); } catch (InterruptedException e) { // silently ignore and destroy all in finally } finally { // just in case, or if interrupted process.destroy(); exitHandler.processExited(process); } } } private static Thread createPipe(InputStream src, OutputStream sink, BrokenPipeHandler bph, boolean autoFlush, boolean autoClose) throws IOException { if (src == null) { if (sink != null && autoClose) sink.close(); return null; } else if (sink == null) { if (autoClose) src.close(); return null; } else { return new Thread( new Pipe(src, sink, bph, autoFlush, autoClose)); } } } }
true
false
null
null
diff --git a/manticore/bundles/net.i2cat.mantychore.network.model/src/main/java/net/i2cat/mantychore/network/model/NetworkModelHelper.java b/manticore/bundles/net.i2cat.mantychore.network.model/src/main/java/net/i2cat/mantychore/network/model/NetworkModelHelper.java index f630e7836..c378742d5 100644 --- a/manticore/bundles/net.i2cat.mantychore.network.model/src/main/java/net/i2cat/mantychore/network/model/NetworkModelHelper.java +++ b/manticore/bundles/net.i2cat.mantychore.network.model/src/main/java/net/i2cat/mantychore/network/model/NetworkModelHelper.java @@ -1,317 +1,333 @@ package net.i2cat.mantychore.network.model; import java.util.ArrayList; import java.util.List; import net.i2cat.mantychore.network.model.domain.NetworkDomain; import net.i2cat.mantychore.network.model.layer.Layer; import net.i2cat.mantychore.network.model.topology.ConnectionPoint; import net.i2cat.mantychore.network.model.topology.CrossConnect; import net.i2cat.mantychore.network.model.topology.Device; import net.i2cat.mantychore.network.model.topology.Interface; import net.i2cat.mantychore.network.model.topology.Link; import net.i2cat.mantychore.network.model.topology.NetworkConnection; import net.i2cat.mantychore.network.model.topology.NetworkElement; import net.i2cat.mantychore.network.model.topology.Path; import net.i2cat.mantychore.network.model.topology.TransportNetworkElement; public class NetworkModelHelper { public static List<NetworkElement> getNetworkElementsExceptTransportElements(NetworkModel model) { return getNetworkElementsExceptTransportElements(model.getNetworkElements()); } public static List<NetworkElement> getNetworkElementsExceptTransportElements(List<NetworkElement> networkElements) { List<NetworkElement> toReturn = new ArrayList<NetworkElement>(); for (NetworkElement elem : networkElements) { if (!(elem instanceof TransportNetworkElement)) { toReturn.add(elem); } } return toReturn; } public static List<Device> getDevices(NetworkModel model) { return getDevices(model.getNetworkElements()); } public static List<Device> getDevices(List<NetworkElement> networkElements) { List<Device> toReturn = new ArrayList<Device>(); for (NetworkElement elem : networkElements) { if (elem instanceof Device) { toReturn.add((Device) elem); } } return toReturn; } public static List<NetworkDomain> getDomains(NetworkModel model) { return getDomains(model.getNetworkElements()); } public static List<NetworkDomain> getDomains(List<NetworkElement> networkElements) { List<NetworkDomain> toReturn = new ArrayList<NetworkDomain>(); for (NetworkElement elem : networkElements) { if (elem instanceof NetworkDomain) { toReturn.add((NetworkDomain) elem); } } return toReturn; } public static List<Link> getLinks(NetworkModel model) { return getLinks(model.getNetworkElements()); } public static List<Link> getLinks(List<NetworkElement> networkElements) { List<Link> toReturn = new ArrayList<Link>(); for (NetworkElement elem : networkElements) { if (elem instanceof Link) { toReturn.add((Link) elem); } } return toReturn; } public static List<Layer> getLayers(NetworkModel model) { return getLayers(model.getNetworkElements()); } public static List<Layer> getLayers(List<NetworkElement> networkElements) { List<Layer> toReturn = new ArrayList<Layer>(); for (NetworkElement elem : networkElements) { if (elem instanceof ConnectionPoint) { Layer layer = ((ConnectionPoint) elem).getLayer(); // TODO implement equals in Layer if (!toReturn.contains(layer)) toReturn.add(layer); } } return toReturn; } public static List<ConnectionPoint> getConnectionPoints(NetworkModel model) { return getConnectionPoints(model.getNetworkElements()); } public static List<ConnectionPoint> getConnectionPoints(List<NetworkElement> networkElements) { List<ConnectionPoint> toReturn = new ArrayList<ConnectionPoint>(); for (NetworkElement elem : networkElements) { if (elem instanceof ConnectionPoint) { toReturn.add((ConnectionPoint) elem); } } return toReturn; } public static List<Interface> getInterfaces(List<NetworkElement> networkElements) { List<Interface> toReturn = new ArrayList<Interface>(); for (NetworkElement elem : networkElements) { if (elem instanceof Interface) { toReturn.add((Interface) elem); } } return toReturn; } @Deprecated public static Interface getInterfaceByName(String interfaceName, NetworkModel model) { for (NetworkElement elem : model.getNetworkElements()) { if (elem instanceof Interface) { if (elem.getName().equals(interfaceName)) return (Interface) elem; } } return null; } /** * Get the interface from Network Model and interface name * * @param networkElements * @return Interface */ public static Interface getInterfaceByName(List<NetworkElement> networkElements, String interfaceName) { Interface toReturn = null; for (NetworkElement elem : networkElements) { if (elem instanceof Interface && elem.getName().equals(interfaceName)) { toReturn = (Interface) elem; break; } } return toReturn; } /** * * @param name * @param networkElements * @return lowest current position of networkElements containing an element named with given name. */ public static int getNetworkElementByName(String name, List<NetworkElement> networkElements) { int pos = 0; for (NetworkElement networkElement : networkElements) { if (networkElement.getName() != null && networkElement.getName().equals(name)) return pos; pos++; } return -1; } + /** + * Return all elements in networkElements being of class clazz. + * + * @param clazz + * @param networkElements + * @return + */ + public static List<NetworkElement> getNetworkElementsByClassName(Class clazz, List<NetworkElement> networkElements) { + List<NetworkElement> matchingElements = new ArrayList<NetworkElement>(); + for (NetworkElement networkElement : networkElements) { + if (networkElement.getClass().equals(clazz)) + matchingElements.add(networkElement); + } + return matchingElements; + } + public static Link linkInterfaces(Interface src, Interface dst, boolean bidiLink) { Link link = new Link(); link.setSource(src); link.setSink(dst); link.setBidirectional(bidiLink); link.setLayer(src.getLayer()); src.setLinkTo(link); if (bidiLink) { dst.setLinkTo(link); } return link; } public static CrossConnect crossConnectInterfaces(Interface src, Interface dst) { CrossConnect xConnect = new CrossConnect(); xConnect.setSource(src); xConnect.setSink(dst); xConnect.setLayer(src.getLayer()); src.setSwitchedTo(xConnect); dst.setSwitchedTo(xConnect); return xConnect; } /** * Removes given NetworkElement from given networkModel (if exists). * * @param toRemove * @param networkModel * @return updated network model */ public static NetworkModel deleteNetworkElementAndReferences(NetworkElement toRemove, NetworkModel networkModel) { if (!networkModel.getNetworkElements().contains(toRemove)) { // TODO throw exception? return networkModel; } if (toRemove instanceof NetworkDomain) { while (((NetworkDomain) toRemove).getHasDevice().size() > 0) { deleteNetworkElementAndReferences(((NetworkDomain) toRemove).getHasDevice().get(0), networkModel); } while (((NetworkDomain) toRemove).getHasInterface().size() > 0) { deleteNetworkElementAndReferences(((NetworkDomain) toRemove).getHasInterface().get(0), networkModel); } networkModel.getNetworkElements().remove(toRemove); toRemove.setLocatedAt(null); toRemove.getInAdminDomains().clear(); } else if (toRemove instanceof Device) { while (((Device) toRemove).getInterfaces().size() > 0) { deleteNetworkElementAndReferences(((Device) toRemove).getInterfaces().get(0), networkModel); } networkModel.getNetworkElements().remove(toRemove); toRemove.setLocatedAt(null); toRemove.getInAdminDomains().clear(); } else if (toRemove instanceof TransportNetworkElement) { deleteTransportNetworkConnectionAndReferences((TransportNetworkElement) toRemove, networkModel); } return networkModel; } public static NetworkModel deleteTransportNetworkConnectionAndReferences(TransportNetworkElement toRemove, NetworkModel networkModel) { if (!networkModel.getNetworkElements().contains(toRemove)) { // TODO throw exception? return networkModel; } if (toRemove instanceof ConnectionPoint) { while (((ConnectionPoint) toRemove).getClientInterfaces().size() > 0) { deleteNetworkElementAndReferences(((ConnectionPoint) toRemove).getClientInterfaces().get(0), networkModel); } if (toRemove instanceof Interface) { if (((Interface) toRemove).getDevice() != null) ((Interface) toRemove).getDevice().getInterfaces().remove(toRemove); deleteNetworkElementAndReferences(((Interface) toRemove).getLinkTo(), networkModel); // TODO WHAT TO DO WITH PATHS??? // should they be removed when its source/sink is ? // should they be removed when an intermediate links/path is? deleteNetworkElementAndReferences(((Interface) toRemove).getConnectedTo(), networkModel); deleteNetworkElementAndReferences(((Interface) toRemove).getSwitchedTo(), networkModel); } if (((ConnectionPoint) toRemove).getServerInterface() != null) { ((ConnectionPoint) toRemove).getServerInterface().getClientInterfaces().remove(toRemove); ((ConnectionPoint) toRemove).setServerInterface(null); } toRemove.setLayer(null); networkModel.getNetworkElements().remove(toRemove); toRemove.setLocatedAt(null); toRemove.getInAdminDomains().clear(); } else if (toRemove instanceof NetworkConnection) { deleteNetworkConnectionAndReferences((NetworkConnection) toRemove, networkModel); } return networkModel; } public static NetworkModel deleteNetworkConnectionAndReferences(NetworkConnection toRemove, NetworkModel networkModel) { if (!networkModel.getNetworkElements().contains(toRemove)) { // TODO throw exception? return networkModel; } if (toRemove instanceof Link) { ((Link) toRemove).getSource().setLinkTo(null); ((Link) toRemove).getSink().setLinkTo(null); ((Link) toRemove).setSource(null); ((Link) toRemove).setSink(null); } else if (toRemove instanceof Path) { ((Path) toRemove).getSource().setLinkTo(null); ((Path) toRemove).getSink().setLinkTo(null); ((Path) toRemove).setSource(null); ((Path) toRemove).setSink(null); // TODO what to do with segments?? // SHOULD THEY BE REMOVED? // intermediate links and paths will still be active // don't remove them by now // just mark they are no longer part of toRemove ((Path) toRemove).getPathSegments().clear(); } else if (toRemove instanceof CrossConnect) { ((CrossConnect) toRemove).getSource().setSwitchedTo(null); ((CrossConnect) toRemove).getSink().setSwitchedTo(null); ((CrossConnect) toRemove).setSource(null); ((CrossConnect) toRemove).setSink(null); } toRemove.setLayer(null); networkModel.getNetworkElements().remove(toRemove); toRemove.setLocatedAt(null); toRemove.getInAdminDomains().clear(); return networkModel; } } diff --git a/manticore/bundles/net.i2cat.mantychore.network.repository/src/test/java/net/i2cat/mantychore/network/repository/tests/NetworkDescriptorToMapperModelTest.java b/manticore/bundles/net.i2cat.mantychore.network.repository/src/test/java/net/i2cat/mantychore/network/repository/tests/NetworkDescriptorToMapperModelTest.java index 831edfef8..fa64dcb3b 100644 --- a/manticore/bundles/net.i2cat.mantychore.network.repository/src/test/java/net/i2cat/mantychore/network/repository/tests/NetworkDescriptorToMapperModelTest.java +++ b/manticore/bundles/net.i2cat.mantychore.network.repository/src/test/java/net/i2cat/mantychore/network/repository/tests/NetworkDescriptorToMapperModelTest.java @@ -1,127 +1,133 @@ package net.i2cat.mantychore.network.repository.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; + +import java.util.List; + import junit.framework.Assert; import net.i2cat.mantychore.network.model.MockNetworkModel; import net.i2cat.mantychore.network.model.NetworkModel; import net.i2cat.mantychore.network.model.NetworkModelHelper; import net.i2cat.mantychore.network.model.topology.Interface; import net.i2cat.mantychore.network.model.topology.NetworkElement; import net.i2cat.mantychore.network.repository.NetworkMapperDescriptorToModel; import net.i2cat.mantychore.network.repository.NetworkMapperModelToDescriptor; import org.junit.Test; import org.opennaas.core.resources.ResourceException; import org.opennaas.core.resources.descriptor.network.NetworkTopology; public class NetworkDescriptorToMapperModelTest { @Test public void testModelToDescriptorWithMockModel() { NetworkTopology networkTopology = NetworkMapperModelToDescriptor.modelToDescriptor(MockNetworkModel.newNetworkModel()); assertNotNull(networkTopology.getNetworkDomains()); assertEquals(networkTopology.getNetworkDomains().size(), 1); /* network description */ assertNotNull(networkTopology.getDevices()); assertEquals(networkTopology.getDevices().get(0).getName(), "router:R-AS2-1"); assertEquals(networkTopology.getDevices().get(1).getName(), "router:R-AS2-2"); assertEquals(networkTopology.getDevices().get(2).getName(), "router:R-AS2-3"); // notice that only references to topology elements start with #, names does not assertNotNull(networkTopology.getDevices()); assertEquals(networkTopology.getDevices().get(0).getName(), "router:R-AS2-1"); assertNotNull(networkTopology.getDevices().get(0).getHasInterfaces()); assertEquals(networkTopology.getDevices().get(0).getHasInterfaces().size(), 3); assertEquals(networkTopology.getDevices().get(0).getHasInterfaces().get(0).getResource(), "#router:R-AS2-1:lt-1/2/0.51"); assertEquals(networkTopology.getDevices().get(0).getHasInterfaces().get(1).getResource(), "#router:R-AS2-1:lt-1/2/0.100"); assertEquals(networkTopology.getDevices().get(0).getHasInterfaces().get(2).getResource(), "#router:R-AS2-1:lo0.1"); assertEquals(networkTopology.getDevices().get(1).getName(), "router:R-AS2-2"); assertNotNull(networkTopology.getDevices().get(1).getHasInterfaces()); assertEquals(networkTopology.getDevices().get(1).getHasInterfaces().size(), 3); assertEquals(networkTopology.getDevices().get(1).getHasInterfaces().get(0).getResource(), "#router:R-AS2-2:lt-1/2/0.102"); assertEquals(networkTopology.getDevices().get(1).getHasInterfaces().get(1).getResource(), "#router:R-AS2-2:lt-1/2/0.101"); assertEquals(networkTopology.getDevices().get(1).getHasInterfaces().get(2).getResource(), "#router:R-AS2-2:lo0.3"); assertEquals(networkTopology.getDevices().get(2).getName(), "router:R-AS2-3"); assertNotNull(networkTopology.getDevices().get(2).getHasInterfaces()); assertEquals(networkTopology.getDevices().get(2).getHasInterfaces().size(), 2); assertEquals(networkTopology.getDevices().get(2).getHasInterfaces().get(0).getResource(), "#router:R-AS2-3:lt-1/2/0.103"); assertEquals(networkTopology.getDevices().get(2).getHasInterfaces().get(1).getResource(), "#router:R-AS2-3:lo0.4"); assertNotNull(networkTopology.getInterfaces()); assertEquals(networkTopology.getInterfaces().size(), 9); assertEquals(networkTopology.getInterfaces().get(0).getName(), "router:R-AS2-1:lt-1/2/0.51"); assertEquals(networkTopology.getInterfaces().get(0).getLinkTo().getName(), "#router:R1:lt-1/2/0.50"); assertEquals(networkTopology.getInterfaces().get(1).getName(), "router:R-AS2-1:lt-1/2/0.100"); assertEquals(networkTopology.getInterfaces().get(1).getLinkTo().getName(), "#router:R-AS2-2:lt-1/2/0.101"); assertEquals(networkTopology.getInterfaces().get(2).getName(), "router:R-AS2-1:lo0.1"); assertEquals(networkTopology.getInterfaces().get(3).getName(), "router:R-AS2-2:lt-1/2/0.102"); assertEquals(networkTopology.getInterfaces().get(3).getLinkTo().getName(), "#router:R-AS2-3:lt-1/2/0.103"); assertEquals(networkTopology.getInterfaces().get(4).getName(), "router:R-AS2-2:lt-1/2/0.101"); assertEquals(networkTopology.getInterfaces().get(4).getLinkTo().getName(), "#router:R-AS2-1:lt-1/2/0.100"); assertEquals(networkTopology.getInterfaces().get(5).getName(), "router:R-AS2-2:lo0.3"); assertEquals(networkTopology.getInterfaces().get(6).getName(), "router:R-AS2-3:lt-1/2/0.103"); assertEquals(networkTopology.getInterfaces().get(6).getLinkTo().getName(), "#router:R-AS2-2:lt-1/2/0.102"); assertEquals(networkTopology.getInterfaces().get(7).getName(), "router:R-AS2-3:lo0.4"); } @Test public void testModelToDescriptorAndViceversa() { try { NetworkModel model1 = MockNetworkModel.newNetworkModel(); NetworkTopology topology1 = NetworkMapperModelToDescriptor.modelToDescriptor(model1); NetworkModel model2 = NetworkMapperDescriptorToModel.descriptorToModel(topology1); NetworkTopology topology2 = NetworkMapperModelToDescriptor.modelToDescriptor(model2); checkModels(model1, model2); Assert.assertEquals(topology1, topology2); } catch (ResourceException e) { Assert.fail("Error mapping descriptor to model: " + e.getMessage()); } } private void checkModels(NetworkModel model1, NetworkModel model2) { Assert.assertEquals(model1.getNetworkElements().size(), model2.getNetworkElements().size()); for (NetworkElement elem1 : model1.getNetworkElements()) { - int elemIndexInModel2 = NetworkModelHelper.getNetworkElementByName(elem1.getName(), model2.getNetworkElements()); - Assert.assertFalse("Elem " + elem1.getName() + " of model1 is in model2.", elemIndexInModel2 == -1); - NetworkElement elem2 = model2.getNetworkElements().get(elemIndexInModel2); - Assert.assertEquals(elem1.getClass(), elem2.getClass()); + List<NetworkElement> tmp_elems = NetworkModelHelper.getNetworkElementsByClassName(elem1.getClass(), model2.getNetworkElements()); + Assert.assertFalse(tmp_elems.isEmpty()); + + if (elem1.getName() != null) { // should be elements without name?? Links has no name, by now. + int elemIndexInModel2 = NetworkModelHelper.getNetworkElementByName(elem1.getName(), tmp_elems); + Assert.assertFalse("Elem " + elem1.getName() + " of model1 is not in model2.", elemIndexInModel2 == -1); + } } for (Interface iface1 : NetworkModelHelper.getInterfaces(model1.getNetworkElements())) { Interface iface2 = NetworkModelHelper.getInterfaceByName(model2.getNetworkElements(), iface1.getName()); - Assert.assertNotNull("Interface " + iface1.getName() + " is also in model2", iface2); + Assert.assertNotNull("Interface " + iface1.getName() + " is not in model2", iface2); if (iface1.getLinkTo() != null) { Assert.assertNotNull(iface2.getLinkTo()); Assert.assertEquals(iface1.getLinkTo().getName(), iface2.getLinkTo().getName()); } if (iface1.getSwitchedTo() != null) { Assert.assertNotNull(iface2.getSwitchedTo()); Assert.assertEquals(iface1.getSwitchedTo().getName(), iface2.getSwitchedTo().getName()); } } } }
false
false
null
null
diff --git a/gpcore/src/test/java/org/geopublishing/atlasViewer/AtlasConfigTest.java b/gpcore/src/test/java/org/geopublishing/atlasViewer/AtlasConfigTest.java index 7f403518..09707eab 100644 --- a/gpcore/src/test/java/org/geopublishing/atlasViewer/AtlasConfigTest.java +++ b/gpcore/src/test/java/org/geopublishing/atlasViewer/AtlasConfigTest.java @@ -1,61 +1,48 @@ package org.geopublishing.atlasViewer; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.net.URL; import org.geopublishing.geopublisher.AtlasConfigEditable; import org.geopublishing.geopublisher.GpTestingUtil; import org.geopublishing.geopublisher.GpTestingUtil.TestAtlas; import org.geopublishing.geopublisher.GpUtil; import org.junit.After; import org.junit.Before; import org.junit.Test; import de.schmitzm.testing.TestingClass; + public class AtlasConfigTest extends TestingClass { private AtlasConfigEditable ace; @Before public void setup() throws Exception { ace = GpTestingUtil.getAtlasConfigE(TestAtlas.small); } @After public void dispose() { if (ace != null) ace.dispose(); } @Test public void testIconAndPopupURL() { assertNotNull("At least the fallback must be found.", ace.getIconURL()); assertNull("Small atlas doesn't have a popup HTML", ace.getPopupHTMLURL()); } @Test public void testFallbackIcons() { URL iconURL = GpUtil.class .getResource(AtlasConfig.JWSICON_RESOURCE_NAME_FALLBACK); assertNotNull(iconURL); assertNotNull(new AtlasConfig().getIconURL()); } - @Test - public void testBasename() { - AtlasConfig ac = new AtlasConfig(); - assertEquals("myatlas", ac.getBaseName()); - - ac.setJnlpBaseUrl("http://www.bahn.de/cool/"); - assertEquals("cool", ac.getBaseName()); - - ac.setJnlpBaseUrl("http://www.bahn.de/cool"); - assertEquals("cool", ac.getBaseName()); - - } - } diff --git a/gpcore/src/test/java/org/geopublishing/geopublisher/GpTestingUtil.java b/gpcore/src/test/java/org/geopublishing/geopublisher/GpTestingUtil.java index e01f075d..75c69ff2 100644 --- a/gpcore/src/test/java/org/geopublishing/geopublisher/GpTestingUtil.java +++ b/gpcore/src/test/java/org/geopublishing/geopublisher/GpTestingUtil.java @@ -1,217 +1,218 @@ /******************************************************************************* * Copyright (c) 2010 Stefan A. Tzeggai. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Stefan A. Tzeggai - initial API and implementation ******************************************************************************/ package org.geopublishing.geopublisher; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.FileUtils; import org.geopublishing.atlasViewer.AVUtil; import org.geopublishing.atlasViewer.AtlasConfig; import org.geopublishing.atlasViewer.dp.layer.DpLayerVectorFeatureSource; import org.geopublishing.atlasViewer.exceptions.AtlasException; import org.geopublishing.atlasViewer.http.Webserver; import org.geopublishing.atlasViewer.map.Map; import org.geopublishing.atlasViewer.swing.AtlasMapLegend; import org.geopublishing.atlasViewer.swing.AtlasViewerGUI; +import org.geopublishing.geopublisher.GpTestingUtil.TestAtlas; import org.geotools.data.DataUtilities; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import org.xml.sax.SAXException; import de.schmitzm.geotools.GTUtil; import de.schmitzm.geotools.gui.GeoMapPane; import de.schmitzm.geotools.gui.MapPaneToolBar; import de.schmitzm.geotools.testing.GTTestingUtil; import de.schmitzm.io.IOUtil; import de.schmitzm.testing.TestingUtil; public class GpTestingUtil extends GTTestingUtil { /** An enumeration of available test-atlases **/ public enum TestAtlas { // TODO Create a type "new" which creates a new empty atlas in tmp dir // on getAce() small("/atlases/ChartDemoAtlas/atlas.gpa"), rasters( "/atlases/rastersAtlas/atlas.gpa"); private final String resourceLocation; TestAtlas(String resourceLocation) { this.resourceLocation = resourceLocation; } public String getReslocation() { return resourceLocation; } public AtlasConfigEditable getAce() { // System.out.println("Start loading test atlas config ..."); try { return getAtlasConfigE(getFile().getParent()); } catch (Exception e) { throw new RuntimeException(e); } } public URL getUrl() { URL resourceUrl = GpUtil.class.getResource(getReslocation()); if (resourceUrl == null) throw new RuntimeException("The test-resource " + getReslocation() + " could not be found in classpath"); else System.out.println("URL for " + getReslocation() + " is " + resourceLocation); return resourceUrl; } /** * Returns a {@link File} to a <code>atlas.gpa</code>. If the atlas * comes from the classpath, it is copied to a temp directory first. */ public File getFile() { try { URL url = getUrl(); File urlToFile = DataUtilities.urlToFile(url); // Unzip to /tmp File td = TestingUtil.getNewTempDir(); if (urlToFile != null) { // // Load Atlas from directory FileUtils.copyDirectory(urlToFile.getParentFile(), td); return new File(td, "atlas.gpa"); } else { File fileFromJarFileUrl = IOUtil.getFileFromJarFileUrl(url); IOUtil.unzipArchive(fileFromJarFileUrl, td); return new File(td, getReslocation()); } } catch (Exception e) { throw new RuntimeException(e); } } } static AtlasConfigEditable getAtlasConfigE(String atlasDir) throws FactoryException, TransformException, AtlasException, SAXException, IOException, ParserConfigurationException { AVUtil.initAtlasLogging(); AtlasViewerGUI.setupResLoMan(new String[] { atlasDir }); /*********************************************************************** * Remove the old geopublisher.properties file, so we always start with * the default */ GPProps.resetProperties(null); AtlasConfigEditable atlasConfig = new AtlasConfigEditable(new File( atlasDir)); GTUtil.initEPSG(); Webserver webserver = new Webserver(); new AMLImportEd().parseAtlasConfig(null, atlasConfig, false); assertNotNull("AtlasConfig is null after parseAtlasConfig!", atlasConfig); assertNotNull("MapPool is null after parseAtlasConfig!", atlasConfig.getMapPool()); assertNotNull("DataPool is null after parseAtlasConfig!", atlasConfig.getDataPool()); return atlasConfig; } /** * Creates a directory in /tmp that can be used to export an atlas. */ public static File createAtlasExportTesttDir() { File atlasExportTesttDir = new File(IOUtil.getTempDir(), "junitTestAtlasExport" + System.currentTimeMillis()); atlasExportTesttDir.mkdirs(); return atlasExportTesttDir; } /** * @throws ParserConfigurationException * @throws IOException * @throws SAXException * @throws TransformException * @throws FactoryException * @throws AtlasException * @Deprecated use {@link #getAtlasConfigE(TestAtlas)} with * {@link TestAtlas.iida2} */ public static AtlasConfigEditable getAtlasConfigE() throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException { return getAtlasConfigE(TestAtlas.small); } public static DpLayerVectorFeatureSource getCities(AtlasConfigEditable ace) { return (DpLayerVectorFeatureSource) ace.getDataPool().get( "vector_village_all_v1.501530158160"); } public static AtlasMapLegend getAtlasMapLegend(AtlasConfigEditable ace) { Map map = ace.getMapPool().get(ace.getMapPool().getStartMapID()); GeoMapPane gmp = new GeoMapPane(); MapPaneToolBar mptb = new MapPaneToolBar(gmp.getMapPane()); return new AtlasMapLegend(gmp, map, ace, mptb); } public static AtlasConfigEditable getAtlasConfigE(TestAtlas type) throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException { return type.getAce(); } public static DpLayerVectorFeatureSource getCities() throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException { return getCities(getAtlasConfigE()); } public static AtlasConfigEditable saveAndLoad(AtlasConfigEditable ace) throws Exception { File tempDir = new File(IOUtil.getTempDir(), "testAtlasImportExport/" + AtlasConfig.ATLASDATA_DIRNAME); tempDir.mkdirs(); File atlasXmlFile = new File(tempDir, AtlasConfigEditable.ATLAS_XML_FILENAME); AMLExporter amlExporter = new AMLExporter(ace); amlExporter.setAtlasXml(atlasXmlFile); boolean saved = amlExporter.saveAtlasConfigEditable(); assertTrue(saved); AtlasConfigEditable ace2 = new AMLImportEd().parseAtlasConfig(null, atlasXmlFile.getParentFile().getParentFile()); FileUtils.deleteDirectory(tempDir); return ace2; } } diff --git a/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/export/ExportWizard.java b/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/export/ExportWizard.java index dede8c6d..d86612b2 100644 --- a/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/export/ExportWizard.java +++ b/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/export/ExportWizard.java @@ -1,224 +1,224 @@ /******************************************************************************* * Copyright (c) 2010 Stefan A. Tzeggai. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Stefan A. Tzeggai - initial API and implementation ******************************************************************************/ package org.geopublishing.geopublisher.gui.export; import java.awt.Component; import java.awt.Dimension; import java.io.File; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import org.apache.log4j.Logger; import org.geopublishing.atlasViewer.swing.AVSwingUtil; import org.geopublishing.geopublisher.AtlasConfigEditable; import org.geopublishing.geopublisher.GPProps; import org.geopublishing.geopublisher.GPProps.Keys; import org.geopublishing.geopublisher.export.GpHosterServerSettings; import org.geopublishing.geopublisher.export.gphoster.GpHosterClient; import org.geopublishing.geopublisher.gui.EditAtlasParamsDialog; import org.geopublishing.geopublisher.gui.settings.GpHosterServerList; import org.geopublishing.geopublisher.swing.GeopublisherGUI; import org.netbeans.api.wizard.WizardDisplayer; import org.netbeans.spi.wizard.Wizard; import org.netbeans.spi.wizard.WizardBranchController; import org.netbeans.spi.wizard.WizardPage; import de.schmitzm.lang.LangUtil; /** * This {@link Wizard} provides an easy way for the Geopublisher user to export * the atlas. * * @see {@link ExportWizardResultProducer} which finally runs the export. * @see {@link ExportWizardPage_Save} * @see {@link ExportWizardPage_TargetPlattformsSelection} * @see {@link ExportWizardPage_ExportFolder} * @see {@link ExportWizardPage_JRECopy} * @see {@link ExportWizardPage_JNLPDefinition} * * @author Stefan A. Tzeggai */ public class ExportWizard extends WizardBranchController { private static final Wizard FTP_BRANCH = new ExportWizardFTPBrancher() .createWizard(); final static protected Logger LOGGER = Logger.getLogger(ExportWizard.class); public static final ExportWizardResultProducer FINISHER = new ExportWizardResultProducer(); /** Used for a all-the-same look of the panels **/ final public static Dimension DEFAULT_WPANEL_SIZE = new Dimension(470, 370); final public static String SAVE_AUTOMATICALLY = "saveAtlas"; final public static String ACE = "ace"; /** Used to identify the JWS check-box in the wizard-data **/ final public static String JWS_CHECKBOX = "exportJWS?"; /** Used to identify the DISK check-box in the wizard-data **/ final public static String DISK_CHECKBOX = "exportDISK?"; /** Used to identify the FTP check-box in the wizard-data **/ final public static String FTP_CHECKBOX = "exportFTP?"; /** Used to identify the DISK ZIP check-box in the wizard-data **/ public static final String DISKZIP_CHECKBOX = "zipDISK"; public static final String COPYJRE = "copyJRE"; public static final String EXPORTFOLDER = "exportFolderAbsolutePath"; public static final String JNLPURL = "jnlpCodebase"; public static final String AGB_ACCEPTED = "agb_accepted?"; public static final String GPH_EMAIL_FIELD = "email_set?"; public static final String GPH_USERNAME = "gph_username"; public static final String GPH_PASSWORD = "gph_password"; /** * Decides wheter the user wants to make his Atlas public, or not. * * @see ExportWizardPage_GpHoster_ExportOptions */ public static final String MAKE_PUBLIC = "public?"; /** Used to identify whether a Sync to FTP is a first one **/ public static final String FTP_FIRST = "firstSync?"; public static final String GPHC = "GpHosterCLient instance key"; protected static final String RESULTPRODUCER_WORKING = "once the deferred export task has started, we put it in the wizardmap with this key. this allows for a button that cancels the export."; // public static Boolean isNewAtlasUpload = null; static Map<Object, Object> initialProperties = new HashMap<Object, Object>(); /** * This constructor also defines the default (first) steps of the wizard * until it branches. */ protected ExportWizard() { super(new WizardPage[] { new ExportWizardPage_Save(), new ExportWizardPage_TargetPlattformsSelection() }); // Create the one and only instance of GpHoster! // The settings to use are defined in the properties GpHosterServerSettings gpss; try { gpss = new GpHosterServerList(GPProps.get(Keys.gpHosterServerList)) .get(GPProps.getInt(Keys.lastGpHosterServerIdx, 0)); } catch (Exception e) { LOGGER.error( "Failed to read the selected GpHosterServer settigs from properties", e); gpss = GpHosterServerSettings.DEFAULT; } final GpHosterClient gphc = new GpHosterClient(gpss); initialProperties.put(GPHC, gphc); } /** * @return whether all required meta-data has been supplied that is need for * a successful export. (Title, Desc, Creator/Vendor in ALL - * languages) + * languages and AtlasBasename) */ private static boolean checkForRequiredMetadata(Component owner, AtlasConfigEditable ace) { + for (String lang : ace.getLanguages()) { - if (ace.getTitle().get(lang) == null + if (ace.getBaseName() == null || ace.getTitle().get(lang) == null || ace.getTitle().get(lang).equals("") || ace.getDesc().get(lang) == null || ace.getDesc().get(lang).equals("") || ace.getCreator().get(lang) == null || ace.getCreator().get(lang).equals("")) { AVSwingUtil.showMessageDialog(owner, GeopublisherGUI.R("Export.Error.MissingMetaData")); return false; } } - return true; } /** * Exports an {@link AtlasConfigEditable} and returns a {@link File} * pointing to the export directory or <code>null</code>. * * return a {@link File} or a {@link JPanel} */ public static Object showWizard(Component owner, AtlasConfigEditable atlasConfigEditable) { while (!checkForRequiredMetadata(owner, atlasConfigEditable)) { EditAtlasParamsDialog editAtlasParamsDialog = new EditAtlasParamsDialog( owner, atlasConfigEditable); editAtlasParamsDialog.setVisible(true); if (editAtlasParamsDialog.isCancelled()) return null; } ExportWizard chartStartWizard = new ExportWizard(); // It's a special // WizardBranchControler Wizard wiz = chartStartWizard.createWizard(); /** * This wizard shall start with featureSource and attributeMetaDataMap * set in the initialProperties map: */ initialProperties.put(ACE, atlasConfigEditable); // Find a nice position for the window // Window parent = SwingUtil.getParentWindow(owner); // parent.getBounds() final Object showWizard = WizardDisplayer.showWizard(wiz, null, null, initialProperties); return showWizard; } /** * It's being called all the time, so the Wizard can figure out which is the * next step. */ @Override public Wizard getWizardForStep(String step, Map wizardData) { // System.out.print("Step: '" + step + "' "); Boolean isJws = (Boolean) wizardData.get(ExportWizard.JWS_CHECKBOX); Boolean isDisk = (Boolean) wizardData.get(ExportWizard.DISK_CHECKBOX); Boolean isFtp = (Boolean) wizardData.get(ExportWizard.FTP_CHECKBOX); Class<WizardPage>[] path = new Class[] {}; if (isDisk != null && isDisk || isJws != null && isJws) path = (Class<WizardPage>[]) LangUtil.extendArray(path, ExportWizardPage_ExportFolder.class); if (isDisk != null && isDisk) path = (Class<WizardPage>[]) LangUtil.extendArray(path, ExportWizardPage_JRECopy.class); if (isJws != null && isJws) path = (Class<WizardPage>[]) LangUtil.extendArray(path, ExportWizardPage_JNLPDefinition.class); if (isFtp != null && isFtp) return FTP_BRANCH; // Last page: path = (Class<WizardPage>[]) LangUtil.extendArray(path, ExportWizardPage_WaitExporting.class); // System.out.println(path.length + " " // + LangUtil.stringConcatWithSep("-> ", path)); return WizardPage.createWizard(path, FINISHER); } }
false
false
null
null
diff --git a/src/app/java/nextapp/echo2/app/update/ServerComponentUpdate.java b/src/app/java/nextapp/echo2/app/update/ServerComponentUpdate.java index 729f1481..f7cf679c 100644 --- a/src/app/java/nextapp/echo2/app/update/ServerComponentUpdate.java +++ b/src/app/java/nextapp/echo2/app/update/ServerComponentUpdate.java @@ -1,411 +1,419 @@ /* * This file is part of the Echo Web Application Framework (hereinafter "Echo"). * Copyright (C) 2002-2005 NextApp, Inc. * * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla 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.mozilla.org/MPL/ * * 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. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. */ package nextapp.echo2.app.update; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import nextapp.echo2.app.Component; /** * A description of a server-side update to a single component, i.e., * an update which has occurred on the server and must be propagated * to the client. * * Describes the addition and removal of children to the component. * Describes modifications to properties of the component. * Describes modifications to the <code>LayoutData</code> states of * children of the component. */ public class ServerComponentUpdate implements Serializable { private static final Component[] EMPTY_COMPONENT_ARRAY = new Component[0]; private static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * The set of child <code>Component</code>s added to the <code>parent</code>. */ private Set addedChildren; /** * The parent component represented in this <code>ServerComponentUpdate</code>. */ private Component parent; /** * A mapping between property names of the <code>parent</code> component and * <code>PropertyUpdate</code>s. */ private Map propertyUpdates; /** * The set of child <code>Component</code>s removed from the <code>parent</code>. */ private Set removedChildren; /** * The set of descendant <code>Component</code>s which are implicitly removed * as they were children of removed children. */ private Set removedDescendants; /** * The set of child <code>Component</code>s whose <code>LayoutData</code> * was updated. */ private Set updatedLayoutDataChildren; /** * Creates a new <code>ServerComponentUpdate</code> representing the given * <code>parent</code> <code>Component</code>. */ public ServerComponentUpdate(Component parent) { this.parent = parent; } /** * Adds a description of an added child to the * <code>ServerComponentUpdate</code>. * * @param child the child being added */ public void addChild(Component child) { if (addedChildren == null) { addedChildren = new HashSet(); } addedChildren.add(child); } /** * Cancels an update to a property. A cancellation of a property update * is performed when the update manager discovers that the state of a * property is already correct on the client. * * @param propertyName the property update to cancel */ public void cancelUpdateProperty(String propertyName) { if (propertyUpdates == null) { return; } propertyUpdates.remove(propertyName); if (propertyUpdates.size() == 0) { propertyUpdates = null; } } /** * Appends the removed child and descendant components of the given * <code>ServerComponentUpdate</code> to this * <code>ServerComponentUpdate</code>'s list of removed descendants. * This method is invoked by the <code>ServerUpdateManager</code> when * a component is removed that is an ancestor of a component that has * been updated. In such a case, the descendant * <code>ServerComponentUpdate</code> is destroyed, * and thus its removed descendant components must be stored in the * ancestor <code>ServerComponentUpdate</code>. * * @param update the <code>ServerComponentUpdate</code> whose removed * descendants are to be appended */ public void appendRemovedDescendants(ServerComponentUpdate update) { // Append removed descendants. if (update.removedDescendants != null) { if (removedDescendants == null) { removedDescendants = new HashSet(); } removedDescendants.addAll(update.removedDescendants); } // Append removed children. if (update.removedChildren != null) { if (removedDescendants == null) { removedDescendants = new HashSet(); } removedDescendants.addAll(update.removedChildren); } } /** * Returns the child components which have been added to the parent. * * @return the added child components */ public Component[] getAddedChildren() { if (addedChildren == null) { return EMPTY_COMPONENT_ARRAY; } else { return (Component[]) addedChildren.toArray(new Component[addedChildren.size()]); } } /** * Returns the parent component being updated. * * @return the parent component */ public Component getParent() { return parent; } /** * Returns the child components which have been removed from the parent. + * These components may or may not have ever been rendered by the container, + * e.g., if a component was added and removed in a single synchronization it + * will show up as a removed component even though the container may have + * never rendered it. * * @return the removed child components * @see #getRemovedDescendants() */ public Component[] getRemovedChildren() { if (removedChildren == null) { return EMPTY_COMPONENT_ARRAY; } else { return (Component[]) removedChildren.toArray(new Component[removedChildren.size()]); } } /** * Returns all descendants of the child components which have been * removed from the parent. This returned array DOES NOT contain the * children which were directly removed from the parent component. + * These components may or may not have ever been rendered by the container, + * e.g., if a component was added and removed in a single synchronization it + * will show up as a removed descendant even though the container may have + * never rendered it. * * @return the removed descendant components * @see #getRemovedChildren() */ public Component[] getRemovedDescendants() { if (removedDescendants == null) { return EMPTY_COMPONENT_ARRAY; } else { return (Component[]) removedDescendants.toArray(new Component[removedDescendants.size()]); } } /** * Returns the child components whose <code>LayoutData</code> properties * have been updated. * * @return the changed child components */ public Component[] getUpdatedLayoutDataChildren() { if (updatedLayoutDataChildren == null) { return EMPTY_COMPONENT_ARRAY; } else { return (Component[]) updatedLayoutDataChildren.toArray(new Component[updatedLayoutDataChildren.size()]); } } /** * Returns a <code>PropertyUpdate</code> describing an update to the * property with the given <code>name</code>. * * @param name the name of the property being updated * @return the <code>PropertyUpdate</code>, or null if none exists * @see #getUpdatedPropertyNames() */ public PropertyUpdate getUpdatedProperty(String name) { return propertyUpdates == null ? null : (PropertyUpdate) propertyUpdates.get(name); } /** * Returns the names of all properties being updated in this update. * * @return the names of all updated properties * @see #getUpdatedPropertyNames() */ public String[] getUpdatedPropertyNames() { if (propertyUpdates == null) { return EMPTY_STRING_ARRAY; } else { return (String[]) propertyUpdates.keySet().toArray(new String[propertyUpdates.size()]); } } /** * Determines if the specified component has been added * as a child in this update. * * @param component the component to test * @return true if the component was added */ public boolean hasAddedChild(Component component) { return addedChildren != null && addedChildren.contains(component); } /** * Determines if the update is adding any children to the parent component. * * @return true if children are being added */ public boolean hasAddedChildren() { return addedChildren != null; } /** * Determines if the specified child was removed from the parent component. * * @param component the potentially removed child * @return true if the child was removed */ public boolean hasRemovedChild(Component component) { return removedChildren != null && removedChildren.contains(component); } /** * Determines if the update is removing children from the parent * component. * * @return true if children are being removed */ public boolean hasRemovedChildren() { return removedChildren != null; } /** * Determines if the update is removing children from the parent that * have descendants. * Having removed descendants implies having removed children. * If none of the children being removed have children, this method * will return false. * * @return true if descendants are being removed */ public boolean hasRemovedDescendants() { return removedDescendants != null; } /** * Determines if the update has child components whose * <code>LayoutData</code> states have changed. * * @return true if <code>LayoutData</code> properties are being updated */ public boolean hasUpdatedLayoutDataChildren() { return updatedLayoutDataChildren != null; } /** * Determines if the update is updating properties of the parent component. * * @return true if properties are being updated */ public boolean hasUpdatedProperties() { return propertyUpdates != null; } /** * Adds a description of a removed child to the * <code>ServerComponentUpdate</code>. * * @param child the child being removed */ public void removeChild(Component child) { if (addedChildren != null && addedChildren.contains(child)) { // Remove child from add list if found. addedChildren.remove(child); } if (updatedLayoutDataChildren != null && updatedLayoutDataChildren.contains(child)) { // Remove child from updated layout data list if found. updatedLayoutDataChildren.remove(child); } if (removedChildren == null) { removedChildren = new HashSet(); } removedChildren.add(child); Component[] descendants = child.getComponents(); for (int i = 0; i < descendants.length; ++i) { removeDescendant(descendants[i]); } } /** * Recursive method to add descriptions of descendants which were * removed. * * @param descendant the removed descendant */ public void removeDescendant(Component descendant) { if (removedDescendants == null) { removedDescendants = new HashSet(); } removedDescendants.add(descendant); Component[] descendants = descendant.getComponents(); for (int i = 0; i < descendants.length; ++i) { removeDescendant(descendants[i]); } } /** * Display debug representation. * * @see java.lang.Object#toString() */ public String toString() { StringBuffer out = new StringBuffer(); out.append(ServerComponentUpdate.class.getName() + "\n"); out.append("- Parent: " + getParent() + "\n"); out.append("- Adds: " + addedChildren + "\n"); out.append("- Removes: " + removedChildren + "\n"); out.append("- DescendantRemoves: " + removedDescendants + "\n"); out.append("- ChildLayoutDataUpdates: " + updatedLayoutDataChildren + "\n"); out.append("- PropertyUpdates: " + propertyUpdates + "\n"); return out.toString(); } /** * Adds a description of an update to a child component's * <code>LayoutData</code> information to the * <code>ServerComponentUpdate</code>. * * @param child the updated child */ public void updateLayoutData(Component child) { if (updatedLayoutDataChildren == null) { updatedLayoutDataChildren = new HashSet(); } updatedLayoutDataChildren.add(child); } /** * Adds a description of an update to a property of the parent component * to the <code>ServerComponentUpdate</code>. * * @param propertyName the name of the property * @param oldValue the previous value of the property * @param newValue the current value of the property */ public void updateProperty(String propertyName, Object oldValue, Object newValue) { if (propertyUpdates == null) { propertyUpdates = new HashMap(); } PropertyUpdate propertyUpdate = new PropertyUpdate(oldValue, newValue); propertyUpdates.put(propertyName, propertyUpdate); } }
false
false
null
null
diff --git a/src/org/ojim/client/ai/valuation/Valuator.java b/src/org/ojim/client/ai/valuation/Valuator.java index a337d64..976666f 100644 --- a/src/org/ojim/client/ai/valuation/Valuator.java +++ b/src/org/ojim/client/ai/valuation/Valuator.java @@ -1,591 +1,605 @@ /* Copyright (C) 2010 - 2011 Fabian Neundorf, Philip Caroli, * Maximilian Madlung, Usman Ghani Ahmed, Jeremias Mechler * * 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 org.ojim.client.ai.valuation; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.ojim.client.SimpleClient; import org.ojim.client.ai.commands.AcceptCommand; import org.ojim.client.ai.commands.AuctionBidCommand; import org.ojim.client.ai.commands.BuildHouseCommand; import org.ojim.client.ai.commands.Command; import org.ojim.client.ai.commands.DeclineCommand; import org.ojim.client.ai.commands.EndTurnCommand; import org.ojim.client.ai.commands.NullCommand; import org.ojim.client.ai.commands.OutOfPrisonCommand; import org.ojim.client.ai.commands.SellCommand; import org.ojim.client.ai.commands.ToggleMortgageCommand; import org.ojim.client.ai.commands.TradeCommand; import org.ojim.log.OJIMLogger; import org.ojim.logic.Logic; import org.ojim.logic.state.Auction; import org.ojim.logic.state.Player; import org.ojim.logic.state.fields.BuyableField; import org.ojim.logic.state.fields.Field; +import org.ojim.logic.state.fields.FieldGroup; import org.ojim.logic.state.fields.Jail; import org.ojim.logic.state.fields.Street; import edu.kit.iti.pse.iface.IServer; /** * Valuator - returns the best command * * @author Jeremias Mechler * */ public class Valuator extends SimpleClient { /** * */ private static final long serialVersionUID = -1145966856856523668L; private double[] weights; private ValuationFunction[] valuationFunctions; private Logic logic; private int playerID; private IServer server; private Logger logger; private int auctionBid; private int auctionSteps = 11; - private int currentStep = 2; + private int currentStep = 1; private boolean endTurn = false; private boolean auctionEndTurn = false; private int[] trade; private int count = 0; private int[] toSell; /** * Constructor * * @param logic * reference to logic * @param server * reference to server * @param playerID * The player's ID */ public Valuator(Logic logic, IServer server, int playerID) { super(logic, playerID, server); assert (logic != null); assert (server != null); this.logic = logic; this.server = server; this.playerID = playerID; weights = new double[ValuationFunction.COUNT]; for (int i = 0; i < weights.length; i++) { weights[i] = 1; } weights[0] = 100000; weights[2] = 50000; this.logger = OJIMLogger.getLogger(this.getClass().toString()); valuationFunctions = new ValuationFunction[6]; valuationFunctions[0] = CapitalValuator.getInstance(); valuationFunctions[1] = PropertyValuator.getInstance(); valuationFunctions[2] = PrisonValuator.getInstance(); valuationFunctions[3] = MortgageValuator.getInstance(); valuationFunctions[4] = PropertyGroupValuator.getInstance(); valuationFunctions[5] = BuildingOnPropertyValuator.getInstance(); for (int i = 0; i < ValuationFunction.COUNT; i++) { assert (valuationFunctions[i] != null); } ValuationParameters.init(logic); trade = new int[40]; } /** * Returns the best command * * @param position * current position * @return command */ public Command returnBestCommand(int position) { if (position >= 40) { throw new IllegalArgumentException("Invalid position: " + position); } PriorityQueue<Command> queue = new PriorityQueue<Command>(); Field field = getGameState().getFieldAt(Math.abs(position)); initFunctions(); // OJIMLogger.changeGlobalLevel(Level.WARNING); // OJIMLogger.changeLogLevel(logger, Level.FINE); // Feld potenziell kaufbar if (!endTurn && !auctionEndTurn) { // System.out.println("turn"); queue.add(buyFields(field)); // Feld potentiell bebaubar queue.add(upgradeStreet()); queue.add(tradeStreet(logic.getGameState().getFieldAt(position))); queue.add(getOutOfJail()); // reicht das? if (queue.peek() instanceof NullCommand) { endTurn = true; } return queue.peek(); } if (endTurn) { endTurn = false; return new EndTurnCommand(logic, server, playerID); } if (auctionEndTurn) { auctionEndTurn = false; return new NullCommand(logic, server, playerID); } assert (false); return new NullCommand(logic, server, playerID); } /** * Acting on a trade offer * * @return Command */ public Command actOnTradeOffer() { initFunctions(); // System.out.println("Trade!"); assert (this.getTradeState() == TradeState.WAITING_PROPOSED); boolean restricted = false; if (getRequiredEstates() != null) { for (BuyableField field : getRequiredEstates()) { if (field.isMortgaged()) { // TODO necessary? assert (false); restricted = true; } if (field instanceof Street && ((Street) field).getBuiltLevel() > 0) { // TODO necessary? assert (false); restricted = true; } } } if (!restricted) { double value = getOfferedCash(); double minus = tradeValuateRequestedEstates(); value += tradeValuateJailCards(); value += tradeValuateOfferedEstates(); minus -= getRequiredCash(); minus += valuationFunctions[0].returnValuation(this.getRequiredCash()); // missing: out of jail cards! if (value + minus > 0) { assert (false); return new AcceptCommand(logic, server, playerID); } } return new DeclineCommand(logic, server, playerID); } /** * Pays back mortgages * * @return command */ public Command paybackMortgages() { initFunctions(); PriorityQueue<Command> queue = new PriorityQueue<Command>(); Command command = new NullCommand(logic, server, playerID); command.setValuation(0); queue.add(command); for (BuyableField field : getMe().getFields()) { if (field.isMortgaged()) { field.setSelected(true); double valuation = getResults(field.getPosition(), field.getMortgagePrice()); System.out.println(valuation); field.setSelected(false); if (valuation >= 0) { command = new ToggleMortgageCommand(logic, server, playerID, field); command.setValuation(valuation); queue.add(command); } } } return queue.peek(); } /** * Acts on auction * * @return Command */ public Command actOnAuction() { initFunctions(); Auction auction = this.getGameState().getAuction(); assert (auction.getState() != AuctionState.NOT_RUNNING); int realValue = (int) getResults(auction.objective.getPosition(), 0); int bidder; if (auction.getHighestBidder() == null) { bidder = -1; } else { bidder = auction.getHighestBidder().getId(); } logger.log(Level.FINE, "state = " + auction.getState().value + " bidder = " + bidder + " highesBid = " + auction.getHighestBid() + " value = " + realValue); if (auction.getState() != AuctionState.THIRD && auction.getHighestBidder() != getMe() && auction.getHighestBid() < realValue && currentStep < auctionSteps) { logger.log(Level.FINE, "Highest bid = " + auction.getHighestBid()); if (auction.getHighestBid() < realValue) { logger.log(Level.FINE, "Valuation " + realValue); - double factor = Math.log(currentStep++) / Math.log(auctionSteps); + double factor = Math.log(0.1 + currentStep++) / Math.log(0.1 + auctionSteps); auctionBid = (int) (factor * realValue); logger.log(Level.FINE, "Bidding " + auctionBid); if (getResults(auction.objective.getPosition(), auctionBid) > 0) { return new AuctionBidCommand(logic, server, playerID, auctionBid); } else { auctionEndTurn = true; return new NullCommand(logic, server, playerID); } } } if (auction.getState() == AuctionState.THIRD) { - currentStep = 2; + currentStep = 1; } if (auction.getHighestBidder() != getMe()) { auctionEndTurn = true; } return new NullCommand(logic, server, playerID); } private double getResults(int position, int amount) { assert (position <= 40 && position >= 0); assert (amount >= 0); double result = weights[0] * valuationFunctions[0].returnValuation(amount); for (int i = 1; i < valuationFunctions.length; i++) { result += weights[i] * valuationFunctions[i].returnValuation(position); } logger.log(Level.INFO, "gesamt = " + result); return result; } private double tradeValuateJailCards() { int offeredCards = getNumberOfOfferedGetOutOfJailCards(); int difference = ValuationParameters.desiredNumberOfOutOfOjailCards - this.getMe().getNumberOfGetOutOfJailCards(); if (difference > 0) { if (offeredCards >= difference) { return ((Jail) getGameState().getFieldAt(10)).getMoneyToPay() * difference; } else { return ((Jail) getGameState().getFieldAt(10)).getMoneyToPay() * offeredCards; } } else { return 0; } } private double tradeValuateEstates(BuyableField[] estates) { assert (estates != null); double result = 0; for (BuyableField estate : estates) { result += getResults(estate.getPosition(), 0); } return result; } private double tradeValuateRequestedEstates() { return (-1) * tradeValuateEstates(getRequiredEstates()); } private double tradeValuateOfferedEstates() { return tradeValuateEstates(getOfferedEstate()); } private void getPropertiesToSell(int requiredCash, boolean mortgage) { int cash = 0; ArrayList<BuyableField> list = new ArrayList<BuyableField>(); PriorityQueue<BuyableField> queue = getMe().getQueue(); // TODO better condition? while (cash < requiredCash && !queue.isEmpty()) { BuyableField temp = queue.poll(); cash += temp.getPrice() / 2; list.add(temp); revaluate(queue); } int[] result = new int[list.size()]; int i = 0; for (BuyableField field : list) { result[i++] = field.getPosition(); } toSell = result; } // beim Hinzufügen alle neu validieren? private void revaluate(PriorityQueue<BuyableField> queue) { BuyableField[] fields = new BuyableField[queue.size()]; int i = 0; while (!queue.isEmpty()) { BuyableField field = queue.poll(); field.setValuation(getResults(field.getPosition(), 0)); fields[i++] = field; } for (BuyableField field : fields) { queue.add(field); } assert (queue.size() == fields.length); } private void sell(int requiredCash) { int initialCash = getLogic().getGameState().getActivePlayer().getBalance(); int newCash = 0; // Property[] toBeSold = new Property[list.size()]; // toBeSold = list.toArray(new Property[0]); // Iterator-Zugriffsfehler? for (BuyableField field : this.getMe().getQueue()) { if (newCash < requiredCash) { int faceValue = field.getPrice(); new SellCommand(logic, server, playerID, field.getPosition(), (int) Math.max(faceValue, field.getValuation()), faceValue / 2).execute(); newCash = logic.getGameState().getActivePlayer().getBalance() - initialCash; assert (newCash != initialCash); // property = null; // field.setSelected(true); } else { field.setSelected(false); } } revaluate(getMe().getQueue()); } private int getPrice(int position) { assert (position < 40 && position >= 0); Field field = logic.getGameState().getFieldAt(position); assert (field instanceof BuyableField); return ((BuyableField) field).getPrice(); } private Command tradeStreet(Field blaField) { count++; Command result = new NullCommand(logic, server, playerID); result.setValuation(0); assert (blaField != null); if (trade[blaField.getPosition()] != count - 1 && blaField instanceof BuyableField - && ((BuyableField) blaField).getOwner() != null && ((BuyableField) blaField).getOwner() != getMe()) { + && ((BuyableField) blaField).getOwner() != null && ((BuyableField) blaField).getOwner() != getMe() + && ((BuyableField) blaField).getFieldGroup().getFields().length > 1 + && fieldsOwned(((BuyableField) blaField).getFieldGroup()) > 0) { trade[blaField.getPosition()] = count; PriorityQueue<BuyableField> queue = new PriorityQueue<BuyableField>(); double streetValue = getResults(blaField.getPosition(), 0); // get possible trade street Field[] myFields = getMe().getFields(); Field[] hisFields = ((BuyableField) blaField).getOwner().getFields(); HashSet<Integer> colorList = new HashSet<Integer>(); for (Field field : hisFields) { if (field instanceof BuyableField) { int color = (((BuyableField) field).getFieldGroup().getColor()); if (color != blaField.getFieldGroup().getColor()) { colorList.add(color); } } } for (Field field : myFields) { if (field instanceof BuyableField) { int color = (((BuyableField) field).getFieldGroup().getColor()); if (colorList.contains(color)) { queue.add((BuyableField) field); } } } revaluate(queue); if (!queue.isEmpty()) { // System.out.println("Val = " + queue.peek().getValuation()); result = new TradeCommand(logic, playerID, server, queue.peek(), (BuyableField) blaField); result.setValuation(1000 * streetValue); } } return result; } + private int fieldsOwned(FieldGroup group) { + Field[] fields = group.getFields(); + int count = 0; + for (Field field : fields) { + if (((BuyableField) field).getOwner() == getMe()) { + count++; + } + } + return count; + } + /** * Acts on negative money * * @return Command */ public Command negative() { if (getMe().getBalance() > 0) { throw new IllegalStateException("Positive cash!"); } logger.log(Level.FINE, "Negative cash!"); int balance = Math.abs(getMe().getBalance()); assert (balance > 0); BuyableField[] result = mortgageBuildings(balance); boolean success = false; if (result.length > 0) { success = true; return new ToggleMortgageCommand(logic, server, playerID, result[0]); } else { LinkedList<BuyableField> list = new LinkedList<BuyableField>(); result = mortgageBuildings(0); if (result.length != 0) { int sum = 0; for (int i = 0; i < result.length; i++) { if (sum < balance) { list.add(result[i]); sum += result[i].getMortgagePrice(); } } if (sum >= balance) { success = true; return new ToggleMortgageCommand(logic, server, playerID, list.toArray(new BuyableField[0])); } } } return new NullCommand(logic, server, playerID); } private BuyableField[] mortgageBuildings(int money) { LinkedList<BuyableField> list = new LinkedList<BuyableField>(); for (BuyableField field : getMe().getFields()) { if (getGameRules().isFieldMortgageable(getMe(), field) && field.getMortgagePrice() >= Math.abs(money)) { list.add(field); } } // assert(getMe().getFields().length > 0); /** * Compares the price of two fields */ final class MoneyComparator implements Comparator<BuyableField> { @Override public int compare(BuyableField o1, BuyableField o2) { return o1.getPrice() - o2.getPrice(); } } BuyableField[] array = list.toArray(new BuyableField[0]); Arrays.sort(array, new MoneyComparator()); return array; } private Command buyFields(Field field) { assert (field != null); if (field instanceof BuyableField && !endTurn) { logger.log(Level.FINE, "BuyableField!"); Player owner = ((BuyableField) field).getOwner(); double realValue = getResults(field.getPosition(), 0); // Feld gehört mir (noch) nicht if (owner != getMe()) { int price = ((BuyableField) field).getPrice(); double valuation = getResults(field.getPosition(), price); // double realValue = getResults(position, 0); // Feld gehört der Bank if (owner == null) { if (valuation > 0) { logger.log(Level.FINE, "Granted"); assert (logic != null); assert (server != null); logger.log(Level.FINE, "Accept"); return new AcceptCommand(logic, server, playerID); // nicht ausreichend, ab wann verkaufen oder handeln? } else if (realValue > 0 && false) { // preis? // getPropertiesToSell(); // sell(); // return new DeclineCommand(logic, server, playerID); } else { // Ablehnen logger.log(Level.FINE, "Decline"); endTurn = true; return new DeclineCommand(logic, server, playerID); } } else { // Trade! logger.log(Level.FINE, "Soon trade"); // return new NullCommand(logic, server, playerID); } } } Command result = new NullCommand(logic, server, playerID); result.setValuation(0); return result; } private Command upgradeStreet() { PriorityQueue<Street> upgradeableStreets = new PriorityQueue<Street>(); for (int i = 0; i < 40; i++) { Field field = getGameState().getFieldAt(i); if (field instanceof Street) { Street street = (Street) field; // assert(getGameRules().isFieldUpgradable(getMe(), field, street.getBuiltLevel() + 1)); if (getGameRules().isFieldUpgradable(getMe(), field, street.getBuiltLevel() + 1)) { street.setSelected(true); street.setValuation(getResults(street.getPosition(), server.getEstateHousePrice(street.getPosition()))); street.setSelected(false); upgradeableStreets.add((Street) field); } } } if (upgradeableStreets.size() > 0 && upgradeableStreets.peek().getValuation() > 0) { Command result = new BuildHouseCommand(logic, server, playerID, upgradeableStreets.peek()); result.setValuation(upgradeableStreets.peek().getValuation()); return result; } else { Command result = new NullCommand(logic, server, playerID); result.setValuation(0); return result; } } private Command getOutOfJail() { assert (getMe() == logic.getGameState().getActivePlayer()); Jail jail = getMe().getJail(); if (jail != null) { assert (false); double valuation = getResults(jail.getPosition(), jail.getMoneyToPay()); if (valuation > 0) { Command result = new OutOfPrisonCommand(logic, server, playerID); result.setValuation(valuation); return result; } } Command result = new EndTurnCommand(logic, server, playerID); result.setValuation(0); return result; } private void initFunctions() { for (ValuationFunction function : valuationFunctions) { assert (function != null); function.setParameters(logic); function.setServer(server); } } }
false
false
null
null
diff --git a/src/com/alsutton/jabber/JabberStream.java b/src/com/alsutton/jabber/JabberStream.java index e123b1e8..9b087f80 100644 --- a/src/com/alsutton/jabber/JabberStream.java +++ b/src/com/alsutton/jabber/JabberStream.java @@ -1,387 +1,387 @@ /* Copyright (c) 2000,2001 Al Sutton (al@alsutton.com) 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. Neither the name of Al Sutton 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 REGENTS 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.alsutton.jabber; import Account.Account; import Client.Config; import Client.StaticData; //#ifdef CONSOLE //# import Console.StanzasList; //#endif import io.Utf8IOStream; import java.io.*; import java.util.*; import javax.microedition.io.*; import xml.*; import locale.SR; import xmpp.XmppError; import xmpp.XmppParser; import xmpp.extensions.IqPing; public class JabberStream extends XmppParser implements Runnable { private Utf8IOStream iostream; /** * The dispatcher thread. */ private JabberDataBlockDispatcher dispatcher; //private boolean rosterNotify; //voffk private String server; // for ping public boolean pingSent; public boolean loggedIn; private boolean xmppV1; private String sessionId; //public void enableRosterNotify(boolean en){ rosterNotify=en; } //voffk /** * Constructor. Connects to the server and sends the jabber welcome message. * */ public JabberStream( String server, String hostAddr, String proxy) throws IOException { this.server=server; boolean waiting=Config.getInstance().istreamWaiting; StreamConnection connection; if (proxy==null) { connection = (StreamConnection) Connector.open(hostAddr); } else { //#if HTTPCONNECT //# connection = io.HttpProxyConnection.open(hostAddr, proxy); //#elif HTTPPOLL //# connection = new io.HttpPollingConnection(hostAddr, proxy); //#else throw new IllegalArgumentException ("no proxy supported"); //#endif } iostream=new Utf8IOStream(connection); dispatcher = new JabberDataBlockDispatcher(this); new Thread( this ). start(); } public void initiateStream() throws IOException { StringBuffer header=new StringBuffer("<stream:stream to='" ).append( server ).append( "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'" ); header.append(" version='1.0'"); if (SR.MS_XMLLANG!=null) { header.append(" xml:lang='").append(SR.MS_XMLLANG).append("'"); } header.append( '>' ); send(header.toString()); header=null; } public boolean tagStart(String name, Vector attributes) { if (name.equals( "stream:stream" ) ) { sessionId = XMLParser.extractAttribute("id", attributes); String version=XMLParser.extractAttribute("version", attributes); xmppV1 = ("1.0".equals(version)); dispatcher.broadcastBeginConversation(); return false; } return super.tagStart(name, attributes); } public boolean isXmppV1() { return xmppV1; } public String getSessionId() { return sessionId; } public void tagEnd(String name) throws XMLException { if (currentBlock == null) { if (name.equals( "stream:stream" ) ) { dispatcher.halt(); iostream.close(); if (Config.getInstance().phoneManufacturer!=Config.NOKIA && Config.getInstance().phoneManufacturer!=Config.NOKIA_9XXX) iostream=null; throw new XMLException("Normal stream shutdown"); } return; } if (currentBlock.getParent() == null) { if (currentBlock.getTagName().equals("stream:error")) { XmppError xe = XmppError.decodeStreamError(currentBlock); dispatcher.halt(); iostream.close(); if (Config.getInstance().phoneManufacturer!=Config.NOKIA && Config.getInstance().phoneManufacturer!=Config.NOKIA_9XXX) iostream=null; throw new XMLException("Stream error: "+xe.toString()); } } super.tagEnd(name); } protected void dispatchXmppStanza(JabberDataBlock currentBlock) { dispatcher.broadcastJabberDataBlock( currentBlock ); } public void startKeepAliveTask(){ Account account=StaticData.getInstance().account; int keepAliveType=account.getKeepAliveType(); if (keepAliveType==0) return; int keepAlivePeriod=account.getKeepAlivePeriod(); if (keepAlive!=null) { keepAlive.destroyTask(); keepAlive=null; } keepAlive=new TimerTaskKeepAlive(keepAlivePeriod, keepAliveType); } /** * The threads run method. Handles the parsing of incomming data in its * own thread. */ public void run() { try { XMLParser parser = new XMLParser( this ); byte cbuf[]=new byte[512]; while (true) { int length=iostream.read(cbuf); if (length==0) { try { Thread.sleep(100); } catch (Exception e) {}; continue; } parser.parse(cbuf, length); } //dispatcher.broadcastTerminatedConnection( null ); } catch( Exception e ) { System.out.println("Exception in parser:"); e.printStackTrace(); dispatcher.broadcastTerminatedConnection(e); }; } /** * Method to close the connection to the server and tell the listener * that the connection has been terminated. */ public void close() { if (keepAlive!=null) keepAlive.destroyTask(); dispatcher.setJabberListener( null ); try { //TODO: see FS#528 try { Thread.sleep(500); } catch (Exception e) {} send( "</stream:stream>" ); int time=10; while (dispatcher.isActive()) { try { Thread.sleep(500); } catch (Exception e) {} if ((--time)<0) break; } //connection.close(); } catch( IOException e ) { } dispatcher.halt(); iostream.close(); if (Config.getInstance().phoneManufacturer!=Config.NOKIA && Config.getInstance().phoneManufacturer!=Config.NOKIA_9XXX) iostream=null; } /** * Method of sending data to the server. * * @param The data to send to the server. */ public void sendKeepAlive(int type) throws IOException { switch (type){ case 3: if (pingSent) { dispatcher.broadcastTerminatedConnection(new Exception("Ping Timeout")); } else { //System.out.println("Ping myself"); ping(); } break; case 2: send("<iq/>"); break; case 1: send(" "); } } public void send( String data ) throws IOException { iostream.send(new StringBuffer(data)); //#ifdef CONSOLE //# if (data.equals("</iq") || data.equals(" ")) //# if (StanzasList.getInstance().enabled) addLog("Ping myself", 1); //# else //# if (StanzasList.getInstance().enabled) addLog(data, 1); //#endif } public void sendBuf( StringBuffer data ) throws IOException { iostream.send(data); //#ifdef CONSOLE //# if (StanzasList.getInstance().enabled) addLog(data.toString(), 1); //#endif } /** * Method of sending a Jabber datablock to the server. * * @param block The data block to send to the server. */ public void send( JabberDataBlock block ) { - new SendJabberDataBlock(block); + new SendJabberDataBlock(block).run(); } //#ifdef CONSOLE //# private int canLog=0; //# //# public void addLog (String data, int type) { //#ifdef PLUGINS //# if (canLog<1) { //# if (StaticData.getInstance().Console) { //# canLog=1; //# } else { //# canLog=-1; //# return; //# } //# } //#endif //# StanzasList.getInstance().add(data, type); //# } //#endif /** * Set the listener to this stream. */ public void addBlockListener(JabberBlockListener listener) { dispatcher.addBlockListener(listener); } public void cancelBlockListener(JabberBlockListener listener) { dispatcher.cancelBlockListener(listener); } public void cancelBlockListenerByClass(Class removeClass) { dispatcher.cancelBlockListenerByClass(removeClass); } public void setJabberListener( JabberListener listener ) { dispatcher.setJabberListener( listener ); } private void ping() { pingSent=true; send(IqPing.query(StaticData.getInstance().account.getServer(), "ping")); } //#if ZLIB public void setZlibCompression() { iostream.setStreamCompression(); } public String getStreamStats() { return iostream.getStreamStats(); } public String getConnectionData() { return iostream.getConnectionData(); } //#endif public long getBytes() { return iostream.getBytes(); } private TimerTaskKeepAlive keepAlive; private class TimerTaskKeepAlive extends TimerTask{ private Timer t; //private int verifyCtr; // int period; private int type; public TimerTaskKeepAlive(int periodSeconds, int type){ t=new Timer(); this.type=type; //this.period=periodSeconds; long periodRun=periodSeconds*1000; // milliseconds t.schedule(this, periodRun, periodRun); } public void run() { try { //System.out.println("Keep-Alive"); if (loggedIn) sendKeepAlive(type); } catch (Exception e) { dispatcher.broadcastTerminatedConnection(e); //e.printStackTrace(); } } public void destroyTask(){ if (t!=null){ this.cancel(); t.cancel(); t=null; } } } private class SendJabberDataBlock implements Runnable { private JabberDataBlock data; public SendJabberDataBlock(JabberDataBlock data) { this.data=data; - new Thread(this).start(); +// new Thread(this).start(); } public void run(){ try { Thread.sleep(100); StringBuffer buf=new StringBuffer(); data.constructXML(buf); sendBuf( buf ); buf=null; } catch (Exception e) { } } } }
false
false
null
null
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index a053b9bbb..31cbc4ee3 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -1,2461 +1,2483 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; import android.net.ConnectivityManager; import android.os.Debug; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.InputConnection; import com.android.inputmethod.accessibility.AccessibilityUtils; import com.android.inputmethod.compat.CompatUtils; import com.android.inputmethod.compat.EditorInfoCompatUtils; import com.android.inputmethod.compat.InputConnectionCompatUtils; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; import com.android.inputmethod.compat.InputMethodServiceCompatWrapper; import com.android.inputmethod.compat.InputTypeCompatUtils; import com.android.inputmethod.compat.SuggestionSpanUtils; import com.android.inputmethod.compat.VibratorCompatWrapper; import com.android.inputmethod.deprecated.LanguageSwitcherProxy; import com.android.inputmethod.deprecated.VoiceProxy; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.KeyboardView; import com.android.inputmethod.keyboard.LatinKeyboardView; import com.android.inputmethod.latin.suggestions.SuggestionsView; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Locale; /** * Input method implementation for Qwerty'ish keyboard. */ public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener, SuggestionsView.Listener { private static final String TAG = LatinIME.class.getSimpleName(); private static final boolean TRACE = false; private static boolean DEBUG; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. * * @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed. */ @SuppressWarnings("dep-ann") public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm"; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. */ public static final String IME_OPTION_NO_MICROPHONE = "noMicrophoneKey"; /** * The private IME option used to indicate that no settings key should be * shown for a given text field. */ public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey"; // TODO: Remove this private option. /** * The private IME option used to indicate that the given text field needs * ASCII code points input. * * @deprecated Use {@link EditorInfo#IME_FLAG_FORCE_ASCII}. */ @SuppressWarnings("dep-ann") public static final String IME_OPTION_FORCE_ASCII = "forceAscii"; /** * The subtype extra value used to indicate that the subtype keyboard layout is capable for * typing ASCII characters. */ public static final String SUBTYPE_EXTRA_VALUE_ASCII_CAPABLE = "AsciiCapable"; /** * The subtype extra value used to indicate that the subtype keyboard layout supports touch * position correction. */ public static final String SUBTYPE_EXTRA_VALUE_SUPPORT_TOUCH_POSITION_CORRECTION = "SupportTouchPositionCorrection"; /** * The subtype extra value used to indicate that the subtype keyboard layout should be loaded * from the specified locale. */ public static final String SUBTYPE_EXTRA_VALUE_KEYBOARD_LOCALE = "KeyboardLocale"; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; private static final int PENDING_IMS_CALLBACK_DURATION = 800; /** * The name of the scheme used by the Package Manager to warn of a new package installation, * replacement or removal. */ private static final String SCHEME_PACKAGE = "package"; // TODO: migrate this to SettingsValues private int mSuggestionVisibility; private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE = R.string.prefs_suggestion_visibility_show_value; private static final int SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE = R.string.prefs_suggestion_visibility_show_only_portrait_value; private static final int SUGGESTION_VISIBILILTY_HIDE_VALUE = R.string.prefs_suggestion_visibility_hide_value; private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] { SUGGESTION_VISIBILILTY_SHOW_VALUE, SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE, SUGGESTION_VISIBILILTY_HIDE_VALUE }; // Magic space: a space that should disappear on space/apostrophe insertion, move after the // punctuation on punctuation insertion, and become a real space on alpha char insertion. // Weak space: a space that should be swapped only by suggestion strip punctuation. // Double space: the state where the user pressed space twice quickly, which LatinIME // resolved as period-space. Undoing this converts the period to a space. // Swap punctuation: the state where a (weak or magic) space and a punctuation from the // suggestion strip have just been swapped. Undoing this swaps them back. private static final int SPACE_STATE_NONE = 0; private static final int SPACE_STATE_DOUBLE = 1; private static final int SPACE_STATE_SWAP_PUNCTUATION = 2; private static final int SPACE_STATE_MAGIC = 3; private static final int SPACE_STATE_WEAK = 4; // Current space state of the input method. This can be any of the above constants. private int mSpaceState; private SettingsValues mSettingsValues; private InputAttributes mInputAttributes; private View mExtractArea; private View mKeyPreviewBackingView; private View mSuggestionsContainer; private SuggestionsView mSuggestionsView; private Suggest mSuggest; private CompletionInfo[] mApplicationSpecifiedCompletions; private InputMethodManagerCompatWrapper mImm; private Resources mResources; private SharedPreferences mPrefs; private KeyboardSwitcher mKeyboardSwitcher; private SubtypeSwitcher mSubtypeSwitcher; private VoiceProxy mVoiceProxy; private UserDictionary mUserDictionary; private UserBigramDictionary mUserBigramDictionary; private UserUnigramDictionary mUserUnigramDictionary; private boolean mIsUserDictionaryAvailable; private WordComposer mWordComposer = new WordComposer(); private int mCorrectionMode; + // Keep track of the last selection range to decide if we need to show word alternatives - private int mLastSelectionStart; - private int mLastSelectionEnd; + private static final int NOT_A_CURSOR_POSITION = -1; + private int mLastSelectionStart = NOT_A_CURSOR_POSITION; + private int mLastSelectionEnd = NOT_A_CURSOR_POSITION; // Whether we are expecting an onUpdateSelection event to fire. If it does when we don't // "expect" it, it means the user actually moved the cursor. private boolean mExpectingUpdateSelection; private int mDeleteCount; private long mLastKeyTime; private AudioManager mAudioManager; private boolean mSilentModeOn; // System-wide current configuration private VibratorCompatWrapper mVibrator; // TODO: Move this flag to VoiceProxy private boolean mConfigurationChanging; // Member variables for remembering the current device orientation. private int mDisplayOrientation; // Object for reacting to adding/removing a dictionary pack. private BroadcastReceiver mDictionaryPackInstallReceiver = new DictionaryPackInstallBroadcastReceiver(this); // Keeps track of most recently inserted text (multi-character key) for reverting private CharSequence mEnteredText; private final ComposingStateManager mComposingStateManager = ComposingStateManager.getInstance(); public final UIHandler mHandler = new UIHandler(this); public static class UIHandler extends StaticInnerHandlerWrapper<LatinIME> { private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_UPDATE_SHIFT_STATE = 1; private static final int MSG_VOICE_RESULTS = 2; private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 3; private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 4; private static final int MSG_SPACE_TYPED = 5; private static final int MSG_SET_BIGRAM_PREDICTIONS = 6; private static final int MSG_PENDING_IMS_CALLBACK = 7; private int mDelayBeforeFadeoutLanguageOnSpacebar; private int mDelayUpdateSuggestions; private int mDelayUpdateShiftState; private int mDurationOfFadeoutLanguageOnSpacebar; private float mFinalFadeoutFactorOfLanguageOnSpacebar; private long mDoubleSpacesTurnIntoPeriodTimeout; public UIHandler(LatinIME outerInstance) { super(outerInstance); } public void onCreate() { final Resources res = getOuterInstance().getResources(); mDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_delay_before_fadeout_language_on_spacebar); mDelayUpdateSuggestions = res.getInteger(R.integer.config_delay_update_suggestions); mDelayUpdateShiftState = res.getInteger(R.integer.config_delay_update_shift_state); mDurationOfFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_duration_of_fadeout_language_on_spacebar); mFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger( R.integer.config_final_fadeout_percentage_of_language_on_spacebar) / 100.0f; mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger( R.integer.config_double_spaces_turn_into_period_timeout); } @Override public void handleMessage(Message msg) { final LatinIME latinIme = getOuterInstance(); final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; final LatinKeyboardView inputView = switcher.getKeyboardView(); switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: latinIme.updateSuggestions(); break; case MSG_UPDATE_SHIFT_STATE: switcher.updateShiftState(); break; case MSG_SET_BIGRAM_PREDICTIONS: latinIme.updateBigramPredictions(); break; case MSG_VOICE_RESULTS: latinIme.mVoiceProxy.handleVoiceResults(latinIme.preferCapitalization() || (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked())); break; case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR: setSpacebarTextFadeFactor(inputView, (1.0f + mFinalFadeoutFactorOfLanguageOnSpacebar) / 2, (Keyboard)msg.obj); sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj), mDurationOfFadeoutLanguageOnSpacebar); break; case MSG_DISMISS_LANGUAGE_ON_SPACEBAR: setSpacebarTextFadeFactor(inputView, mFinalFadeoutFactorOfLanguageOnSpacebar, (Keyboard)msg.obj); break; } } public void postUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), mDelayUpdateSuggestions); } public void cancelUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); } public boolean hasPendingUpdateSuggestions() { return hasMessages(MSG_UPDATE_SUGGESTIONS); } public void postUpdateShiftKeyState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState); } public void cancelUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); } public void postUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS), mDelayUpdateSuggestions); } public void cancelUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); } public void updateVoiceResults() { sendMessage(obtainMessage(MSG_VOICE_RESULTS)); } private static void setSpacebarTextFadeFactor(LatinKeyboardView inputView, float fadeFactor, Keyboard oldKeyboard) { if (inputView == null) return; final Keyboard keyboard = inputView.getKeyboard(); if (keyboard == oldKeyboard) { inputView.updateSpacebar(fadeFactor, SubtypeSwitcher.getInstance().needsToDisplayLanguage( keyboard.mId.mLocale)); } } public void startDisplayLanguageOnSpacebar(boolean localeChanged) { final LatinIME latinIme = getOuterInstance(); removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR); removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR); final LatinKeyboardView inputView = latinIme.mKeyboardSwitcher.getKeyboardView(); if (inputView != null) { final Keyboard keyboard = latinIme.mKeyboardSwitcher.getKeyboard(); // The language is always displayed when the delay is negative. final boolean needsToDisplayLanguage = localeChanged || mDelayBeforeFadeoutLanguageOnSpacebar < 0; // The language is never displayed when the delay is zero. if (mDelayBeforeFadeoutLanguageOnSpacebar != 0) { setSpacebarTextFadeFactor(inputView, needsToDisplayLanguage ? 1.0f : mFinalFadeoutFactorOfLanguageOnSpacebar, keyboard); } // The fadeout animation will start when the delay is positive. if (localeChanged && mDelayBeforeFadeoutLanguageOnSpacebar > 0) { sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard), mDelayBeforeFadeoutLanguageOnSpacebar); } } } public void startDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED), mDoubleSpacesTurnIntoPeriodTimeout); } public void cancelDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); } public boolean isAcceptingDoubleSpaces() { return hasMessages(MSG_SPACE_TYPED); } // Working variables for the following methods. private boolean mIsOrientationChanging; private boolean mPendingSuccessiveImsCallback; private boolean mHasPendingStartInput; private boolean mHasPendingFinishInputView; private boolean mHasPendingFinishInput; private EditorInfo mAppliedEditorInfo; public void startOrientationChanging() { removeMessages(MSG_PENDING_IMS_CALLBACK); resetPendingImsCallback(); mIsOrientationChanging = true; final LatinIME latinIme = getOuterInstance(); if (latinIme.isInputViewShown()) { latinIme.mKeyboardSwitcher.saveKeyboardState(); } } private void resetPendingImsCallback() { mHasPendingFinishInputView = false; mHasPendingFinishInput = false; mHasPendingStartInput = false; } private void executePendingImsCallback(LatinIME latinIme, EditorInfo editorInfo, boolean restarting) { if (mHasPendingFinishInputView) latinIme.onFinishInputViewInternal(mHasPendingFinishInput); if (mHasPendingFinishInput) latinIme.onFinishInputInternal(); if (mHasPendingStartInput) latinIme.onStartInputInternal(editorInfo, restarting); resetPendingImsCallback(); } public void onStartInput(EditorInfo editorInfo, boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the second onStartInput after orientation changed. mHasPendingStartInput = true; } else { if (mIsOrientationChanging && restarting) { // This is the first onStartInput after orientation changed. mIsOrientationChanging = false; mPendingSuccessiveImsCallback = true; } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputInternal(editorInfo, restarting); } } public void onStartInputView(EditorInfo editorInfo, boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK) && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { // Typically this is the second onStartInputView after orientation changed. resetPendingImsCallback(); } else { if (mPendingSuccessiveImsCallback) { // This is the first onStartInputView after orientation changed. mPendingSuccessiveImsCallback = false; resetPendingImsCallback(); sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), PENDING_IMS_CALLBACK_DURATION); } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputViewInternal(editorInfo, restarting); mAppliedEditorInfo = editorInfo; } } public void onFinishInputView(boolean finishingInput) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInputView after orientation changed. mHasPendingFinishInputView = true; } else { final LatinIME latinIme = getOuterInstance(); latinIme.onFinishInputViewInternal(finishingInput); mAppliedEditorInfo = null; } } public void onFinishInput() { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInput after orientation changed. mHasPendingFinishInput = true; } else { final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, null, false); latinIme.onFinishInputInternal(); } } } @Override public void onCreate() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs = prefs; LatinImeLogger.init(this, prefs); LanguageSwitcherProxy.init(this, prefs); InputMethodManagerCompatWrapper.init(this); SubtypeSwitcher.init(this); KeyboardSwitcher.init(this, prefs); AccessibilityUtils.init(this); super.onCreate(); mImm = InputMethodManagerCompatWrapper.getInstance(); mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mVibrator = VibratorCompatWrapper.getInstance(this); mHandler.onCreate(); DEBUG = LatinImeLogger.sDBG; final Resources res = getResources(); mResources = res; loadSettings(); // TODO: remove the following when it's not needed by updateCorrectionMode() any more mInputAttributes = new InputAttributes(null, false /* isFullscreenMode */); Utils.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { initSuggest(); tryGC = false; } catch (OutOfMemoryError e) { tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e); } } mDisplayOrientation = res.getConfiguration().orientation; // Register to receive ringer mode change and network state change. // Also receive installation and removal of a dictionary pack. final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, filter); mVoiceProxy = VoiceProxy.init(this, prefs, mHandler); final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); packageFilter.addDataScheme(SCHEME_PACKAGE); registerReceiver(mDictionaryPackInstallReceiver, packageFilter); final IntentFilter newDictFilter = new IntentFilter(); newDictFilter.addAction( DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION); registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); } // Has to be package-visible for unit tests /* package */ void loadSettings() { if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (null == mSubtypeSwitcher) mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mSettingsValues = new SettingsValues(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr()); resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); } private void initSuggest() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = LocaleUtils.constructLocaleFromString(localeStr); final Resources res = mResources; final Locale savedLocale = LocaleUtils.setSystemLocale(res, keyboardLocale); final ContactsDictionary oldContactsDictionary; if (mSuggest != null) { oldContactsDictionary = mSuggest.getContactsDictionary(); mSuggest.close(); } else { oldContactsDictionary = null; } int mainDicResId = Utils.getMainDictionaryResourceId(res); mSuggest = new Suggest(this, mainDicResId, keyboardLocale); if (mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } mUserDictionary = new UserDictionary(this, localeStr); mSuggest.setUserDictionary(mUserDictionary); mIsUserDictionaryAvailable = mUserDictionary.isEnabled(); resetContactsDictionary(oldContactsDictionary); mUserUnigramDictionary = new UserUnigramDictionary(this, this, localeStr, Suggest.DIC_USER_UNIGRAM); mSuggest.setUserUnigramDictionary(mUserUnigramDictionary); mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER_BIGRAM); mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); LocaleUtils.setSystemLocale(res, savedLocale); } /** * Resets the contacts dictionary in mSuggest according to the user settings. * * This method takes an optional contacts dictionary to use. Since the contacts dictionary * does not depend on the locale, it can be reused across different instances of Suggest. * The dictionary will also be opened or closed as necessary depending on the settings. * * @param oldContactsDictionary an optional dictionary to use, or null */ private void resetContactsDictionary(final ContactsDictionary oldContactsDictionary) { final boolean shouldSetDictionary = (null != mSuggest && mSettingsValues.mUseContactsDict); final ContactsDictionary dictionaryToUse; if (!shouldSetDictionary) { // Make sure the dictionary is closed. If it is already closed, this is a no-op, // so it's safe to call it anyways. if (null != oldContactsDictionary) oldContactsDictionary.close(); dictionaryToUse = null; } else if (null != oldContactsDictionary) { // Make sure the old contacts dictionary is opened. If it is already open, this is a // no-op, so it's safe to call it anyways. oldContactsDictionary.reopen(this); dictionaryToUse = oldContactsDictionary; } else { dictionaryToUse = new ContactsDictionary(this, Suggest.DIC_CONTACTS); } if (null != mSuggest) { mSuggest.setContactsDictionary(dictionaryToUse); } } /* package private */ void resetSuggestMainDict() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = LocaleUtils.constructLocaleFromString(localeStr); int mainDicResId = Utils.getMainDictionaryResourceId(mResources); mSuggest.resetMainDict(this, mainDicResId, keyboardLocale); } @Override public void onDestroy() { if (mSuggest != null) { mSuggest.close(); mSuggest = null; } unregisterReceiver(mReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); mVoiceProxy.destroy(); LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); } @Override public void onConfigurationChanged(Configuration conf) { mSubtypeSwitcher.onConfigurationChanged(conf); mComposingStateManager.onFinishComposingText(); // If orientation changed while predicting, commit the change if (mDisplayOrientation != conf.orientation) { mDisplayOrientation = conf.orientation; mHandler.startOrientationChanging(); final InputConnection ic = getCurrentInputConnection(); commitTyped(ic); if (ic != null) ic.finishComposingText(); // For voice input if (isShowingOptionDialog()) mOptionsDialog.dismiss(); } mConfigurationChanging = true; super.onConfigurationChanged(conf); mVoiceProxy.onConfigurationChanged(conf); mConfigurationChanging = false; // This will work only when the subtype is not supported. LanguageSwitcherProxy.onConfigurationChanged(conf); } @Override public View onCreateInputView() { return mKeyboardSwitcher.onCreateInputView(); } @Override public void setInputView(View view) { super.setInputView(view); mExtractArea = getWindow().getWindow().getDecorView() .findViewById(android.R.id.extractArea); mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing); mSuggestionsContainer = view.findViewById(R.id.suggestions_container); mSuggestionsView = (SuggestionsView) view.findViewById(R.id.suggestions_view); if (mSuggestionsView != null) mSuggestionsView.setListener(this, view); if (LatinImeLogger.sVISUALDEBUG) { mKeyPreviewBackingView.setBackgroundColor(0x10FF0000); } } @Override public void setCandidatesView(View view) { // To ensure that CandidatesView will never be set. return; } @Override public void onStartInput(EditorInfo editorInfo, boolean restarting) { mHandler.onStartInput(editorInfo, restarting); } @Override public void onStartInputView(EditorInfo editorInfo, boolean restarting) { mHandler.onStartInputView(editorInfo, restarting); } @Override public void onFinishInputView(boolean finishingInput) { mHandler.onFinishInputView(finishingInput); } @Override public void onFinishInput() { mHandler.onFinishInput(); } private void onStartInputInternal(EditorInfo editorInfo, boolean restarting) { super.onStartInput(editorInfo, restarting); } private void onStartInputViewInternal(EditorInfo editorInfo, boolean restarting) { super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; LatinKeyboardView inputView = switcher.getKeyboardView(); if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + ((editorInfo == null) ? "none" : String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions))); } LatinImeLogger.onStartInputView(editorInfo); // In landscape mode, this method gets called without the input view being created. if (inputView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(editorInfo, restarting); } mSubtypeSwitcher.updateParametersOnStartInputView(); // Most such things we decide below in initializeInputAttributesAndGetMode, but we need to // know now whether this is a password text field, because we need to know now whether we // want to enable the voice button. final VoiceProxy voiceIme = mVoiceProxy; final int inputType = (editorInfo != null) ? editorInfo.inputType : 0; voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(inputType) || InputTypeCompatUtils.isVisiblePasswordInputType(inputType)); // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); mInputAttributes = new InputAttributes(editorInfo, isFullscreenMode()); mApplicationSpecifiedCompletions = null; inputView.closing(); mEnteredText = null; mWordComposer.reset(); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; loadSettings(); updateCorrectionMode(); updateSuggestionVisibility(mResources); if (mSuggest != null && mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } mVoiceProxy.loadSettings(editorInfo, mPrefs); // This will work only when the subtype is not supported. LanguageSwitcherProxy.loadSettings(); if (mSubtypeSwitcher.isKeyboardMode()) { switcher.loadKeyboard(editorInfo, mSettingsValues); } if (mSuggestionsView != null) mSuggestionsView.clear(); setSuggestionStripShownInternal( isSuggestionsStripVisible(), /* needsInputViewShown */ false); // Delay updating suggestions because keyboard input view may not be shown at this point. mHandler.postUpdateSuggestions(); mHandler.cancelDoubleSpacesTimer(); inputView.setKeyPreviewPopupEnabled(mSettingsValues.mKeyPreviewPopupOn, mSettingsValues.mKeyPreviewPopupDismissDelay); inputView.setProximityCorrectionEnabled(true); voiceIme.onStartInputView(inputView.getWindowToken()); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } @Override public void onWindowHidden() { super.onWindowHidden(); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); } private void onFinishInputInternal() { super.onFinishInput(); LatinImeLogger.commit(); mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); if (mUserUnigramDictionary != null) mUserUnigramDictionary.flushPendingWrites(); if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites(); } private void onFinishInputViewInternal(boolean finishingInput) { super.onFinishInputView(finishingInput); mKeyboardSwitcher.onFinishInputView(); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.cancelAllMessages(); // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestions(); } @Override public void onUpdateExtractedText(int token, ExtractedText text) { super.onUpdateExtractedText(token, text); mVoiceProxy.showPunctuationHintIfNecessary(); } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); if (DEBUG) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", lss=" + mLastSelectionStart + ", lse=" + mLastSelectionEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + candidatesStart + ", ce=" + candidatesEnd); } mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart); // If the current selection in the text view changes, we should // clear whatever candidate text we have. final boolean selectionChanged = (newSelStart != candidatesEnd || newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart; final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1; if (!mExpectingUpdateSelection) { // TAKE CARE: there is a race condition when we enter this test even when the user // did not explicitly move the cursor. This happens when typing fast, where two keys // turn this flag on in succession and both onUpdateSelection() calls arrive after // the second one - the first call successfully avoids this test, but the second one // enters. For the moment we rely on candidatesCleared to further reduce the impact. if (SPACE_STATE_WEAK == mSpaceState) { // Test for no WEAK_SPACE action because there is a race condition that may end up // in coming here on a normal key press. We set this to NONE because after // a cursor move, we don't want the suggestion strip to swap the space with the // newly inserted punctuation. mSpaceState = SPACE_STATE_NONE; } if (((mWordComposer.isComposingWord()) || mVoiceProxy.isVoiceInputHighlighted()) && (selectionChanged || candidatesCleared)) { mWordComposer.reset(); updateSuggestions(); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } mComposingStateManager.onFinishComposingText(); mVoiceProxy.setVoiceInputHighlighted(false); } else if (!mWordComposer.isComposingWord()) { mWordComposer.reset(); updateSuggestions(); } } mExpectingUpdateSelection = false; mHandler.postUpdateShiftKeyState(); // TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not // here. It would probably be too expensive to call directly here but we may want to post a // message to delay it. The point would be to unify behavior between backspace to the // end of a word and manually put the pointer at the end of the word. // Make a note of the cursor position mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; } /** * This is called when the user has clicked on the extracted text view, * when running in fullscreen mode. The default implementation hides * the suggestions view when this happens, but only if the extracted text * editor has a vertical scroll bar because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (isSuggestionsRequested()) return; super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the suggestions view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedCursorMovement(int dx, int dy) { if (isSuggestionsRequested()) return; super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { LatinImeLogger.commit(); mKeyboardSwitcher.onHideWindow(); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } mVoiceProxy.hideVoiceWindow(mConfigurationChanging); super.hideWindow(); } @Override public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) { if (DEBUG) { Log.i(TAG, "Received completions:"); if (applicationSpecifiedCompletions != null) { for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); } } } if (mInputAttributes.mApplicationSpecifiedCompletionOn) { mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; if (applicationSpecifiedCompletions == null) { clearSuggestions(); return; } SuggestedWords.Builder builder = new SuggestedWords.Builder() .setApplicationSpecifiedCompletions(applicationSpecifiedCompletions) .setTypedWordValid(false) .setHasMinimalSuggestion(false); // When in fullscreen mode, show completions generated by the application setSuggestions(builder.build()); mWordComposer.deleteAutoCorrection(); setSuggestionStripShown(true); } } private void setSuggestionStripShownInternal(boolean shown, boolean needsInputViewShown) { // TODO: Modify this if we support suggestions with hard keyboard if (onEvaluateInputViewShown() && mSuggestionsContainer != null) { final boolean shouldShowSuggestions = shown && (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true); if (isFullscreenMode()) { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.GONE); } else { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE); } } } private void setSuggestionStripShown(boolean shown) { setSuggestionStripShownInternal(shown, /* needsInputViewShown */true); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); final KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView == null || mSuggestionsContainer == null) return; // In fullscreen mode, the height of the extract area managed by InputMethodService should // be considered. // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; final int backingHeight = (mKeyPreviewBackingView.getVisibility() == View.GONE) ? 0 : mKeyPreviewBackingView.getHeight(); final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0 : mSuggestionsContainer.getHeight(); final int extraHeight = extractHeight + backingHeight + suggestionsHeight; int touchY = extraHeight; // Need to set touchable region only if input view is being shown if (mKeyboardSwitcher.isInputViewShown()) { if (mSuggestionsContainer.getVisibility() == View.VISIBLE) { touchY -= suggestionsHeight; } final int touchWidth = inputView.getWidth(); final int touchHeight = inputView.getHeight() + extraHeight // Extend touchable region below the keyboard. + EXTENDED_TOUCHABLE_REGION_HEIGHT; if (DEBUG) { Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth + " height=" + touchHeight); } setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight); } outInsets.contentTopInsets = touchY; outInsets.visibleTopInsets = touchY; } @Override public boolean onEvaluateFullscreenMode() { // Reread resource value here, because this method is called by framework anytime as needed. final boolean isFullscreenModeAllowed = mSettingsValues.isFullscreenModeAllowed(getResources()); return super.onEvaluateFullscreenMode() && isFullscreenModeAllowed; } @Override public void updateFullscreenMode() { super.updateFullscreenMode(); if (mKeyPreviewBackingView == null) return; // In fullscreen mode, no need to have extra space to show the key preview. // If not, we should have extra space above the keyboard to show the key preview. mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { if (mSuggestionsView != null && mSuggestionsView.handleBack()) { return true; } final LatinKeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView(); if (keyboardView != null && keyboardView.handleBack()) { return true; } } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // Enable shift key and DPAD to do selections if (mKeyboardSwitcher.isInputViewShown() && mKeyboardSwitcher.isShiftedOrShiftLocked()) { KeyEvent newEvent = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); final InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(newEvent); return true; } break; } return super.onKeyUp(keyCode, event); } public void commitTyped(final InputConnection ic) { if (!mWordComposer.isComposingWord()) return; final CharSequence typedWord = mWordComposer.getTypedWord(); mWordComposer.onCommitWord(WordComposer.COMMIT_TYPE_USER_TYPED_WORD); if (typedWord.length() > 0) { if (ic != null) { ic.commitText(typedWord, 1); } addToUserUnigramAndBigramDictionaries(typedWord, UserUnigramDictionary.FREQUENCY_FOR_TYPED); } updateSuggestions(); } public boolean getCurrentAutoCapsState() { final InputConnection ic = getCurrentInputConnection(); EditorInfo ei = getCurrentInputEditorInfo(); if (mSettingsValues.mAutoCap && ic != null && ei != null && ei.inputType != InputType.TYPE_NULL) { return ic.getCursorCapsMode(ei.inputType) != 0; } return false; } // "ic" may be null private void swapSwapperAndSpaceWhileInBatchEdit(final InputConnection ic) { if (null == ic) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == Keyboard.CODE_SPACE) { ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); mKeyboardSwitcher.updateShiftState(); } } private boolean maybeDoubleSpaceWhileInBatchEdit(final InputConnection ic) { if (mCorrectionMode == Suggest.CORRECTION_NONE) return false; if (ic == null) return false; final CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Utils.canBeFollowedByPeriod(lastThree.charAt(0)) && lastThree.charAt(1) == Keyboard.CODE_SPACE && lastThree.charAt(2) == Keyboard.CODE_SPACE && mHandler.isAcceptingDoubleSpaces()) { mHandler.cancelDoubleSpacesTimer(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); mKeyboardSwitcher.updateShiftState(); return true; } return false; } // "ic" must not be null private static void maybeRemovePreviousPeriod(final InputConnection ic, CharSequence text) { // When the text's first character is '.', remove the previous period // if there is one. final CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_PERIOD && text.charAt(0) == Keyboard.CODE_PERIOD) { ic.deleteSurroundingText(1, 0); } } // "ic" may be null private static void removeTrailingSpaceWhileInBatchEdit(final InputConnection ic) { if (ic == null) return; final CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_SPACE) { ic.deleteSurroundingText(1, 0); } } @Override public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); // Suggestion strip should be updated after the operation of adding word to the // user dictionary mHandler.postUpdateSuggestions(); return true; } private static boolean isAlphabet(int code) { return Character.isLetter(code); } private void onSettingsKeyPressed() { if (isShowingOptionDialog()) return; if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) { showSubtypeSelectorAndSettings(); } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(false /* exclude aux subtypes */)) { showOptionsMenu(); } else { launchSettings(); } } // Virtual codes representing custom requests. These are used in onCustomRequest() below. public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1; public static final int CODE_HAPTIC_AND_AUDIO_FEEDBACK = 2; @Override public boolean onCustomRequest(int requestCode) { if (isShowingOptionDialog()) return false; switch (requestCode) { case CODE_SHOW_INPUT_METHOD_PICKER: if (Utils.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { mImm.showInputMethodPicker(); return true; } return false; case CODE_HAPTIC_AND_AUDIO_FEEDBACK: hapticAndAudioFeedback(Keyboard.CODE_UNSPECIFIED); return true; } return false; } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } private void insertPunctuationFromSuggestionStrip(final InputConnection ic, final int code) { final CharSequence beforeText = ic != null ? ic.getTextBeforeCursor(1, 0) : null; final int toLeft = TextUtils.isEmpty(beforeText) ? 0 : beforeText.charAt(0); final boolean shouldRegisterSwapPunctuation; // If we have a space left of the cursor and it's a weak or a magic space, then we should // swap it, and override the space state with SPACESTATE_SWAP_PUNCTUATION. // To swap it, we fool handleSeparator to think the previous space state was a // magic space. if (Keyboard.CODE_SPACE == toLeft && mSpaceState == SPACE_STATE_WEAK && mSettingsValues.isMagicSpaceSwapper(code)) { mSpaceState = SPACE_STATE_MAGIC; shouldRegisterSwapPunctuation = true; } else { shouldRegisterSwapPunctuation = false; } onCodeInput(code, new int[] { code }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); if (shouldRegisterSwapPunctuation) { mSpaceState = SPACE_STATE_SWAP_PUNCTUATION; } } // Implementation of {@link KeyboardActionListener}. @Override public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) { final long when = SystemClock.uptimeMillis(); if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; final KeyboardSwitcher switcher = mKeyboardSwitcher; // The space state depends only on the last character pressed and its own previous // state. Here, we revert the space state to neutral if the key is actually modifying // the input contents (any non-shift key), which is what we should do for // all inputs that do not result in a special state. Each character handling is then // free to override the state as they see fit. final int spaceState = mSpaceState; // TODO: Consolidate the double space timer, mLastKeyTime, and the space state. if (primaryCode != Keyboard.CODE_SPACE) { mHandler.cancelDoubleSpacesTimer(); } switch (primaryCode) { case Keyboard.CODE_DELETE: mSpaceState = SPACE_STATE_NONE; handleBackspace(spaceState); mDeleteCount++; mExpectingUpdateSelection = true; LatinImeLogger.logOnDelete(); break; case Keyboard.CODE_SHIFT: case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: // Shift and symbol key is handled in onPressKey() and onReleaseKey(). break; case Keyboard.CODE_SETTINGS: onSettingsKeyPressed(); break; case Keyboard.CODE_CAPSLOCK: // Caps lock code is handled in KeyboardSwitcher.onCodeInput() below. hapticAndAudioFeedback(primaryCode); break; case Keyboard.CODE_SHORTCUT: mSubtypeSwitcher.switchToShortcutIME(); break; case Keyboard.CODE_TAB: handleTab(); // There are two cases for tab. Either we send a "next" event, that may change the // focus but will never move the cursor. Or, we send a real tab keycode, which some // applications may accept or ignore, and we don't know whether this will move the // cursor or not. So actually, we don't really know. // So to go with the safer option, we'd rather behave as if the user moved the // cursor when they didn't than the opposite. We also expect that most applications // will actually use tab only for focus movement. // To sum it up: do not update mExpectingUpdateSelection here. break; default: mSpaceState = SPACE_STATE_NONE; if (mSettingsValues.isWordSeparator(primaryCode)) { handleSeparator(primaryCode, x, y, spaceState); } else { handleCharacter(primaryCode, keyCodes, x, y, spaceState); } mExpectingUpdateSelection = true; break; } switcher.onCodeInput(primaryCode); // Reset after any single keystroke mEnteredText = null; } @Override public void onTextInput(CharSequence text) { mVoiceProxy.commitVoiceInput(); final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); commitTyped(ic); maybeRemovePreviousPeriod(ic, text); ic.commitText(text, 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT); mSpaceState = SPACE_STATE_NONE; mEnteredText = text; mWordComposer.reset(); } @Override public void onCancelInput() { // User released a finger outside any key mKeyboardSwitcher.onCancelInput(); } private void handleBackspace(final int spaceState) { if (mVoiceProxy.logAndRevertVoiceInput()) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); handleBackspaceWhileInBatchEdit(spaceState, ic); ic.endBatchEdit(); } // "ic" may not be null. private void handleBackspaceWhileInBatchEdit(final int spaceState, final InputConnection ic) { mVoiceProxy.handleBackspace(); // In many cases, we may have to put the keyboard in auto-shift state again. mHandler.postUpdateShiftKeyState(); if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) { // Cancel multi-character input: remove the text we just entered. // This is triggered on backspace after a key that inputs multiple characters, // like the smiley key or the .com key. ic.deleteSurroundingText(mEnteredText.length(), 0); // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. // In addition we know that spaceState is false, and that we should not be // reverting any autocorrect at this point. So we can safely return. return; } if (mWordComposer.isComposingWord()) { final int length = mWordComposer.size(); if (length > 0) { mWordComposer.deleteLast(); ic.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); // If we have deleted the last remaining character of a word, then we are not // isComposingWord() any more. if (!mWordComposer.isComposingWord()) { // Not composing word any more, so we can show bigrams. mHandler.postUpdateBigramPredictions(); } else { // Still composing a word, so we still have letters to deduce a suggestion from. mHandler.postUpdateSuggestions(); } } else { ic.deleteSurroundingText(1, 0); } } else { // We should be very careful about auto-correction cancellation and suggestion // resuming here. The behavior needs to be different according to text field types, // and it would be much clearer to test for them explicitly here rather than // relying on implicit values like "whether the suggestion strip is displayed". if (mWordComposer.didAutoCorrectToAnotherWord()) { Utils.Stats.onAutoCorrectionCancellation(); cancelAutoCorrect(ic); return; } if (SPACE_STATE_DOUBLE == spaceState) { if (revertDoubleSpace(ic)) { // No need to reset mSpaceState, it has already be done (that's why we // receive it as a parameter) return; } } else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) { if (revertSwapPunctuation(ic)) { // Likewise return; } } // See the comment above: must be careful about resuming auto-suggestion. if (mSuggestionsView != null && mSuggestionsView.dismissAddToDictionaryHint()) { // Go back to the suggestion mode if the user canceled the // "Touch again to save". // NOTE: In general, we don't revert the word when backspacing // from a manual suggestion pick. We deliberately chose a // different behavior only in the case of picking the first // suggestion (typed word). It's intentional to have made this // inconsistent with backspacing after selecting other suggestions. restartSuggestionsOnManuallyPickedTypedWord(ic); } else { - ic.deleteSurroundingText(1, 0); - if (mDeleteCount > DELETE_ACCELERATE_AT) { - ic.deleteSurroundingText(1, 0); + // Here we must check whether there is a selection. If so we should remove the + // selected text, otherwise we should just delete the character before the cursor. + if (mLastSelectionStart != mLastSelectionEnd) { + final int lengthToDelete = mLastSelectionEnd - mLastSelectionStart; + ic.setSelection(mLastSelectionEnd, mLastSelectionEnd); + ic.deleteSurroundingText(lengthToDelete, 0); + } else { + if (NOT_A_CURSOR_POSITION == mLastSelectionEnd) { + // We don't know whether there is a selection or not. We just send a false + // hardware key event and let TextView sort it out for us. The problem + // here is, this is asynchronous with respect to the input connection + // batch edit, so it may flicker. But this only ever happens if backspace + // is pressed just after the IME is invoked, and then again only once. + // TODO: add an API call that gets the selection indices. This is available + // to the IME in the general case via onUpdateSelection anyway, and would + // allow us to remove this race condition. + sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); + } else { + ic.deleteSurroundingText(1, 0); + } + if (mDeleteCount > DELETE_ACCELERATE_AT) { + ic.deleteSurroundingText(1, 0); + } } if (isSuggestionsRequested()) { restartSuggestionsOnWordBeforeCursorIfAtEndOfWord(ic); } } } } private void handleTab() { final int imeOptions = getCurrentInputEditorInfo().imeOptions; if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) { sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB); return; } final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; // True if keyboard is in either chording shift or manual temporary upper case mode. final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase(); if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionNext(ic); } else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions) && isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionPrevious(ic); } } private void handleCharacter(final int primaryCode, final int[] keyCodes, final int x, final int y, final int spaceState) { mVoiceProxy.handleCharacter(); final InputConnection ic = getCurrentInputConnection(); if (null != ic) ic.beginBatchEdit(); // TODO: if ic is null, does it make any sense to call this? handleCharacterWhileInBatchEdit(primaryCode, keyCodes, x, y, spaceState, ic); if (null != ic) ic.endBatchEdit(); } // "ic" may be null without this crashing, but the behavior will be really strange private void handleCharacterWhileInBatchEdit(final int primaryCode, final int[] keyCodes, final int x, final int y, final int spaceState, final InputConnection ic) { if (SPACE_STATE_MAGIC == spaceState && mSettingsValues.isMagicSpaceStripper(primaryCode)) { if (null != ic) removeTrailingSpaceWhileInBatchEdit(ic); } boolean isComposingWord = mWordComposer.isComposingWord(); int code = primaryCode; if ((isAlphabet(code) || mSettingsValues.isSymbolExcludedFromWordSeparators(code)) && isSuggestionsRequested() && !isCursorTouchingWord()) { if (!isComposingWord) { // Reset entirely the composing state anyway, then start composing a new word unless // the character is a single quote. The idea here is, single quote is not a // separator and it should be treated as a normal character, except in the first // position where it should not start composing a word. isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != code); mWordComposer.reset(); clearSuggestions(); mComposingStateManager.onFinishComposingText(); } } final KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isShiftedOrShiftLocked()) { if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT || keyCodes[0] > Character.MAX_CODE_POINT) { return; } code = keyCodes[0]; if (switcher.isAlphabetMode() && Character.isLowerCase(code)) { // In some locales, such as Turkish, Character.toUpperCase() may return a wrong // character because it doesn't take care of locale. final String upperCaseString = new String(new int[] {code}, 0, 1) .toUpperCase(mSubtypeSwitcher.getInputLocale()); if (upperCaseString.codePointCount(0, upperCaseString.length()) == 1) { code = upperCaseString.codePointAt(0); } else { // Some keys, such as [eszett], have upper case as multi-characters. onTextInput(upperCaseString); return; } } } if (isComposingWord) { mWordComposer.add(code, keyCodes, x, y); if (ic != null) { // If it's the first letter, make note of auto-caps state if (mWordComposer.size() == 1) { mWordComposer.setAutoCapitalized(getCurrentAutoCapsState()); mComposingStateManager.onStartComposingText(); } ic.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); } mHandler.postUpdateSuggestions(); } else { sendKeyChar((char)code); } if (SPACE_STATE_MAGIC == spaceState && mSettingsValues.isMagicSpaceSwapper(primaryCode)) { if (null != ic) swapSwapperAndSpaceWhileInBatchEdit(ic); } if (mSettingsValues.isWordSeparator(code)) { Utils.Stats.onSeparator((char)code, x, y); } else { Utils.Stats.onNonSeparator((char)code, x, y); } } private void handleSeparator(final int primaryCode, final int x, final int y, final int spaceState) { mVoiceProxy.handleSeparator(); mComposingStateManager.onFinishComposingText(); // Should dismiss the "Touch again to save" message when handling separator if (mSuggestionsView != null && mSuggestionsView.dismissAddToDictionaryHint()) { mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // Handle separator final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mWordComposer.isComposingWord()) { // In certain languages where single quote is a separator, it's better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the elision // requires the last vowel to be removed. final boolean shouldAutoCorrect = mSettingsValues.mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; if (shouldAutoCorrect && primaryCode != Keyboard.CODE_SINGLE_QUOTE) { commitCurrentAutoCorrection(primaryCode, ic); } else { commitTyped(ic); } } final boolean swapMagicSpace; if (Keyboard.CODE_ENTER == primaryCode && (SPACE_STATE_MAGIC == spaceState || SPACE_STATE_SWAP_PUNCTUATION == spaceState)) { removeTrailingSpaceWhileInBatchEdit(ic); swapMagicSpace = false; } else if (SPACE_STATE_MAGIC == spaceState) { if (mSettingsValues.isMagicSpaceSwapper(primaryCode)) { swapMagicSpace = true; } else { swapMagicSpace = false; if (mSettingsValues.isMagicSpaceStripper(primaryCode)) { removeTrailingSpaceWhileInBatchEdit(ic); } } } else { swapMagicSpace = false; } sendKeyChar((char)primaryCode); if (Keyboard.CODE_SPACE == primaryCode) { if (isSuggestionsRequested()) { if (maybeDoubleSpaceWhileInBatchEdit(ic)) { mSpaceState = SPACE_STATE_DOUBLE; } else if (!isShowingPunctuationList()) { mSpaceState = SPACE_STATE_WEAK; } } mHandler.startDoubleSpacesTimer(); if (!isCursorTouchingWord()) { mHandler.cancelUpdateSuggestions(); mHandler.postUpdateBigramPredictions(); } } else { if (swapMagicSpace) { swapSwapperAndSpaceWhileInBatchEdit(ic); mSpaceState = SPACE_STATE_MAGIC; } // Set punctuation right away. onUpdateSelection will fire but tests whether it is // already displayed or not, so it's okay. setPunctuationSuggestions(); } Utils.Stats.onSeparator((char)primaryCode, x, y); if (ic != null) { ic.endBatchEdit(); } } private CharSequence getTextWithUnderline(final CharSequence text) { return mComposingStateManager.isAutoCorrectionIndicatorOn() ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text) : mWordComposer.getTypedWord(); } private void handleClose() { commitTyped(getCurrentInputConnection()); mVoiceProxy.handleClose(); requestHideSelf(0); LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); } public boolean isSuggestionsRequested() { return mInputAttributes.mIsSettingsSuggestionStripOn && (mCorrectionMode > 0 || isShowingSuggestionsStrip()); } public boolean isShowingPunctuationList() { if (mSuggestionsView == null) return false; return mSettingsValues.mSuggestPuncList == mSuggestionsView.getSuggestions(); } public boolean isShowingSuggestionsStrip() { return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE) || (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE && mDisplayOrientation == Configuration.ORIENTATION_PORTRAIT); } public boolean isSuggestionsStripVisible() { if (mSuggestionsView == null) return false; if (mSuggestionsView.isShowingAddToDictionaryHint()) return true; if (!isShowingSuggestionsStrip()) return false; if (mInputAttributes.mApplicationSpecifiedCompletionOn) return true; return isSuggestionsRequested(); } public void switchToKeyboardView() { if (DEBUG) { Log.d(TAG, "Switch to keyboard view."); } View v = mKeyboardSwitcher.getKeyboardView(); if (v != null) { // Confirms that the keyboard view doesn't have parent view. ViewParent p = v.getParent(); if (p != null && p instanceof ViewGroup) { ((ViewGroup) p).removeView(v); } setInputView(v); } setSuggestionStripShown(isSuggestionsStripVisible()); updateInputViewShown(); mHandler.postUpdateSuggestions(); } public void clearSuggestions() { setSuggestions(SuggestedWords.EMPTY); } public void setSuggestions(SuggestedWords words) { if (mSuggestionsView != null) { mSuggestionsView.setSuggestions(words); mKeyboardSwitcher.onAutoCorrectionStateChanged( words.hasWordAboveAutoCorrectionScoreThreshold()); } // Put a blue underline to a word in TextView which will be auto-corrected. final InputConnection ic = getCurrentInputConnection(); if (ic != null) { final boolean oldAutoCorrectionIndicator = mComposingStateManager.isAutoCorrectionIndicatorOn(); final boolean newAutoCorrectionIndicator = Utils.willAutoCorrect(words); if (oldAutoCorrectionIndicator != newAutoCorrectionIndicator) { mComposingStateManager.setAutoCorrectionIndicatorOn(newAutoCorrectionIndicator); if (DEBUG) { Log.d(TAG, "Flip the indicator. " + oldAutoCorrectionIndicator + " -> " + newAutoCorrectionIndicator); if (newAutoCorrectionIndicator != mComposingStateManager.isAutoCorrectionIndicatorOn()) { throw new RuntimeException("Couldn't flip the indicator! We are not " + "composing a word right now."); } } final CharSequence textWithUnderline = getTextWithUnderline(mWordComposer.getTypedWord()); if (!TextUtils.isEmpty(textWithUnderline)) { ic.setComposingText(textWithUnderline, 1); } } } } public void updateSuggestions() { // Check if we have a suggestion engine attached. if ((mSuggest == null || !isSuggestionsRequested()) && !mVoiceProxy.isVoiceInputHighlighted()) { if (mWordComposer.isComposingWord()) { Log.w(TAG, "Called updateSuggestions but suggestions were not requested!"); mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); } return; } mHandler.cancelUpdateSuggestions(); mHandler.cancelUpdateBigramPredictions(); if (!mWordComposer.isComposingWord()) { setPunctuationSuggestions(); return; } // TODO: May need a better way of retrieving previous word final InputConnection ic = getCurrentInputConnection(); final CharSequence prevWord; if (null == ic) { prevWord = null; } else { prevWord = EditingUtils.getPreviousWord(ic, mSettingsValues.mWordSeparators); } // getSuggestedWordBuilder handles gracefully a null value of prevWord final SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(mWordComposer, prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(), mCorrectionMode); boolean autoCorrectionAvailable = !mInputAttributes.mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection(); final CharSequence typedWord = mWordComposer.getTypedWord(); // Here, we want to promote a whitelisted word if exists. // TODO: Change this scheme - a boolean is not enough. A whitelisted word may be "valid" // but still autocorrected from - in the case the whitelist only capitalizes the word. // The whitelist should be case-insensitive, so it's not possible to be consistent with // a boolean flag. Right now this is handled with a slight hack in // WhitelistDictionary#shouldForciblyAutoCorrectFrom. final int quotesCount = mWordComposer.trailingSingleQuotesCount(); final boolean allowsToBeAutoCorrected = AutoCorrection.allowsToBeAutoCorrected( mSuggest.getUnigramDictionaries(), // If the typed string ends with a single quote, for dictionary lookup purposes // we behave as if the single quote was not here. Here, we are looking up the // typed string in the dictionary (to avoid autocorrecting from an existing // word, so for consistency this lookup should be made WITHOUT the trailing // single quote. quotesCount > 0 ? typedWord.subSequence(0, typedWord.length() - quotesCount) : typedWord, preferCapitalization()); if (mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) { autoCorrectionAvailable |= (!allowsToBeAutoCorrected); } // Don't auto-correct words with multiple capital letter autoCorrectionAvailable &= !mWordComposer.isMostlyCaps(); // Basically, we update the suggestion strip only when suggestion count > 1. However, // there is an exception: We update the suggestion strip whenever typed word's length // is 1 or typed word is found in dictionary, regardless of suggestion count. Actually, // in most cases, suggestion count is 1 when typed word's length is 1, but we do always // need to clear the previous state when the user starts typing a word (i.e. typed word's // length == 1). if (typedWord != null) { if (builder.size() > 1 || typedWord.length() == 1 || (!allowsToBeAutoCorrected) || mSuggestionsView.isShowingAddToDictionaryHint()) { builder.setTypedWordValid(!allowsToBeAutoCorrected).setHasMinimalSuggestion( autoCorrectionAvailable); } else { SuggestedWords previousSuggestions = mSuggestionsView.getSuggestions(); if (previousSuggestions == mSettingsValues.mSuggestPuncList) { if (builder.size() == 0) { return; } previousSuggestions = SuggestedWords.EMPTY; } builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions); } } showSuggestions(builder.build(), typedWord); } public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { final boolean shouldBlockAutoCorrectionBySafetyNet = Utils.shouldBlockAutoCorrectionBySafetyNet(suggestedWords, mSuggest); if (shouldBlockAutoCorrectionBySafetyNet) { suggestedWords.setShouldBlockAutoCorrection(); } setSuggestions(suggestedWords); if (suggestedWords.size() > 0) { if (shouldBlockAutoCorrectionBySafetyNet) { mWordComposer.setAutoCorrection(typedWord); } else if (suggestedWords.hasAutoCorrectionWord()) { mWordComposer.setAutoCorrection(suggestedWords.getWord(1)); } else { mWordComposer.setAutoCorrection(typedWord); } } else { // TODO: replace with mWordComposer.deleteAutoCorrection()? mWordComposer.setAutoCorrection(null); } setSuggestionStripShown(isSuggestionsStripVisible()); } private void commitCurrentAutoCorrection(final int separatorCodePoint, final InputConnection ic) { // Complete any pending suggestions query first if (mHandler.hasPendingUpdateSuggestions()) { mHandler.cancelUpdateSuggestions(); updateSuggestions(); } final CharSequence autoCorrection = mWordComposer.getAutoCorrectionOrNull(); if (autoCorrection != null) { final String typedWord = mWordComposer.getTypedWord(); if (TextUtils.isEmpty(typedWord)) { throw new RuntimeException("We have an auto-correction but the typed word " + "is empty? Impossible! I must commit suicide."); } Utils.Stats.onAutoCorrection(typedWord, autoCorrection.toString(), separatorCodePoint); mExpectingUpdateSelection = true; commitChosenWord(autoCorrection, WordComposer.COMMIT_TYPE_DECIDED_WORD); // Add the word to the user unigram dictionary if it's not a known word addToUserUnigramAndBigramDictionaries(autoCorrection, UserUnigramDictionary.FREQUENCY_FOR_TYPED); if (!typedWord.equals(autoCorrection) && null != ic) { // This will make the correction flash for a short while as a visual clue // to the user that auto-correction happened. InputConnectionCompatUtils.commitCorrection(ic, mLastSelectionEnd - typedWord.length(), typedWord, autoCorrection); } } } @Override public void pickSuggestionManually(int index, CharSequence suggestion) { mComposingStateManager.onFinishComposingText(); SuggestedWords suggestions = mSuggestionsView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mInputAttributes.mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { if (ic != null) { final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; ic.commitCompletion(completionInfo); } if (mSuggestionsView != null) { mSuggestionsView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be swapped // if it was a magic or a weak space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final int rawPrimaryCode = suggestion.charAt(0); // Maybe apply the "bidi mirrored" conversions for parentheses final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final boolean isRtl = keyboard != null && keyboard.mIsRtlKeyboard; final int primaryCode = Key.getRtlParenthesisCode(rawPrimaryCode, isRtl); insertPunctuationFromSuggestionStrip(ic, primaryCode); // TODO: the following endBatchEdit seems useless, check if (ic != null) { ic.endBatchEdit(); } return; } // We need to log before we commit, because the word composer will store away the user // typed word. LatinImeLogger.logOnManualSuggestion(mWordComposer.getTypedWord().toString(), suggestion.toString(), index, suggestions.mWords); mExpectingUpdateSelection = true; commitChosenWord(suggestion, WordComposer.COMMIT_TYPE_MANUAL_PICK); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToUserUnigramAndBigramDictionaries(suggestion, UserUnigramDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } // Follow it with a space if (mInputAttributes.mInsertSpaceOnPickSuggestionManually) { sendMagicSpace(); } // We should show the "Touch again to save" hint if the user pressed the first entry // AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mSuggest.hasMainDictionary() is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mSuggest.hasMainDictionary() // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); Utils.Stats.onSeparator((char)Keyboard.CODE_SPACE, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. updateBigramPredictions(); // Updating the predictions right away may be slow and feel unresponsive on slower // terminals. On the other hand if we just postUpdateBigramPredictions() it will // take a noticeable delay to update them which may feel uneasy. } else { if (mIsUserDictionaryAvailable) { mSuggestionsView.showAddToDictionaryHint( suggestion, mSettingsValues.mHintToSaveText); } else { mHandler.postUpdateSuggestions(); } } if (ic != null) { ic.endBatchEdit(); } } /** * Commits the chosen word to the text field and saves it for later retrieval. */ private void commitChosenWord(final CharSequence bestWord, final int commitType) { final InputConnection ic = getCurrentInputConnection(); if (ic != null) { mVoiceProxy.rememberReplacedWord(bestWord, mSettingsValues.mWordSeparators); if (mSettingsValues.mEnableSuggestionSpanInsertion) { final SuggestedWords suggestedWords = mSuggestionsView.getSuggestions(); ic.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan( this, bestWord, suggestedWords), 1); } else { ic.commitText(bestWord, 1); } } // TODO: figure out here if this is an auto-correct or if the best word is actually // what user typed. Note: currently this is done much later in // WordComposer#didAutoCorrectToAnotherWord by string equality of the remembered // strings. mWordComposer.onCommitWord(commitType); } private static final WordComposer sEmptyWordComposer = new WordComposer(); public void updateBigramPredictions() { if (mSuggest == null || !isSuggestionsRequested()) return; if (!mSettingsValues.mBigramPredictionEnabled) { setPunctuationSuggestions(); return; } final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(), mSettingsValues.mWordSeparators); SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(sEmptyWordComposer, prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(), mCorrectionMode); if (builder.size() > 0) { // Explicitly supply an empty typed word (the no-second-arg version of // showSuggestions will retrieve the word near the cursor, we don't want that here) showSuggestions(builder.build(), ""); } else { if (!isShowingPunctuationList()) setPunctuationSuggestions(); } } public void setPunctuationSuggestions() { setSuggestions(mSettingsValues.mSuggestPuncList); setSuggestionStripShown(isSuggestionsStripVisible()); } private void addToUserUnigramAndBigramDictionaries(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, false); } private void addToOnlyBigramDictionary(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, true); } /** * Adds to the UserBigramDictionary and/or UserUnigramDictionary * @param selectedANotTypedWord true if it should be added to bigram dictionary if possible */ private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta, boolean selectedANotTypedWord) { if (suggestion == null || suggestion.length() < 1) return; // Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be // adding words in situations where the user or application really didn't // want corrections enabled or learned. if (!(mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) { return; } if (null != mSuggest && null != mUserUnigramDictionary) { final boolean selectedATypedWordAndItsInUserUnigramDic = !selectedANotTypedWord && mUserUnigramDictionary.isValidWord(suggestion); final boolean isValidWord = AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true); final boolean needsToAddToUserUnigramDictionary = selectedATypedWordAndItsInUserUnigramDic || !isValidWord; if (needsToAddToUserUnigramDictionary) { mUserUnigramDictionary.addWord(suggestion.toString(), frequencyDelta); } } if (mUserBigramDictionary != null) { // We don't want to register as bigrams words separated by a separator. // For example "I will, and you too" : we don't want the pair ("will" "and") to be // a bigram. final InputConnection ic = getCurrentInputConnection(); if (null != ic) { final CharSequence prevWord = EditingUtils.getPreviousWord(ic, mSettingsValues.mWordSeparators); if (!TextUtils.isEmpty(prevWord)) { mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString()); } } } } public boolean isCursorTouchingWord() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !mSettingsValues.isWordSeparator(toLeft.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !mSettingsValues.isWordSeparator(toRight.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toRight.charAt(0))) { return true; } return false; } // "ic" must not be null private static boolean sameAsTextBeforeCursor(final InputConnection ic, CharSequence text) { CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0); return TextUtils.equals(text, beforeText); } // "ic" must not be null /** * Check if the cursor is actually at the end of a word. If so, restart suggestions on this * word, else do nothing. */ private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord( final InputConnection ic) { // Bail out if the cursor is not at the end of a word (cursor must be preceded by // non-whitespace, non-separator, non-start-of-text) // Example ("|" is the cursor here) : <SOL>"|a" " |a" " | " all get rejected here. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(1, 0); if (TextUtils.isEmpty(textBeforeCursor) || mSettingsValues.isWordSeparator(textBeforeCursor.charAt(0))) return; // Bail out if the cursor is in the middle of a word (cursor must be followed by whitespace, // separator or end of line/text) // Example: "test|"<EOL> "te|st" get rejected here final CharSequence textAfterCursor = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(textAfterCursor) && !mSettingsValues.isWordSeparator(textAfterCursor.charAt(0))) return; // Bail out if word before cursor is 0-length or a single non letter (like an apostrophe) // Example: " -|" gets rejected here but "e-|" and "e|" are okay CharSequence word = EditingUtils.getWordAtCursor(ic, mSettingsValues.mWordSeparators); // We don't suggest on leading single quotes, so we have to remove them from the word if // it starts with single quotes. while (!TextUtils.isEmpty(word) && Keyboard.CODE_SINGLE_QUOTE == word.charAt(0)) { word = word.subSequence(1, word.length()); } if (TextUtils.isEmpty(word)) return; final char firstChar = word.charAt(0); // we just tested that word is not empty if (word.length() == 1 && !Character.isLetter(firstChar)) return; // We only suggest on words that start with a letter or a symbol that is excluded from // word separators (see #handleCharacterWhileInBatchEdit). if (!(isAlphabet(firstChar) || mSettingsValues.isSymbolExcludedFromWordSeparators(firstChar))) { return; } // Okay, we are at the end of a word. Restart suggestions. restartSuggestionsOnWordBeforeCursor(ic, word); } // "ic" must not be null private void restartSuggestionsOnWordBeforeCursor(final InputConnection ic, final CharSequence word) { mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard()); mComposingStateManager.onStartComposingText(); ic.deleteSurroundingText(word.length(), 0); ic.setComposingText(word, 1); mHandler.postUpdateSuggestions(); } // "ic" must not be null private void cancelAutoCorrect(final InputConnection ic) { mWordComposer.resumeSuggestionOnKeptWord(); final String originallyTypedWord = mWordComposer.getTypedWord(); final CharSequence autoCorrectedTo = mWordComposer.getAutoCorrectionOrNull(); final int cancelLength = autoCorrectedTo.length(); final CharSequence separator = ic.getTextBeforeCursor(1, 0); if (DEBUG) { final String wordBeforeCursor = ic.getTextBeforeCursor(cancelLength + 1, 0).subSequence(0, cancelLength) .toString(); if (!TextUtils.equals(autoCorrectedTo, wordBeforeCursor)) { throw new RuntimeException("cancelAutoCorrect check failed: we thought we were " + "reverting \"" + autoCorrectedTo + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); } if (TextUtils.equals(originallyTypedWord, wordBeforeCursor)) { throw new RuntimeException("cancelAutoCorrect check failed: we wanted to cancel " + "auto correction and revert to \"" + originallyTypedWord + "\" but we found this very string before the cursor"); } } ic.deleteSurroundingText(cancelLength + 1, 0); ic.commitText(originallyTypedWord, 1); // Re-insert the separator ic.commitText(separator, 1); mWordComposer.deleteAutoCorrection(); mWordComposer.onCommitWord(WordComposer.COMMIT_TYPE_CANCEL_AUTO_CORRECT); Utils.Stats.onSeparator(separator.charAt(0), WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // "ic" must not be null private void restartSuggestionsOnManuallyPickedTypedWord(final InputConnection ic) { // Note: this relies on the last word still being held in the WordComposer, in // the field for suggestion resuming. // Note: in the interest of code simplicity, we may want to just call // restartSuggestionsOnWordBeforeCursorIfAtEndOfWord instead, but retrieving // the old WordComposer allows to reuse the actual typed coordinates. mWordComposer.resumeSuggestionOnKeptWord(); // We resume suggestion, and then we want to set the composing text to the content // of the word composer again. But since we just manually picked a word, there is // no composing text at the moment, so we have to delete the word before we set a // new composing text. final int restartLength = mWordComposer.size(); if (DEBUG) { final String wordBeforeCursor = ic.getTextBeforeCursor(restartLength + 1, 0).subSequence(0, restartLength) .toString(); if (!TextUtils.equals(mWordComposer.getTypedWord(), wordBeforeCursor)) { throw new RuntimeException("restartSuggestionsOnManuallyPickedTypedWord " + "check failed: we thought we were reverting \"" + mWordComposer.getTypedWord() + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); } } // Warning: this +1 takes into account the extra space added by the manual pick process. ic.deleteSurroundingText(restartLength + 1, 0); ic.setComposingText(mWordComposer.getTypedWord(), 1); mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // "ic" must not be null private boolean revertDoubleSpace(final InputConnection ic) { mHandler.cancelDoubleSpacesTimer(); // Here we test whether we indeed have a period and a space before us. This should not // be needed, but it's there just in case something went wrong. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(2, 0); if (!". ".equals(textBeforeCursor)) { // We should not have come here if we aren't just after a ". ". throw new RuntimeException("Tried to revert double-space combo but we didn't find " + "\". \" just before the cursor."); } ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(" ", 1); ic.endBatchEdit(); return true; } private static boolean revertSwapPunctuation(final InputConnection ic) { // Here we test whether we indeed have a space and something else before us. This should not // be needed, but it's there just in case something went wrong. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(2, 0); // NOTE: This does not work with surrogate pairs. Hopefully when the keyboard is able to // enter surrogate pairs this code will have been removed. if (Keyboard.CODE_SPACE != textBeforeCursor.charAt(1)) { // We should not have come here if the text before the cursor is not a space. throw new RuntimeException("Tried to revert a swap of punctuation but we didn't " + "find a space just before the cursor."); } ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(" " + textBeforeCursor.subSequence(0, 1), 1); ic.endBatchEdit(); return true; } public boolean isWordSeparator(int code) { return mSettingsValues.isWordSeparator(code); } private void sendMagicSpace() { sendKeyChar((char)Keyboard.CODE_SPACE); mSpaceState = SPACE_STATE_MAGIC; mKeyboardSwitcher.updateShiftState(); } public boolean preferCapitalization() { return mWordComposer.isFirstCharCapitalized(); } // Notify that language or mode have been changed and toggleLanguage will update KeyboardID // according to new language or mode. public void onRefreshKeyboard() { if (!CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) { // Before Honeycomb, Voice IME is in LatinIME and it changes the current input view, // so that we need to re-create the keyboard input view here. setInputView(mKeyboardSwitcher.onCreateInputView()); } // When the device locale is changed in SetupWizard etc., this method may get called via // onConfigurationChanged before SoftInputWindow is shown. if (mKeyboardSwitcher.getKeyboardView() != null) { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettingsValues); } initSuggest(); loadSettings(); } private void hapticAndAudioFeedback(int primaryCode) { vibrate(); playKeyClick(primaryCode); } @Override public void onPressKey(int primaryCode) { final KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isVibrateAndSoundFeedbackRequired()) { hapticAndAudioFeedback(primaryCode); } switcher.onPressKey(primaryCode); } @Override public void onReleaseKey(int primaryCode, boolean withSliding) { mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding); } // receive ringer mode change and network state change. private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { updateRingerMode(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { mSubtypeSwitcher.onNetworkStateChanged(intent); } } }; // update flags for silent mode private void updateRingerMode() { if (mAudioManager == null) { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (mAudioManager == null) return; } mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL); } private void playKeyClick(int primaryCode) { // if mAudioManager is null, we don't have the ringer state yet // mAudioManager will be set by updateRingerMode if (mAudioManager == null) { if (mKeyboardSwitcher.getKeyboardView() != null) { updateRingerMode(); } } if (isSoundOn()) { final int sound; switch (primaryCode) { case Keyboard.CODE_DELETE: sound = AudioManager.FX_KEYPRESS_DELETE; break; case Keyboard.CODE_ENTER: sound = AudioManager.FX_KEYPRESS_RETURN; break; case Keyboard.CODE_SPACE: sound = AudioManager.FX_KEYPRESS_SPACEBAR; break; default: sound = AudioManager.FX_KEYPRESS_STANDARD; break; } mAudioManager.playSoundEffect(sound, mSettingsValues.mFxVolume); } } public void vibrate() { if (!mSettingsValues.mVibrateOn) { return; } if (mSettingsValues.mKeypressVibrationDuration < 0) { // Go ahead with the system default LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) { inputView.performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } } else if (mVibrator != null) { mVibrator.vibrate(mSettingsValues.mKeypressVibrationDuration); } } public boolean isAutoCapitalized() { return mWordComposer.isAutoCapitalized(); } boolean isSoundOn() { return mSettingsValues.mSoundOn && !mSilentModeOn; } private void updateCorrectionMode() { // TODO: cleanup messy flags final boolean shouldAutoCorrect = mSettingsValues.mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; mCorrectionMode = shouldAutoCorrect ? Suggest.CORRECTION_FULL : Suggest.CORRECTION_NONE; mCorrectionMode = (mSettingsValues.mBigramSuggestionEnabled && shouldAutoCorrect) ? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode; } private void updateSuggestionVisibility(final Resources res) { final String suggestionVisiblityStr = mSettingsValues.mShowSuggestionsSetting; for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) { if (suggestionVisiblityStr.equals(res.getString(visibility))) { mSuggestionVisibility = visibility; break; } } } protected void launchSettings() { launchSettingsClass(Settings.class); } public void launchDebugSettings() { launchSettingsClass(DebugSettings.class); } protected void launchSettingsClass(Class<? extends PreferenceActivity> settingsClass) { handleClose(); Intent intent = new Intent(); intent.setClass(LatinIME.this, settingsClass); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { // TODO: Should use new string "Select active input modes". getString(R.string.language_selection_title), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: Intent intent = CompatUtils.getInputLanguageSelectionIntent( Utils.getInputMethodId(mImm, getPackageName()), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(items, listener) .setTitle(title); showOptionDialogInternal(builder.create()); } private void showOptionsMenu() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { getString(R.string.selectInputMethod), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: mImm.showInputMethodPicker(); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(items, listener) .setTitle(title); showOptionDialogInternal(builder.create()); } @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; p.println(" Keyboard mode = " + keyboardMode); p.println(" mIsSuggestionsRequested=" + mInputAttributes.mIsSettingsSuggestionStripOn); p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" isComposingWord=" + mWordComposer.isComposingWord()); p.println(" mAutoCorrectEnabled=" + mSettingsValues.mAutoCorrectEnabled); p.println(" mSoundOn=" + mSettingsValues.mSoundOn); p.println(" mVibrateOn=" + mSettingsValues.mVibrateOn); p.println(" mKeyPreviewPopupOn=" + mSettingsValues.mKeyPreviewPopupOn); p.println(" mInputAttributes=" + mInputAttributes.toString()); } }
false
false
null
null
diff --git a/core/src/main/java/com/dtolabs/rundeck/core/authorization/AuthorizationException.java b/core/src/main/java/com/dtolabs/rundeck/core/authorization/AuthorizationException.java index 360bd5a06..bcfc90b41 100644 --- a/core/src/main/java/com/dtolabs/rundeck/core/authorization/AuthorizationException.java +++ b/core/src/main/java/com/dtolabs/rundeck/core/authorization/AuthorizationException.java @@ -1,42 +1,42 @@ /* * Copyright 2010 DTO Labs, Inc. (http://dtolabs.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.core.authorization; import com.dtolabs.rundeck.core.CoreException; /** * AuthorizationException */ public class AuthorizationException extends CoreException { public AuthorizationException(final String msg) { super(msg); } public AuthorizationException(final Throwable e) { super(e.getMessage()); } public AuthorizationException(final String msg, final Throwable e) { - super(msg + ". cause: " + e.getCause().getMessage()); + super(msg + (null != e.getCause() ? ". cause: "+ e.getCause().getMessage() : "")); } public AuthorizationException(final String user, final String script, final String matchedRoles) { super("User: " + user + ", matching roles: " + matchedRoles + ", is not allowed to execute a script: " + script); } }
true
false
null
null
diff --git a/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java b/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java index d5391410..f11d4cf3 100644 --- a/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java +++ b/org.maven.ide.eclipse.editor.tests/src/org/maven/ide/eclipse/editor/pom/PomEditorTest.java @@ -1,645 +1,648 @@ /******************************************************************************* * Copyright (c) 2008 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 *******************************************************************************/ package org.maven.ide.eclipse.editor.pom; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Writer; import org.apache.maven.model.Model; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.IPreferenceConstants; import org.eclipse.ui.internal.WorkbenchPlugin; import org.eclipse.ui.internal.util.PrefUtil; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.wst.sse.ui.StructuredTextEditor; import org.maven.ide.eclipse.MavenPlugin; import org.maven.ide.eclipse.core.IMavenConstants; import org.maven.ide.eclipse.project.IProjectConfigurationManager; import org.maven.ide.eclipse.project.ProjectImportConfiguration; import com.windowtester.finder.swt.ShellFinder; import com.windowtester.runtime.IUIContext; import com.windowtester.runtime.WT; import com.windowtester.runtime.WaitTimedOutException; import com.windowtester.runtime.WidgetSearchException; import com.windowtester.runtime.condition.HasTextCondition; import com.windowtester.runtime.condition.IConditionMonitor; import com.windowtester.runtime.condition.IHandler; import com.windowtester.runtime.locator.WidgetReference; import com.windowtester.runtime.swt.UITestCaseSWT; import com.windowtester.runtime.swt.condition.eclipse.FileExistsCondition; import com.windowtester.runtime.swt.condition.shell.ShellDisposedCondition; import com.windowtester.runtime.swt.condition.shell.ShellShowingCondition; import com.windowtester.runtime.swt.internal.condition.NotCondition; import com.windowtester.runtime.swt.internal.condition.eclipse.DirtyEditorCondition; import com.windowtester.runtime.swt.locator.ButtonLocator; import com.windowtester.runtime.swt.locator.CTabItemLocator; import com.windowtester.runtime.swt.locator.NamedWidgetLocator; import com.windowtester.runtime.swt.locator.SWTWidgetLocator; import com.windowtester.runtime.swt.locator.TableItemLocator; import com.windowtester.runtime.swt.locator.TreeItemLocator; import com.windowtester.runtime.swt.locator.eclipse.ViewLocator; import com.windowtester.runtime.util.ScreenCapture; /** * @author Eugene Kuleshov * @author Anton Kraev */ public class PomEditorTest extends UITestCaseSWT { private static final String FIND_REPLACE = "Find/Replace"; static final String TEST_POM_POM_XML = "test-pom/pom.xml"; static final String TAB_POM_XML = null; // "pom.xml"; static final String TAB_OVERVIEW = IMavenConstants.PLUGIN_ID + ".pom.overview"; // "Overview"; static final String TAB_DEPENDENCIES = IMavenConstants.PLUGIN_ID + ".pom.dependencies"; static final String TAB_REPOSITORIES = IMavenConstants.PLUGIN_ID + ".pom.repositories"; static final String TAB_BUILD = IMavenConstants.PLUGIN_ID + ".pom.build"; static final String TAB_PLUGINS = IMavenConstants.PLUGIN_ID + ".pom.plugins"; static final String TAB_REPORTING = IMavenConstants.PLUGIN_ID + ".pom.reporting"; static final String TAB_PROFILES = IMavenConstants.PLUGIN_ID + ".pom.profiles"; static final String TAB_TEAM = IMavenConstants.PLUGIN_ID + ".pom.team"; static final String TAB_DEPENDENCY_TREE = IMavenConstants.PLUGIN_ID + ".pom.dependencyTree"; static final String TAB_DEPENDENCY_GRAPH = IMavenConstants.PLUGIN_ID + ".pom.dependencyGraph"; private static final String PROJECT_NAME = "test-pom"; IUIContext ui; IWorkspaceRoot root; IWorkspace workspace; protected void setUp() throws Exception { super.setUp(); WorkbenchPlugin.getDefault().getPreferenceStore().setValue(IPreferenceConstants.RUN_IN_BACKGROUND, true); PrefUtil.getAPIPreferenceStore().setValue(IWorkbenchPreferenceConstants.ENABLE_ANIMATIONS, false); ShellFinder.bringRootToFront(getActivePage().getWorkbenchWindow().getShell().getDisplay()); workspace = ResourcesPlugin.getWorkspace(); root = workspace.getRoot(); ui = getUI(); if("Welcome".equals(getActivePage().getActivePart().getTitle())) { ui.close(new CTabItemLocator("Welcome")); } // close unnecessary tabs (different versions have different defaults in java perspective) // closeView("org.eclipse.mylyn.tasks.ui.views.tasks", "Task List"); // closeView("org.eclipse.ui.views.ContentOutline", "Outline"); } protected void oneTimeSetup() throws Exception { super.oneTimeSetup(); ShellFinder.bringRootToFront(getActivePage().getWorkbenchWindow().getShell().getDisplay()); ui = getUI(); if("Welcome".equals(getActivePage().getActivePart().getTitle())) { ui.close(new CTabItemLocator("Welcome")); } IConditionMonitor monitor = (IConditionMonitor) getUI().getAdapter(IConditionMonitor.class); monitor.add(new ShellShowingCondition("Save Resource"), // new IHandler() { public void handle(IUIContext ui) { try { ui.click(new ButtonLocator("&Yes")); } catch(WidgetSearchException ex) { // ignore } } }); IPerspectiveRegistry perspectiveRegistry = PlatformUI.getWorkbench().getPerspectiveRegistry(); IPerspectiveDescriptor perspective = perspectiveRegistry .findPerspectiveWithId("org.eclipse.jdt.ui.JavaPerspective"); getActivePage().setPerspective(perspective); createTestProject(); } public void testUpdatingArtifactIdInXmlPropagatedToForm() throws Exception { openPomFile(); selectEditorTab(TAB_POM_XML); replaceText("test-pom", "test-pom1"); selectEditorTab(TAB_OVERVIEW); assertTextValue("artifactId", "test-pom1"); } public void testFormToXmlAndXmlToFormInParentArtifactId() throws Exception { // test FORM->XML and XML->FORM update of parentArtifactId selectEditorTab(TAB_OVERVIEW); ui.click(new SWTWidgetLocator(Label.class, "Parent")); setTextValue("parentArtifactId", "parent2"); selectEditorTab(TAB_POM_XML); replaceText("parent2", "parent3"); selectEditorTab(TAB_OVERVIEW); assertTextValue("parentArtifactId", "parent3"); } public void testNewSectionCreation() throws Exception { ui.click(new SWTWidgetLocator(Label.class, "Organization")); ui.click(new NamedWidgetLocator("organizationName")); ui.enterText("orgfoo"); selectEditorTab(TAB_POM_XML); replaceText("orgfoo", "orgfoo1"); selectEditorTab(TAB_OVERVIEW); assertTextValue("organizationName", "orgfoo1"); } public void testUndoRedo() throws Exception { //test undo ui.keyClick(SWT.CTRL, 'z'); assertTextValue("organizationName", "orgfoo"); //test redo ui.keyClick(SWT.CTRL, 'y'); assertTextValue("organizationName", "orgfoo1"); } public void testDeletingScmSectionInXmlPropagatedToForm() throws Exception { selectEditorTab(TAB_OVERVIEW); ui.click(new SWTWidgetLocator(Label.class, "SCM")); setTextValue("scmUrl", "http://svn.sonatype.org/m2eclipse"); assertTextValue("scmUrl", "http://svn.sonatype.org/m2eclipse"); selectEditorTab(TAB_POM_XML); delete("<scm>", "</scm>"); selectEditorTab(TAB_OVERVIEW); assertTextValue("scmUrl", ""); selectEditorTab(TAB_POM_XML); delete("<organization>", "</organization>"); selectEditorTab(TAB_OVERVIEW); assertTextValue("organizationName", ""); setTextValue("scmUrl", "http://svn.sonatype.org/m2eclipse"); assertTextValue("scmUrl", "http://svn.sonatype.org/m2eclipse"); } public void testExternalModificationEditorClean() throws Exception { // save editor ui.keyClick(SWT.CTRL, 's'); Thread.sleep(2000); // externally replace file contents IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFile(new Path(TEST_POM_POM_XML)); File f = new File(file.getLocation().toOSString()); String text = getContents(f); setContents(f, text.replace("parent3", "parent4")); // reload the file ui.click(new CTabItemLocator("Package Explorer")); ui.click(new CTabItemLocator(TEST_POM_POM_XML)); // ui.contextClick(new TreeItemLocator(TEST_POM_POM_XML, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), "Refresh"); ui.wait(new ShellShowingCondition("File Changed")); ui.click(new ButtonLocator("&Yes")); assertTextValue("parentArtifactId", "parent4"); // verify that value changed in xml and in the form selectEditorTab(TAB_POM_XML); String editorText = getEditorText(); assertTrue(editorText, editorText.contains("<artifactId>parent4</artifactId>")); // XXX verify that value changed on a page haven't been active before } // test that form and xml is not updated when refused to pickup external changes public void testExternalModificationNotUpdate() throws Exception { // XXX test that form and xml are not updated when refused to pickup external changes } // XXX update for new modification code public void testExternalModificationEditorDirty() throws Exception { // make editor dirty ui.click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent4", "parent5"); selectEditorTab(TAB_OVERVIEW); // externally replace file contents IFile file = root.getFile(new Path(TEST_POM_POM_XML)); File f = new File(file.getLocation().toOSString()); String text = getContents(f); setContents(f, text.replace("parent4", "parent6")); // reload the file ui.click(new CTabItemLocator("Package Explorer")); // ui.click(new CTabItemLocator("*" + TEST_POM_POM_XML)); // take dirty state into the account ui.keyClick(SWT.F12); // ui.contextClick(new TreeItemLocator(TEST_POM_POM_XML, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), "Refresh"); ui.wait(new ShellShowingCondition("File Changed")); ui.click(new ButtonLocator("&Yes")); assertTextValue("parentArtifactId", "parent6"); // verify that value changed in xml and in the form selectEditorTab(TAB_POM_XML); String editorText = getEditorText(); assertTrue(editorText, editorText.contains("<artifactId>parent6</artifactId>")); // XXX verify that value changed on a page haven't been active before } public void testEditorIsClosedWhenProjectIsClosed() throws Exception { // XXX test editor is closed when project is closed } public void testEditorIsClosedWhenProjectIsDeleted() throws Exception { // XXX test editor is closed when project is deleted } public void testNewEditorIsClean() throws Exception { // close/open the file ui.close(new CTabItemLocator(TEST_POM_POM_XML)); ui.click(2, new TreeItemLocator(TEST_POM_POM_XML, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer"))); // test the editor is clean ui.assertThat(new NotCondition(new DirtyEditorCondition())); } //MNGECLIPSE-874 public void testUndoAfterSave() throws Exception { // make a change ui.click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent6", "parent7"); selectEditorTab(TAB_OVERVIEW); //save file ui.keyClick(SWT.CTRL, 's'); // test the editor is clean ui.assertThat(new NotCondition(new DirtyEditorCondition())); // undo change ui.keyClick(SWT.CTRL, 'z'); // test the editor is dirty ui.assertThat(new DirtyEditorCondition()); //test the value assertTextValue("parentArtifactId", "parent6"); //save file ui.keyClick(SWT.CTRL, 's'); } public void testAfterUndoEditorIsClean() throws Exception { // make a change ui.click(new CTabItemLocator(TEST_POM_POM_XML)); selectEditorTab(TAB_POM_XML); replaceText("parent6", "parent7"); selectEditorTab(TAB_OVERVIEW); // undo change ui.keyClick(SWT.CTRL, 'z'); // test the editor is clean ui.assertThat(new NotCondition(new DirtyEditorCondition())); } public void testEmptyFile() throws Exception { ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator( "org.eclipse.jdt.ui.PackageExplorer")), "New/File"); ui.wait(new ShellShowingCondition("New File")); ui.enterText("test.pom"); ui.click(new ButtonLocator("&Finish")); ui.wait(new ShellDisposedCondition("Progress Information")); ui.wait(new ShellDisposedCondition("New File")); assertTextValue("artifactId", ""); setTextValue("artifactId", "artf1"); selectEditorTab(TAB_POM_XML); replaceText("artf1", "artf2"); selectEditorTab(TAB_OVERVIEW); assertTextValue("artifactId", "artf2"); ui.keyClick(SWT.CTRL, 's'); ui.close(new CTabItemLocator(PROJECT_NAME + "/test.pom")); } //MNGECLIPSE-834 public void testDiscardedFileDeletion() throws Exception { String name = PROJECT_NAME + "/another.pom"; ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator( "org.eclipse.jdt.ui.PackageExplorer")), "New/File"); ui.wait(new ShellShowingCondition("New File")); ui.enterText("another.pom"); ui.keyClick(WT.CR); ui.wait(new ShellDisposedCondition("Progress Information")); ui.wait(new ShellDisposedCondition("New File")); ui.keyClick(SWT.CTRL, 's'); ui.close(new CTabItemLocator(name)); ui.click(2, new TreeItemLocator(PROJECT_NAME + "/another.pom", new ViewLocator( "org.eclipse.jdt.ui.PackageExplorer"))); ui.click(new NamedWidgetLocator("groupId")); ui.enterText("1"); ui.close(new CTabItemLocator("*" + name)); ui.wait(new ShellDisposedCondition("Progress Information")); ui.wait(new ShellShowingCondition("Save Resource")); ui.click(new ButtonLocator("&No")); ui.contextClick(new TreeItemLocator(name, new ViewLocator( "org.eclipse.jdt.ui.PackageExplorer")), "Delete"); ui.wait(new ShellDisposedCondition("Progress Information")); ui.wait(new ShellShowingCondition("Confirm Delete")); ui.keyClick(WT.CR); IFile file = root.getFile(new Path(name)); ui.wait(new FileExistsCondition(file, false)); } //MNGECLIPSE-833 public void testSaveAfterPaste() throws Exception { String name = PROJECT_NAME + "/another.pom"; String str = "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\"><modelVersion>4.0.0</modelVersion> <groupId>test</groupId> <artifactId>parent</artifactId> <packaging>pom</packaging> <version>0.0.1-SNAPSHOT</version></project>"; IFile file = root.getFile(new Path(name)); file.create(new ByteArrayInputStream(str.getBytes()), true, null); ui.wait(new ShellDisposedCondition("Progress Information")); ui.click(2, new TreeItemLocator(PROJECT_NAME + "/another.pom", new ViewLocator( "org.eclipse.jdt.ui.PackageExplorer"))); selectEditorTab(TAB_POM_XML); ui.wait(new NotCondition(new DirtyEditorCondition())); findText("</project>"); ui.keyClick(WT.ARROW_LEFT); putIntoClipboard("<properties><sample>sample</sample></properties>"); ui.keyClick(SWT.CTRL, 'v'); ui.wait(new DirtyEditorCondition()); ui.keyClick(SWT.CTRL, 's'); ui.wait(new NotCondition(new DirtyEditorCondition())); } // MNGECLIPSE-835 public void testModulesEditorActivation() throws Exception { openPomFile(); selectEditorTab(TAB_OVERVIEW); ui.click(new ButtonLocator("Add...")); ui.click(new TableItemLocator("?")); ui.enterText("foo1"); ui.keyClick(WT.CR); ui.keyClick(WT.CR); ui.click(new ButtonLocator("Add...")); ui.click(new TableItemLocator("?")); ui.enterText("foo2"); ui.keyClick(WT.CR); ui.keyClick(WT.CR); // save ui.keyClick(SWT.CTRL, 's'); ui.click(new TableItemLocator("foo1")); ui.click(new TableItemLocator("foo2")); try { // test the editor is clean ui.assertThat(new NotCondition(new DirtyEditorCondition())); } finally { ui.keyClick(SWT.CTRL, 's'); } } private void closeView(String id, String title) throws Exception { IViewPart view = getActivePage().findView(id); if (view != null) { ui.close(new CTabItemLocator(title)); } } private void putIntoClipboard(final String str) throws Exception { // ui.contextClick(new TreeItemLocator(PROJECT_NAME, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), "New/File"); // ui.wait(new ShellShowingCondition("New File")); // ui.enterText("t.txt"); // ui.keyClick(WT.CR); // ui.wait(new ShellDisposedCondition("Progress Information")); // ui.wait(new ShellDisposedCondition("New File")); // ui.enterText(str); // ui.keyClick(SWT.CTRL, 'a'); // ui.keyClick(SWT.CTRL, 'c'); // ui.keyClick(SWT.CTRL, 'z'); // ui.close(new CTabItemLocator("t.txt")); Display.getDefault().syncExec(new Runnable() { public void run() { Clipboard clipboard = new Clipboard(Display.getDefault()); TextTransfer transfer = TextTransfer.getInstance(); clipboard.setContents(new String[] {str}, new Transfer[] {transfer}); clipboard.dispose(); } }); } private void createTestProject() throws CoreException { // create new project with POM using new project wizard // ui.contextClick(new SWTWidgetLocator(Tree.class, new ViewLocator("org.eclipse.jdt.ui.PackageExplorer")), // "Ne&w/Maven Project"); // ui.wait(new ShellShowingCondition("New Maven Project")); // ui.click(new ButtonLocator("Create a &simple project (skip archetype selection)")); // ui.click(new ButtonLocator("&Next >")); // ui.enterText("org.foo"); // ui.keyClick(WT.TAB); // ui.enterText("test-pom"); // ui.click(new ButtonLocator("&Finish")); // ui.wait(new ShellDisposedCondition("New Maven Project")); IProjectConfigurationManager configurationManager = MavenPlugin.getDefault().getProjectConfigurationManager(); Model model = new Model(); model.setModelVersion("4.0.0"); model.setGroupId("org.foo"); model.setArtifactId("test-pom"); model.setVersion("1.0.0"); String[] folders = new String[0]; ProjectImportConfiguration config = new ProjectImportConfiguration(); IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME); IPath location = null; configurationManager.createSimpleProject(project, location, model, folders, config, new NullProgressMonitor()); } private void selectEditorTab(final String id) { final MavenPomEditor editor = (MavenPomEditor) getActivePage().getActiveEditor(); Display.getDefault().syncExec(new Runnable() { public void run() { editor.setActivePage(id); } }); } private String openPomFile() { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IFile file = root.getFile(new Path(TEST_POM_POM_XML)); final IEditorInput editorInput = new FileEditorInput(file); Display.getDefault().syncExec(new Runnable() { public void run() { try { getActivePage().openEditor(editorInput, "org.maven.ide.eclipse.editor.MavenPomEditor", true); } catch(PartInitException ex) { throw new RuntimeException(ex); } } }); return file.getLocation().toOSString(); } private String getContents(File aFile) throws Exception { StringBuilder contents = new StringBuilder(); BufferedReader input = new BufferedReader(new FileReader(aFile)); String line = null; //not declared within while loop while((line = input.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } return contents.toString(); } static public void setContents(File aFile, String aContents) throws Exception { Writer output = new BufferedWriter(new FileWriter(aFile)); output.write(aContents); output.flush(); output.close(); } private void delete(String startMarker, final String endMarker) throws WaitTimedOutException { final MavenPomEditor editor = (MavenPomEditor) getActivePage().getActiveEditor(); final StructuredTextEditor[] sse = new StructuredTextEditor[1]; Display.getDefault().syncExec(new Runnable() { public void run() { sse[0] = (StructuredTextEditor) editor.getActiveEditor(); } }); @SuppressWarnings("restriction") IDocument structuredDocument = sse[0].getModel().getStructuredDocument(); String text = structuredDocument.get(); int pos1 = text.indexOf(startMarker); int pos2 = text.indexOf(endMarker); text = text.substring(0, pos1) + text.substring(pos2 + endMarker.length()); structuredDocument.set(text); } private void assertTextValue(String id, String value) { ui.assertThat(new HasTextCondition(new NamedWidgetLocator(id), value)); } private void setTextValue(String id, String value) throws WidgetSearchException { ui.setFocus(new NamedWidgetLocator(id)); ui.keyClick(SWT.CTRL, 'a'); ui.enterText(value); } private void replaceText(String src, String target) throws WaitTimedOutException, WidgetSearchException { ui.keyClick(SWT.CTRL, 'f'); ui.wait(new ShellShowingCondition(FIND_REPLACE)); - ScreenCapture.createScreenCapture(); ui.enterText(src); ui.keyClick(WT.TAB); + ScreenCapture.createScreenCapture(); + ui.enterText(target); + ScreenCapture.createScreenCapture(); + ui.keyClick(SWT.ALT, 'a'); // "replace all" ui.close(new SWTWidgetLocator(Shell.class, FIND_REPLACE)); ui.wait(new ShellDisposedCondition(FIND_REPLACE)); ScreenCapture.createScreenCapture(); } private void findText(String src) throws WaitTimedOutException, WidgetSearchException { ui.keyClick(SWT.CTRL, 'f'); ui.wait(new ShellShowingCondition(FIND_REPLACE)); ui.enterText(src); ui.keyClick(WT.CR); // "find" ui.close(new SWTWidgetLocator(Shell.class, FIND_REPLACE)); ui.wait(new ShellDisposedCondition(FIND_REPLACE)); } ISelectionProvider getSelectionProvider() { return getEditorSite().getSelectionProvider(); } private IEditorSite getEditorSite() { IEditorPart editor = getActivePage().getActiveEditor(); IEditorSite editorSite = editor.getEditorSite(); return editorSite; } IWorkbenchPage getActivePage() { IWorkbench workbench = PlatformUI.getWorkbench(); IWorkbenchWindow window = workbench.getWorkbenchWindows()[0]; return window.getActivePage(); } private String getEditorText() { final String[] texts = new String[1]; Display.getDefault().syncExec(new Runnable() { public void run() { try { WidgetReference ref = (WidgetReference) ui.find(new SWTWidgetLocator(StyledText.class)); texts[0] = ((StyledText) ref.getWidget()).getText(); } catch(WidgetSearchException ex) { // ignore } } }); return texts[0]; } }
false
false
null
null
diff --git a/src/de/fuberlin/projecta/analysis/ast/nodes/Block.java b/src/de/fuberlin/projecta/analysis/ast/nodes/Block.java index a3d5af67..51c48f01 100644 --- a/src/de/fuberlin/projecta/analysis/ast/nodes/Block.java +++ b/src/de/fuberlin/projecta/analysis/ast/nodes/Block.java @@ -1,86 +1,87 @@ package de.fuberlin.projecta.analysis.ast.nodes; import de.fuberlin.commons.lexer.TokenType; import de.fuberlin.projecta.analysis.SymbolTableStack; import de.fuberlin.projecta.parser.ISyntaxTree; public class Block extends Statement { /** * Used for naming conventions in declarations */ private int registerCounter; @Override public void buildSymbolTable(SymbolTableStack stack){ + stack.push(); for(int i = 0; i < this.getChildrenCount(); i++){ ((AbstractSyntaxTree)(this.getChild(i))).buildSymbolTable(stack); } table = stack.pop(); } @Override public boolean checkSemantics() { for(int i = 0; i < this.getChildrenCount(); i++){ if(!((AbstractSyntaxTree)this.getChild(i)).checkSemantics()){ return false; } } return true; } // using super implementation for genCode public int getNewRegister(){ return ++registerCounter; } protected boolean hasReturnStatement(){ if(this.getChildrenCount() > 0){ ISyntaxTree last = this.getChild(this.getChildrenCount() - 1); if(last instanceof Block){ return ((Block) last).hasReturnStatement(); }else{ return last instanceof Return; } } return false; } protected boolean couldAmmendReturnStatement() { // Blocks don't exist if they are empty! ISyntaxTree lastStatement = this.getChild(this.getChildrenCount() - 1); if (lastStatement instanceof Block) { return ((Block) lastStatement).couldAmmendReturnStatement(); } else if (lastStatement instanceof Do ) { return ((Do) lastStatement).couldAmmendReturnStatement(); } else if (lastStatement instanceof IfElse ) { return ((IfElse) lastStatement).couldAmmendReturnStatement(); } else if (lastStatement instanceof BinaryOp) { BinaryOp binOp = (BinaryOp) lastStatement; if (binOp.getOp() == TokenType.OP_ASSIGN) { // first child has to be an identifier. This is checked beforehand! Return r = new Return(); r.addChild(binOp.getChild(0)); this.addChild(r); return true; } // it is an operation. A return statement will be created with this operation } else if (lastStatement instanceof Break || lastStatement instanceof Print || lastStatement instanceof If || lastStatement instanceof While){ return false; } Return r = new Return(); r.addChild(lastStatement); this.removeChild(this.getChildrenCount() - 1); this.addChild(r); return true; } @Override public boolean checkTypes() { // TODO Auto-generated method stub return false; } } diff --git a/src/de/fuberlin/projecta/analysis/ast/nodes/FuncDef.java b/src/de/fuberlin/projecta/analysis/ast/nodes/FuncDef.java index 897df401..ad1d6b68 100644 --- a/src/de/fuberlin/projecta/analysis/ast/nodes/FuncDef.java +++ b/src/de/fuberlin/projecta/analysis/ast/nodes/FuncDef.java @@ -1,152 +1,152 @@ package de.fuberlin.projecta.analysis.ast.nodes; import java.util.ArrayList; import java.util.List; import de.fuberlin.commons.lexer.TokenType; import de.fuberlin.projecta.analysis.EntryType; import de.fuberlin.projecta.analysis.SymbolTableStack; import de.fuberlin.projecta.lexer.BasicTokenType; public class FuncDef extends AbstractSyntaxTree { @Override public boolean checkSemantics() { for (int i = 0; i < this.getChildrenCount(); i++) { if (!((AbstractSyntaxTree) this.getChild(i)).checkSemantics()) { return false; } // if not, we have an empty method. The semantics of empty methods // is defined as correct if (this.getChild(this.getChildrenCount() - 1) instanceof Block) { Block block = (Block) this .getChild(this.getChildrenCount() - 1); if (!(block.getChild(block.getChildrenCount() - 1) instanceof Return)) { if (((BasicType) this.getChild(0)).getType() != BasicTokenType.VOID) { return canInsertReturn(block); } else { // no return type. so just add empty return Return r = new Return(); block.addChild(r); } } } else if (((BasicType) this.getChild(0)).getType() != BasicTokenType.VOID) { // we do not have any statements but a return type => BAD!!! return false; } } return true; } @Override public void buildSymbolTable(SymbolTableStack stack) { Type type = (Type) getChild(0); Id id = (Id) getChild(1); stack.push(); // these are parameters ((AbstractSyntaxTree) getChild(2)).buildSymbolTable(stack); - List<EntryType> parameters = stack.top().getEntries(); - - if (this.getChildrenCount() == 4) - ((AbstractSyntaxTree) getChild(3)).buildSymbolTable(stack); // this - // is - // the - // block, - // it - // can - // handle everything itself - + List<EntryType> parameters = stack.pop().getEntries(); + + if (this.getChildrenCount() == 4) { + // this is the block, it can + // handle everything itself + ((AbstractSyntaxTree) getChild(3)).buildSymbolTable(stack); + for (EntryType entry : parameters) { + ((AbstractSyntaxTree) getChild(3)).getTable() + .insertEntry(entry); + } + } EntryType entry = new EntryType(id, type, parameters); stack.top().insertEntry(entry); } @Override public String genCode() { return "define " + ((Type) getChild(0)).genCode() + " @" + ((Id) getChild(1)).genCode() + "(" + ((Params) getChild(2)).genCode() + ") nounwind { \n" + ((Block) getChild(3)).genCode() + "}"; } /** * Nodes that should produce an error: break, print Nodes that cannot pop up * here: BasicType, Declaration, Params, Program, FuncDef, Record, (Return) * * @param methodBlock * @return */ private boolean canInsertReturn(AbstractSyntaxTree methodBlock) { // We don't have return statement, so just insert one // which one depends on the last statement... AbstractSyntaxTree lastStatement = (AbstractSyntaxTree) methodBlock .getChild(methodBlock.getChildrenCount() - 1); ArrayList<Class<? extends Statement>> showStoppers = new ArrayList<Class<? extends Statement>>(); showStoppers.add(Break.class); showStoppers.add(Print.class); showStoppers.add(If.class); // It doesn't matter whether 'If'-block has return statement or not. Condition could be 'false' -> no return can be implied showStoppers.add(While.class); //see above if (showStoppers.contains(lastStatement.getClass())) { // or throw SemanticException... return false; } // We have to go through for possible return statements if (lastStatement instanceof Block) { Block block = (Block) lastStatement; if (!block.hasReturnStatement()) { return block.couldAmmendReturnStatement(); } else { return true; } } if (lastStatement instanceof Do) { Do doLoop = (Do) lastStatement; if (!doLoop.hasReturnStatement()) { return doLoop.couldAmmendReturnStatement(); } else { return true; } } if (lastStatement instanceof IfElse) { IfElse ifElse = (IfElse) lastStatement; if (!ifElse.hasReturnStatement()) { return ifElse.couldAmmendReturnStatement(); } else { return true; } } if (lastStatement instanceof BinaryOp) { BinaryOp binOp = (BinaryOp) lastStatement; if (binOp.getOp() == TokenType.OP_ASSIGN) { // first child has to be an identifier. This is checked beforehand! Return r = new Return(); r.addChild(binOp.getChild(0)); methodBlock.addChild(r); return true; } // it is an operation. A return statement will be created with this operation } // last statement is no control structure nor is it a show stopper => // just hang last statement node under a new return node Return r = new Return(); methodBlock.removeChild(methodBlock.getChildrenCount() - 1); r.addChild(lastStatement); methodBlock.addChild(r); return false; } @Override public boolean checkTypes() { // TODO Auto-generated method stub return false; } }
false
false
null
null
diff --git a/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MutableProjectRegistryTest.java b/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MutableProjectRegistryTest.java index 5131123b..c6cda601 100644 --- a/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MutableProjectRegistryTest.java +++ b/org.eclipse.m2e.tests/src/org/eclipse/m2e/tests/MutableProjectRegistryTest.java @@ -1,218 +1,219 @@ /******************************************************************************* * Copyright (c) 2008-2010 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.m2e.tests; import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.apache.maven.project.MavenProject; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; + +import org.apache.maven.project.MavenProject; + import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.embedder.IMaven; import org.eclipse.m2e.core.internal.project.registry.Capability; import org.eclipse.m2e.core.internal.project.registry.MavenProjectFacade; import org.eclipse.m2e.core.internal.project.registry.MutableProjectRegistry; import org.eclipse.m2e.core.internal.project.registry.ProjectRegistry; import org.eclipse.m2e.core.internal.project.registry.ProjectRegistryReader; import org.eclipse.m2e.core.project.MavenProjectChangedEvent; import org.eclipse.m2e.tests.common.AbstractMavenProjectTestCase; @SuppressWarnings("restriction") public class MutableProjectRegistryTest extends AbstractMavenProjectTestCase { private IMaven maven = MavenPlugin.getDefault().getMaven(); public void testAddProject() throws Exception { IProject project = createExisting("dummy", "resources/dummy"); ProjectRegistry state = new ProjectRegistry(); MavenProjectFacade f1 = newProjectFacade(project.getFile("p1.xml")); MavenProjectFacade f2 = newProjectFacade(project.getFile("p2.xml")); MutableProjectRegistry delta1 = new MutableProjectRegistry(state); delta1.setProject(f1.getPom(), f1); List<MavenProjectChangedEvent> events = state.apply(delta1); assertEquals(1, events.size()); assertEquals(MavenProjectChangedEvent.KIND_ADDED, events.get(0).getKind()); assertSame(f1, events.get(0).getMavenProject()); MutableProjectRegistry delta2 = new MutableProjectRegistry(state); delta2.setProject(f2.getPom(), f2); MavenProjectFacade[] facades = delta2.getProjects(); assertEquals(2, facades.length); assertSame(f1, delta2.getProjectFacade(f1.getPom())); assertSame(f2, delta2.getProjectFacade(f2.getPom())); events = state.apply(delta2); assertEquals(1, events.size()); assertEquals(MavenProjectChangedEvent.KIND_ADDED, events.get(0).getKind()); assertSame(f2, events.get(0).getMavenProject()); } public void testReplaceProject() throws Exception { IProject project = createExisting("dummy", "resources/dummy"); ProjectRegistry state = new ProjectRegistry(); MavenProjectFacade f1 = newProjectFacade(project.getFile("p1.xml")); MavenProjectFacade f2 = newProjectFacade(project.getFile("p1.xml")); MutableProjectRegistry delta = new MutableProjectRegistry(state); delta.setProject(f1.getPom(), f1); state.apply(delta); delta = new MutableProjectRegistry(state); delta.setProject(f2.getPom(), f2); MavenProjectFacade[] facades = delta.getProjects(); assertEquals(1, facades.length); assertSame(f2, facades[0]); assertSame(f2, delta.getProjectFacade(f1.getPom())); assertSame(f1, state.getProjects()[0]); List<MavenProjectChangedEvent> events = state.apply(delta); assertEquals(1, events.size()); assertEquals(MavenProjectChangedEvent.KIND_CHANGED, events.get(0).getKind()); assertSame(f1, events.get(0).getOldMavenProject()); assertSame(f2, events.get(0).getMavenProject()); } public void testRemoveProject() throws Exception { IProject project = createExisting("dummy", "resources/dummy"); ProjectRegistry state = new ProjectRegistry(); MavenProjectFacade f1 = newProjectFacade(project.getFile("p1.xml")); MutableProjectRegistry delta = new MutableProjectRegistry(state); delta.setProject(f1.getPom(), f1); state.apply(delta); delta = new MutableProjectRegistry(state); delta.removeProject(f1.getPom(), f1.getArtifactKey()); assertNull(delta.getProjectFacade(f1.getPom())); assertNull(delta.getWorkspaceArtifact(f1.getArtifactKey())); assertEquals(0, delta.getProjects().length); assertSame(f1, state.getProjects()[0]); List<MavenProjectChangedEvent> events = state.apply(delta); assertNull(state.getProjectFacade(f1.getPom())); assertNull(state.getWorkspaceArtifact(f1.getArtifactKey())); assertEquals(0, state.getProjects().length); assertEquals(1, events.size()); assertEquals(MavenProjectChangedEvent.KIND_REMOVED, events.get(0).getKind()); assertSame(f1, events.get(0).getOldMavenProject()); assertNull(events.get(0).getMavenProject()); } public void testRemoveUnknownProject() throws Exception { IProject project = createExisting("dummy", "resources/dummy"); ProjectRegistry state = new ProjectRegistry(); MutableProjectRegistry delta = new MutableProjectRegistry(state); MavenProjectFacade f1 = newProjectFacade(project.getFile("p1.xml")); delta.removeProject(f1.getPom(), f1.getArtifactKey()); assertNull(delta.getProjectFacade(f1.getPom())); assertEquals(0, delta.getProjects().length); List<MavenProjectChangedEvent> events = state.apply(delta); assertNull(state.getProjectFacade(f1.getPom())); assertEquals(0, state.getProjects().length); assertTrue(events.isEmpty()); } - public void testIllageStateMerge() throws Exception { + public void testIllegalStateMerge() throws Exception { ProjectRegistry state = new ProjectRegistry(); MutableProjectRegistry delta = new MutableProjectRegistry(state); state.apply(delta); try { state.apply(delta); fail("IllegalStateException is expected"); } catch (IllegalStateException expected) { // } - } public void testDetectNoLongerExistingProjectsInWorkspaceState() throws Exception { ProjectRegistry state = new ProjectRegistry(); MutableProjectRegistry delta = new MutableProjectRegistry(state); IProject project = createExisting("dummy", "resources/dummy"); IFile pom = project.getFile("p1.xml"); delta.setProject(pom, newProjectFacade(pom)); state.apply(delta); File tmpDir = File.createTempFile("m2e-" + getName(), "dir"); tmpDir.delete(); tmpDir.mkdir(); ProjectRegistryReader reader = new ProjectRegistryReader(tmpDir); reader.writeWorkspaceState(state); project.delete(true, true, monitor); state = reader.readWorkspaceState(null); assertFalse(state.isValid()); new File(tmpDir, "workspaceState.ser").delete(); tmpDir.delete(); } public void testForeignClassesInSerializedProjectRegistry() throws Exception { ProjectRegistry state = new ProjectRegistry(); MutableProjectRegistry delta = new MutableProjectRegistry(state); IProject project = createExisting("dummy", "resources/dummy"); IFile pom = project.getFile("p1.xml"); delta.setProject(pom, newProjectFacade(pom)); Set<Capability> capabilities = new HashSet<Capability>(); capabilities.add(new TestCapability("test", "test", "1")); delta.setCapabilities(pom, capabilities); state.apply(delta); File tmpDir = File.createTempFile("m2e-" + getName(), "dir"); tmpDir.delete(); tmpDir.mkdir(); ProjectRegistryReader reader = new ProjectRegistryReader(tmpDir); reader.writeWorkspaceState(state); state = reader.readWorkspaceState(null); assertTrue(state.isValid()); new File(tmpDir, "workspaceState.ser").delete(); tmpDir.delete(); } private MavenProjectFacade newProjectFacade(IFile pom) throws Exception { MavenProject mavenProject = maven.readProject(pom.getLocation().toFile(), monitor); return new MavenProjectFacade(null, pom, mavenProject, null, null); } }
false
false
null
null
diff --git a/org.projectusus.ui.dependencygraph/src/org/projectusus/ui/dependencygraph/common/NodeLabelProvider.java b/org.projectusus.ui.dependencygraph/src/org/projectusus/ui/dependencygraph/common/NodeLabelProvider.java index 87305d42..aea8bfa9 100644 --- a/org.projectusus.ui.dependencygraph/src/org/projectusus/ui/dependencygraph/common/NodeLabelProvider.java +++ b/org.projectusus.ui.dependencygraph/src/org/projectusus/ui/dependencygraph/common/NodeLabelProvider.java @@ -1,167 +1,162 @@ package org.projectusus.ui.dependencygraph.common; import static org.eclipse.jdt.ui.ISharedImages.IMG_OBJS_CLASS; import static org.eclipse.jdt.ui.ISharedImages.IMG_OBJS_PACKAGE; import static org.eclipse.jdt.ui.JavaElementLabels.P_COMPRESSED; import static org.eclipse.zest.core.widgets.ZestStyles.CONNECTIONS_DOT; import static org.eclipse.zest.core.widgets.ZestStyles.CONNECTIONS_SOLID; import static org.projectusus.ui.colors.UsusColors.BLACK; import static org.projectusus.ui.colors.UsusColors.DARK_GREY; import static org.projectusus.ui.colors.UsusColors.DARK_RED; import static org.projectusus.ui.colors.UsusColors.getSharedColors; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.zest.core.viewers.EntityConnectionData; import org.eclipse.zest.core.viewers.IEntityConnectionStyleProvider; import org.eclipse.zest.core.viewers.IEntityStyleProvider; import org.projectusus.core.basis.GraphNode; import org.projectusus.core.filerelations.model.Packagename; import org.projectusus.core.proportions.rawdata.ClassRepresenter; import org.projectusus.core.util.Defect; import org.projectusus.ui.colors.UsusColors; public class NodeLabelProvider extends LabelProvider implements IEntityStyleProvider, IEntityConnectionStyleProvider { @Override public String getText( Object element ) { if( element instanceof GraphNode ) { return getText( (GraphNode)element ); } if( element instanceof EntityConnectionData ) { return getText( (EntityConnectionData)element ); } throw new Defect( "Type not supported: " + element.getClass().toString() ); } private String getText( EntityConnectionData data ) { GraphNode dest = (GraphNode)data.dest; return dest.getEdgeEndLabel(); } private String getText( GraphNode node ) { if( node.isPackage() ) { return getText( node.getNodeJavaElement() ); } return node.getNodeName(); } private String getText( IJavaElement javaElement ) { return JavaElementLabels.getTextLabel( javaElement, P_COMPRESSED ); } @Override public Image getImage( Object element ) { if( element instanceof GraphNode ) { return getImage( (GraphNode)element ); } return null; } private Image getImage( GraphNode node ) { String imageName = node.isPackage() ? IMG_OBJS_PACKAGE : IMG_OBJS_CLASS; return JavaUI.getSharedImages().getImage( imageName ); } // From IEntityStyleProvider public Color getBackgroundColour( Object element ) { if( element instanceof GraphNode ) { Packagename packageName = ((GraphNode)element).getRelatedPackage(); return UsusColors.getSharedColors().getNodeColorFor( packageName.hashCode() ); } return null; } public Color getNodeHighlightColor( Object entity ) { - // TODO Auto-generated method stub return null; } public Color getBorderColor( Object entity ) { return getSharedColors().getColor( BLACK ); } public Color getBorderHighlightColor( Object entity ) { - // TODO Auto-generated method stub return null; } public int getBorderWidth( Object entity ) { - // TODO Auto-generated method stub return 0; } public Color getForegroundColour( Object entity ) { if( isVeryDark( entity ) ) { return getSharedColors().getColor( UsusColors.WHITE ); } return getSharedColors().getColor( BLACK ); } private boolean isVeryDark( Object entity ) { float[] hsb = getBackgroundColour( entity ).getRGB().getHSB(); float saturation = hsb[1]; float brightness = hsb[2]; - return (saturation > 0.5 && brightness > 0.9); + return (saturation > 0.6 || brightness < 0.85); } public IFigure getTooltip( Object entity ) { if( entity instanceof GraphNode ) { Label label = new Label(); GraphNode node = (GraphNode)entity; label.setText( getText( node.getNodeJavaElement() ) ); return label; } return null; } public boolean fisheyeNode( Object entity ) { - // TODO Auto-generated method stub return false; } // From IEntityConnectionStyleProvider public int getConnectionStyle( Object src, Object dest ) { if( areClassesInDifferentPackages( src, dest ) ) { return CONNECTIONS_SOLID; } return CONNECTIONS_DOT; } private boolean areClassesInDifferentPackages( Object src, Object dest ) { if( (src instanceof ClassRepresenter) && dest instanceof ClassRepresenter ) { ClassRepresenter srcClass = (ClassRepresenter)src; ClassRepresenter destClass = (ClassRepresenter)dest; return !srcClass.getPackagename().equals( destClass.getPackagename() ); } return false; } public Color getColor( Object src, Object dest ) { if( areClassesInDifferentPackages( src, dest ) ) { return getSharedColors().getColor( DARK_RED ); } return getSharedColors().getColor( DARK_GREY ); } public Color getHighlightColor( Object src, Object dest ) { - // TODO Auto-generated method stub return null; } public int getLineWidth( Object src, Object dest ) { if( areClassesInDifferentPackages( src, dest ) ) { return 2; } return 1; } }
false
false
null
null
diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/GroovyCompilationUnitDeclaration.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/GroovyCompilationUnitDeclaration.java index f7592a9a9..d009171a2 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/GroovyCompilationUnitDeclaration.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/GroovyCompilationUnitDeclaration.java @@ -1,2158 +1,2165 @@ /******************************************************************************* * Copyright (c) 2009 Codehaus.org, SpringSource, 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: * Andy Clement - Initial API and implementation * Andrew Eisenberg - Additional work *******************************************************************************/ package org.codehaus.jdt.groovy.internal.compiler.ast; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.Comment; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.ImportNode; import org.codehaus.groovy.ast.ImportNodeCompatibilityWrapper; import org.codehaus.groovy.ast.InnerClassNode; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.ast.PackageNode; import org.codehaus.groovy.ast.Parameter; import org.codehaus.groovy.ast.TaskEntry; import org.codehaus.groovy.ast.expr.ConstantExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.ListExpression; import org.codehaus.groovy.ast.expr.PropertyExpression; import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.control.CompilationUnit; import org.codehaus.groovy.control.ErrorCollector; import org.codehaus.groovy.control.MultipleCompilationErrorsException; import org.codehaus.groovy.control.Phases; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.Message; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.control.messages.SyntaxErrorMessage; import org.codehaus.groovy.syntax.PreciseSyntaxException; import org.codehaus.groovy.syntax.RuntimeParserException; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.tools.GroovyClass; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Javadoc; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.impl.IrritantSet; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment; import org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding; import org.eclipse.jdt.internal.compiler.lookup.TypeIds; import org.eclipse.jdt.internal.compiler.problem.AbortCompilation; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jdt.internal.compiler.problem.ProblemReporter; import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities; import org.eclipse.jdt.internal.core.util.Util; import org.objectweb.asm.Opcodes; /** * A subtype of JDT CompilationUnitDeclaration that represents a groovy source file. It overrides methods as appropriate, delegating * to the groovy infrastructure. * * @author Andy Clement */ @SuppressWarnings("restriction") public class GroovyCompilationUnitDeclaration extends CompilationUnitDeclaration { // The groovy compilation unit shared by all files in the same project private CompilationUnit groovyCompilationUnit; // The groovy sourceunit (a member of the groovyCompilationUnit) private SourceUnit groovySourceUnit; private CompilerOptions compilerOptions; private boolean checkGenerics; public static boolean defaultCheckGenerics = false; public static boolean earlyTransforms = true; private boolean isScript = false; private static final boolean DEBUG_TASK_TAGS = false; public GroovyCompilationUnitDeclaration(ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength, CompilationUnit groovyCompilationUnit, SourceUnit groovySourceUnit, CompilerOptions compilerOptions) { super(problemReporter, compilationResult, sourceLength); this.groovyCompilationUnit = groovyCompilationUnit; this.groovySourceUnit = groovySourceUnit; this.compilerOptions = compilerOptions; this.checkGenerics = defaultCheckGenerics; } /** * Take the comments information from the parse and apply it to the compilation unit */ private void setComments() { List<Comment> groovyComments = this.groovySourceUnit.getComments(); if (groovyComments == null || groovyComments.size() == 0) { return; } this.comments = new int[groovyComments.size()][2]; for (int c = 0, max = groovyComments.size(); c < max; c++) { Comment groovyComment = groovyComments.get(c); this.comments[c] = groovyComment.getPositions(compilationResult.lineSeparatorPositions); // System.out.println("Comment recorded on " + groovySourceUnit.getName() + " " + this.comments[c][0] + ">" // + this.comments[c][1]); } } /** * Drives the Groovy Compilation Unit for this project through to the specified phase. Yes on a call for one groovy file to * processToPhase(), all the groovy files in the project proceed to that phase. This isn't ideal but doesn't necessarily cause a * problem. But it does mean progress reporting for the compilation is incorrect as it jumps rather than smoothly going from 1 * to 100%. * * @param phase the phase to process up to * @return true if clean processing, false otherwise */ public boolean processToPhase(int phase) { boolean alreadyHasProblems = compilationResult.hasProblems(); // Our replacement error collector doesn't cause an exception, instead they are checked for post 'compile' try { - groovyCompilationUnit.compile(phase); + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(groovyCompilationUnit.getTransformLoader()); + groovyCompilationUnit.compile(phase); + } finally { + Thread.currentThread().setContextClassLoader(cl); + } if (groovySourceUnit.getErrorCollector().hasErrors()) { recordProblems(groovySourceUnit.getErrorCollector().getErrors()); return false; } else { return true; } } catch (MultipleCompilationErrorsException problems) { AbortCompilation abort = getAbortCompilation(problems); if (abort != null) { System.out.println("Abort compilation"); throw abort; } else { System.err.println("exception handling"); // alternative to catching this is fleshing out the ErrorCollector // sub type we have and asking it if there // are errors at the end of a run... problems.printStackTrace(); recordProblems(problems.getErrorCollector().getErrors()); } } catch (GroovyBugError gbr) { // FIXASC (M3) really, the GBE should not be thrown in the first place // we shouldn't need to silently fail here. if (alreadyHasProblems) { // do not log the error because it is likely to have // occurred because of the existing problem System.err.println("Ignoring GroovyBugError since it is likely caused by earlier issues. Ignored problem is '" + gbr.getMessage() + "'"); } else { boolean reportit = true; if (gbr.getCause() instanceof AbortCompilation) { // might be nothing to log - AbortCompilations can occur 'normally' during processing // when jobs are stopped due to any results they produce being stale. AbortCompilation abort = (AbortCompilation) gbr.getCause(); if (abort.isSilent) { reportit = false; } } if (reportit) { System.err.println("Groovy Bug --- " + gbr.getBugText()); gbr.printStackTrace(); // The groovy compiler threw an exception // FIXASC (M3) Should record these errors as a problem on the project // should *not* throw these because of bad syntax in the file Util.log(gbr, "Groovy bug when compiling."); } } } return false; } private org.eclipse.jdt.internal.compiler.problem.AbortCompilation getAbortCompilation( MultipleCompilationErrorsException problems) { ErrorCollector collector = problems.getErrorCollector(); if (collector.getErrorCount() == 1 && problems.getErrorCollector().getError(0) instanceof ExceptionMessage) { Exception abort = ((ExceptionMessage) problems.getErrorCollector().getError(0)).getCause(); return abort instanceof AbortCompilation ? (AbortCompilation) abort : null; } return null; } /** * @return the *groovy* compilation unit shared by all files in the same project */ public CompilationUnit getCompilationUnit() { return groovyCompilationUnit; } /** * Populate the compilation unit based on the successful parse. */ public void populateCompilationUnitDeclaration() { ModuleNode moduleNode = groovySourceUnit.getAST(); // if (moduleNode.encounteredUnrecoverableError()) { // String msg = "Groovy: Unrecoverable error during processing - source file contains invalid syntax"; // int sev = ProblemSeverities.Error; // CategorizedProblem p = new DefaultProblemFactory().createProblem(getFileName(), 0, new String[] { msg }, 0, // new String[] { msg }, sev, 0, 1, 1, 0); // this.problemReporter.record(p, compilationResult, this); // } createPackageDeclaration(moduleNode); createImports(moduleNode); createTypeDeclarations(moduleNode); } // make protected for testing protected void createImports(ModuleNode moduleNode) { List<ImportNode> importNodes = moduleNode.getImports(); List<ImportNode> importPackages = ImportNodeCompatibilityWrapper.getStarImports(moduleNode); Map<String, ImportNode> importStatics = ImportNodeCompatibilityWrapper.getStaticImports(moduleNode); Map<String, ImportNode> importStaticStars = ImportNodeCompatibilityWrapper.getStaticStarImports(moduleNode); if (importNodes.size() > 0 || importPackages.size() > 0 || importStatics.size() > 0 || importStaticStars.size() > 0) { int importNum = 0; imports = new ImportReference[importNodes.size() + importPackages.size() + importStatics.size() + importStaticStars.size()]; for (ImportNode importNode : importNodes) { char[][] splits = CharOperation.splitOn('.', importNode.getClassName().toCharArray()); ImportReference ref = null; ClassNode type = importNode.getType(); int typeStartOffset = startOffset(type); int typeEndOffset = endOffset(type); if (importNode.getAlias() != null && importNode.getAlias().length() > 0) { // FIXASC will need extra positional info for the 'as' and the alias ref = new AliasImportReference(importNode.getAlias().toCharArray(), splits, positionsFor(splits, typeStartOffset, typeEndOffset), false, ClassFileConstants.AccDefault); } else { ref = new ImportReference(splits, positionsFor(splits, typeStartOffset, typeEndOffset), false, ClassFileConstants.AccDefault); } ref.sourceEnd = Math.max(typeEndOffset - 1, ref.sourceStart); // For error reporting, Eclipse wants -1 ref.declarationSourceStart = importNode.getStart(); ref.declarationSourceEnd = importNode.getEnd(); ref.declarationEnd = ref.sourceEnd; imports[importNum++] = ref; } for (ImportNode importPackage : importPackages) { String importText = importPackage.getText(); // when calculating these offsets, assume no extraneous whitespace int packageStartOffset = importPackage.getStart() + "import ".length(); int packageEndOffset = packageStartOffset + importText.length() - "import ".length() - ".*".length(); char[][] splits = CharOperation.splitOn('.', importPackage.getPackageName().substring(0, importPackage.getPackageName().length() - 1).toCharArray()); ImportReference ref = new ImportReference(splits, positionsFor(splits, packageStartOffset, packageEndOffset), true, ClassFileConstants.AccDefault); // import * style only have slocs for the entire ImportNode and not for the embedded type ref.sourceEnd = packageEndOffset; ref.declarationSourceStart = importPackage.getStart(); ref.declarationSourceEnd = importPackage.getEnd(); ref.declarationEnd = ref.sourceEnd; imports[importNum++] = ref; } for (Map.Entry<String, ImportNode> importStatic : importStatics.entrySet()) { ImportNode importNode = importStatic.getValue(); String importName = importNode.getClassName() + "." + importStatic.getKey(); char[][] splits = CharOperation.splitOn('.', importName.toCharArray()); ImportReference ref = null; ClassNode type = importNode.getType(); int typeStartOffset = startOffset(type); int typeEndOffset = endOffset(type); if (importNode.getAlias() != null && importNode.getAlias().length() > 0) { // FIXASC will need extra positional info for the 'as' and the alias ref = new AliasImportReference(importNode.getAlias().toCharArray(), splits, positionsFor(splits, typeStartOffset, typeEndOffset), false, ClassFileConstants.AccDefault | ClassFileConstants.AccStatic); } else { ref = new ImportReference(splits, positionsFor(splits, typeStartOffset, typeEndOffset), false, ClassFileConstants.AccDefault | ClassFileConstants.AccStatic); } ref.sourceEnd = Math.max(typeEndOffset - 1, ref.sourceStart); // For error reporting, Eclipse wants -1 ref.declarationSourceStart = importNode.getStart(); ref.declarationSourceEnd = importNode.getEnd(); ref.declarationEnd = ref.sourceEnd; imports[importNum++] = ref; } for (Map.Entry<String, ImportNode> importStaticStar : importStaticStars.entrySet()) { String classname = importStaticStar.getKey(); ImportNode importNode = importStaticStar.getValue(); ClassNode importedType = importNode.getType(); int typeStartOffset = importedType != null ? startOffset(importedType) : 0; int typeEndOffset = importedType != null ? endOffset(importedType) : 0; char[][] splits = CharOperation.splitOn('.', classname.toCharArray()); ImportReference ref = new ImportReference(splits, positionsFor(splits, typeStartOffset, typeEndOffset), true, ClassFileConstants.AccDefault | ClassFileConstants.AccStatic); ref.sourceEnd = Math.max(typeEndOffset - 1, ref.sourceStart); // For error reporting, Eclipse wants -1 ref.declarationSourceStart = importNode.getStart(); ref.declarationSourceEnd = importNode.getEnd(); ref.declarationEnd = ref.sourceEnd; imports[importNum++] = ref; } // ensure proper lexical order if (imports != null) { Arrays.sort(imports, new Comparator<ImportReference>() { public int compare(ImportReference left, ImportReference right) { return left.sourceStart - right.sourceStart; } }); } } } /** * Build a JDT package declaration based on the groovy one */ private void createPackageDeclaration(ModuleNode moduleNode) { if (moduleNode.hasPackageName()) { PackageNode packageNode = moduleNode.getPackage();// Node(); String packageName = moduleNode.getPackageName(); if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } long start = startOffset(packageNode); long end = endOffset(packageNode); char[][] packageReference = CharOperation.splitOn('.', packageName.toCharArray()); currentPackage = new ImportReference(packageReference, positionsFor(packageReference, start, end), true, ClassFileConstants.AccDefault); currentPackage.declarationSourceStart = currentPackage.sourceStart; currentPackage.declarationSourceEnd = currentPackage.sourceEnd; currentPackage.declarationEnd = currentPackage.sourceEnd; // FIXASC (M3) not right, there may be spaces between package keyword and decl. Just the first example of position // problems currentPackage.declarationSourceStart = currentPackage.sourceStart - "package ".length(); currentPackage.declarationEnd = currentPackage.declarationSourceEnd = currentPackage.sourceEnd; } } /** * Convert groovy annotations into JDT annotations * * @return an array of annotations or null if there are none */ private Annotation[] transformAnnotations(List<AnnotationNode> groovyAnnotations) { // FIXASC positions are crap if (groovyAnnotations != null && groovyAnnotations.size() > 0) { List<Annotation> annotations = new ArrayList<Annotation>(); for (AnnotationNode annotationNode : groovyAnnotations) { ClassNode annoType = annotationNode.getClassNode(); Map<String, Expression> memberValuePairs = annotationNode.getMembers(); // FIXASC (M3) do more than pure marker annotations and do annotation values if (memberValuePairs == null || memberValuePairs.size() == 0) { // Marker annotation: TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd(); MarkerAnnotation annotation = new MarkerAnnotation(annotationReference, annotationNode.getStart()); annotation.declarationSourceEnd = annotation.sourceEnd; annotations.add(annotation); } else { if (memberValuePairs.size() == 1 && memberValuePairs.containsKey("value")) { // Single member annotation // Code written to only manage a single class literal value annotation - so that @RunWith works Expression value = memberValuePairs.get("value"); if (value instanceof PropertyExpression) { String pExpression = ((PropertyExpression) value).getPropertyAsString(); if (pExpression.equals("class")) { TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd(); SingleMemberAnnotation annotation = new SingleMemberAnnotation(annotationReference, annotationNode.getStart()); annotation.memberValue = new ClassLiteralAccess(value.getEnd(), classLiteralToTypeReference((PropertyExpression) value)); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getNameWithoutPackage().length(); annotations.add(annotation); } } else if (value instanceof VariableExpression && annoType.getName().endsWith("RunWith")) { // FIXASC special case for 'RunWith(Foo)' where for some reason groovy doesn't mind the missing // '.class' // FIXASC test this TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd(); SingleMemberAnnotation annotation = new SingleMemberAnnotation(annotationReference, annotationNode.getStart()); String v = ((VariableExpression) value).getName(); TypeReference ref = null; int start = annotationReference.sourceStart; int end = annotationReference.sourceEnd; if (v.indexOf(".") == -1) { ref = new SingleTypeReference(v.toCharArray(), toPos(start, end - 1)); } else { char[][] splits = CharOperation.splitOn('.', v.toCharArray()); ref = new QualifiedTypeReference(splits, positionsFor(splits, start, end - 2)); } annotation.memberValue = new ClassLiteralAccess(value.getEnd(), ref); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getNameWithoutPackage().length(); annotations.add(annotation); // FIXASC underlining for SuppressWarnings doesn't seem right when included in messages } else if (annoType.getName().equals("SuppressWarnings") && (value instanceof ConstantExpression || value instanceof ListExpression)) { if (value instanceof ListExpression) { ListExpression listExpression = (ListExpression) value; // FIXASC tidy up all this junk (err, i mean 'refactor') once we have confidence in test // coverage List<Expression> listOfExpressions = listExpression.getExpressions(); TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd() - 1; SingleMemberAnnotation annotation = new SingleMemberAnnotation(annotationReference, annotationNode.getStart()); ArrayInitializer arrayInitializer = new ArrayInitializer(); arrayInitializer.expressions = new org.eclipse.jdt.internal.compiler.ast.Expression[listOfExpressions .size()]; for (int c = 0; c < listOfExpressions.size(); c++) { ConstantExpression cExpression = (ConstantExpression) listOfExpressions.get(c); String v = (String) cExpression.getValue(); TypeReference ref = null; int start = cExpression.getStart(); int end = cExpression.getEnd() - 1; if (v.indexOf(".") == -1) { ref = new SingleTypeReference(v.toCharArray(), toPos(start, end - 1)); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getNameWithoutPackage().length() - 1; } else { char[][] splits = CharOperation.splitOn('.', v.toCharArray()); ref = new QualifiedTypeReference(splits, positionsFor(splits, start, end - 2)); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getName().length() - 1; } arrayInitializer.expressions[c] = new StringLiteral(v.toCharArray(), start, end, -1); } annotation.memberValue = arrayInitializer; annotations.add(annotation); } else { ConstantExpression constantExpression = (ConstantExpression) value; if (value.getType().getName().equals("java.lang.String")) { // single value, eg. @SuppressWarnings("unchecked") // FIXASC tidy up all this junk (err, i mean 'refactor') once we have confidence in test // coverage // FIXASC test positional info for conjured up anno refs TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd() - 1; SingleMemberAnnotation annotation = new SingleMemberAnnotation(annotationReference, annotationNode.getStart()); String v = (String) constantExpression.getValue(); TypeReference ref = null; int start = constantExpression.getStart(); int end = constantExpression.getEnd() - 1; if (v.indexOf(".") == -1) { ref = new SingleTypeReference(v.toCharArray(), toPos(start, end - 1)); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getNameWithoutPackage().length() - 1; } else { char[][] splits = CharOperation.splitOn('.', v.toCharArray()); ref = new QualifiedTypeReference(splits, positionsFor(splits, start, end - 2)); annotation.declarationSourceEnd = annotation.sourceStart + annoType.getName().length() - 1; } annotation.memberValue = new StringLiteral(v.toCharArray(), start, end, -1); annotations.add(annotation); } } } } else if (annoType.getNameWithoutPackage().equals("Test")) { // normal annotation (with at least one member value pair) // GRECLIPSE-569 // treat as a marker annotation // this is specifically written so that annotations like @Test(expected = FooException) can be found TypeReference annotationReference = createTypeReferenceForClassNode(annoType); annotationReference.sourceStart = annotationNode.getStart(); annotationReference.sourceEnd = annotationNode.getEnd(); MarkerAnnotation annotation = new MarkerAnnotation(annotationReference, annotationNode.getStart()); annotation.declarationSourceEnd = annotation.sourceEnd; annotations.add(annotation); } } } if (annotations.size() > 0) { return annotations.toArray(new Annotation[annotations.size()]); } } return null; } private TypeReference classLiteralToTypeReference(PropertyExpression value) { // should be a class literal node assert value.getPropertyAsString().equals("class"); // FIXASC ignore type parameters for now Expression candidate = value.getObjectExpression(); List<char[]> nameParts = new LinkedList<char[]>(); while (candidate instanceof PropertyExpression) { nameParts.add(0, ((PropertyExpression) candidate).getPropertyAsString().toCharArray()); candidate = ((PropertyExpression) candidate).getObjectExpression(); } if (candidate instanceof VariableExpression) { nameParts.add(0, ((VariableExpression) candidate).getName().toCharArray()); } char[][] namePartsArr = nameParts.toArray(new char[nameParts.size()][]); long[] poss = positionsFor(namePartsArr, value.getObjectExpression().getStart(), value.getObjectExpression().getEnd()); TypeReference ref; if (namePartsArr.length > 1) { ref = new QualifiedTypeReference(namePartsArr, poss); } else if (namePartsArr.length == 1) { ref = new SingleTypeReference(namePartsArr[0], poss[0]); } else { // should not happen ref = TypeReference.baseTypeReference(nameToPrimitiveTypeId.get("void"), 0); } return ref; } /** * Find any javadoc that terminates on one of the two lines before the specified line, return the first bit encountered. A * little crude but will cover a lot of common cases... <br> */ // FIXASC when the parser correctly records javadoc for nodes alongside them during a parse, we will not have to search private Javadoc findJavadoc(int line) { // System.out.println("Looking for javadoc for line " + line); for (Comment comment : groovySourceUnit.getComments()) { if (comment.isJavadoc()) { // System.out.println("Checking against comment ending on " + comment.getLastLine()); if (comment.getLastLine() + 1 == line || comment.getLastLine() + 2 == line) { int[] pos = comment.getPositions(compilationResult.lineSeparatorPositions); // System.out.println("Comment says it is from line=" + comment.sline + ",col=" + comment.scol + " to line=" // + comment.eline + ",col=" + comment.ecol); // System.out.println("Returning positions " + pos[0] + ">" + pos[1]); return new Javadoc(pos[0], pos[1]); } } } return null; } /** * Build JDT TypeDeclarations for the groovy type declarations that were parsed from the source file. */ private void createTypeDeclarations(ModuleNode moduleNode) { List<ClassNode> moduleClassNodes = moduleNode.getClasses(); List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>(); Map<ClassNode, TypeDeclaration> fromClassNodeToDecl = new HashMap<ClassNode, TypeDeclaration>(); char[] mainName = toMainName(compilationResult.getFileName()); boolean isInner = false; List<ClassNode> classNodes = null; classNodes = moduleClassNodes; Map<ClassNode, List<TypeDeclaration>> innersToRecord = new HashMap<ClassNode, List<TypeDeclaration>>(); for (ClassNode classNode : classNodes) { if (!classNode.isPrimaryClassNode()) { continue; } GroovyTypeDeclaration typeDeclaration = new GroovyTypeDeclaration(compilationResult, classNode); typeDeclaration.annotations = transformAnnotations(classNode.getAnnotations()); // FIXASC duplicates code further down, tidy this up if (classNode instanceof InnerClassNode) { InnerClassNode innerClassNode = (InnerClassNode) classNode; ClassNode outerClass = innerClassNode.getOuterClass(); String outername = outerClass.getNameWithoutPackage(); String newInner = innerClassNode.getNameWithoutPackage().substring(outername.length() + 1); typeDeclaration.name = newInner.toCharArray(); isInner = true; } else { typeDeclaration.name = classNode.getNameWithoutPackage().toCharArray(); isInner = false; } // classNode.getInnerClasses(); // classNode. boolean isInterface = classNode.isInterface(); int mods = classNode.getModifiers(); if ((mods & Opcodes.ACC_ENUM) != 0) { // remove final mods = mods & ~Opcodes.ACC_FINAL; } // FIXASC should this modifier be set? // mods |= Opcodes.ACC_PUBLIC; // FIXASC should not do this for inner classes, just for top level types // FIXASC does this make things visible that shouldn't be? mods = mods & ~(Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED); if (!isInner) { if ((mods & Opcodes.ACC_STATIC) != 0) { mods = mods & ~(Opcodes.ACC_STATIC); } } typeDeclaration.modifiers = mods & ~(isInterface ? Opcodes.ACC_ABSTRACT : 0); if (!(classNode instanceof InnerClassNode)) { if (!CharOperation.equals(typeDeclaration.name, mainName)) { typeDeclaration.bits |= ASTNode.IsSecondaryType; } } fixupSourceLocationsForTypeDeclaration(typeDeclaration, classNode); if (classNode.getGenericsTypes() != null) { GenericsType[] genericInfo = classNode.getGenericsTypes(); // Example case here: Foo<T extends Number & I> // the type parameter is T, the 'type' is Number and the bounds for the type parameter are just the extra bound // I. typeDeclaration.typeParameters = new TypeParameter[genericInfo.length]; for (int tp = 0; tp < genericInfo.length; tp++) { TypeParameter typeParameter = new TypeParameter(); typeParameter.name = genericInfo[tp].getName().toCharArray(); ClassNode[] upperBounds = genericInfo[tp].getUpperBounds(); if (upperBounds != null) { // FIXASC (M3) Positional info for these references? typeParameter.type = createTypeReferenceForClassNode(upperBounds[0]); typeParameter.bounds = (upperBounds.length > 1 ? new TypeReference[upperBounds.length - 1] : null); for (int b = 1, max = upperBounds.length; b < max; b++) { typeParameter.bounds[b - 1] = createTypeReferenceForClassNode(upperBounds[b]); typeParameter.bounds[b - 1].bits |= ASTNode.IsSuperType; } } typeDeclaration.typeParameters[tp] = typeParameter; } } boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) != 0; configureSuperClass(typeDeclaration, classNode.getSuperClass(), isEnum); configureSuperInterfaces(typeDeclaration, classNode); typeDeclaration.methods = createMethodAndConstructorDeclarations(classNode, isEnum, compilationResult); typeDeclaration.fields = createFieldDeclarations(classNode); typeDeclaration.properties = classNode.getProperties(); if (classNode instanceof InnerClassNode) { InnerClassNode innerClassNode = (InnerClassNode) classNode; ClassNode outerClass = innerClassNode.getOuterClass(); String outername = outerClass.getNameWithoutPackage(); String newInner = innerClassNode.getNameWithoutPackage().substring(outername.length() + 1); typeDeclaration.name = newInner.toCharArray(); // Record that we need to set the parent of this inner type later List<TypeDeclaration> inners = innersToRecord.get(outerClass); if (inners == null) { inners = new ArrayList<TypeDeclaration>(); innersToRecord.put(outerClass, inners); } inners.add(typeDeclaration); } else { typeDeclarations.add(typeDeclaration); } fromClassNodeToDecl.put(classNode, typeDeclaration); } // For inner types, now attach them to their parents. This was not done earlier as sometimes the types are processed in // such an order that inners are dealt with before outers for (Map.Entry<ClassNode, List<TypeDeclaration>> innersToRecordEntry : innersToRecord.entrySet()) { TypeDeclaration outerTypeDeclaration = fromClassNodeToDecl.get(innersToRecordEntry.getKey()); // Check if there is a problem locating the parent for the inner if (outerTypeDeclaration == null) { throw new GroovyEclipseBug("Failed to find the type declaration for " + innersToRecordEntry.getKey().getName()); } List<TypeDeclaration> newInnersList = innersToRecordEntry.getValue(); outerTypeDeclaration.memberTypes = newInnersList.toArray(new TypeDeclaration[newInnersList.size()]); } types = typeDeclarations.toArray(new TypeDeclaration[typeDeclarations.size()]); } public char[] toMainName(char[] fileName) { if (fileName == null) { return new char[0]; } int start = CharOperation.lastIndexOf('/', fileName) + 1; if (start == 0 || start < CharOperation.lastIndexOf('\\', fileName)) start = CharOperation.lastIndexOf('\\', fileName) + 1; int end = CharOperation.lastIndexOf('.', fileName); if (end == -1) end = fileName.length; return CharOperation.subarray(fileName, start, end); } /** * Build JDT representations of all the method/ctors on the groovy type */ private AbstractMethodDeclaration[] createMethodAndConstructorDeclarations(ClassNode classNode, boolean isEnum, CompilationResult compilationResult) { List<AbstractMethodDeclaration> accumulatedDeclarations = new ArrayList<AbstractMethodDeclaration>(); createConstructorDeclarations(classNode, isEnum, accumulatedDeclarations); createMethodDeclarations(classNode, isEnum, accumulatedDeclarations); return accumulatedDeclarations.toArray(new AbstractMethodDeclaration[accumulatedDeclarations.size()]); } /** * Build JDT representations of all the fields on the groovy type. <br> * Enum field handling<br> * Groovy handles them as follows: they have the ACC_ENUM bit set and the type is the type of the declaring enum type. When * building declarations, if you want the SourceTypeBinding to correctly build an enum field binding (in * SourceTypeBinding.resolveTypeFor(FieldBinding)) then you need to: (1) avoid setting modifiers, the enum fields are not * expected to have any modifiers (2) leave the type as null, that is how these things are identified by JDT. */ private FieldDeclaration[] createFieldDeclarations(ClassNode classNode) { List<FieldDeclaration> fieldDeclarations = new ArrayList<FieldDeclaration>(); List<FieldNode> fieldNodes = classNode.getFields(); if (fieldNodes != null) { for (FieldNode fieldNode : fieldNodes) { boolean isEnumField = (fieldNode.getModifiers() & Opcodes.ACC_ENUM) != 0; boolean isSynthetic = (fieldNode.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0; if (!isSynthetic) { // JavaStubGenerator ignores private fields but I don't // think we want to here FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldNode.getName().toCharArray(), 0, 0); fieldDeclaration.annotations = transformAnnotations(fieldNode.getAnnotations()); if (!isEnumField) { fieldDeclaration.modifiers = fieldNode.getModifiers() & ~0x4000; // 4000 == AccEnum fieldDeclaration.type = createTypeReferenceForClassNode(fieldNode.getType()); } fieldDeclaration.javadoc = new Javadoc(108, 132); fixupSourceLocationsForFieldDeclaration(fieldDeclaration, fieldNode, isEnumField); fieldDeclarations.add(fieldDeclaration); } } } return fieldDeclarations.toArray(new FieldDeclaration[fieldDeclarations.size()]); } /** * Build JDT representations of all the constructors on the groovy type */ private void createConstructorDeclarations(ClassNode classNode, boolean isEnum, List<AbstractMethodDeclaration> accumulatedMethodDeclarations) { List<ConstructorNode> constructorNodes = classNode.getDeclaredConstructors(); char[] ctorName = null; if (classNode instanceof InnerClassNode) { InnerClassNode innerClassNode = (InnerClassNode) classNode; ClassNode outerClass = innerClassNode.getOuterClass(); String outername = outerClass.getNameWithoutPackage(); String newInner = innerClassNode.getNameWithoutPackage().substring(outername.length() + 1); ctorName = newInner.toCharArray(); } else { ctorName = classNode.getNameWithoutPackage().toCharArray(); } // Do we need a default constructor? boolean needsDefaultCtor = constructorNodes.size() == 0 && !classNode.isInterface(); if (needsDefaultCtor) { ConstructorDeclaration constructor = new ConstructorDeclaration(compilationResult); constructor.bits |= ASTNode.IsDefaultConstructor; if (isEnum) { constructor.modifiers = ClassFileConstants.AccPrivate; } else { constructor.modifiers = ClassFileConstants.AccPublic; } constructor.selector = ctorName; accumulatedMethodDeclarations.add(constructor); } for (ConstructorNode constructorNode : constructorNodes) { ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult); fixupSourceLocationsForConstructorDeclaration(constructorDeclaration, constructorNode); constructorDeclaration.annotations = transformAnnotations(constructorNode.getAnnotations()); // FIXASC should we just use the constructor node modifiers or does groovy make all constructors public apart from // those on enums? constructorDeclaration.modifiers = isEnum ? ClassFileConstants.AccPrivate : ClassFileConstants.AccPublic; constructorDeclaration.selector = ctorName; constructorDeclaration.arguments = createArguments(constructorNode.getParameters(), false); if (constructorNode.hasDefaultValue()) { createConstructorVariants(constructorNode, constructorDeclaration, accumulatedMethodDeclarations, compilationResult, isEnum); } else { accumulatedMethodDeclarations.add(constructorDeclaration); } } if (earlyTransforms) { executeEarlyTransforms_ConstructorRelated(ctorName, classNode, accumulatedMethodDeclarations); } } /** * Augment set of constructors based on annotations. If the annotations are going to trigger additional constructors later, add * them here. */ private void executeEarlyTransforms_ConstructorRelated(char[] ctorName, ClassNode classNode, List<AbstractMethodDeclaration> accumulatedMethodDeclarations) { List<AnnotationNode> annos = classNode.getAnnotations(); boolean hasImmutableAnnotation = false; if (annos != null) { for (AnnotationNode anno : annos) { if (anno.getClassNode() != null && anno.getClassNode().getName().equals("Immutable")) { hasImmutableAnnotation = true; } } } // TODO probably ought to check if clashing import rather than assuming it is groovy-eclipse Immutable (even though that is // very likely) if (hasImmutableAnnotation) { // @Immutable action: new constructor // TODO Should check against existing ones before creating a duplicate but quite ugly, and // groovy will be checking anyway... List<FieldNode> fields = classNode.getFields(); Argument[] arguments = new Argument[fields.size()]; for (int i = 0; i < fields.size(); i++) { FieldNode field = fields.get(i); TypeReference parameterTypeReference = createTypeReferenceForClassNode(field.getType()); // TODO should set type reference position arguments[i] = new Argument(fields.get(i).getName().toCharArray(), toPos(field.getStart(), field.getEnd() - 1), parameterTypeReference, ClassFileConstants.AccPublic); arguments[i].declarationSourceStart = fields.get(i).getStart(); } ConstructorDeclaration constructor = new ConstructorDeclaration(compilationResult); constructor.selector = ctorName; constructor.modifiers = ClassFileConstants.AccPublic; constructor.arguments = arguments; accumulatedMethodDeclarations.add(constructor); } } /** * Create JDT Argument representations of Groovy parameters */ private Argument[] createArguments(Parameter[] ps, boolean isMain) { if (ps == null || ps.length == 0) { return null; } Argument[] arguments = new Argument[ps.length]; for (int i = 0; i < ps.length; i++) { Parameter parameter = ps[i]; TypeReference parameterTypeReference = createTypeReferenceForClassNode(parameter.getType()); // not doing this for now: // if (isMain) { // parameterTypeReference = new ArrayTypeReference("String".toCharArray(), 1, // (parameterTypeReference.sourceStart << 32) | parameterTypeReference.sourceEnd); // } arguments[i] = new Argument(parameter.getName().toCharArray(), toPos(parameter.getStart(), parameter.getEnd() - 1), parameterTypeReference, ClassFileConstants.AccPublic); arguments[i].declarationSourceStart = parameter.getStart(); } if (isVargs(ps) /* && !isMain */) { arguments[ps.length - 1].type.bits |= ASTNode.IsVarArgs; } return arguments; } /** * Build JDT representations of all the methods on the groovy type */ private void createMethodDeclarations(ClassNode classNode, boolean isEnum, List<AbstractMethodDeclaration> accumulatedDeclarations) { List<MethodNode> methods = classNode.getMethods(); for (MethodNode methodNode : methods) { if (isEnum && methodNode.isSynthetic()) { // skip values() method and valueOf(String) String name = methodNode.getName(); Parameter[] params = methodNode.getParameters(); if (name.equals("values") && params.length == 0) { continue; } if (name.equals("valueOf") && params.length == 1 && params[0].getType().equals(ClassHelper.STRING_TYPE)) { continue; } } MethodDeclaration methodDeclaration = createMethodDeclaration(classNode, methodNode, isEnum, compilationResult); // methodDeclaration.javadoc = new Javadoc(0, 20); if (methodNode.hasDefaultValue()) { createMethodVariants(methodNode, methodDeclaration, accumulatedDeclarations, compilationResult); } else { accumulatedDeclarations.add(methodDeclaration); } } } /** * Called if a method has some 'defaulting' arguments and will compute all the variants (including the one with all parameters). */ private void createMethodVariants(MethodNode method, MethodDeclaration methodDecl, List<AbstractMethodDeclaration> accumulatedDeclarations, CompilationResult compilationResult) { List<Argument[]> variants = getVariantsAllowingForDefaulting(method.getParameters(), methodDecl.arguments); for (Argument[] variant : variants) { MethodDeclaration variantMethodDeclaration = genMethodDeclarationVariant(method, variant, methodDecl.returnType, compilationResult); addUnlessDuplicate(accumulatedDeclarations, variantMethodDeclaration); } } /** * In the given list of groovy parameters, some are defined as defaulting to an initial value. This method computes all the * variants of defaulting parameters allowed and returns a List of Argument arrays. Each argument array represents a variation. */ private List<Argument[]> getVariantsAllowingForDefaulting(Parameter[] groovyParams, Argument[] jdtArguments) { List<Argument[]> variants = new ArrayList<Argument[]>(); int psCount = groovyParams.length; Parameter[] wipableParameters = new Parameter[psCount]; System.arraycopy(groovyParams, 0, wipableParameters, 0, psCount); // Algorithm: wipableParameters is the 'full list' of parameters at the start. As the loop is repeated, all the non-null // values in the list indicate a parameter variation. On each repeat we null the last one in the list that // has an initial expression. This is repeated until there are no more left to null. List<Argument> oneVariation = new ArrayList<Argument>(); int nextToLetDefault = -1; do { oneVariation.clear(); nextToLetDefault = -1; // Create a variation based on the non null entries left in th elist for (int p = 0; p < psCount; p++) { if (wipableParameters[p] != null) { oneVariation.add(jdtArguments[p]); if (wipableParameters[p].hasInitialExpression()) { nextToLetDefault = p; } } } if (nextToLetDefault != -1) { wipableParameters[nextToLetDefault] = null; } Argument[] argumentsVariant = (oneVariation.size() == 0 ? null : oneVariation .toArray(new Argument[oneVariation.size()])); variants.add(argumentsVariant); } while (nextToLetDefault != -1); return variants; } /** * Add the new declaration to the list of those already built unless it clashes with an existing one. This can happen where the * default parameter mechanism causes creation of a variant that collides with an existing declaration. I'm not sure if Groovy * should be reporting an error when this occurs, but Grails does actually do it and gets no error. */ private void addUnlessDuplicate(List<AbstractMethodDeclaration> accumulatedDeclarations, AbstractMethodDeclaration newDeclaration) { boolean isDuplicate = false; for (AbstractMethodDeclaration aMethodDecl : accumulatedDeclarations) { if (CharOperation.equals(aMethodDecl.selector, newDeclaration.selector)) { Argument[] mdArgs = aMethodDecl.arguments; Argument[] vmdArgs = newDeclaration.arguments; int mdArgsLen = mdArgs == null ? 0 : mdArgs.length; int vmdArgsLen = vmdArgs == null ? 0 : vmdArgs.length; if (mdArgsLen == vmdArgsLen) { boolean argsTheSame = true; for (int i = 0; i < mdArgsLen; i++) { // FIXASC this comparison can fail if some are fully qualified and some not - in fact it // suggests that default param variants should be built by augmentMethod() in a similar way to // the GroovyObject methods, rather than during type declaration construction - but not super urgent right // now if (!CharOperation.equals(mdArgs[i].type.getTypeName(), vmdArgs[i].type.getTypeName())) { argsTheSame = false; break; } } if (argsTheSame) { isDuplicate = true; break; } } } } if (!isDuplicate) { accumulatedDeclarations.add(newDeclaration); } } /** * Called if a constructor has some 'defaulting' arguments and will compute all the variants (including the one with all * parameters). */ private void createConstructorVariants(ConstructorNode constructorNode, ConstructorDeclaration constructorDecl, List<AbstractMethodDeclaration> accumulatedDeclarations, CompilationResult compilationResult, boolean isEnum) { List<Argument[]> variants = getVariantsAllowingForDefaulting(constructorNode.getParameters(), constructorDecl.arguments); for (Argument[] variant : variants) { ConstructorDeclaration constructorDeclaration = new ConstructorDeclaration(compilationResult); constructorDeclaration.annotations = transformAnnotations(constructorNode.getAnnotations()); constructorDeclaration.modifiers = isEnum ? ClassFileConstants.AccPrivate : ClassFileConstants.AccPublic; constructorDeclaration.selector = constructorDecl.selector; constructorDeclaration.arguments = variant; fixupSourceLocationsForConstructorDeclaration(constructorDeclaration, constructorNode); addUnlessDuplicate(accumulatedDeclarations, constructorDeclaration); } } /** * Create a JDT MethodDeclaration that represents a groovy MethodNode */ private MethodDeclaration createMethodDeclaration(ClassNode classNode, MethodNode methodNode, boolean isEnum, CompilationResult compilationResult) { if (classNode.isAnnotationDefinition()) { AnnotationMethodDeclaration methodDeclaration = new AnnotationMethodDeclaration(compilationResult); int modifiers = methodNode.getModifiers(); modifiers &= ~(ClassFileConstants.AccSynthetic | ClassFileConstants.AccTransient); methodDeclaration.annotations = transformAnnotations(methodNode.getAnnotations()); methodDeclaration.modifiers = modifiers; if (methodNode.hasAnnotationDefault()) { methodDeclaration.modifiers |= ClassFileConstants.AccAnnotationDefault; } methodDeclaration.selector = methodNode.getName().toCharArray(); fixupSourceLocationsForMethodDeclaration(methodDeclaration, methodNode); ClassNode returnType = methodNode.getReturnType(); methodDeclaration.returnType = createTypeReferenceForClassNode(returnType); return methodDeclaration; } else { MethodDeclaration methodDeclaration = new MethodDeclaration(compilationResult); // TODO refactor - extract method GenericsType[] generics = methodNode.getGenericsTypes(); // generic method if (generics != null && generics.length != 0) { methodDeclaration.typeParameters = new TypeParameter[generics.length]; for (int tp = 0; tp < generics.length; tp++) { TypeParameter typeParameter = new TypeParameter(); typeParameter.name = generics[tp].getName().toCharArray(); ClassNode[] upperBounds = generics[tp].getUpperBounds(); if (upperBounds != null) { // FIXASC Positional info for these references? typeParameter.type = createTypeReferenceForClassNode(upperBounds[0]); typeParameter.bounds = (upperBounds.length > 1 ? new TypeReference[upperBounds.length - 1] : null); for (int b = 1, max = upperBounds.length; b < max; b++) { typeParameter.bounds[b - 1] = createTypeReferenceForClassNode(upperBounds[b]); typeParameter.bounds[b - 1].bits |= ASTNode.IsSuperType; } } methodDeclaration.typeParameters[tp] = typeParameter; } } boolean isMain = false; // Note: modifiers for the MethodBinding constructed for this declaration will be created marked with // AccVarArgs if the bitset for the type reference in the final argument is marked IsVarArgs int modifiers = methodNode.getModifiers(); modifiers &= ~(ClassFileConstants.AccSynthetic | ClassFileConstants.AccTransient); methodDeclaration.annotations = transformAnnotations(methodNode.getAnnotations()); methodDeclaration.modifiers = modifiers; methodDeclaration.selector = methodNode.getName().toCharArray(); // Need to capture the rule in Verifier.adjustTypesIfStaticMainMethod(MethodNode node) // if (node.getName().equals("main") && node.isStatic()) { // Parameter[] params = node.getParameters(); // if (params.length == 1) { // Parameter param = params[0]; // if (param.getType() == null || param.getType()==ClassHelper.OBJECT_TYPE) { // param.setType(ClassHelper.STRING_TYPE.makeArray()); // ClassNode returnType = node.getReturnType(); // if(returnType == ClassHelper.OBJECT_TYPE) { // node.setReturnType(ClassHelper.VOID_TYPE); // } // } // } Parameter[] params = methodNode.getParameters(); ClassNode returnType = methodNode.getReturnType(); // source of 'static main(args)' would become 'static Object main(Object args)' - so transform here if ((modifiers & ClassFileConstants.AccStatic) != 0 && params != null && params.length == 1 && methodNode.getName().equals("main")) { Parameter p = params[0]; if (p.getType() == null || p.getType().getName().equals(ClassHelper.OBJECT)) { String name = p.getName(); params = new Parameter[1]; params[0] = new Parameter(ClassHelper.STRING_TYPE.makeArray(), name); if (returnType.getName().equals(ClassHelper.OBJECT)) { returnType = ClassHelper.VOID_TYPE; } } } methodDeclaration.arguments = createArguments(params, isMain); methodDeclaration.returnType = createTypeReferenceForClassNode(returnType); fixupSourceLocationsForMethodDeclaration(methodDeclaration, methodNode); return methodDeclaration; } } /** * Create a JDT representation of a groovy MethodNode - but with some parameters defaulting */ private MethodDeclaration genMethodDeclarationVariant(MethodNode methodNode, Argument[] alternativeArguments, TypeReference returnType, CompilationResult compilationResult) { MethodDeclaration methodDeclaration = new MethodDeclaration(compilationResult); int modifiers = methodNode.getModifiers(); modifiers &= ~(ClassFileConstants.AccSynthetic | ClassFileConstants.AccTransient); methodDeclaration.annotations = transformAnnotations(methodNode.getAnnotations()); methodDeclaration.modifiers = modifiers; methodDeclaration.selector = methodNode.getName().toCharArray(); methodDeclaration.arguments = alternativeArguments; methodDeclaration.returnType = returnType; fixupSourceLocationsForMethodDeclaration(methodDeclaration, methodNode); return methodDeclaration; } private void configureSuperInterfaces(TypeDeclaration typeDeclaration, ClassNode classNode) { ClassNode[] interfaces = classNode.getInterfaces(); if (interfaces != null && interfaces.length > 0) { typeDeclaration.superInterfaces = new TypeReference[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { typeDeclaration.superInterfaces[i] = createTypeReferenceForClassNode(interfaces[i]); } } else { typeDeclaration.superInterfaces = new TypeReference[0]; } } private void configureSuperClass(TypeDeclaration typeDeclaration, ClassNode superclass, boolean isEnum) { if (isEnum && superclass.getName().equals("java.lang.Enum")) { // Don't wire it in, JDT will do it typeDeclaration.superclass = null; } else { // If the start position is 0 the superclass wasn't actually declared, it was added by Groovy if (!(superclass.getStart() == 0 && superclass.equals(ClassHelper.OBJECT_TYPE))) { typeDeclaration.superclass = createTypeReferenceForClassNode(superclass); } } } // --- helper code private final static Map<Character, Integer> charToTypeId = new HashMap<Character, Integer>(); private final static Map<String, Integer> nameToPrimitiveTypeId = new HashMap<String, Integer>(); static { charToTypeId.put('D', TypeIds.T_double); charToTypeId.put('I', TypeIds.T_int); charToTypeId.put('F', TypeIds.T_float); charToTypeId.put('J', TypeIds.T_long); charToTypeId.put('Z', TypeIds.T_boolean); charToTypeId.put('B', TypeIds.T_byte); charToTypeId.put('C', TypeIds.T_char); charToTypeId.put('S', TypeIds.T_short); nameToPrimitiveTypeId.put("double", TypeIds.T_double); nameToPrimitiveTypeId.put("int", TypeIds.T_int); nameToPrimitiveTypeId.put("float", TypeIds.T_float); nameToPrimitiveTypeId.put("long", TypeIds.T_long); nameToPrimitiveTypeId.put("boolean", TypeIds.T_boolean); nameToPrimitiveTypeId.put("byte", TypeIds.T_byte); nameToPrimitiveTypeId.put("char", TypeIds.T_char); nameToPrimitiveTypeId.put("short", TypeIds.T_short); nameToPrimitiveTypeId.put("void", TypeIds.T_void); try { String value = System.getProperty(" earlyTransforms"); if (value != null) { if (value.equalsIgnoreCase("true")) { System.out.println("groovyeclipse.earlyTransforms = true"); earlyTransforms = true; } else if (value.equalsIgnoreCase("false")) { System.out.println("groovyeclipse.earlyTransforms = false"); earlyTransforms = false; } } } catch (Throwable t) { // -- } } /** * For some input array (usually representing a reference), work out the offset positions, assuming they are dotted. <br> * Currently this uses the size of each component to move from start towards end. For the very last one it makes the end * position 'end' because in some cases just adding 1+length of previous reference isn't enough. For example in java.util.List[] * the end will be the end of [] but reference will only contain 'java' 'util' 'List' * <p> * Because the 'end' is quite often wrong right now (for example on a return type 'java.util.List[]' the end can be two * characters off the end (set to the start of the method name...) - we are just computing the positional information from the * start. */ // FIXASC seems that sometimes, especially for types that are defined as 'def', but are converted to java.lang.Object, end // < start. This causes no end of problems. I don't think it is so much the 'declaration' as the fact that is no reference and // really what is computed here is the reference for something actually specified in the source code. Coming up with fake // positions for something not specified is not entirely unreasonable we should check // if the reference in particular needed creating at all in the first place... private long[] positionsFor(char[][] reference, long start, long end) { long[] result = new long[reference.length]; if (start < end) { // Do the right thing long pos = start; for (int i = 0, max = result.length; i < max; i++) { long s = pos; pos = pos + reference[i].length - 1; // jump to the last char of the name result[i] = ((s << 32) | pos); pos += 2; // jump onto the following '.' then off it } } else { // FIXASC this case shouldn't happen (end<start) - uncomment following if to collect diagnostics long pos = (start << 32) | start; for (int i = 0, max = result.length; i < max; i++) { result[i] = pos; } } return result; } /** * Convert from an array ClassNode into a TypeReference. */ private TypeReference createTypeReferenceForArrayName(ClassNode node, int start, int end) { String signature = node.getName(); int dim = 0; ClassNode componentType = node; while (componentType.isArray()) { dim++; componentType = componentType.getComponentType(); } if (componentType.isPrimitive()) { Integer ii = charToTypeId.get(signature.charAt(dim)); if (ii == null) { throw new IllegalStateException("node " + node + " reported it had a primitive component type, but it does not..."); } else { TypeReference baseTypeReference = TypeReference.baseTypeReference(ii, dim); baseTypeReference.sourceStart = start; baseTypeReference.sourceEnd = start + componentType.getName().length(); return baseTypeReference; } } if (dim == 0) { throw new IllegalStateException("Array classnode with dimensions 0?? node:" + node.getName()); } // array component is something like La.b.c; ... or sometimes just [[Z (where Z is a type, not primitive) String arrayComponentTypename = signature.substring(dim); if (arrayComponentTypename.charAt(arrayComponentTypename.length() - 1) == ';') { arrayComponentTypename = signature.substring(dim + 1, signature.length() - 1); // chop off '['s 'L' and ';' } if (arrayComponentTypename.indexOf(".") == -1) { return createJDTArrayTypeReference(arrayComponentTypename, dim, start, end); } else { return createJDTArrayQualifiedTypeReference(arrayComponentTypename, dim, start, end); } } // because 'length' is computed as 'end-start+1' and start==-1 indicates it does not exist, then // to have a length of 0 the end must be -2. private static long NON_EXISTENT_POSITION = toPos(-1, -2); /** * Pack start and end positions into a long - no adjustments are made to the values passed in, the caller must make any required * adjustments. */ private static long toPos(long start, long end) { if (start == 0 && end <= 0) { return NON_EXISTENT_POSITION; } return ((start << 32) | end); } private TypeReference createTypeReferenceForClassNode(GenericsType genericsType) { if (genericsType.isWildcard()) { ClassNode[] bounds = genericsType.getUpperBounds(); if (bounds != null) { // FIXASC other bounds? // positions example: (29>31)Set<(33>54)? extends (43>54)Serializable> TypeReference boundReference = createTypeReferenceForClassNode(bounds[0]); Wildcard wildcard = new Wildcard(Wildcard.EXTENDS); wildcard.sourceStart = genericsType.getStart(); wildcard.sourceEnd = boundReference.sourceEnd(); wildcard.bound = boundReference; return wildcard; } else if (genericsType.getLowerBound() != null) { // positions example: (67>69)Set<(71>84)? super (79>84)Number> TypeReference boundReference = createTypeReferenceForClassNode(genericsType.getLowerBound()); Wildcard wildcard = new Wildcard(Wildcard.SUPER); wildcard.sourceStart = genericsType.getStart(); wildcard.sourceEnd = boundReference.sourceEnd(); wildcard.bound = boundReference; return wildcard; } else { Wildcard w = new Wildcard(Wildcard.UNBOUND); w.sourceStart = genericsType.getStart(); w.sourceEnd = genericsType.getStart(); return w; } // FIXASC what does the check on this next really line mean? } else if (!genericsType.getType().isGenericsPlaceHolder()) { TypeReference typeReference = createTypeReferenceForClassNode(genericsType.getType()); return typeReference; } else { // this means it is a placeholder. As an example, if the reference is to 'List' // then the genericsType info may include a placeholder for the type variable (as the user // didn't fill it in as anything) and so for this example the genericsType is 'E extends java.lang.Object' // I don't think we need a type reference for this as the type references we are constructed // here are representative of what the user did in the source, not the resolved result of that. // throw new GroovyEclipseBug(); return null; } } private TypeReference createTypeReferenceForClassNode(ClassNode classNode) { int start = startOffset(classNode); int end = endOffset(classNode); List<TypeReference> typeArguments = null; // need to distinguish between raw usage of a type 'List' and generics // usage 'List<T>' - it basically depends upon whether the type variable reference can be // resolved within the current 'scope' - if it cannot then this is probably a raw // reference (yes?) if (classNode.isUsingGenerics()) { GenericsType[] genericsInfo = classNode.getGenericsTypes(); for (int g = 0; g < genericsInfo.length; g++) { // ClassNode typeArgumentClassNode = genericsInfo[g].getType(); TypeReference tr = createTypeReferenceForClassNode(genericsInfo[g]); if (tr != null) { if (typeArguments == null) { typeArguments = new ArrayList<TypeReference>(); } typeArguments.add(tr); } // if (!typeArgumentClassNode.isGenericsPlaceHolder()) { // typeArguments.add(createTypeReferenceForClassNode(typeArgumentClassNode)); // } } } String name = classNode.getName(); if (name.length() == 1 && name.charAt(0) == '?') { return new Wildcard(Wildcard.UNBOUND); } // array? [Ljava/lang/String; if (name.charAt(0) == '[') { return createTypeReferenceForArrayName(classNode, start, end); } if (nameToPrimitiveTypeId.containsKey(name)) { return TypeReference.baseTypeReference(nameToPrimitiveTypeId.get(name), 0); } if (name.indexOf(".") == -1) { if (typeArguments == null) { TypeReference tr = verify(new SingleTypeReference(name.toCharArray(), toPos(start, end - 1))); if (!checkGenerics) { tr.bits |= TypeReference.IgnoreRawTypeCheck; } return tr; } else { // FIXASC determine when array dimension used in this case, // is it 'A<T[]> or some silliness? long l = toPos(start, end - 1); return new ParameterizedSingleTypeReference(name.toCharArray(), typeArguments.toArray(new TypeReference[typeArguments.size()]), 0, l); } } else { char[][] compoundName = CharOperation.splitOn('.', name.toCharArray()); if (typeArguments == null) { TypeReference tr = new QualifiedTypeReference(compoundName, positionsFor(compoundName, start, end)); if (!checkGenerics) { tr.bits |= TypeReference.IgnoreRawTypeCheck; } return tr; } else { // FIXASC support individual parameterization of component // references A<String>.B<Wibble> TypeReference[][] typeReferences = new TypeReference[compoundName.length][]; typeReferences[compoundName.length - 1] = typeArguments.toArray(new TypeReference[typeArguments.size()]); return new ParameterizedQualifiedTypeReference(compoundName, typeReferences, 0, positionsFor(compoundName, start, end)); } } } private final static boolean DEBUG = false; // FIXASC this is useless - use proper positions private long[] getPositionsFor(char[][] compoundName) { long[] ls = new long[compoundName.length]; for (int i = 0; i < compoundName.length; i++) { ls[i] = 0; } return ls; } // FIXASC are costly regens being done for all the classes??? @SuppressWarnings("unchecked") @Override public void generateCode() { boolean successful = processToPhase(Phases.ALL); if (successful) { // At the end of this method we want to make this call for each of the classes generated during processing // // compilationResult.record(classname.toCharArray(), new GroovyClassFile(classname, classbytes, foundBinding, path)); // // For each generated class (in groovyCompilationUnit.getClasses()) we know: // String classname = groovyClass.getName(); = this is the name of the generated type (doesn't matter where the // declaration was) // byte[] classbytes = groovyClass.getBytes(); = duh // String path = groovyClass.getName().replace('.', '/'); = where to put it on disk // The only tricky piece of information is discovering the binding that gave rise to the type. This is complicated // in groovy because it is not policing that the package name matches the directory structure. // Effectively the connection between the TypeDeclaration (which points to the binding) and the // groovy created component is lost - if that were maintained we would not have to go hunting for it. // On finishing processing we have access to the generated classes but GroovyClassFile objects have no idea what // their originating ClassNode was. // Under eclipse I've extended GroovyClassFile objects to remember their sourceUnit and ClassNode - this means // we have to do very little hunting for the binding and don't have to mess around with strings (chopping off // packages, etc). // This returns all of them, for all source files List<GroovyClass> classes = groovyCompilationUnit.getClasses(); if (DEBUG) { log("Processing sourceUnit " + groovySourceUnit.getName()); } for (GroovyClass clazz : classes) { ClassNode classnode = clazz.getClassNode(); if (DEBUG) { log("Looking at class " + clazz.getName()); log("ClassNode where it came from " + classnode); } // Only care about those coming about because of this groovySourceUnit if (clazz.getSourceUnit() == groovySourceUnit) { if (DEBUG) { log("It is from this source unit"); } // Worth continuing String classname = clazz.getName(); SourceTypeBinding binding = null; if (types != null && types.length != 0) { binding = findBinding(types, clazz.getClassNode()); } if (DEBUG) { log("Binding located?" + (binding != null)); } if (binding == null) { // closures will be represented as InnerClassNodes ClassNode current = classnode; while (current instanceof InnerClassNode && binding == null) { current = ((InnerClassNode) current).getOuterClass(); binding = findBinding(types, current); if (DEBUG) { log("Had another look because it is in an InnerClassNode, found binding? " + (binding != null)); } } } if (binding == null) { RuntimeException rEx = new RuntimeException("Couldn't find binding for '" + classname + "': do you maybe have a duplicate type around?"); rEx.printStackTrace(); Util.log(rEx, "Couldn't find binding for '" + classname + "': do you maybe have a duplicate type around?"); } else { // Suppress class file output if it is a script boolean isScript = false; if (binding.scope != null && (binding.scope.parent instanceof GroovyCompilationUnitScope)) { GroovyCompilationUnitScope gcuScope = (GroovyCompilationUnitScope) binding.scope.parent; if (gcuScope.isScript()) { isScript = true; } } if (!isScript) { byte[] classbytes = clazz.getBytes(); String path = clazz.getName().replace('.', '/'); compilationResult.record(classname.toCharArray(), new GroovyClassFile(classname, classbytes, binding, path)); } } } } } } private void log(String message) { System.out.println(message); } private SourceTypeBinding findBinding(TypeDeclaration[] typedeclarations, ClassNode cnode) { for (TypeDeclaration typedeclaration : typedeclarations) { GroovyTypeDeclaration groovyTypeDeclaration = (GroovyTypeDeclaration) typedeclaration; if (groovyTypeDeclaration.getClassNode().equals(cnode)) { return groovyTypeDeclaration.binding; } if (typedeclaration.memberTypes != null) { SourceTypeBinding binding = findBinding(typedeclaration.memberTypes, cnode); if (binding != null) { return binding; } } } return null; } // --- private int startOffset(org.codehaus.groovy.ast.ASTNode astnode) { // int l = fromLineColumnToOffset(astnode.getLineNumber(), // astnode.getColumnNumber()) - 1; // return l; return (Math.max(astnode.getStart(), 0)); } private int endOffset(org.codehaus.groovy.ast.ASTNode astnode) { // starts from 0 and dont want the char after it, i want the last char // return fromLineColumnToOffset(astnode.getLineNumber(), // astnode.getLastColumnNumber()) - 2; // return astnode.getEnd(); return (Math.max(astnode.getEnd(), 0)); } // here be dragons private void recordProblems(List<?> errors) { // FIXASC look at this error situation (described below), surely we need to do it? // Due to the nature of driving all groovy entities through compilation together, we can accumulate messages for other // compilation units whilst processing the one we wanted to. Per GRE396 this can manifest as recording the wrong thing // against the wrong type. That is the only case I have seen of it, so I'm not putting in the general mechanism for all // errors yet, I'm just dealing with RuntimeParserExceptions. The general strategy would be to compare the ModuleNode // for each message with the ModuleNode currently being processed - if they differ then this isn't a message for this // unit and so we ignore it. If we do deal with it then we remember that we did (in errorsRecorded) and remove it from // the list of those to process. List errorsRecorded = new ArrayList(); // FIXASC poor way to get the errors attached to the files // FIXASC does groovy ever produce warnings? How are they treated here? for (Iterator<?> iterator = errors.iterator(); iterator.hasNext();) { SyntaxException syntaxException = null; Message message = (Message) iterator.next(); StringWriter sw = new StringWriter(); message.write(new PrintWriter(sw)); String msg = sw.toString(); CategorizedProblem p = null; int line = 0; int sev = 0; int scol = 0; int ecol = 0; if (message instanceof SimpleMessage) { SimpleMessage simpleMessage = (SimpleMessage) message; sev |= ProblemSeverities.Error; String simpleText = simpleMessage.getMessage(); if (simpleText.length() > 1 && simpleText.charAt(0) == '\n') { simpleText = simpleText.substring(1); } msg = "Groovy:" + simpleText; if (msg.indexOf("\n") != -1) { msg = msg.substring(0, msg.indexOf("\n")); } } if (message instanceof SyntaxErrorMessage) { SyntaxErrorMessage errorMessage = (SyntaxErrorMessage) message; syntaxException = errorMessage.getCause(); sev |= ProblemSeverities.Error; // FIXASC in the short term, prefixed groovy to indicate // where it came from String actualMessage = syntaxException.getMessage(); if (actualMessage.length() > 1 && actualMessage.charAt(0) == '\n') { actualMessage = actualMessage.substring(1); } msg = "Groovy:" + actualMessage; if (msg.indexOf("\n") != -1) { msg = msg.substring(0, msg.indexOf("\n")); } line = syntaxException.getLine(); scol = errorMessage.getCause().getStartColumn(); ecol = errorMessage.getCause().getEndColumn() - 1; } int soffset = -1; int eoffset = -1; if (message instanceof ExceptionMessage) { ExceptionMessage em = (ExceptionMessage) message; + sev |= ProblemSeverities.Error; if (em.getCause() instanceof RuntimeParserException) { RuntimeParserException rpe = (RuntimeParserException) em.getCause(); sev |= ProblemSeverities.Error; msg = "Groovy:" + rpe.getMessage(); if (msg.indexOf("\n") != -1) { msg = msg.substring(0, msg.indexOf("\n")); } ModuleNode errorModuleNode = rpe.getModule(); ModuleNode thisModuleNode = this.getModuleNode(); if (!errorModuleNode.equals(thisModuleNode)) { continue; } soffset = rpe.getNode().getStart(); eoffset = rpe.getNode().getEnd() - 1; // need to work out the line again as it may be wrong line = 0; while (compilationResult.lineSeparatorPositions[line] < soffset && line < compilationResult.lineSeparatorPositions.length) { line++; } line++; // from an array index to a real 'line number' } } if (syntaxException instanceof PreciseSyntaxException) { soffset = ((PreciseSyntaxException) syntaxException).getStartOffset(); eoffset = ((PreciseSyntaxException) syntaxException).getEndOffset(); // need to work out the line again as it may be wrong line = 0; while (line < compilationResult.lineSeparatorPositions.length && compilationResult.lineSeparatorPositions[line] < soffset) { line++; } ; line++; // from an array index to a real 'line number' } else { if (soffset == -1) { soffset = getOffset(compilationResult.lineSeparatorPositions, line, scol); } if (eoffset == -1) { eoffset = getOffset(compilationResult.lineSeparatorPositions, line, ecol); } } if (soffset > eoffset) { eoffset = soffset; } if (soffset > sourceEnd) { soffset = sourceEnd; eoffset = sourceEnd; } char[] filename = getFileName(); p = new DefaultProblemFactory().createProblem(filename, 0, new String[] { msg }, 0, new String[] { msg }, sev, soffset, eoffset, line, scol); this.problemReporter.record(p, compilationResult, this); errorsRecorded.add(message); System.err.println(new String(compilationResult.getFileName()) + ": " + line + " " + msg); } errors.removeAll(errorsRecorded); } private int getOffset(int[] lineSeparatorPositions, int line, int col) { if (lineSeparatorPositions.length > (line - 2) && line > 1) { return lineSeparatorPositions[line - 2] + col; } else { return col; } } @Override public CompilationUnitScope buildCompilationUnitScope(LookupEnvironment lookupEnvironment) { GroovyCompilationUnitScope gcus = new GroovyCompilationUnitScope(this, lookupEnvironment); gcus.setIsScript(isScript); return gcus; } public ModuleNode getModuleNode() { return groovySourceUnit == null ? null : groovySourceUnit.getAST(); } public SourceUnit getSourceUnit() { return groovySourceUnit; } // TODO find a better home for this? @Override public org.eclipse.jdt.core.dom.CompilationUnit getSpecialDomCompilationUnit(org.eclipse.jdt.core.dom.AST ast) { return new org.codehaus.jdt.groovy.core.dom.GroovyCompilationUnit(ast); } /** * Try to get the source locations for type declarations to be as correct as possible */ private void fixupSourceLocationsForTypeDeclaration(GroovyTypeDeclaration typeDeclaration, ClassNode classNode) { // start and end of the name of class // scripts do not have a name, so use start instead typeDeclaration.sourceStart = Math.max(classNode.getNameStart(), classNode.getStart()); typeDeclaration.sourceEnd = Math.max(classNode.getNameEnd(), classNode.getStart()); // start and end of the entire declaration including Javadoc and ending at the last close bracket int line = classNode.getLineNumber(); Javadoc doc = findJavadoc(line); typeDeclaration.javadoc = doc; typeDeclaration.declarationSourceStart = doc == null ? classNode.getStart() : doc.sourceStart; // Without the -1 we can hit AIOOBE in org.eclipse.jdt.internal.core.Member.getJavadocRange where it calls getText() // because the source range length causes us to ask for more data than is in the buffer. What does this mean? // For hovers, the AIOOBE is swallowed and you just see no hover box. typeDeclaration.declarationSourceEnd = classNode.getEnd() - 1; // * start at the opening brace and end at the closing brace // except that scripts do not have a name, use the start instead // FIXADE this is not exactly right since getNameEnd() comes before extends and implements clauses typeDeclaration.bodyStart = Math.max(classNode.getNameEnd(), classNode.getStart()); // seems to be the same as declarationSourceEnd typeDeclaration.bodyEnd = classNode.getEnd() - 1; // start of the modifiers after the javadoc typeDeclaration.modifiersSourceStart = classNode.getStart(); } /** * Try to get the source locations for constructor declarations to be as correct as possible */ private void fixupSourceLocationsForConstructorDeclaration(ConstructorDeclaration ctorDeclaration, ConstructorNode ctorNode) { ctorDeclaration.sourceStart = ctorNode.getNameStart(); ctorDeclaration.sourceEnd = ctorNode.getNameEnd(); // start and end of method declaration including JavaDoc // ending with closing '}' or ';' if abstract int line = ctorNode.getLineNumber(); Javadoc doc = findJavadoc(line); ctorDeclaration.javadoc = doc; ctorDeclaration.declarationSourceStart = doc == null ? ctorNode.getStart() : doc.sourceStart; ctorDeclaration.declarationSourceEnd = ctorNode.getEnd() - 1; // start of method's modifier list (after Javadoc is ended) ctorDeclaration.modifiersSourceStart = ctorNode.getStart(); // opening bracket ctorDeclaration.bodyStart = // try for opening bracket ctorNode.getCode() != null ? ctorNode.getCode().getStart() : // handle abstract constructor. not sure if this can ever happen, but you never know with Groovy ctorNode.getNameEnd(); // closing bracket or ';' same as declarationSourceEnd ctorDeclaration.bodyEnd = ctorNode.getEnd() - 1; } /** * Try to get the source locations for method declarations to be as correct as possible */ private void fixupSourceLocationsForMethodDeclaration(MethodDeclaration methodDeclaration, MethodNode methodNode) { // run() method for scripts has no name, so use the start of the method instead methodDeclaration.sourceStart = Math.max(methodNode.getNameStart(), methodNode.getStart()); methodDeclaration.sourceEnd = Math.max(methodNode.getNameEnd(), methodNode.getStart()); // start and end of method declaration including JavaDoc // ending with closing '}' or ';' if abstract int line = methodNode.getLineNumber(); Javadoc doc = findJavadoc(line); methodDeclaration.javadoc = doc; methodDeclaration.declarationSourceStart = doc == null ? methodNode.getStart() : doc.sourceStart; methodDeclaration.declarationSourceEnd = methodNode.getEnd() - 1; // start of method's modifier list (after Javadoc is ended) methodDeclaration.modifiersSourceStart = methodNode.getStart(); // opening bracket methodDeclaration.bodyStart = // try for opening bracket methodNode.getCode() != null ? methodNode.getCode().getStart() : // run() method for script has no opening bracket // also need to handle abstract methods Math.max(methodNode.getNameEnd(), methodNode.getStart()); // closing bracket or ';' same as declarationSourceEnd methodDeclaration.bodyEnd = methodNode.getEnd() - 1; } /** * Try to get the source locations for field declarations to be as correct as possible */ private void fixupSourceLocationsForFieldDeclaration(FieldDeclaration fieldDeclaration, FieldNode fieldNode, boolean isEnumField) { // TODO (groovy) each area marked with a '*' is only approximate // and can be revisited to make more precise // Here, we distinguish between the declaration and the fragment // e.g.- def x = 9, y = "l" // 'x = 9,' and 'y = "l"' are the fragments and 'def x = 9, y = "l"' is the declaration // the start and end of the fragment name fieldDeclaration.sourceStart = fieldNode.getNameStart(); fieldDeclaration.sourceEnd = fieldNode.getNameEnd(); // start of the declaration (including javadoc?) int line = fieldNode.getLineNumber(); Javadoc doc = findJavadoc(line); fieldDeclaration.javadoc = doc; if (isEnumField) { // they have no 'leading' type declaration or modifiers fieldDeclaration.declarationSourceStart = fieldNode.getNameStart(); fieldDeclaration.declarationSourceEnd = fieldNode.getNameEnd() - 1; } else { fieldDeclaration.declarationSourceStart = doc == null ? fieldNode.getStart() : doc.sourceStart; // the end of the fragment including initializer (and trailing ',') fieldDeclaration.declarationSourceEnd = fieldNode.getEnd() - 1; } // * first character of the declaration's modifier fieldDeclaration.modifiersSourceStart = fieldNode.getStart(); // end of the entire Field declaration (after all fragments and including ';' if exists) fieldDeclaration.declarationEnd = fieldNode.getEnd(); // * end of the type declaration part of the declaration (the same for each fragment) // eg- int x, y corresponds to the location after 'int' fieldDeclaration.endPart1Position = fieldNode.getNameStart(); // * just before the start of the next fragment // (or the end of the entire declaration if it is the last one) // (how is this different from declarationSourceEnd?) fieldDeclaration.endPart2Position = fieldNode.getEnd() - 1; } /** * @return true if this is varargs, using the same definition as in AsmClassGenerator.isVargs(Parameter[]) */ private boolean isVargs(Parameter[] parameters) { if (parameters.length == 0) { return false; } ClassNode clazz = parameters[parameters.length - 1].getType(); return (clazz.isArray()); } // for testing public String print() { return toString(); } public GroovyCompilationUnitScope getScope() { return (GroovyCompilationUnitScope) scope; } // -- overridden behaviour from the supertype @Override public void resolve() { processToPhase(Phases.SEMANTIC_ANALYSIS); checkForTags(); setComments(); } /** * Check any comments from the source file for task tag markers. */ private void checkForTags() { if (this.compilerOptions == null) { return; } List<Comment> comments = groovySourceUnit.getComments(); if (comments == null) { return; } char[][] taskTags = this.compilerOptions.taskTags; char[][] taskPriorities = this.compilerOptions.taskPriorities; boolean caseSensitiveTags = this.compilerOptions.isTaskCaseSensitive; try { if (taskTags != null) { // For each comment find all task tags within it and cope with for (Comment comment : comments) { List<TaskEntry> allTasksInComment = new ArrayList<TaskEntry>(); for (int t = 0; t < taskTags.length; t++) { String taskTag = new String(taskTags[t]); String taskPriority = null; if (taskPriorities != null) { taskPriority = new String(taskPriorities[t]); } allTasksInComment.addAll(comment.getPositionsOf(taskTag, taskPriority, compilationResult.lineSeparatorPositions, caseSensitiveTags)); } if (!allTasksInComment.isEmpty()) { // Need to check quickly for clashes for (int t1 = 0; t1 < allTasksInComment.size(); t1++) { for (int t2 = 0; t2 < allTasksInComment.size(); t2++) { if (t1 == t2) continue; TaskEntry taskOne = allTasksInComment.get(t1); TaskEntry taskTwo = allTasksInComment.get(t2); if (DEBUG_TASK_TAGS) { System.out.println("Comparing " + taskOne.toString() + " and " + taskTwo.toString()); } if ((taskOne.start + taskOne.taskTag.length() + 1) == taskTwo.start) { // Adjacent tags taskOne.isAdjacentTo = taskTwo; } else { if ((taskOne.getEnd() > taskTwo.start) && (taskOne.start < taskTwo.start)) { taskOne.setEnd(taskTwo.start - 1); if (DEBUG_TASK_TAGS) { System.out.println("trim " + taskOne.toString() + " and " + taskTwo.toString()); } } else if (taskTwo.getEnd() > taskOne.start && taskTwo.start < taskOne.start) { taskTwo.setEnd(taskOne.start - 1); if (DEBUG_TASK_TAGS) { System.out.println("trim " + taskOne.toString() + " and " + taskTwo.toString()); } } } } } for (TaskEntry taskEntry : allTasksInComment) { this.problemReporter.referenceContext = this; if (DEBUG_TASK_TAGS) { System.out.println("Adding task " + taskEntry.toString()); } problemReporter.task(taskEntry.taskTag, taskEntry.getText(), taskEntry.taskPriority, taskEntry.start, taskEntry.getEnd()); } } } } } catch (AbortCompilation ac) { // that is ok... probably cancelled } catch (Throwable t) { Util.log(t, "Unexpected problem processing task tags in " + groovySourceUnit.getName()); new RuntimeException("Unexpected problem processing task tags in " + groovySourceUnit.getName(), t).printStackTrace(); } } @Override public void analyseCode() { processToPhase(Phases.CANONICALIZATION); } @Override public void abort(int abortLevel, CategorizedProblem problem) { // FIXASC look at callers of this, should we be following the abort on first problem policy? super.abort(abortLevel, problem); } @Override public void checkUnusedImports() { super.checkUnusedImports(); } @Override public void cleanUp() { // FIXASC any tidy up for us to do? super.cleanUp(); } @Override public CompilationResult compilationResult() { return super.compilationResult(); } @Override public TypeDeclaration declarationOfType(char[][] typeName) { return super.declarationOfType(typeName); } @Override public void finalizeProblems() { super.finalizeProblems(); } @Override public char[] getFileName() { return super.getFileName(); } @Override public char[] getMainTypeName() { // FIXASC necessary to return something for groovy? return super.getMainTypeName(); } @Override public boolean hasErrors() { return super.hasErrors(); } @Override public boolean isEmpty() { return super.isEmpty(); } @Override public boolean isPackageInfo() { return super.isPackageInfo(); } @Override public StringBuffer print(int indent, StringBuffer output) { // FIXASC additional stuff to print? return super.print(indent, output); } @Override public void propagateInnerEmulationForAllLocalTypes() { // FIXASC anything to do here for groovy inner types? super.propagateInnerEmulationForAllLocalTypes(); } @Override public void record(LocalTypeBinding localType) { super.record(localType); } @Override public void recordStringLiteral(StringLiteral literal, boolean fromRecovery) { // FIXASC assert not called for groovy, surely super.recordStringLiteral(literal, fromRecovery); } @Override public void recordSuppressWarnings(IrritantSet irritants, Annotation annotation, int scopeStart, int scopeEnd) { super.recordSuppressWarnings(irritants, annotation, scopeStart, scopeEnd); } @Override public void tagAsHavingErrors() { super.tagAsHavingErrors(); } @Override public void traverse(ASTVisitor visitor, CompilationUnitScope unitScope) { // FIXASC are we well formed enough for this? super.traverse(visitor, unitScope); } @Override public ASTNode concreteStatement() { // FIXASC assert not called for groovy, surely return super.concreteStatement(); } @Override public boolean isImplicitThis() { // FIXASC assert not called for groovy, surely return super.isImplicitThis(); } @Override public boolean isSuper() { // FIXASC assert not called for groovy, surely return super.isSuper(); } @Override public boolean isThis() { // FIXASC assert not called for groovy, surely return super.isThis(); } @Override public int sourceEnd() { return super.sourceEnd(); } @Override public int sourceStart() { return super.sourceStart(); } @Override public String toString() { // FIXASC anything to add? return super.toString(); } @Override public void traverse(ASTVisitor visitor, BlockScope scope) { // FIXASC in a good state for traversal? what would cause this to trigger? super.traverse(visitor, scope); } // -- builders for JDT TypeReference subclasses /** * Create a JDT ArrayTypeReference.<br> * Positional information: * <p> * For a single array reference, for example 'String[]' start will be 'S' and end will be the char after ']'. When the * ArrayTypeReference is built we need these positions for the result: sourceStart - the 'S'; sourceEnd - the ']'; * originalSourceEnd - the 'g' */ private ArrayTypeReference createJDTArrayTypeReference(String arrayComponentTypename, int dimensions, int start, int end) { ArrayTypeReference atr = new ArrayTypeReference(arrayComponentTypename.toCharArray(), dimensions, toPos(start, end - 1)); atr.originalSourceEnd = atr.sourceStart + arrayComponentTypename.length() - 1; return atr; } /** * Create a JDT ArrayQualifiedTypeReference.<br> * Positional information: * <p> * For a qualified array reference, for example 'java.lang.Number[][]' start will be 'j' and end will be the char after ']'. * When the ArrayQualifiedTypeReference is built we need these positions for the result: sourceStart - the 'j'; sourceEnd - the * final ']'; the positions computed for the reference components would be j..a l..g and N..r */ private ArrayQualifiedTypeReference createJDTArrayQualifiedTypeReference(String arrayComponentTypename, int dimensions, int start, int end) { char[][] compoundName = CharOperation.splitOn('.', arrayComponentTypename.toCharArray()); ArrayQualifiedTypeReference aqtr = new ArrayQualifiedTypeReference(compoundName, dimensions, positionsFor(compoundName, start, end - dimensions * 2)); aqtr.sourceEnd = end - 1; return aqtr; } /** * Check the supplied TypeReference. If there are problems with the construction of a TypeReference then these may not surface * until it is used later, perhaps when reconciling. The easiest way to check there will not be problems later is to check it at * construction time. * * @param toVerify the type reference to check * @param does the type reference really exist in the source or is it conjured up based on the source * @return the verified type reference * @throws IllegalStateException if the type reference is malformed */ private TypeReference verify(TypeReference toVerify) { if (GroovyCheckingControl.checkTypeReferences) { if (toVerify.getClass().equals(SingleTypeReference.class)) { SingleTypeReference str = (SingleTypeReference) toVerify; if (str.sourceStart == -1) { if (str.sourceEnd != -2) { throw new IllegalStateException("TypeReference '" + new String(str.token) + " should end at -2"); } } else { if (str.sourceEnd < str.sourceStart) { throw new IllegalStateException("TypeReference '" + new String(str.token) + " should end at " + str.sourceStart + " or later"); } } } else { throw new IllegalStateException("Cannot verify type reference of this class " + toVerify.getClass()); } } return toVerify; } public void tagAsScript() { this.isScript = true; } }
false
false
null
null
diff --git a/photoviewer/src/com/android/ex/photo/loaders/PhotoBitmapLoader.java b/photoviewer/src/com/android/ex/photo/loaders/PhotoBitmapLoader.java index 7049370..fe42e0d 100644 --- a/photoviewer/src/com/android/ex/photo/loaders/PhotoBitmapLoader.java +++ b/photoviewer/src/com/android/ex/photo/loaders/PhotoBitmapLoader.java @@ -1,158 +1,160 @@ /* * Copyright (C) 2011 Google Inc. * Licensed to 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.ex.photo.loaders; import android.content.AsyncTaskLoader; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.util.DisplayMetrics; import com.android.ex.photo.fragments.PhotoViewFragment; import com.android.ex.photo.util.ImageUtils; /** * Loader for the bitmap of a photo. */ public class PhotoBitmapLoader extends AsyncTaskLoader<Bitmap> { private String mPhotoUri; private Bitmap mBitmap; public PhotoBitmapLoader(Context context, String photoUri) { super(context); mPhotoUri = photoUri; } public void setPhotoUri(String photoUri) { mPhotoUri = photoUri; } @Override public Bitmap loadInBackground() { Context context = getContext(); if (context != null && mPhotoUri != null) { final ContentResolver resolver = context.getContentResolver(); Bitmap bitmap = ImageUtils.createLocalBitmap(resolver, Uri.parse(mPhotoUri), PhotoViewFragment.sPhotoSize); - bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM); + if (bitmap != null) { + bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM); + } return bitmap; } return null; } /** * Called when there is new data to deliver to the client. The * super class will take care of delivering it; the implementation * here just adds a little more logic. */ @Override public void deliverResult(Bitmap bitmap) { if (isReset()) { // An async query came in while the loader is stopped. We // don't need the result. if (bitmap != null) { onReleaseResources(bitmap); } } Bitmap oldBitmap = mBitmap; mBitmap = bitmap; if (isStarted()) { // If the Loader is currently started, we can immediately // deliver its results. super.deliverResult(bitmap); } // At this point we can release the resources associated with // 'oldBitmap' if needed; now that the new result is delivered we // know that it is no longer in use. if (oldBitmap != null && oldBitmap != bitmap && !oldBitmap.isRecycled()) { onReleaseResources(oldBitmap); } } /** * Handles a request to start the Loader. */ @Override protected void onStartLoading() { if (mBitmap != null) { // If we currently have a result available, deliver it // immediately. deliverResult(mBitmap); } if (takeContentChanged() || mBitmap == null) { // If the data has changed since the last time it was loaded // or is not currently available, start a load. forceLoad(); } } /** * Handles a request to stop the Loader. */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } /** * Handles a request to cancel a load. */ @Override public void onCanceled(Bitmap bitmap) { super.onCanceled(bitmap); // At this point we can release the resources associated with 'bitmap' // if needed. onReleaseResources(bitmap); } /** * Handles a request to completely reset the Loader. */ @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); // At this point we can release the resources associated with 'bitmap' // if needed. if (mBitmap != null) { onReleaseResources(mBitmap); mBitmap = null; } } /** * Helper function to take care of releasing resources associated * with an actively loaded data set. */ protected void onReleaseResources(Bitmap bitmap) { if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } } } diff --git a/photoviewer/src/com/android/ex/photo/util/ImageUtils.java b/photoviewer/src/com/android/ex/photo/util/ImageUtils.java index 8564457..d852d65 100644 --- a/photoviewer/src/com/android/ex/photo/util/ImageUtils.java +++ b/photoviewer/src/com/android/ex/photo/util/ImageUtils.java @@ -1,175 +1,175 @@ /* * Copyright (C) 2011 Google Inc. * Licensed to 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.ex.photo.util; import android.content.ContentResolver; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Point; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.util.Log; import com.android.ex.photo.PhotoViewActivity; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Image utilities */ public class ImageUtils { // Logging private static final String TAG = "ImageUtils"; /** Minimum class memory class to use full-res photos */ private final static long MIN_NORMAL_CLASS = 32; /** Minimum class memory class to use small photos */ private final static long MIN_SMALL_CLASS = 24; public static enum ImageSize { EXTRA_SMALL, SMALL, NORMAL, } public static final ImageSize sUseImageSize; static { // On HC and beyond, assume devices are more capable if (Build.VERSION.SDK_INT >= 11) { sUseImageSize = ImageSize.NORMAL; } else { if (PhotoViewActivity.sMemoryClass >= MIN_NORMAL_CLASS) { // We have plenty of memory; use full sized photos sUseImageSize = ImageSize.NORMAL; } else if (PhotoViewActivity.sMemoryClass >= MIN_SMALL_CLASS) { // We have slight less memory; use smaller sized photos sUseImageSize = ImageSize.SMALL; } else { // We have little memory; use very small sized photos sUseImageSize = ImageSize.EXTRA_SMALL; } } } /** * @return true if the MimeType type is image */ public static boolean isImageMimeType(String mimeType) { return mimeType != null && mimeType.startsWith("image/"); } /** * Create a bitmap from a local URI * * @param resolver The ContentResolver * @param uri The local URI * @param maxSize The maximum size (either width or height) * - * @return The new bitmap + * @return The new bitmap or null */ public static Bitmap createLocalBitmap(ContentResolver resolver, Uri uri, int maxSize) { InputStream inputStream = null; try { final BitmapFactory.Options opts = new BitmapFactory.Options(); final Point bounds = getImageBounds(resolver, uri); inputStream = resolver.openInputStream(uri); opts.inSampleSize = Math.max(bounds.x / maxSize, bounds.y / maxSize); final Bitmap decodedBitmap = decodeStream(inputStream, null, opts); // Correct thumbnail orientation as necessary // TODO: Fix rotation if it's actually a problem //return rotateBitmap(resolver, uri, decodedBitmap); return decodedBitmap; } catch (FileNotFoundException exception) { // Do nothing - the photo will appear to be missing } catch (IOException exception) { // Do nothing - the photo will appear to be missing } catch (IllegalArgumentException exception) { // Do nothing - the photo will appear to be missing } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ignore) { } } return null; } /** * Wrapper around {@link BitmapFactory#decodeStream(InputStream, Rect, * BitmapFactory.Options)} that returns {@code null} on {@link * OutOfMemoryError}. * * @param is The input stream that holds the raw data to be decoded into a * bitmap. * @param outPadding If not null, return the padding rect for the bitmap if * it exists, otherwise set padding to [-1,-1,-1,-1]. If * no bitmap is returned (null) then padding is * unchanged. * @param opts null-ok; Options that control downsampling and whether the * image should be completely decoded, or just is size returned. * @return The decoded bitmap, or null if the image data could not be * decoded, or, if opts is non-null, if opts requested only the * size be returned (in opts.outWidth and opts.outHeight) */ public static Bitmap decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts) { try { return BitmapFactory.decodeStream(is, outPadding, opts); } catch (OutOfMemoryError oome) { Log.e(TAG, "ImageUtils#decodeStream(InputStream, Rect, Options) threw an OOME", oome); return null; } } /** * Gets the image bounds * * @param resolver The ContentResolver * @param uri The uri * * @return The image bounds */ private static Point getImageBounds(ContentResolver resolver, Uri uri) throws IOException { final BitmapFactory.Options opts = new BitmapFactory.Options(); InputStream inputStream = null; try { opts.inJustDecodeBounds = true; inputStream = resolver.openInputStream(uri); decodeStream(inputStream, null, opts); return new Point(opts.outWidth, opts.outHeight); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException ignore) { } } } }
false
false
null
null
diff --git a/providers/denominator-ultradns/src/main/java/denominator/ultradns/UltraDNSGeoResourceRecordSetApi.java b/providers/denominator-ultradns/src/main/java/denominator/ultradns/UltraDNSGeoResourceRecordSetApi.java index e37ded0..e0072ec 100644 --- a/providers/denominator-ultradns/src/main/java/denominator/ultradns/UltraDNSGeoResourceRecordSetApi.java +++ b/providers/denominator-ultradns/src/main/java/denominator/ultradns/UltraDNSGeoResourceRecordSetApi.java @@ -1,233 +1,251 @@ package denominator.ultradns; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterators.concat; import static com.google.common.collect.Iterators.filter; import static com.google.common.collect.Iterators.transform; import static denominator.model.ResourceRecordSets.typeEqualTo; import static denominator.ultradns.UltraDNSPredicates.isGeolocationPool; import static org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType.IPV4; import static org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType.IPV6; import java.util.EnumSet; import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import javax.inject.Inject; import org.jclouds.ultradns.ws.UltraDNSWSApi; import org.jclouds.ultradns.ws.domain.DirectionalGroup; import org.jclouds.ultradns.ws.domain.DirectionalGroupCoordinates; import org.jclouds.ultradns.ws.domain.DirectionalPool; import org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType; import org.jclouds.ultradns.ws.domain.DirectionalPoolRecord; import org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail; import org.jclouds.ultradns.ws.domain.IdAndName; import org.jclouds.ultradns.ws.features.DirectionalGroupApi; import org.jclouds.ultradns.ws.features.DirectionalPoolApi; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ComparisonChain; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Multimap; import com.google.common.collect.Ordering; import dagger.Lazy; import denominator.ResourceTypeToValue; import denominator.model.ResourceRecordSet; import denominator.profile.GeoResourceRecordSetApi; public final class UltraDNSGeoResourceRecordSetApi implements GeoResourceRecordSetApi { private final Set<String> types; private final Multimap<String, String> regions; private final DirectionalGroupApi groupApi; private final DirectionalPoolApi poolApi; private final GroupGeoRecordByNameTypeIterator.Factory iteratorFactory; private final String zoneName; UltraDNSGeoResourceRecordSetApi(Set<String> types, Multimap<String, String> regions, DirectionalGroupApi groupApi, DirectionalPoolApi poolApi, GroupGeoRecordByNameTypeIterator.Factory iteratorFactory, String zoneName) { this.types = types; this.regions = regions; this.groupApi = groupApi; this.poolApi = poolApi; this.iteratorFactory = iteratorFactory; this.zoneName = zoneName; } @Override public Set<String> getSupportedTypes() { return types; } @Override public Multimap<String, String> getSupportedRegions() { return regions; } @Override public Iterator<ResourceRecordSet<?>> list() { return concat(poolApi.list().filter(isGeolocationPool()) .transform(new Function<DirectionalPool, Iterator<ResourceRecordSet<?>>>() { @Override public Iterator<ResourceRecordSet<?>> apply(DirectionalPool pool) { return allByDName(pool.getDName()); } }).iterator()); } private Iterator<ResourceRecordSet<?>> allByDName(final String dname) { - // TODO: remove when type "0" can be specified + // TODO: remove when type "0" can be specified (UMP-5738 Dodgers release of UltraDNS) return concat(transform(EnumSet.allOf(RecordType.class).iterator(), new Function<RecordType, Iterator<ResourceRecordSet<?>>>() { @Override public Iterator<ResourceRecordSet<?>> apply(RecordType input) { return iteratorForDNameAndDirectionalType(dname, input); } })); } @Override public Iterator<ResourceRecordSet<?>> listByName(String name) { return allByDName(checkNotNull(name, "name")); } @Override public Iterator<ResourceRecordSet<?>> listByNameAndType(String name, final String type) { checkNotNull(name, "name"); checkNotNull(type, "type"); if ("CNAME".equals(type)) { // retain original type (this will filter out A, AAAA) return filter( concat(iteratorForDNameAndDirectionalType(name, IPV4), iteratorForDNameAndDirectionalType(name, IPV6)), typeEqualTo(type)); } else if ("A".equals(type) || "AAAA".equals(type)) { RecordType dirType = "AAAA".equals(type) ? IPV6 : IPV4; Iterator<ResourceRecordSet<?>> iterator = iteratorForDNameAndDirectionalType(name, dirType); // retain original type (this will filter out CNAMEs) return filter(iterator, typeEqualTo(type)); } else { return iteratorForDNameAndDirectionalType(name, RecordType.valueOf(type)); } } @Override public Optional<ResourceRecordSet<?>> getByNameTypeAndGroup(String name, String type, String group) { Iterator<DirectionalPoolRecordDetail> records = recordsByNameTypeAndGroupName(name, type, group); Iterator<ResourceRecordSet<?>> iterator = iteratorFactory.create(records); if (iterator.hasNext()) return Optional.<ResourceRecordSet<?>> of(iterator.next()); return Optional.absent(); } private Iterator<DirectionalPoolRecordDetail> recordsByNameTypeAndGroupName(String name, String type, String group) { checkNotNull(name, "name"); checkNotNull(type, "type"); checkNotNull(group, "group"); Iterator<DirectionalPoolRecordDetail> records; if ("CNAME".equals(type)) { records = filter( concat(recordsForNameTypeAndGroup(name, "A", group), recordsForNameTypeAndGroup(name, "AAAA", group)), isCNAME); } else { records = recordsForNameTypeAndGroup(name, type, group); } return records; } private Iterator<DirectionalPoolRecordDetail> recordsForNameTypeAndGroup(String name, String type, String group) { int typeValue = checkNotNull(new ResourceTypeToValue().get(type), "typeValue for %s", type); DirectionalGroupCoordinates coord = DirectionalGroupCoordinates.builder() .zoneName(zoneName) .recordName(name) .recordType(typeValue) .groupName(group).build(); return groupApi.listRecordsByGroupCoordinates(coord).iterator(); } @Override public void applyRegionsToNameTypeAndGroup(Multimap<String, String> regions, String name, String type, String group) { - for (Iterator<DirectionalPoolRecordDetail> i = recordsByNameTypeAndGroupName(name, type, group); i.hasNext();) { + Iterator<DirectionalPoolRecordDetail> iterator = recordsByNameTypeAndGroupName(name, type, group); + Map<DirectionalPoolRecordDetail, DirectionalGroup> updates = groupsToUpdate(iterator, regions); + if (updates.isEmpty()) + return; + for (Entry<DirectionalPoolRecordDetail, DirectionalGroup> update : updates.entrySet()) { + DirectionalPoolRecordDetail detail = update.getKey(); + // TODO: ensure forceOverlapTransfer (Dodgers release of UltraDNS) + poolApi.updateRecordAndGroup(detail.getId(), detail.getRecord(), update.getValue()); + } + } + + private Map<DirectionalPoolRecordDetail, DirectionalGroup> groupsToUpdate( + Iterator<DirectionalPoolRecordDetail> iterator, Multimap<String, String> regions) { + Builder<DirectionalPoolRecordDetail, DirectionalGroup> toUpdate = ImmutableMap.builder(); + + for (Iterator<DirectionalPoolRecordDetail> i = iterator; i.hasNext();) { DirectionalPoolRecordDetail detail = i.next(); - DirectionalPoolRecord record = detail.getRecord(); DirectionalGroup directionalGroup = groupApi.get(detail.getGeolocationGroup().get().getId()); - if (!regions.equals(directionalGroup.getRegionToTerritories())){ - DirectionalGroup update = directionalGroup.toBuilder().regionToTerritories(regions).build(); - poolApi.updateRecordAndGroup(detail.getId(), record, update); + if (!regions.equals(directionalGroup.getRegionToTerritories())) { + toUpdate.put(detail, directionalGroup.toBuilder().regionToTerritories(regions).build()); } } + return toUpdate.build(); } @Override public void applyTTLToNameTypeAndGroup(int ttl, String name, String type, String group) { for (Iterator<DirectionalPoolRecordDetail> i = recordsByNameTypeAndGroupName(name, type, group); i.hasNext();) { DirectionalPoolRecordDetail detail = i.next(); DirectionalPoolRecord record = detail.getRecord(); if (record.getTTL() != ttl) poolApi.updateRecord(detail.getId(), record.toBuilder().ttl(ttl).build()); } } private Iterator<ResourceRecordSet<?>> iteratorForDNameAndDirectionalType(String name, RecordType dirType) { return iteratorFactory.create(poolApi.listRecordsByDNameAndType(name, dirType.getCode()) .toSortedList(byTypeAndGeoGroup).iterator()); } static Optional<IdAndName> group(DirectionalPoolRecordDetail in) { return in.getGeolocationGroup().or(in.getGroup()); } private static final Ordering<DirectionalPoolRecordDetail> byTypeAndGeoGroup = new Ordering<DirectionalPoolRecordDetail>() { @Override public int compare(DirectionalPoolRecordDetail left, DirectionalPoolRecordDetail right) { checkState(group(left).isPresent(), "expected record to be in a geolocation group: %s", left); checkState(group(right).isPresent(), "expected record to be in a geolocation group: %s", right); return ComparisonChain.start() .compare(left.getRecord().getType(), right.getRecord().getType()) .compare(group(left).get().getName(), group(right).get().getName()).result(); } }; static final class Factory implements GeoResourceRecordSetApi.Factory { private final Set<String> types; private final Lazy<Multimap<String, String>> regions; private final UltraDNSWSApi api; private final Supplier<IdAndName> account; private final GroupGeoRecordByNameTypeIterator.Factory iteratorFactory; @Inject Factory(@denominator.config.profile.Geo Set<String> types, @denominator.config.profile.Geo Lazy<Multimap<String, String>> regions, UltraDNSWSApi api, Supplier<IdAndName> account, GroupGeoRecordByNameTypeIterator.Factory iteratorFactory) { this.types = types; this.regions = regions; this.api = api; this.account = account; this.iteratorFactory = iteratorFactory; } @Override public Optional<GeoResourceRecordSetApi> create(String zoneName) { checkNotNull(zoneName, "zoneName was null"); return Optional.<GeoResourceRecordSetApi> of( - new UltraDNSGeoResourceRecordSetApi(types, regions.get(), + new UltraDNSGeoResourceRecordSetApi(types, regions.get(), api.getDirectionalGroupApiForAccount(account.get().getId()), api.getDirectionalPoolApiForZone(zoneName), iteratorFactory, zoneName)); } } private final Predicate<DirectionalPoolRecordDetail> isCNAME = new Predicate<DirectionalPoolRecordDetail>() { @Override public boolean apply(DirectionalPoolRecordDetail input) { return "CNAME".equals(input.getRecord().getType()); } }; }
false
false
null
null
diff --git a/javasrc/src/org/ccnx/ccn/impl/CCNNetworkManager.java b/javasrc/src/org/ccnx/ccn/impl/CCNNetworkManager.java index 1cfa859c5..1550cef33 100644 --- a/javasrc/src/org/ccnx/ccn/impl/CCNNetworkManager.java +++ b/javasrc/src/org/ccnx/ccn/impl/CCNNetworkManager.java @@ -1,1493 +1,1493 @@ /* * Part of the CCNx Java Library. * * Copyright (C) 2008, 2009, 2010, 2011 Palo Alto Research Center, Inc. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. You should have received * a copy of the GNU Lesser General Public License along with this library; * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA. */ package org.ccnx.ccn.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.util.ArrayList; import java.util.Set; import java.util.SortedMap; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import org.ccnx.ccn.CCNFilterListener; import org.ccnx.ccn.CCNInterestListener; import org.ccnx.ccn.ContentVerifier; import org.ccnx.ccn.KeyManager; import org.ccnx.ccn.config.SystemConfiguration; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats; import org.ccnx.ccn.impl.CCNStats.CCNEnumStats.IStatsEnum; import org.ccnx.ccn.impl.InterestTable.Entry; import org.ccnx.ccn.impl.encoding.XMLEncodable; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.content.ContentEncodingException; import org.ccnx.ccn.profiles.ccnd.CCNDaemonException; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager; import org.ccnx.ccn.profiles.ccnd.PrefixRegistrationManager.ForwardingEntry; import org.ccnx.ccn.profiles.context.ServiceDiscoveryProfile; import org.ccnx.ccn.profiles.security.KeyProfile; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.Interest; import org.ccnx.ccn.protocol.PublisherPublicKeyDigest; import org.ccnx.ccn.protocol.WirePacket; /** * The low level interface to ccnd. Connects to a ccnd. For UDP it must maintain the connection by * sending heartbeats to it. Other functions include reading and writing interests and content * to/from the ccnd, starting handler threads to feed interests and content to registered handlers, * and refreshing unsatisfied interests. * * This class attempts to notice when a ccnd has died and to reconnect to a ccnd when it is restarted. * * It also handles the low level output "tap" functionality - this allows inspection or logging of * all the communications with ccnd. * * Starts a separate thread to listen to, decode and handle incoming data from ccnd. */ public class CCNNetworkManager implements Runnable { public static final int DEFAULT_AGENT_PORT = 9695; // ccnx registered port public static final String DEFAULT_AGENT_HOST = "localhost"; public static final String PROP_AGENT_PORT = "ccn.agent.port"; public static final String PROP_AGENT_HOST = "ccn.agent.host"; public static final String PROP_TAP = "ccn.tap"; public static final String ENV_TAP = "CCN_TAP"; // match C library public static final int PERIOD = 2000; // period for occasional ops in ms. public static final int MAX_PERIOD = PERIOD * 8; public static final String KEEPALIVE_NAME = "/HereIAm"; public static final int THREAD_LIFE = 8; // in seconds public static final int MAX_PAYLOAD = 8800; // number of bytes in UDP payload /** * Definitions for which network protocol to use. This allows overriding * the current default. */ public enum NetworkProtocol { UDP (17), TCP (6); NetworkProtocol(Integer i) { this._i = i; } private final Integer _i; public Integer value() { return _i; } } /* * This ccndId is set on the first connection with 'ccnd' and is the * 'device name' that all of our control communications will use to * ensure that we are talking to our local 'ccnd'. */ protected static Integer _idSyncer = new Integer(0); protected static PublisherPublicKeyDigest _ccndId = null; protected Integer _faceID = null; protected CCNDIdGetter _getter = null; /* * Static singleton. */ protected Thread _thread = null; // the main processing thread protected ThreadPoolExecutor _threadpool = null; // pool service for callback threads protected CCNNetworkChannel _channel = null; // for use by run thread only! protected boolean _run = true; // protected ContentObject _keepalive; protected FileOutputStream _tapStreamOut = null; protected FileOutputStream _tapStreamIn = null; protected long _lastHeartbeat = 0; protected int _port = DEFAULT_AGENT_PORT; protected String _host = DEFAULT_AGENT_HOST; protected NetworkProtocol _protocol = SystemConfiguration.AGENT_PROTOCOL; // For handling protocol to speak to ccnd, must have keys protected KeyManager _keyManager; protected int _localPort = -1; // Tables of interests/filters: users must synchronize on collection protected InterestTable<InterestRegistration> _myInterests = new InterestTable<InterestRegistration>(); protected InterestTable<Filter> _myFilters = new InterestTable<Filter>(); public static final boolean DEFAULT_PREFIX_REG = true; protected boolean _usePrefixReg = DEFAULT_PREFIX_REG; protected PrefixRegistrationManager _prefixMgr = null; protected Timer _periodicTimer = null; protected boolean _timersSetup = false; protected TreeMap<ContentName, RegisteredPrefix> _registeredPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); /** * Keep track of prefixes that are actually registered with ccnd (as opposed to Filters used * to dispatch interests). There may be several filters for each registered prefix. */ public class RegisteredPrefix implements CCNInterestListener { private int _refCount = 1; private ForwardingEntry _forwarding = null; // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. private long _lifetime = -1; // in seconds private long _nextRefresh = -1; private boolean _closing = false; // Flags in process of closing private boolean _wasClosing = false; // See below for reason for this private boolean _doRemove = true; // To avoid removing just registered prefixes public RegisteredPrefix(ForwardingEntry forwarding) { _forwarding = forwarding; if (null != forwarding) { _lifetime = forwarding.getLifetime(); _nextRefresh = System.currentTimeMillis() + (_lifetime / 2); } } /** * Waiter for prefixes being deregistered. This is because we don't want to * wait for the prefix to be deregistered normally, but if we try to re-register * it we have to to avoid races. */ public Interest handleContent(ContentObject data, Interest interest) { synchronized (this) { _closing = false; // We have to clear this, otherwise we could deadlock if setInterestFilter // grabs us after this notifyAll(); } // If setInterestFilter grabbed us right here, we would have cleared _closing (necessary to avoid // deadlocks) but we would have actually deregistered so setInterestFilter needs to know that. It can // because _wasClosing is still set. synchronized (_registeredPrefixes) { if (_doRemove) // Avoid removing a just registered prefix from the map _registeredPrefixes.remove(_forwarding.getPrefixName()); } return null; } } /** * Do scheduled interest and registration refreshes */ private class PeriodicWriter extends TimerTask { // TODO Interest refresh time is supposed to "decay" over time but there are currently // unresolved problems with this. public void run() { //this method needs to do a few things // - reopen connection to ccnd if down // - refresh interests // - refresh prefix registrations // - heartbeats boolean refreshError = false; if (_protocol == NetworkProtocol.UDP) { if (!_channel.isConnected()) { //we are not connected. reconnect attempt is in the heartbeat function... _channel.heartbeat(); } } if (!_channel.isConnected()) { //we tried to reconnect and failed, try again next loop Log.fine(Log.FAC_NETMANAGER, "Not Connected to ccnd, try again in {0}ms", CCNNetworkChannel.SOCKET_TIMEOUT); _lastHeartbeat = 0; if (_run) _periodicTimer.schedule(new PeriodicWriter(), CCNNetworkChannel.SOCKET_TIMEOUT); return; } long ourTime = System.currentTimeMillis(); long minInterestRefreshTime = PERIOD + ourTime; // Library.finest("Refreshing interests (size " + _myInterests.size() + ")"); // Re-express interests that need to be re-expressed try { synchronized (_myInterests) { for (Entry<InterestRegistration> entry : _myInterests.values()) { InterestRegistration reg = entry.value(); // allow some slop for scheduling if (ourTime + 20 > reg.nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh interest: {0}", reg.interest); _lastHeartbeat = ourTime; reg.nextRefresh = ourTime + reg.nextRefreshPeriod; try { write(reg.interest); } catch (NotYetConnectedException nyce) { refreshError = true; } } if (minInterestRefreshTime > reg.nextRefresh) minInterestRefreshTime = reg.nextRefresh; } } } catch (ContentEncodingException xmlex) { Log.severe(Log.FAC_NETMANAGER, "PeriodicWriter interest refresh thread failure (Malformed datagram): {0}", xmlex.getMessage()); Log.warningStackTrace(xmlex); refreshError = true; } // Re-express prefix registrations that need to be re-expressed // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. // FIXME: so lets not go around the loop doing nothing... for now. long minFilterRefreshTime = PERIOD + ourTime; if (false && _usePrefixReg) { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { RegisteredPrefix rp = _registeredPrefixes.get(prefix); if (null != rp._forwarding && rp._lifetime != -1 && rp._nextRefresh != -1) { if (ourTime > rp._nextRefresh) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Refresh registration: {0}", prefix); rp._nextRefresh = -1; try { ForwardingEntry forwarding = _prefixMgr.selfRegisterPrefix(prefix); if (null != forwarding) { rp._lifetime = forwarding.getLifetime(); // filter.nextRefresh = new Date().getTime() + (filter.lifetime / 2); _lastHeartbeat = System.currentTimeMillis(); rp._nextRefresh = _lastHeartbeat + (rp._lifetime / 2); } rp._forwarding = forwarding; } catch (CCNDaemonException e) { Log.warning(e.getMessage()); // XXX - don't think this is right rp._forwarding = null; rp._lifetime = -1; rp._nextRefresh = -1; refreshError = true; } } if (minFilterRefreshTime > rp._nextRefresh) minFilterRefreshTime = rp._nextRefresh; } } // for (Entry<Filter> entry: _myFilters.values()) } // synchronized (_myFilters) } // _usePrefixReg if (refreshError) { Log.warning(Log.FAC_NETMANAGER, "we have had an error when refreshing an interest or prefix registration... do we need to reconnect to ccnd?"); } long currentTime = System.currentTimeMillis(); long checkInterestDelay = minInterestRefreshTime - currentTime; if (checkInterestDelay < 0) checkInterestDelay = 0; if (checkInterestDelay > PERIOD) checkInterestDelay = PERIOD; long checkPrefixDelay = minFilterRefreshTime - currentTime; if (checkPrefixDelay < 0) checkPrefixDelay = 0; if (checkPrefixDelay > PERIOD) checkPrefixDelay = PERIOD; long useMe; if (checkInterestDelay < checkPrefixDelay) { useMe = checkInterestDelay; } else { useMe = checkPrefixDelay; } if (_protocol == NetworkProtocol.UDP) { //we haven't sent anything... maybe need to send a heartbeat if ((currentTime - _lastHeartbeat) >= CCNNetworkChannel.HEARTBEAT_PERIOD) { _lastHeartbeat = currentTime; _channel.heartbeat(); } //now factor in heartbeat time long timeToHeartbeat = CCNNetworkChannel.HEARTBEAT_PERIOD - (currentTime - _lastHeartbeat); if (useMe > timeToHeartbeat) useMe = timeToHeartbeat; } if (useMe < 20) { useMe = 20; } if (_run) _periodicTimer.schedule(new PeriodicWriter(), useMe); } /* run */ } /* private class PeriodicWriter extends TimerTask */ /** * First time startup of timing stuff after first registration * We don't bother to "unstartup" if everything is deregistered * @throws IOException */ private void setupTimers() throws IOException { if (!_timersSetup) { _timersSetup = true; _channel.init(); if (_protocol == NetworkProtocol.UDP) { _channel.heartbeat(); _lastHeartbeat = System.currentTimeMillis(); } // Create timer for periodic behavior _periodicTimer = new Timer(true); _periodicTimer.schedule(new PeriodicWriter(), PERIOD); } } /** Generic superclass for registration objects that may have a listener * Handles invalidation and pending delivery consistently to enable * subclass to call listener callback without holding any library locks, * yet avoid delivery to a cancelled listener. */ protected abstract class ListenerRegistration implements Runnable { protected Object listener; protected CCNNetworkManager manager; public Semaphore sema = null; //used to block thread waiting for data or null if none public Object owner = null; protected boolean deliveryPending = false; protected long id; public abstract void deliver(); /** * This is called when removing interest or content handlers. It's purpose * is to insure that once the remove call begins it completes atomically without more * handlers being triggered. Note that there is still not full atomicity here * because a dispatch to handler might be in progress and we don't hold locks * throughout the dispatch to avoid deadlocks. */ public void invalidate() { // There may be a pending delivery in progress, and it doesn't // happen while holding this lock because that would give the // application callback code power to block library processing. // Instead, we use a flag that is checked and set under this lock // to be sure that on exit from invalidate() there will be. // Back off to avoid livelock for (int i = 0; true; i = (2 * i + 1) & 63) { synchronized (this) { // Make invalid, this will prevent any new delivery that comes // along from doing anything. this.listener = null; this.sema = null; // Return only if no delivery is in progress now (or if we are // called out of our own handler) if (!deliveryPending || (Thread.currentThread().getId() == id)) { return; } } if (i == 0) { Thread.yield(); } else { if (i > 3) Log.finer(Log.FAC_NETMANAGER, "invalidate spin {0}", i); try { Thread.sleep(i); } catch (InterruptedException e) { } } } } /** * Calls the client handler */ public void run() { id = Thread.currentThread().getId(); synchronized (this) { // Mark us pending delivery, so that any invalidate() that comes // along will not return until delivery has finished this.deliveryPending = true; } try { // Delivery may synchronize on this object to access data structures // but should hold no locks when calling the listener deliver(); } catch (Exception ex) { Log.warning(Log.FAC_NETMANAGER, "failed delivery: {0}", ex); } finally { synchronized(this) { this.deliveryPending = false; } } } /** Equality based on listener if present, so multiple objects can * have the same interest registered without colliding */ public boolean equals(Object obj) { if (obj instanceof ListenerRegistration) { ListenerRegistration other = (ListenerRegistration)obj; if (this.owner == other.owner) { if (null == this.listener && null == other.listener){ return super.equals(obj); } else if (null != this.listener && null != other.listener) { return this.listener.equals(other.listener); } } } return false; } public int hashCode() { if (null != this.listener) { if (null != owner) { return owner.hashCode() + this.listener.hashCode(); } else { return this.listener.hashCode(); } } else { return super.hashCode(); } } } /* protected abstract class ListenerRegistration implements Runnable */ /** * Record of Interest * listener must be set (non-null) for cases of standing Interest that holds * until canceled by the application. The listener should be null when a * thread is blocked waiting for data, in which case the thread will be * blocked on semaphore. */ protected class InterestRegistration extends ListenerRegistration { public final Interest interest; ContentObject data = null; protected long nextRefresh; // next time to refresh the interest protected long nextRefreshPeriod = SystemConfiguration.INTEREST_REEXPRESSION_DEFAULT; // period to wait before refresh // All internal client interests must have an owner public InterestRegistration(CCNNetworkManager mgr, Interest i, CCNInterestListener l, Object owner) { manager = mgr; interest = i; listener = l; this.owner = owner; if (null == listener) { sema = new Semaphore(0); } nextRefresh = System.currentTimeMillis() + nextRefreshPeriod; } /** * Return true if data was added. * If data is already pending for delivery for this interest, the * interest is already consumed and this new data cannot be delivered. * @throws NullPointerException If obj is null */ public synchronized boolean add(ContentObject obj) { if (null == data) { // No data pending, this obj will consume interest this.data = obj; // we let this raise exception if obj == null return true; } else { // Data is already pending, this interest is already consumed, cannot add obj return false; } } /** * This used to be called just data, but its similarity * to a simple accessor made the fact that it cleared the data * really confusing and error-prone... * Pull the available data out for processing. * @return */ public synchronized ContentObject popData() { ContentObject result = this.data; this.data = null; return result; } /** * Deliver content to a registered handler */ public void deliver() { try { if (null != this.listener) { // Standing interest: call listener callback ContentObject pending = null; CCNInterestListener listener = null; synchronized (this) { if (null != this.data && null != this.listener) { pending = this.data; this.data = null; listener = (CCNInterestListener)this.listener; } } // Call into client code without holding any library locks if (null != pending) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback (" + pending + " data) for: {0}", this.interest.name()); synchronized (this) { // DKS -- dynamic interests, unregister the interest here and express new one if we have one // previous interest is final, can't update it this.deliveryPending = false; } manager.unregisterInterest(this); // paul r. note - contract says interest will be gone after the call into user's code. // Eventually this may be modified for "pipelining". // DKS TODO tension here -- what object does client use to cancel? // Original implementation had expressInterest return a descriptor // used to cancel it, perhaps we should go back to that. Otherwise // we may need to remember at least the original interest for cancellation, // or a fingerprint representation that doesn't include the exclude filter. // DKS even more interesting -- how do we update our interest? Do we? // it's final now to avoid contention, but need to change it or change // the registration. Interest updatedInterest = listener.handleContent(pending, interest); // Possibly we should optimize here for the case where the same interest is returned back // (now we would unregister it, then reregister it) but need to be careful that the timing // behavior is right if we do that if (null != updatedInterest) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback: updated interest to express: {0}", updatedInterest.name()); // luckily we saved the listener // if we want to cancel this one before we get any data, we need to remember the // updated interest in the listener manager.expressInterest(this.owner, updatedInterest, listener); } } else { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback skipped (no data) for: {0}", this.interest.name()); } } else { synchronized (this) { if (null != this.sema) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Data consumes pending get: {0}", this.interest.name()); // Waiting thread will pickup data -- wake it up // If this interest came from net or waiting thread timed out, // then no thread will be waiting but no harm is done if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "releasing {0}", this.sema); this.sema.release(); } } if (null == this.sema) { // this is no longer valid registration if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Interest callback skipped (not valid) for: {0}", this.interest.name()); } } } catch (Exception ex) { Log.warning(Log.FAC_NETMANAGER, "failed to deliver data: {0}", ex); Log.warningStackTrace(ex); } } /** * Start a thread to deliver data to a registered handler */ public void run() { synchronized (this) { // For now only one piece of data may be delivered per InterestRegistration // This might change when "pipelining" is implemented if (deliveryPending) return; } super.run(); } } /* protected class InterestRegistration extends ListenerRegistration */ /** * Record of a filter describing portion of namespace for which this * application can respond to interests. Used to deliver incoming interests * to registered interest handlers */ protected class Filter extends ListenerRegistration { protected Interest interest; // interest to be delivered // extra interests to be delivered: separating these allows avoidance of ArrayList obj in many cases protected ArrayList<Interest> extra = new ArrayList<Interest>(1); protected ContentName prefix = null; public Filter(CCNNetworkManager mgr, ContentName n, CCNFilterListener l, Object o) { prefix = n; listener = l; owner = o; manager = mgr; } public synchronized boolean add(Interest i) { if (null == interest) { interest = i; return true; } else { // Special case, more than 1 interest pending for delivery // Only 1 interest gets added at a time, but more than 1 // may arrive before a callback is dispatched if (null == extra) { extra = new ArrayList<Interest>(1); } extra.add(i); return false; } } /** * Deliver interest to a registered handler */ public void deliver() { try { Interest pending = null; ArrayList<Interest> pendingExtra = null; CCNFilterListener listener = null; // Grab pending interest(s) under the lock synchronized (this) { if (null != this.interest && null != this.listener) { pending = interest; interest = null; if (null != this.extra) { pendingExtra = extra; extra = null; // Don't create new ArrayList for extra here, will be done only as needed in add() } } listener = (CCNFilterListener)this.listener; } // pending signifies whether there is anything if (null != pending) { // Call into client code without holding any library locks if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Filter callback for: {0}", prefix); listener.handleInterest(pending); // Now extra callbacks for additional interests if (null != pendingExtra) { int countExtra = 0; for (Interest pi : pendingExtra) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) { countExtra++; Log.finer(Log.FAC_NETMANAGER, "Filter callback (extra {0} of {1}) for: {2}", countExtra, pendingExtra.size(), prefix); } listener.handleInterest(pi); } } } else { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Filter callback skipped (no interests) for: {0}", prefix); } } catch (RuntimeException ex) { Log.warning(Log.FAC_NETMANAGER, "failed to deliver interest: {0}", ex); Log.warningStackTrace(ex); } } @Override public String toString() { return prefix.toString(); } } /* protected class Filter extends ListenerRegistration */ private class CCNDIdGetter implements Runnable { CCNNetworkManager _networkManager; KeyManager _keyManager; @SuppressWarnings("unused") public CCNDIdGetter(CCNNetworkManager networkManager, KeyManager keyManager) { _networkManager = networkManager; _keyManager = keyManager; } public void run() { boolean isNull = false; PublisherPublicKeyDigest sentID = null; synchronized (_idSyncer) { isNull = (null == _ccndId); } if (isNull) { try { sentID = fetchCCNDId(_networkManager, _keyManager); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, "CCNDIdGetter: call to fetchCCNDId returned null."); } synchronized(_idSyncer) { _ccndId = sentID; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "CCNDIdGetter: ccndId {0}", ContentName.componentPrintURI(sentID.digest())); } } /* null == _ccndId */ } /* run() */ } /* private class CCNDIdGetter implements Runnable */ /** * The constructor. Attempts to connect to a ccnd at the currently specified port number * @throws IOException if the port is invalid */ public CCNNetworkManager(KeyManager keyManager) throws IOException { if (null == keyManager) { // Unless someone gives us one later, we won't be able to register filters. Log this. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "CCNNetworkManager: being created with null KeyManager. Must set KeyManager later to be able to register filters."); } _keyManager = keyManager; // Determine port at which to contact agent String portval = System.getProperty(PROP_AGENT_PORT); if (null != portval) { try { _port = new Integer(portval); } catch (Exception ex) { throw new IOException("Invalid port '" + portval + "' specified in " + PROP_AGENT_PORT); } Log.warning(Log.FAC_NETMANAGER, "Non-standard CCN agent port " + _port + " per property " + PROP_AGENT_PORT); } String hostval = System.getProperty(PROP_AGENT_HOST); if (null != hostval && hostval.length() > 0) { _host = hostval; Log.warning(Log.FAC_NETMANAGER, "Non-standard CCN agent host " + _host + " per property " + PROP_AGENT_HOST); } _protocol = SystemConfiguration.AGENT_PROTOCOL; if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Contacting CCN agent at " + _host + ":" + _port); String tapname = System.getProperty(PROP_TAP); if (null == tapname) { tapname = System.getenv(ENV_TAP); } if (null != tapname) { long msecs = System.currentTimeMillis(); long secs = msecs/1000; msecs = msecs % 1000; String unique_tapname = tapname + "-T" + Thread.currentThread().getId() + "-" + secs + "-" + msecs; setTap(unique_tapname); } _channel = new CCNNetworkChannel(_host, _port, _protocol, _tapStreamIn); _ccndId = null; _channel.open(); // Create callback threadpool and main processing thread _threadpool = (ThreadPoolExecutor)Executors.newCachedThreadPool(); _threadpool.setKeepAliveTime(THREAD_LIFE, TimeUnit.SECONDS); _thread = new Thread(this, "CCNNetworkManager"); _thread.start(); } /** * Shutdown the connection to ccnd and all threads associated with this network manager */ public void shutdown() { Log.info(Log.FAC_NETMANAGER, "Shutdown requested"); _run = false; if (_periodicTimer != null) _periodicTimer.cancel(); if (null != _channel) { try { setTap(null); _channel.close(); } catch (IOException io) { // Ignore since we're shutting down } } } /** * Get the protocol this network manager is using * @return the protocol */ public NetworkProtocol getProtocol() { return _protocol; } /** * Turns on writing of all packets to a file for test/debug * Overrides any previous setTap or environment/property setting. * Pass null to turn off tap. * @param pathname name of tap file */ public void setTap(String pathname) throws IOException { // Turn off any active tap if (null != _tapStreamOut) { FileOutputStream closingStream = _tapStreamOut; _tapStreamOut = null; closingStream.close(); } if (null != _tapStreamIn) { FileOutputStream closingStream = _tapStreamIn; _tapStreamIn = null; closingStream.close(); } if (pathname != null && pathname.length() > 0) { _tapStreamOut = new FileOutputStream(new File(pathname + "_out")); _tapStreamIn = new FileOutputStream(new File(pathname + "_in")); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Tap writing to {0}", pathname); } } /** * Get the CCN Name of the 'ccnd' we're connected to. * * @return the CCN Name of the 'ccnd' this CCNNetworkManager is connected to. * @throws IOException */ public PublisherPublicKeyDigest getCCNDId() throws IOException { /* * Now arrange to have the ccndId read. We can't do that here because we need * to return back to the create before we know we get the answer back. We can * cause the prefix registration to wait. */ PublisherPublicKeyDigest sentID = null; boolean doFetch = false; synchronized (_idSyncer) { if (null == _ccndId) { doFetch = true; } else { return _ccndId; } } if (doFetch) { sentID = fetchCCNDId(this, _keyManager); if (null == sentID) { Log.severe(Log.FAC_NETMANAGER, "getCCNDId: call to fetchCCNDId returned null."); return null; } } synchronized (_idSyncer) { _ccndId = sentID; return _ccndId; } } /** * */ public KeyManager getKeyManager() { return _keyManager; } /** * */ public void setKeyManager(KeyManager manager) { _keyManager = manager; } /** * Write content to ccnd * * @param co the content * @return the same content that was passed into the method * * TODO - code doesn't actually throw either of these exceptions but need to fix upper * level code to compensate when they are removed. * @throws IOException * @throws InterruptedException */ public ContentObject put(ContentObject co) throws IOException, InterruptedException { _stats.increment(StatsEnum.Puts); try { write(co); } catch (ContentEncodingException e) { Log.warning(Log.FAC_NETMANAGER, "Exception in lowest-level put for object {0}! {1}", co.name(), e); } return co; } /** * get content matching an interest from ccnd. Expresses an interest, waits for ccnd to * return matching the data, then removes the interest and returns the data to the caller. * * TODO should probably handle InterruptedException at this level instead of throwing it to * higher levels * * @param interest the interest * @param timeout time to wait for return in ms * @return ContentObject or null on timeout * @throws IOException on incorrect interest data * @throws InterruptedException if process is interrupted during wait */ public ContentObject get(Interest interest, long timeout) throws IOException, InterruptedException { _stats.increment(StatsEnum.Gets); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "get: {0} with timeout: {1}", interest, timeout); InterestRegistration reg = new InterestRegistration(this, interest, null, null); expressInterest(reg); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "blocking for {0} on {1}", interest.name(), reg.sema); // Await data to consume the interest if (timeout == SystemConfiguration.NO_TIMEOUT) reg.sema.acquire(); // currently no timeouts else reg.sema.tryAcquire(timeout, TimeUnit.MILLISECONDS); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "unblocked for {0} on {1}", interest.name(), reg.sema); // Typically the main processing thread will have registered the interest // which must be undone here, but no harm if never registered unregisterInterest(reg); return reg.popData(); } /** * We express interests to the ccnd and register them within the network manager * * @param caller must not be null * @param interest the interest * @param callbackListener listener to callback on receipt of data * @throws IOException on incorrect interest */ public void expressInterest( Object caller, Interest interest, CCNInterestListener callbackListener) throws IOException { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if (null == callbackListener) { throw new NullPointerException("expressInterest: callbackListener cannot be null"); } if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "expressInterest: {0}", interest); InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); expressInterest(reg); } private void expressInterest(InterestRegistration reg) throws IOException { _stats.increment(StatsEnum.ExpressInterest); try { registerInterest(reg); write(reg.interest); } catch (ContentEncodingException e) { unregisterInterest(reg); throw e; } } /** * Cancel this query with all the repositories we sent * it to. * * @param caller must not be null * @param interest * @param callbackListener */ public void cancelInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { if (null == callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. throw new NullPointerException("cancelInterest: callbackListener cannot be null"); } _stats.increment(StatsEnum.CancelInterest); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "cancelInterest: {0}", interest.name()); // Remove interest from repeated presentation to the network. unregisterInterest(caller, interest, callbackListener); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) throws IOException { setInterestFilter(caller, filter, callbackListener, null); } /** * Register a standing interest filter with callback to receive any * matching interests seen. Any interests whose prefix completely matches "filter" will * be delivered to the listener. Also if this filter matches no currently registered * prefixes, register its prefix with ccnd. * * @param caller must not be null * @param filter ContentName containing prefix of interests to match * @param callbackListener a CCNFilterListener * @param registrationFlags to use for this registration. * @throws IOException */ public void setInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener, Integer registrationFlags) throws IOException { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "setInterestFilter: {0}", filter); if ((null == _keyManager) || (!_keyManager.initialized() || (null == _keyManager.getDefaultKeyID()))) { Log.warning(Log.FAC_NETMANAGER, "Cannot set interest filter -- key manager not ready!"); throw new IOException("Cannot set interest filter -- key manager not ready!"); } // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. setupTimers(); if (_usePrefixReg) { try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } synchronized(_registeredPrefixes) { RegisteredPrefix oldPrefix = getRegisteredPrefix(filter); if (null != oldPrefix) { synchronized (oldPrefix) { if (oldPrefix._closing) { try { oldPrefix.wait(); } catch (InterruptedException e) {} // XXX do we need to worry about this? } if (oldPrefix._wasClosing) { _registeredPrefixes.remove(filter); registerPrefix(filter, registrationFlags); oldPrefix._doRemove = false; } else { oldPrefix._refCount++; } } } else { registerPrefix(filter, registrationFlags); } } } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, "setInterestFilter: unexpected CCNDaemonException: " + e.getMessage()); throw new IOException(e.getMessage()); } } Filter newOne = new Filter(this, filter, callbackListener, caller); synchronized (_myFilters) { _myFilters.add(filter, newOne); } } /** * Must be called with _registeredPrefixes locked * * @param filter * @param registrationFlags * @throws CCNDaemonException */ private void registerPrefix(ContentName filter, Integer registrationFlags) throws CCNDaemonException { ForwardingEntry entry; if (null == registrationFlags) { entry = _prefixMgr.selfRegisterPrefix(filter); } else { entry = _prefixMgr.selfRegisterPrefix(filter, null, registrationFlags, Integer.MAX_VALUE); } RegisteredPrefix newPrefix = new RegisteredPrefix(entry); _registeredPrefixes.put(filter, newPrefix); // FIXME: The lifetime of a prefix is returned in seconds, not milliseconds. The refresh code needs // to understand this. This isn't a problem for now because the lifetime we request when we register a // prefix we use Integer.MAX_VALUE as the requested lifetime. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "setInterestFilter: entry.lifetime: " + entry.getLifetime() + " entry.faceID: " + entry.getFaceID()); } /** * Unregister a standing interest filter * * @param caller must not be null * @param filter currently registered filter * @param callbackListener the CCNFilterListener registered to it */ public void cancelInterestFilter(Object caller, ContentName filter, CCNFilterListener callbackListener) { // TODO - use of "caller" should be reviewed - don't believe this is currently serving // serving any useful purpose. if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINE) ) Log.fine(Log.FAC_NETMANAGER, "cancelInterestFilter: {0}", filter); Filter newOne = new Filter(this, filter, callbackListener, caller); Entry<Filter> found = null; synchronized (_myFilters) { found = _myFilters.remove(filter, newOne); } if (null != found) { Filter thisOne = found.value(); thisOne.invalidate(); if (_usePrefixReg) { // Deregister it with ccnd only if the refCount would go to 0 synchronized (_registeredPrefixes) { RegisteredPrefix prefix = getRegisteredPrefix(filter); - if (null != prefix && prefix._refCount <= 1) { + if (null != prefix) { synchronized (prefix) { if (prefix._refCount <= 1) { ForwardingEntry entry = prefix._forwarding; // Since we are piggybacking registration entries we can legitimately have a "last" registration entry on a prefix that had // been piggybacked on a higher registration earlier so the entries name would not match the filter. // //if (!entry.getPrefixName().equals(filter)) { // Log.severe(Log.FAC_NETMANAGER, "cancelInterestFilter filter name {0} does not match recorded name {1}", filter, entry.getPrefixName()); //} try { if (null == _prefixMgr) { _prefixMgr = new PrefixRegistrationManager(this); } prefix._closing = true; prefix._wasClosing = true; _prefixMgr.unRegisterPrefix(filter, prefix, entry.getFaceID()); } catch (CCNDaemonException e) { Log.warning(Log.FAC_NETMANAGER, "cancelInterestFilter failed with CCNDaemonException: " + e.getMessage()); } } else prefix._refCount--; } } } } } } /** * Merge prefixes so we only add a new one when it doesn't have a * common ancestor already registered. * * @param prefix * @return prefix that incorporates or matches this one or null if none found */ protected RegisteredPrefix getRegisteredPrefix(ContentName prefix) { synchronized(_registeredPrefixes) { // MM: This is a dumb way to search a TreeMap for a prefix. // TreeMap is sorted and should exploit that. for (ContentName name: _registeredPrefixes.keySet()) { if (name.equals(prefix) || name.isPrefixOf(prefix)) return _registeredPrefixes.get(name); } } return null; } protected void write(ContentObject data) throws ContentEncodingException { _stats.increment(StatsEnum.WriteObject); WirePacket packet = new WirePacket(data); writeInner(packet); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "Wrote content object: {0}", data.name()); } /** * Don't do this unless you know what you are doing! * @param interest * @throws ContentEncodingException */ public void write(Interest interest) throws ContentEncodingException { _stats.increment(StatsEnum.WriteInterest); WirePacket packet = new WirePacket(interest); writeInner(packet); } // DKS TODO unthrown exception private void writeInner(WirePacket packet) throws ContentEncodingException { try { byte[] bytes = packet.encode(); ByteBuffer datagram = ByteBuffer.wrap(bytes); synchronized (_channel) { int result = _channel.write(datagram); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "Wrote datagram (" + datagram.position() + " bytes, result " + result + ")"); if( result < bytes.length ) { _stats.increment(StatsEnum.WriteUnderflows); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.INFO) ) Log.info(Log.FAC_NETMANAGER, "Wrote datagram {0} bytes to channel, but packet was {1} bytes", result, bytes.length); } if (null != _tapStreamOut) { try { _tapStreamOut.write(bytes); } catch (IOException io) { Log.warning(Log.FAC_NETMANAGER, "Unable to write packet to tap stream for debugging"); } } } } catch (IOException io) { _stats.increment(StatsEnum.WriteErrors); // We do not see errors on send typically even if // agent is gone, so log each but do not track Log.warning(Log.FAC_NETMANAGER, "Error sending packet: " + io.toString()); } } /** * Pass things on to the network stack. * @throws IOException */ private InterestRegistration registerInterest(InterestRegistration reg) throws IOException { // Add to standing interests table setupTimers(); if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINEST) ) Log.finest(Log.FAC_NETMANAGER, "registerInterest for {0}, and obj is " + _myInterests.hashCode(), reg.interest.name()); synchronized (_myInterests) { _myInterests.add(reg.interest, reg); } return reg; } private void unregisterInterest(Object caller, Interest interest, CCNInterestListener callbackListener) { InterestRegistration reg = new InterestRegistration(this, interest, callbackListener, caller); unregisterInterest(reg); } /** * @param reg - registration to unregister * * Important Note: This can indirectly need to obtain the lock for "reg" with the lock on * "myInterests" held. Therefore it can't be called when holding the lock for "reg". */ private void unregisterInterest(InterestRegistration reg) { synchronized (_myInterests) { Entry<InterestRegistration> found = _myInterests.remove(reg.interest, reg); if (null != found) { found.value().invalidate(); } } } /** * Thread method: this thread will handle reading datagrams and * starts threads to dispatch data to handlers registered for it. */ public void run() { if (! _run) { Log.warning(Log.FAC_NETMANAGER, "CCNNetworkManager run() called after shutdown"); return; } //WirePacket packet = new WirePacket(); if( Log.isLoggable(Level.INFO) ) Log.info("CCNNetworkManager processing thread started for port: " + _localPort); while (_run) { try { XMLEncodable packet = _channel.getPacket(); if (null == packet) { continue; } if (packet instanceof ContentObject) { _stats.increment(StatsEnum.ReceiveObject); ContentObject co = (ContentObject)packet; if( Log.isLoggable(Level.FINER) ) Log.finer("Data from net for port: " + _localPort + " {0}", co.name()); // SystemConfiguration.logObject("Data from net:", co); deliverData(co); // External data never goes back to network, never held onto here // External data never has a thread waiting, so no need to release sema } else if (packet instanceof Interest) { _stats.increment(StatsEnum.ReceiveInterest); Interest interest = (Interest) packet; if( Log.isLoggable(Level.FINEST) ) Log.finest("Interest from net for port: " + _localPort + " {0}", interest); InterestRegistration oInterest = new InterestRegistration(this, interest, null, null); deliverInterest(oInterest); // External interests never go back to network } // for interests } catch (Exception ex) { _stats.increment(StatsEnum.ReceiveUnknown); Log.severe(Log.FAC_NETMANAGER, "Processing thread failure (UNKNOWN): " + ex.getMessage() + " for port: " + _localPort); Log.warningStackTrace(ex); } } _threadpool.shutdown(); Log.info(Log.FAC_NETMANAGER, "Shutdown complete for port: " + _localPort); } /** * Internal delivery of interests to pending filter listeners * @param ireg */ protected void deliverInterest(InterestRegistration ireg) { _stats.increment(StatsEnum.DeliverInterest); // Call any listeners with matching filters synchronized (_myFilters) { for (Filter filter : _myFilters.getValues(ireg.interest.name())) { if (filter.owner != ireg.owner) { if( Log.isLoggable(Log.FAC_NETMANAGER, Level.FINER) ) Log.finer(Log.FAC_NETMANAGER, "Schedule delivery for interest: {0}", ireg.interest); if (filter.add(ireg.interest)) _threadpool.execute(filter); } } } } /** * Deliver data to blocked getters and registered interests * @param co */ protected void deliverData(ContentObject co) { _stats.increment(StatsEnum.DeliverContent); synchronized (_myInterests) { for (InterestRegistration ireg : _myInterests.getValues(co)) { if (ireg.add(co)) { // this is a copy of the data _stats.increment(StatsEnum.DeliverContentMatchingInterests); _threadpool.execute(ireg); } } } } protected PublisherPublicKeyDigest fetchCCNDId(CCNNetworkManager mgr, KeyManager keyManager) throws IOException { try { ContentName serviceKeyName = new ContentName(ServiceDiscoveryProfile.localServiceName(ServiceDiscoveryProfile.CCND_SERVICE_NAME), KeyProfile.KEY_NAME_COMPONENT); Interest i = new Interest(serviceKeyName); i.scope(1); ContentObject c = mgr.get(i, SystemConfiguration.CCNDID_DISCOVERY_TIMEOUT); if (null == c) { String msg = ("fetchCCNDId: ccndID discovery failed due to timeout."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } PublisherPublicKeyDigest sentID = c.signedInfo().getPublisherKeyID(); // TODO: This needs to be fixed once the KeyRepository is fixed to provide a KeyManager if (null != keyManager) { ContentVerifier v = new ContentObject.SimpleVerifier(sentID, keyManager); if (!v.verify(c)) { String msg = ("fetchCCNDId: ccndID discovery reply failed to verify."); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } else { Log.severe(Log.FAC_NETMANAGER, "fetchCCNDId: do not have a KeyManager. Cannot verify ccndID."); return null; } return sentID; } catch (InterruptedException e) { Log.warningStackTrace(e); throw new IOException(e.getMessage()); } catch (IOException e) { String reason = e.getMessage(); Log.warningStackTrace(e); String msg = ("fetchCCNDId: Unexpected IOException in ccndID discovery Interest reason: " + reason); Log.severe(Log.FAC_NETMANAGER, msg); throw new IOException(msg); } } /* PublisherPublicKeyDigest fetchCCNDId() */ /** * Reregister all current prefixes with ccnd after ccnd goes down and then comes back up * @throws IOException */ private void reregisterPrefixes() throws IOException { TreeMap<ContentName, RegisteredPrefix> newPrefixes = new TreeMap<ContentName, RegisteredPrefix>(); try { synchronized (_registeredPrefixes) { for (ContentName prefix : _registeredPrefixes.keySet()) { ForwardingEntry entry = _prefixMgr.selfRegisterPrefix(prefix); RegisteredPrefix newPrefixEntry = new RegisteredPrefix(entry); newPrefixEntry._refCount = _registeredPrefixes.get(prefix)._refCount; newPrefixes.put(prefix, newPrefixEntry); } _registeredPrefixes.clear(); _registeredPrefixes.putAll(newPrefixes); } } catch (CCNDaemonException cde) { _channel.close(); } } // ============================================================== // Statistics protected CCNEnumStats<StatsEnum> _stats = new CCNEnumStats<StatsEnum>(StatsEnum.Puts); public CCNStats getStats() { return _stats; } public enum StatsEnum implements IStatsEnum { // ==================================== // Just edit this list, dont need to change anything else Puts ("ContentObjects", "The number of put calls"), Gets ("ContentObjects", "The number of get calls"), WriteInterest ("calls", "The number of calls to write(Interest)"), WriteObject ("calls", "The number of calls to write(ContentObject)"), WriteErrors ("count", "Error count for writeInner()"), WriteUnderflows ("count", "The count of times when the bytes written to the channel < buffer size"), ExpressInterest ("calls", "The number of calls to expressInterest"), CancelInterest ("calls", "The number of calls to cancelInterest"), DeliverInterest ("calls", "The number of calls to deliverInterest"), DeliverContent ("calls", "The number of calls to cancelInterest"), DeliverContentMatchingInterests ("calls", "Count of the calls to threadpool.execute in handleData()"), ReceiveObject ("objects", "Receive count of ContentObjects from channel"), ReceiveInterest ("interests", "Receive count of Interests from channel"), ReceiveUnknown ("calls", "Receive count of unknown type from channel"), ; // ==================================== // This is the same for every user of IStatsEnum protected final String _units; protected final String _description; protected final static String [] _names; static { _names = new String[StatsEnum.values().length]; for(StatsEnum stat : StatsEnum.values() ) _names[stat.ordinal()] = stat.toString(); } StatsEnum(String units, String description) { _units = units; _description = description; } public String getDescription(int index) { return StatsEnum.values()[index]._description; } public int getIndex(String name) { StatsEnum x = StatsEnum.valueOf(name); return x.ordinal(); } public String getName(int index) { return StatsEnum.values()[index].toString(); } public String getUnits(int index) { return StatsEnum.values()[index]._units; } public String [] getNames() { return _names; } } }
true
false
null
null
diff --git a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerASTTest.java b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerASTTest.java index f62d685c6..b231d92a3 100644 --- a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerASTTest.java +++ b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerASTTest.java @@ -1,120 +1,118 @@ /** * <copyright> * * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation * * </copyright> * - * $Id: JMergerASTTest.java,v 1.8 2008/04/22 13:35:39 emerks Exp $ + * $Id: JMergerASTTest.java,v 1.9 2008/05/29 14:56:37 marcelop Exp $ */ package org.eclipse.emf.test.tools.merger; import java.io.File; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.emf.codegen.merge.java.facade.FacadeHelper; import org.eclipse.emf.codegen.merge.java.facade.ast.ASTFacadeHelper; import org.eclipse.emf.codegen.util.CodeGenUtil; /** * Each test method in this class works with same directory as {@link JMergerTest}. * <p> * This test should contain special test cases that require special code executed for them. * Special cases will use directory returned by {@link #getDefaultDataDirectory()}. * <p> * In addition, this test is ran automatically by {@link JMergerTestSuite} for all input directories. * * @see #JMergerASTTest(TestSuite, File) */ public class JMergerASTTest extends JMergerTest { /** * @param name */ public JMergerASTTest(String name) { super(name); } /** * Adds itself to test suite if possible by {@link #addItself(TestSuite)}. * <p> * Sets test name to be <code>mergeAST</code>. * * @param ts * @param dataDirectory * @see #mergeAST() */ public JMergerASTTest(TestSuite ts, File dataDirectory) { super(ts, dataDirectory); setName("mergeAST"); } /** * Name of the expected output file when AST facade implementation is used. * @see #getTestSpecificExpectedOutput() */ public static final String AST_EXPECTED_OUTPUT_FILENAME = "ASTMergerExpected.java"; /** * Special test cases that are not in {@link JMergerTestSuite} - * - * @return */ public static Test suite() { TestSuite ts = new TestSuite("JMerger AST Test"); ts.addTest(new JMergerJDOMTest("merge4")); return ts; } /* * Bugzilla 163856 */ public void merge4() throws Exception { applyGenModelEditorFormatting = true; verifyMerge(expectedOutput, mergeFiles()); } /** * Method to be used in tests created based on data directories. * * @throws Exception * @see #addItself(TestSuite) * @see JMergerTestSuite */ public void mergeAST() throws Exception { merge(); } @Override protected void instanceTest(FacadeHelper facadeHelper) { assertTrue(ASTFacadeHelper.class.isInstance(facadeHelper)); } @Override protected FacadeHelper instanciateFacadeHelper() { FacadeHelper facadeHelper = CodeGenUtil.instantiateFacadeHelper(ASTFacadeHelper.class.getCanonicalName()); return facadeHelper; } @Override protected File getTestSpecificExpectedOutput() { return new File(getDataDirectory(), AST_EXPECTED_OUTPUT_FILENAME); } } diff --git a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerJDOMTest.java b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerJDOMTest.java index 794a74913..f84603381 100644 --- a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerJDOMTest.java +++ b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerJDOMTest.java @@ -1,138 +1,136 @@ /** * <copyright> * * Copyright (c) 2004-2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation * * </copyright> * * $Id: */ package org.eclipse.emf.test.tools.merger; import java.io.File; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.emf.codegen.merge.java.facade.FacadeHelper; import org.eclipse.emf.codegen.merge.java.facade.jdom.JDOMFacadeHelper; import org.eclipse.emf.codegen.util.CodeGenUtil; import org.eclipse.jdt.core.JavaCore; /** * Each test method in this class works with same directory as {@link JMergerTest}. * <p> * This test should contain special test cases that require special code executed for them. * Special cases will use directory returned by {@link #getDefaultDataDirectory()}. * <p> * In addition, this test is ran automatically by {@link JMergerTestSuite} for all input directories. * * @see #JMergerJDOMTest(TestSuite, File) */ public class JMergerJDOMTest extends JMergerTest { /** * @param name */ public JMergerJDOMTest(String name) { super(name); } /** * Adds itself to test suite if possible by {@link #addItself(TestSuite)}. * <p> * Sets test name to be <code>mergeJDOM</code>. * * @param ts * @param dataDirectory * @see #mergeJDOM() */ public JMergerJDOMTest(TestSuite ts, File dataDirectory) { super(ts, dataDirectory); setName("mergeJDOM"); } /** * Name of the expected output file when JDOM facade implementation is used. * @see #getTestSpecificExpectedOutput() */ public static final String JDOM_EXPECTED_OUTPUT_FILENAME = "JDOMMergerExpected.java"; /** * Special test cases that are not in {@link JMergerTestSuite} - * - * @return */ public static Test suite() { TestSuite ts = new TestSuite("JMerger JDOM Test"); ts.addTest(new JMergerJDOMTest("merge4")); return ts; } /* * Bugzilla 163856 */ public void merge4() throws Exception { adjustSourceCompatibility(JavaCore.VERSION_1_5); applyGenModelEditorFormatting = true; verifyMerge(expectedOutput, mergeFiles()); } /** * Method to be used in tests created based on data directories. * @throws Exception * @see #addItself(TestSuite) * @see JMergerTestSuite */ public void mergeJDOM() throws Exception { merge(); } @Override protected void instanceTest(FacadeHelper facadeHelper) { assertTrue(JDOMFacadeHelper.class.isInstance(facadeHelper)); } @Override protected FacadeHelper instanciateFacadeHelper() { FacadeHelper facadeHelper = CodeGenUtil.instantiateFacadeHelper(JDOMFacadeHelper.class.getCanonicalName()); return facadeHelper; } @Override protected File getTestSpecificExpectedOutput() { return new File(getDataDirectory(), JDOM_EXPECTED_OUTPUT_FILENAME); } /** * Adds itself only if java version is 1.4 based on directory ({@link #computeExpectedOutputFile()} * and if possible by {@link JMergerTest#addItself(TestSuite)}. * * @see org.eclipse.emf.test.tools.merger.JMergerTest#addItself(junit.framework.TestSuite) */ @Override public void addItself(TestSuite ts) { String javaVersion = computeJavaVersion(); if (JavaCore.VERSION_1_4.equals(javaVersion)) { super.addItself(ts); } } } diff --git a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerTestSuite.java b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerTestSuite.java index 76982907f..d01444dce 100644 --- a/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerTestSuite.java +++ b/tests/org.eclipse.emf.test.tools/src/org/eclipse/emf/test/tools/merger/JMergerTestSuite.java @@ -1,181 +1,177 @@ /** * <copyright> * * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation * * </copyright> * - * $Id: JMergerTestSuite.java,v 1.6 2008/04/22 13:35:39 emerks Exp $ + * $Id: JMergerTestSuite.java,v 1.7 2008/05/29 14:56:37 marcelop Exp $ */ package org.eclipse.emf.test.tools.merger; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.regex.Pattern; import junit.framework.TestSuite; import org.eclipse.emf.test.common.TestUtil; import org.eclipse.emf.test.tools.AllSuites; /** * Runs JDOM {@link JMergerJDOMTest} or AST {@link JMergerASTTest} or both * for each data directory <code>/data/merge.input/&lt;java version&gt;/merge*</code>. * <p> * Each test determines if it can be ran for each data directory. * * @see JMergerTest#DIRECTORY_NAMES_TO_JAVA_VERSIONS * @see JMergerJDOMTest#JMergerJDOMTest(TestSuite, File) * @see JMergerASTTest#JMergerASTTest(TestSuite, File) */ public class JMergerTestSuite extends TestSuite { /** * Filter for the directories that will be used as data directories for tests. */ protected static class JMergerDataDirectoryFilter implements FilenameFilter { protected static final Pattern EXCLUDE_DATA_DIRECTORY_NAME_PATTERN = Pattern.compile("^(?:CVS)|(?:\\..*)$"); protected static final Pattern INCLUDE_DATA_DIRECTORY_NAME_PATTERN = Pattern.compile(".*"); // use something like this line to restrict the test // protected static final Pattern INCLUDE_DATA_DIRECTORY_NAME_PATTERN = Pattern.compile("(bugzilla|178183)"); public boolean accept(File dir, String name) { // must be a directory and must match the pattern File dataDirectoryCandidate = new File(dir, name); return dataDirectoryCandidate.isDirectory() && !EXCLUDE_DATA_DIRECTORY_NAME_PATTERN.matcher(name).matches() && INCLUDE_DATA_DIRECTORY_NAME_PATTERN.matcher(name).matches(); } } /** * Default root data directory containing java versions subdirectories. * <p> * Default is /data/merge.input * @see JMergerTest#DIRECTORY_NAMES_TO_JAVA_VERSIONS */ protected static final File DEFAULT_ROOT_DIRECTORY = new File(TestUtil.getPluginDirectory(AllSuites.PLUGIN_ID) + File.separator + "data" + File.separator + "merge.input"); /** * @param name */ public JMergerTestSuite(String name) { super(name); populateSuite(); } - /** - * @return - */ public static TestSuite suite() { return new JMergerTestSuite("JMerger Test Suite"); } /** * @return root data directory containing subdirectories for different versions of Java * @see JMergerTest#DIRECTORY_NAMES_TO_JAVA_VERSIONS */ protected File determineRootDataDirectory() { return DEFAULT_ROOT_DIRECTORY; } /** * Populates suite with test cases for each data directory. */ protected void populateSuite() { File rootDataDirsDirectory = determineRootDataDirectory(); assertTrue("Directory " + determineRootDataDirectory().getAbsolutePath() + " does not exist.", rootDataDirsDirectory.exists()); assertTrue("Directory " + determineRootDataDirectory().getAbsolutePath() + " is not a directory.", rootDataDirsDirectory.isDirectory()); // loop for all directories of all java versions for (String javaVersionDirectoryName : JMergerTest.DIRECTORY_NAMES_TO_JAVA_VERSIONS.keySet()) { File dataDirsDirectory = new File(rootDataDirsDirectory, javaVersionDirectoryName); if (dataDirsDirectory.isDirectory()) { addTest(createTestSuiteRecursively(dataDirsDirectory)); } } assertFalse("Subdirectories " + JMergerTest.DIRECTORY_NAMES_TO_JAVA_VERSIONS.keySet().toString() + " under " + rootDataDirsDirectory.getAbsolutePath() + " must contain subdirectories with source, target and output files.", countTestCases() == 0); } /** * Creates a test suite recursively for all directories in the directory tree. * Directories used as input must be accepted by {@link JMergerDataDirectoryFilter}. * @param directory root directory to create test suite for * @return resulting test suite */ protected TestSuite createTestSuiteRecursively(File directory) { TestSuite thisDirectoryTest = createSingleInputTestSuite(directory); // if there are no test cases for this directory, try to create test suites from subdirectories if (thisDirectoryTest.countTestCases() == 0) { String[] dataDirectoriesNames = directory.list(new JMergerDataDirectoryFilter()); if (dataDirectoriesNames.length > 0) { TestSuite testSuite = new TestSuite(directory.getName()); Arrays.sort(dataDirectoriesNames); for (String dataDirectoryName : dataDirectoriesNames) { File dataDirectory = new File(directory, dataDirectoryName); testSuite.addTest(createTestSuiteRecursively(dataDirectory)); } return testSuite; } } return thisDirectoryTest; } /** * Creates and returns test suite for a single input directory. * * @param dataDirectory directory containing directory with subDirectoryName - * @return */ protected TestSuite createSingleInputTestSuite(File dataDirectory) { TestSuite ts = new TestSuite(dataDirectory.getName()); addTestCases(ts, dataDirectory); return ts; } /** * Adds tests that can be ran for the given data directory to the test suite. * * @param ts test suite to add tests to * @param dataDirectory */ protected void addTestCases(TestSuite ts, File dataDirectory) { // create and, if possible, add test cases to the suite new JMergerASTTest(ts, dataDirectory); new JMergerJDOMTest(ts, dataDirectory); } }
false
false
null
null
diff --git a/src/main/java/edu/rivfader/commands/PrintQuery.java b/src/main/java/edu/rivfader/commands/PrintQuery.java index d550409..d5465b1 100644 --- a/src/main/java/edu/rivfader/commands/PrintQuery.java +++ b/src/main/java/edu/rivfader/commands/PrintQuery.java @@ -1,91 +1,97 @@ package edu.rivfader.commands; import edu.rivfader.data.Database; import edu.rivfader.relalg.IRelAlgExpr; import edu.rivfader.relalg.IQualifiedColumnName; import edu.rivfader.relalg.IQualifiedNameRow; import edu.rivfader.relalg.Evaluator; +import edu.rivfader.profiling.ProfilingEvaluator; +import edu.rivfader.profiling.Block1Costs; +import edu.rivfader.profiling.ICostAccumulator; + import java.io.Writer; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.LinkedList; import java.util.Collections; /** * Implements the command to print the results of a certain query. * @author harald */ public class PrintQuery implements ICommand { /** * contains the query to execute. */ private IRelAlgExpr query; /** * constucts a new printQuery command. * @param pQuery the query to execute. */ public PrintQuery(final IRelAlgExpr pQuery) { query = pQuery; } private String buildColumns(final IQualifiedNameRow source) { List<IQualifiedColumnName> ns; // names StringBuilder o; // output boolean f; // first ns = new LinkedList<IQualifiedColumnName>(source.columns()); Collections.sort(ns); o = new StringBuilder(); f = true; for (IQualifiedColumnName cn : ns) { // current name if (!f) { o.append(" "); } f = false; o.append(cn.getTable() + "." + cn.getColumn()); } o.append('\n'); return o.toString(); } private String buildValueRow(final IQualifiedNameRow source) { List<IQualifiedColumnName> ns; // names StringBuilder o; // output boolean f; // first ns = new LinkedList<IQualifiedColumnName>(source.columns()); Collections.sort(ns); o = new StringBuilder(); f = true; for (IQualifiedColumnName cn : ns) { // current name if (!f) { o.append(" "); } f = false; o.append(source.getData(cn)); } o.append('\n'); return o.toString(); } @Override public void execute(final Database context, final Writer output) throws IOException { - Evaluator e = new Evaluator(context); + ICostAccumulator costs = new Block1Costs(); + Evaluator e = new ProfilingEvaluator(context, costs); Iterator<IQualifiedNameRow> rows = e.transform(query); if(!rows.hasNext()) { output.write("Empty result set.\n"); return; } IQualifiedNameRow current = rows.next(); output.write(buildColumns(current)); output.write(buildValueRow(current)); while(rows.hasNext()) { output.write(buildValueRow(rows.next())); } + output.write("Costs: " + costs.getCost() + "\n"); } } diff --git a/src/main/java/edu/rivfader/profiling/ProfilingEvaluator.java b/src/main/java/edu/rivfader/profiling/ProfilingEvaluator.java index dbb8c9c..726a2ee 100644 --- a/src/main/java/edu/rivfader/profiling/ProfilingEvaluator.java +++ b/src/main/java/edu/rivfader/profiling/ProfilingEvaluator.java @@ -1,48 +1,52 @@ package edu.rivfader.profiling; import edu.rivfader.data.Database; import edu.rivfader.relalg.IRelAlgExpr; import edu.rivfader.relalg.Evaluator; import edu.rivfader.relalg.Selection; +import edu.rivfader.relalg.SelectionEvaluationIterator; import edu.rivfader.relalg.Projection; +import edu.rivfader.relalg.ProjectionEvaluationIterator; import edu.rivfader.relalg.Product; import edu.rivfader.relalg.IQualifiedNameRow; import java.util.Iterator; public class ProfilingEvaluator extends Evaluator { private ICostAccumulator statisticsDestination; public ProfilingEvaluator(Database context, ICostAccumulator pStatisticsDestination) { super(context); statisticsDestination = pStatisticsDestination; } @Override public ICountingIterator<IQualifiedNameRow> transform(IRelAlgExpr e) { return new CountingIterator<IQualifiedNameRow>(super.transform(e)); } @Override public Iterator<IQualifiedNameRow> transformSelection(Selection s) { ICountingIterator<IQualifiedNameRow> inputSet = transform(s.getSubExpression()); - return new SelectionStatisticsIterator(s, inputSet, + return new SelectionStatisticsIterator(s, + new SelectionEvaluationIterator(s.getPredicate(), inputSet), statisticsDestination, inputSet); } @Override public Iterator<IQualifiedNameRow> transformProjection(Projection p) { return new ProjectionStatisticsIterator(statisticsDestination, - transform(p.getSubExpression()), - p); + new ProjectionEvaluationIterator( + transform(p.getSubExpression()), + p.getSelectedFields()), p); } @Override public Iterator<IQualifiedNameRow> transformProduct(Product p) { return new ProductStatisticsIterator(p, statisticsDestination, - transform(p)); + super.transformProduct(p)); } } diff --git a/src/main/java/edu/rivfader/relalg/Evaluator.java b/src/main/java/edu/rivfader/relalg/Evaluator.java index 3d03e94..1b180d2 100644 --- a/src/main/java/edu/rivfader/relalg/Evaluator.java +++ b/src/main/java/edu/rivfader/relalg/Evaluator.java @@ -1,64 +1,65 @@ package edu.rivfader.relalg; import edu.rivfader.data.Database; import edu.rivfader.data.Row; import edu.rivfader.relalg.rowselector.IRowSelector; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.LinkedList; import java.util.NoSuchElementException; import java.io.IOException; /** * evaluates a rel alg expression in a database into a lazily computed * set of rows. * @author harald */ public class Evaluator extends BaseRelalgTransformation<Iterator<IQualifiedNameRow>> implements IRelAlgExprTransformation<Iterator<IQualifiedNameRow>> { private Database context; public Evaluator(Database pContext) { context = pContext; } @Override public Iterator<IQualifiedNameRow> transformProduct(Product p){ return new ProductEvaluationIterator(p.getLeft(), p.getRight(), this); } @Override public Iterator<IQualifiedNameRow> transformProjection(Projection p){ return new ProjectionEvaluationIterator(transform(p.getSubExpression()), p.getSelectedFields()); } @Override public Iterator<IQualifiedNameRow> transformSelection(Selection s){ return new SelectionEvaluationIterator(s.getPredicate(), transform(s.getSubExpression())); } @Override public Iterator<IQualifiedNameRow> transformLoadTable(LoadTable l){ try { return new LoadTableEvaluationIterator( context.loadTable(l.getName()), l.getName()); } catch (IOException e) { throw new RuntimeException("loading the table did not work", e); } } @Override public Iterator<IQualifiedNameRow> transformRenameTable(RenameTable r){ + r.setDatabase(context); return new RenameTableEvaluationIterator(r.getSource().load(), r.getName()); } }
false
false
null
null
diff --git a/src/cgeo/geocaching/cgGPXParser.java b/src/cgeo/geocaching/cgGPXParser.java index a4b196112..e3cc3d253 100644 --- a/src/cgeo/geocaching/cgGPXParser.java +++ b/src/cgeo/geocaching/cgGPXParser.java @@ -1,547 +1,551 @@ package cgeo.geocaching; import android.os.Handler; import android.os.Message; import android.sax.Element; import android.sax.EndElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.text.Html; import android.util.Log; import android.util.Xml; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.xml.sax.Attributes; public class cgGPXParser { private cgeoapplication app = null; private cgBase base = null; private int listId = 1; private cgSearch search = null; private Handler handler = null; private cgCache cache = new cgCache(); private cgTrackable trackable = new cgTrackable(); private cgLog log = new cgLog(); private boolean htmlShort = true; private boolean htmlLong = true; private String type = null; private String sym = null; private String ns = null; private ArrayList<String> nsGCList = new ArrayList<String>(); private final Pattern patternGeocode = Pattern.compile("(GC[0-9A-Z]+)", Pattern.CASE_INSENSITIVE); private String name = null; private String cmt = null; private String desc = null; public cgGPXParser(cgeoapplication appIn, cgBase baseIn, int listIdIn, cgSearch searchIn) { app = appIn; base = baseIn; listId = listIdIn; search = searchIn; nsGCList.add("http://www.groundspeak.com/cache/1/1"); // PQ 1.1 nsGCList.add("http://www.groundspeak.com/cache/1/0/1"); // PQ 1.0.1 nsGCList.add("http://www.groundspeak.com/cache/1/0"); // PQ 1.0 } public long parse(File file, int version, Handler handlerIn) { handler = handlerIn; if (file == null) { return 0l; } if (version == 11) { ns = "http://www.topografix.com/GPX/1/1"; // GPX 1.1 } else { ns = "http://www.topografix.com/GPX/1/0"; // GPX 1.0 } final RootElement root = new RootElement(ns, "gpx"); final Element waypoint = root.getChild(ns, "wpt"); // waypoint - attributes waypoint.setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { try { if (attrs.getIndex("lat") > -1) { cache.latitude = new Double(attrs.getValue("lat")); } if (attrs.getIndex("lon") > -1) { cache.longitude = new Double(attrs.getValue("lon")); } } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse waypoint's latitude and/or longitude."); } } }); // waypoint waypoint.setEndElementListener(new EndElementListener() { public void end() { if (cache.geocode == null || cache.geocode.length() == 0) { // try to find geocode somewhere else String geocode = null; Matcher matcherGeocode = null; if (name != null && geocode == null) { matcherGeocode = patternGeocode.matcher(name); while (matcherGeocode.find()) { if (matcherGeocode.groupCount() > 0) { geocode = matcherGeocode.group(1); } } } if (desc != null && geocode == null) { matcherGeocode = patternGeocode.matcher(desc); while (matcherGeocode.find()) { if (matcherGeocode.groupCount() > 0) { geocode = matcherGeocode.group(1); } } } if (cmt != null && geocode == null) { matcherGeocode = patternGeocode.matcher(cmt); while (matcherGeocode.find()) { if (matcherGeocode.groupCount() > 0) { geocode = matcherGeocode.group(1); } } } if (geocode != null && geocode.length() > 0) { cache.geocode = geocode; } geocode = null; matcherGeocode = null; } if (cache.geocode != null && cache.geocode.length() > 0 && cache.latitude != null && cache.longitude != null && ((type == null && sym == null) || (type != null && type.indexOf("geocache") > -1) || (sym != null && sym.indexOf("geocache") > -1))) { cache.latitudeString = base.formatCoordinate(cache.latitude, "lat", true); cache.longitudeString = base.formatCoordinate(cache.longitude, "lon", true); if (cache.inventory != null) { cache.inventoryItems = cache.inventory.size(); } else { cache.inventoryItems = 0; } cache.reason = listId; cache.updated = new Date().getTime(); cache.detailedUpdate = new Date().getTime(); cache.detailed = true; app.addCacheToSearch(search, cache); } if (handler != null) { final Message msg = new Message(); msg.obj = search.getCount(); handler.sendMessage(msg); } htmlShort = true; htmlLong = true; type = null; sym = null; name = null; desc = null; cmt = null; cache = null; cache = new cgCache(); } }); // waypoint.time waypoint.getChild(ns, "time").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { try { cache.hidden = cgBase.dateGPXIn.parse(body.trim()); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse cache date: " + e.toString()); } } }); // waypoint.name waypoint.getChild(ns, "name").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { name = body; final String content = Html.fromHtml(body).toString().trim(); cache.name = content; if (cache.name.length() > 2 && cache.name.substring(0, 2).equalsIgnoreCase("GC") == true) { cache.geocode = cache.name.toUpperCase(); } } }); // waypoint.desc waypoint.getChild(ns, "desc").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { desc = body; final String content = Html.fromHtml(body).toString().trim(); cache.shortdesc = content; } }); // waypoint.cmt waypoint.getChild(ns, "cmt").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { cmt = body; final String content = Html.fromHtml(body).toString().trim(); cache.description = content; } }); // waypoint.type waypoint.getChild(ns, "type").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String[] content = body.split("\\|"); if (content.length > 0) { type = content[0].toLowerCase().trim(); } } }); // waypoint.sym waypoint.getChild(ns, "sym").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { body = body.toLowerCase(); sym = body; if (body.indexOf("geocache") != -1 && body.indexOf("found") != -1) { cache.found = true; } } }); + + // for GPX 1.0, cache info comes from waypoint node (so called private children, + // for GPX 1.1 from extensions node + final Element cacheParent = version == 11 ? waypoint.getChild(ns, "extensions") : waypoint; for (String nsGC : nsGCList) { // waypoints.cache - final Element gcCache = waypoint.getChild(nsGC, "cache"); + final Element gcCache = cacheParent.getChild(nsGC, "cache"); gcCache.setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1) { cache.cacheid = attrs.getValue("id"); } if (attrs.getIndex("archived") > -1) { final String at = attrs.getValue("archived").toLowerCase(); if (at.equals("true")) { cache.archived = true; } else { cache.archived = false; } } if (attrs.getIndex("available") > -1) { final String at = attrs.getValue("available").toLowerCase(); if (at.equals("true")) { cache.disabled = false; } else { cache.disabled = true; } } } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse cache attributes."); } } }); // waypoint.cache.name gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String content = Html.fromHtml(body).toString().trim(); cache.name = content; } }); // waypoint.cache.owner gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String content = Html.fromHtml(body).toString().trim(); cache.owner = content; } }); // waypoint.cache.type gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String content = cgBase.cacheTypes.get(body.toLowerCase()); cache.type = content; } }); // waypoint.cache.container gcCache.getChild(nsGC, "container").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String content = body.toLowerCase(); cache.size = content; } }); // waypoint.cache.difficulty gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { try { cache.difficulty = new Float(body); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse difficulty: " + e.toString()); } } }); // waypoint.cache.terrain gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { try { cache.terrain = new Float(body); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse terrain: " + e.toString()); } } }); // waypoint.cache.country gcCache.getChild(nsGC, "country").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { if (cache.location == null || cache.location.length() == 0) { cache.location = body.trim(); } else { cache.location = cache.location + ", " + body.trim(); } } }); // waypoint.cache.state gcCache.getChild(nsGC, "state").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { if (cache.location == null || cache.location.length() == 0) { cache.location = body.trim(); } else { cache.location = body.trim() + ", " + cache.location; } } }); // waypoint.cache.encoded_hints gcCache.getChild(nsGC, "encoded_hints").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { cache.hint = body.trim(); } }); // waypoint.cache.short_description gcCache.getChild(nsGC, "short_description").setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { try { if (attrs.getIndex("html") > -1) { final String at = attrs.getValue("html").toLowerCase(); if (at.equals("false")) { htmlShort = false; } } } catch (Exception e) { // nothing } } }); gcCache.getChild(nsGC, "short_description").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { if (htmlShort == false) { cache.shortdesc = Html.fromHtml(body).toString(); } else { cache.shortdesc = body; } } }); // waypoint.cache.long_description gcCache.getChild(nsGC, "long_description").setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { try { if (attrs.getIndex("html") > -1) { final String at = attrs.getValue("html").toLowerCase(); if (at.equals("false")) { htmlLong = false; } } } catch (Exception e) { // nothing } } }); gcCache.getChild(nsGC, "long_description").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { if (htmlLong == false) { cache.description = Html.fromHtml(body).toString().trim(); } else { cache.description = body; } } }); // waypoint.cache.travelbugs final Element gcTBs = gcCache.getChild(nsGC, "travelbugs"); // waypoint.cache.travelbugs.travelbug gcTBs.getChild(nsGC, "travelbug").setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { trackable = new cgTrackable(); try { if (attrs.getIndex("ref") > -1) { trackable.geocode = attrs.getValue("ref").toUpperCase(); } } catch (Exception e) { // nothing } } }); // waypoint.cache.travelbug final Element gcTB = gcTBs.getChild(nsGC, "travelbug"); gcTB.setEndElementListener(new EndElementListener() { public void end() { if (trackable.geocode != null && trackable.geocode.length() > 0 && trackable.name != null && trackable.name.length() > 0) { if (cache.inventory == null) cache.inventory = new ArrayList<cgTrackable>(); cache.inventory.add(trackable); } } }); // waypoint.cache.travelbugs.travelbug.name gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { String content = Html.fromHtml(body).toString(); trackable.name = content; } }); // waypoint.cache.logs final Element gcLogs = gcCache.getChild(nsGC, "logs"); // waypoint.cache.log final Element gcLog = gcLogs.getChild(nsGC, "log"); gcLog.setStartElementListener(new StartElementListener() { public void start(Attributes attrs) { log = new cgLog(); try { if (attrs.getIndex("id") > -1) { log.id = Integer.parseInt(attrs.getValue("id")); } } catch (Exception e) { // nothing } } }); gcLog.setEndElementListener(new EndElementListener() { public void end() { if (log.log != null && log.log.length() > 0) { if (cache.logs == null) cache.logs = new ArrayList<cgLog>(); cache.logs.add(log); } } }); // waypoint.cache.logs.log.date gcLog.getChild(nsGC, "date").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { try { log.date = cgBase.dateGPXIn.parse(body.trim()).getTime(); } catch (Exception e) { Log.w(cgSettings.tag, "Failed to parse log date: " + e.toString()); } } }); // waypoint.cache.logs.log.type gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { final String content = body.trim().toLowerCase(); if (cgBase.logTypes0.containsKey(content) == true) { log.type = cgBase.logTypes0.get(content); } else { log.type = 4; } } }); // waypoint.cache.logs.log.finder gcLog.getChild(nsGC, "finder").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { String content = Html.fromHtml(body).toString(); log.author = content; } }); // waypoint.cache.logs.log.finder gcLog.getChild(nsGC, "text").setEndTextElementListener(new EndTextElementListener() { public void end(String body) { String content = Html.fromHtml(body).toString(); log.log = content; } }); } try { Xml.parse(new FileInputStream(file), Xml.Encoding.UTF_8, root.getContentHandler()); return search.getCurrentId(); } catch (Exception e) { Log.e(cgSettings.tag, "Cannot parse .gpx file " + file.getAbsolutePath() + " as GPX " + version + ": " + e.toString()); } return 0l; } }
false
false
null
null
diff --git a/LunchList/src/edu/mines/csci498/bwisdom/lunchlist/DetailForm.java b/LunchList/src/edu/mines/csci498/bwisdom/lunchlist/DetailForm.java index 9aedcb7..80f0e85 100644 --- a/LunchList/src/edu/mines/csci498/bwisdom/lunchlist/DetailForm.java +++ b/LunchList/src/edu/mines/csci498/bwisdom/lunchlist/DetailForm.java @@ -1,31 +1,14 @@ package edu.mines.csci498.bwisdom.lunchlist; -import android.app.Activity; -import android.content.Intent; -import android.database.Cursor; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; import android.os.Bundle; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.RadioGroup; -import android.widget.TextView; -import android.widget.Toast; -import android.util.Log; +import android.support.v4.app.FragmentActivity; -public class DetailForm extends Activity { +public class DetailForm extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.detail_activity); } }
false
false
null
null
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/host/XMLDocument.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/host/XMLDocument.java index 3aab5760d..d7e64fcd4 100644 --- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/host/XMLDocument.java +++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/host/XMLDocument.java @@ -1,335 +1,335 @@ /* * Copyright (c) 2002-2008 Gargoyle Software Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: * * "This product includes software developed by Gargoyle Software Inc. * (http://www.GargoyleSoftware.com/)." * * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * 4. The name "Gargoyle Software" must not be used to endorse or promote * products derived from this software without prior written permission. * For written permission, please contact info@GargoyleSoftware.com. * 5. Products derived from this software may not be called "HtmlUnit", nor may * "HtmlUnit" appear in their name, without prior written permission of * Gargoyle Software Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 GARGOYLE * SOFTWARE INC. OR ITS 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.gargoylesoftware.htmlunit.javascript.host; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.mozilla.javascript.Context; import com.gargoylesoftware.htmlunit.WebRequestSettings; import com.gargoylesoftware.htmlunit.WebResponse; import com.gargoylesoftware.htmlunit.WebResponseData; import com.gargoylesoftware.htmlunit.WebResponseImpl; import com.gargoylesoftware.htmlunit.WebWindow; import com.gargoylesoftware.htmlunit.html.DomCData; import com.gargoylesoftware.htmlunit.html.DomComment; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.DomText; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.SimpleScriptable; import com.gargoylesoftware.htmlunit.xml.XmlAttr; import com.gargoylesoftware.htmlunit.xml.XmlElement; import com.gargoylesoftware.htmlunit.xml.XmlPage; /** * A JavaScript object for XMLDocument. * * @version $Revision$ * @author Ahmed Ashour */ public class XMLDocument extends Document { private static final long serialVersionUID = 1225601711396578064L; private boolean async_ = true; private boolean preserveWhiteSpace_; private XMLDOMParseError parseError_; /** * Creates a new instance. JavaScript objects must have a default constructor. */ public XMLDocument() { this(null); } /** * Creates a new instance, with associated XmlPage. * @param enclosingWindow */ XMLDocument(final WebWindow enclosingWindow) { if (enclosingWindow != null) { try { final XmlPage page = new XmlPage((WebResponse) null, enclosingWindow); setDomNode(page); } catch (final IOException e) { throw Context.reportRuntimeError("IOException: " + e); } } } /** * Sets the <tt>async</tt> attribute. * @param async Whether or not to send the request to the server asynchronously. */ public void jsxSet_async(final boolean async) { this.async_ = async; } /** * Returns Whether or not to send the request to the server asynchronously. * @return the <tt>async</tt> attribute. */ public boolean jsxGet_async() { return async_; } /** * Loads an XML document from the specified location. * * @param xmlSrouce A string containing a URL that specifies the location of the XML file. * @return true if the load succeeded; false if the load failed. */ public boolean jsxFunction_load(final String xmlSrouce) { if (async_) { getLog().debug("XMLDocument.load(): 'async' is true, currently treated as false."); } try { final HtmlPage htmlPage = (HtmlPage) getWindow().getWebWindow().getEnclosedPage(); final WebRequestSettings settings = new WebRequestSettings(htmlPage.getFullyQualifiedUrl(xmlSrouce)); final WebResponse webResponse = getWindow().getWebWindow().getWebClient().loadWebResponse(settings); final XmlPage page = new XmlPage(webResponse, getWindow().getWebWindow(), false); setDomNode(page); return true; } catch (final IOException e) { final XMLDOMParseError parseError = jsxGet_parseError(); parseError.setErrorCode(-1); parseError.setFilepos(1); parseError.setLine(1); parseError.setLinepos(1); parseError.setReason(e.getMessage()); parseError.setSrcText("xml"); parseError.setUrl(xmlSrouce); getLog().debug("Error parsing XML from '" + xmlSrouce + "'", e); return false; } } /** * Loads an XML document using the supplied string. * * @param strXML A string containing the XML string to load into this XML document object. * This string can contain an entire XML document or a well-formed fragment. * @return true if the load succeeded; false if the load failed. */ public boolean jsxFunction_loadXML(final String strXML) { try { final List<NameValuePair> emptyList = Collections.emptyList(); final WebResponseData data = new WebResponseData(strXML.getBytes(), HttpStatus.SC_OK, null, emptyList); final WebResponse webResponse = new WebResponseImpl(data, null, null, 0); final XmlPage page = new XmlPage(webResponse, getWindow().getWebWindow()); setDomNode(page); return true; } catch (final IOException e) { getLog().debug("Error parsing XML\n" + strXML, e); return false; } } /** * {@inheritDoc} */ @Override protected Object getWithPreemption(final String name) { return NOT_FOUND; } /** * {@inheritDoc} */ @Override public SimpleScriptable makeScriptableFor(final DomNode domNode) { final SimpleScriptable scriptable; if (domNode instanceof XmlElement) { scriptable = new XMLElement(); } else if (domNode instanceof XmlAttr) { final XMLAttribute attribute = new XMLAttribute(); attribute.init(domNode.getNodeName(), (XmlElement) domNode.getParentDomNode()); scriptable = attribute; } else if (domNode instanceof DomText || domNode instanceof DomCData || domNode instanceof DomComment) { scriptable = new TextImpl(); } else { throw new IllegalArgumentException("Can not make scriptable for " + domNode); } scriptable.setPrototype(getPrototype(scriptable.getClass())); scriptable.setParentScope(getParentScope()); scriptable.setDomNode(domNode); return scriptable; } /** * Gets the JavaScript property "documentElement" for the document. * @return The root node for the document. */ //TODO: should be removed, as super.jsxGet_documentElement should not be Html dependent @Override public SimpleScriptable jsxGet_documentElement() { final XmlElement documentElement = ((XmlPage) getDomNodeOrDie()).getDocumentXmlElement(); if (documentElement == null) { return null; } return getScriptableFor(documentElement); } /** * Gets the JavaScript property "parseError" for the document. * @return The ParserError object for the document. */ public XMLDOMParseError jsxGet_parseError() { if (parseError_ == null) { parseError_ = new XMLDOMParseError(); parseError_.setPrototype(getPrototype(parseError_.getClass())); parseError_.setParentScope(getParentScope()); } return parseError_; } /** * Contains the XML representation of the node and all its descendants. * @return An XML representation of this node and all its descendants. */ public String jsxGet_xml() { final XMLSerializer seralizer = new XMLSerializer(); seralizer.setParentScope(getWindow()); seralizer.setPrototype(getPrototype(seralizer.getClass())); return seralizer.jsxFunction_serializeToString((Node) jsxGet_documentElement()); } /** * Gets the current white space handling. * @return the current white space handling. */ public boolean jsxGet_preserveWhiteSpace() { return preserveWhiteSpace_; } /** * Specifies the white space handling. * @param preserveWhiteSpace white space handling. */ public void jsxSet_preserveWhiteSpace(final boolean preserveWhiteSpace) { this.preserveWhiteSpace_ = preserveWhiteSpace; } /** * This method is used to set * <a href="http://msdn2.microsoft.com/en-us/library/ms766391.aspx">second-level properties</a> * on the DOM object. * * @param name The name of the property to be set. * @param value The value of the specified property. */ public void jsxFunction_setProperty(final String name, final String value) { //empty implementation } /** * Applies the specified xpath expression to this node's context and returns the generated list of matching nodes. * @param expression A string specifying an XPath expression. * @return list of the found elements. */ public HTMLCollection jsxFunction_selectNodes(final String expression) { final HTMLCollection collection = new HTMLCollection(this); collection.init(getDomNodeOrDie(), expression); return collection; } /** * Applies the specified pattern-matching operation to this node's context and returns the first matching node. * @param expression A string specifying an XPath expression. * @return the first node that matches the given pattern-matching operation. * If no nodes match the expression, returns a null value. */ public Object jsxFunction_selectSingleNode(final String expression) { final HTMLCollection collection = jsxFunction_selectNodes(expression); if (collection.jsxGet_length() > 0) { return collection.get(0, collection); } else { return null; } } /** * Returns all the descendant elements with the specified tag name. * @param tagName the name to search for. * @return all the descendant elements with the specified tag name. */ @Override - public Object jsxFunction_getElementsByTagName(final String tagName) { + public HTMLCollection jsxFunction_getElementsByTagName(final String tagName) { final HTMLCollection collection = new HTMLCollection(this); collection.init(getDomNodeOrDie().getFirstDomChild(), "//" + tagName); return collection; } /** * {@inheritDoc} * Returns {@link #NOT_FOUND}. */ @Override public Object jsxGet_body() { return NOT_FOUND; } /** * {@inheritDoc} */ @Override public Object jsxFunction_getElementById(final String id) { return null; } /** * {@inheritDoc} */ @Override protected boolean limitAppendChildToIE() { return false; } }
true
false
null
null
diff --git a/RestFB/source/library/com/restfb/package-info.java b/RestFB/source/library/com/restfb/package-info.java index 1db17fd2..ae720465 100644 --- a/RestFB/source/library/com/restfb/package-info.java +++ b/RestFB/source/library/com/restfb/package-info.java @@ -1,26 +1,28 @@ /* * Copyright (c) 2010 Mark Allen. * * 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. */ /** - * TODO: RestFB tutorial. + * <a href="http://restfb.com">RestFB</a> is a simple and flexible <a href="http://wiki.developers.facebook.com/index.php/API">Facebook REST API</a> client. + * <p> + * For full documentation and sample code, please see <a href="http://restfb.com">the RestFB website</a>. */ package com.restfb; \ No newline at end of file
true
false
null
null
diff --git a/src/net/cscott/sdr/package-info.java b/src/net/cscott/sdr/package-info.java index 38cfed9..372189a 100644 --- a/src/net/cscott/sdr/package-info.java +++ b/src/net/cscott/sdr/package-info.java @@ -1,27 +1,28 @@ /** * This package contains the main game class ({@link net.cscott.sdr.App}) and * a text UI ({@link net.cscott.sdr.PMSD}), as well as interface * definitions needed to tie the various pieces together. * @doc.test Run all PMSD <a href="doc-files/">test cases</a>: * (fail-first development: note which cases are currently failing) * js> PMSD.runAllTests() * FAILED TESTS: - * acey-deucey-1 at line 55 + * acey-deucey-1 at line 79 * acey-deucey-2 at line 22 * acey-deucey-3 at line 15 + * acey-deucey-5 at line 117 * breathing-2 at line 26 * cast-1 at line 69 * concentric-1 at line 83 * cross-fold-1 at line 20 * dopaso-1 at line 39 * hinge-1 at line 36 * parse-2 at line 7 * pass-to-the-center-2 at line 8 * pass-to-the-center-3 at line 26 * peel-the-top-1 at line 32 * siamese-1 at line 30 * sweep-3 at line 23 * trade-2 at line 13 * trade-by at line 43 */ package net.cscott.sdr;
false
false
null
null
diff --git a/src/net/colar/netbeans/fan/indexer/FanIndexerFactory.java b/src/net/colar/netbeans/fan/indexer/FanIndexerFactory.java index f440887..ab5bdae 100644 --- a/src/net/colar/netbeans/fan/indexer/FanIndexerFactory.java +++ b/src/net/colar/netbeans/fan/indexer/FanIndexerFactory.java @@ -1,88 +1,86 @@ /* * Thibaut Colar Sep 2, 2009 */ package net.colar.netbeans.fan.indexer; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.netbeans.modules.parsing.api.Snapshot; import org.netbeans.modules.parsing.spi.indexing.Context; import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer; import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory; import org.netbeans.modules.parsing.spi.indexing.Indexable; import org.netbeans.modules.parsing.spi.indexing.support.IndexingSupport; /** * Indexer Factory impl. * @author thibautc */ public class FanIndexerFactory extends EmbeddingIndexerFactory { static{System.err.println("Fantom - Init indexer Factory");} public static final String NAME = "FanIndexer"; public static final int VERSION = 1; @Override public EmbeddingIndexer createIndexer(Indexable indexable, Snapshot snapshot) { if (snapshot.getSource().getFileObject() != null) { return new FanIndexer(); } return null; } @Override - public void filesDeleted(Collection<? extends Indexable> deleted, Context context) + public void filesDeleted(Iterable<? extends Indexable> deleted, Context context) { try { IndexingSupport is = IndexingSupport.getInstance(context); Iterator<? extends Indexable> it = deleted.iterator(); while (it.hasNext()) { is.removeDocuments(it.next()); } } catch (IOException e) { e.printStackTrace(); } } @Override - public void filesDirty(Collection<? extends Indexable> dirty, Context context) + public void filesDirty(Iterable<? extends Indexable> iterable, Context context) { try { IndexingSupport is = IndexingSupport.getInstance(context); - Iterator<? extends Indexable> it = dirty.iterator(); + Iterator<? extends Indexable> it = iterable.iterator(); while (it.hasNext()) { is.markDirtyDocuments(it.next()); } } catch (IOException e) { e.printStackTrace(); } } @Override public String getIndexerName() { return NAME; } @Override public int getIndexVersion() { return VERSION; } - - }
false
false
null
null
diff --git a/src/jgossit/server/Scoreboard.java b/src/jgossit/server/Scoreboard.java index 10df539..9445712 100644 --- a/src/jgossit/server/Scoreboard.java +++ b/src/jgossit/server/Scoreboard.java @@ -1,243 +1,245 @@ package jgossit.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Scoreboard extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String league = req.getParameter("league"); String date = req.getParameter("date"); if (league == null || date == null) resp.sendRedirect("scoreboard.html"); getScoreboard(league, date, resp.getWriter()); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { doPost(req, resp); } private static final String TEAMSCORE_CLASS = "ysptblclbg5"; private static final String SCORES_CLASS = "yspscores"; private static final String SCOREBOARD_CLASS = "scores"; private static final String SCOREBOARD_DIV_ID = "nba:scoreboard"; private static final String JQUERY_CODE = "<link type=\"text/css\" href=\"jquery-ui.css\" rel=\"Stylesheet\"/>\n" + "<script type=\"text/javascript\" src=\"jquery-1.9.1.js\"></script>\n" + "<script type=\"text/javascript\" src=\"jquery-ui.js\"></script>\n" + "<script>\n" + " window.onload=function()\n" + " {\n" + " $(\"tr.ysptblclbg5 td[class='yspscores'], tr.ysptblclbg5 td span[class='yspscores']:even\").click(function () {\n" + " $(this).css(\"border\", \"none\").css(\"color\",\"black\");\n" + " });\n" + "\n" + " $(\"table.scores + table\").click(function () {\n" + " $(this).children().css(\"visibility\",\"visible\");\n" + " $(this).css(\"border\", \"none\");\n" + " });\n" + " };\n" + "</script>"; private void getScoreboard(String league, String date, PrintWriter printWriter) throws IOException { String address = "http://sports.yahoo.com/" + league + "/scoreboard?d=" + date; URL url = new URL(address); HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.setUseCaches(false); urlConnection.setDefaultUseCaches(false); urlConnection.addRequestProperty("Cache-Control", "no-cache,max-age=0"); urlConnection.addRequestProperty("Pragma", "no-cache"); BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line = null; boolean inScoreHeader = false; boolean inTeamScore = false; boolean recapTableNext = false; boolean inRecapTable = false; boolean inBody = false; boolean inScoreboard = false; int periods = 0; int[] homeScores = {0,0,0,0}; int[] awayScores = {0,0,0,0}; boolean awayTeam = true; boolean overtime = false; while ((line = br.readLine()) != null) { if (line.equals("</head>")) printWriter.println(JQUERY_CODE); if (line.contains("class=\"" + TEAMSCORE_CLASS + "\"")) inTeamScore = true; if (line.contains("class=\"" + SCOREBOARD_CLASS + "\"")) inScoreHeader = true; if(inBody) { if (!line.contains(SCOREBOARD_DIV_ID)) continue; else { inBody = false; inScoreboard = true; } } if (inScoreboard && line.startsWith("</div><script")) // end of scoreboard { line = "</div>\n</body>\n</html>"; printWriter.println(line); break; } if(inTeamScore) { if (line.contains("</tr>")) { inTeamScore = false; recapTableNext = true; } else { line = line.replaceFirst("img ", "img style='visibility:hidden' "); // hide winner image if (line.contains("td class=\"" + SCORES_CLASS + "\"")) { line = line.replaceFirst("class=", "style='border:1px dotted red;color:EEEEDD' class="); if (line.indexOf(">")+1 == line.indexOf("</")) // pad quarter scores line = line.replaceFirst(">",">00"); else if (line.indexOf(">")+2 == line.indexOf("</")) line = line.replaceFirst(">",">0"); periods++; if (periods < 5) { - int periodScore = Integer.parseInt(line.substring(line.indexOf(">")+1, line.indexOf("</"))); + int periodScore = 0; + if (!line.contains("&nbsp;")) + periodScore = Integer.parseInt(line.substring(line.indexOf(">")+1, line.indexOf("</"))); int cumulativeScore = 0; if (awayTeam) { awayScores[periods-1] = periodScore; for (int i=0;i<periods;i++) cumulativeScore += awayScores[i]; } else { homeScores[periods-1] = periodScore; for (int i=0;i<periods;i++) cumulativeScore += homeScores[i]; } if (periods > 1) line = line.replaceFirst("</","(" + cumulativeScore + ")</"); } } else if(!line.contains("<td") && line.contains("span class=\"" + SCORES_CLASS + "\"")) { line = line.replaceFirst("class=", "style='border:1px dotted red;color:FFFFCC' class="); if (line.contains("<b>")) // pad winner total score { if (line.indexOf(">")+10 == line.indexOf("</span")) // less than 100 line = line.replaceFirst(">",">0"); else if (line.indexOf(">")+9 == line.indexOf("</span")) // less than 10? line = line.replaceFirst(">",">00"); } else // pad loser total score { if (line.indexOf(">")+3 == line.indexOf("</span")) // less than 100 line = line.replaceFirst(">",">0"); else if (line.indexOf(">")+2 == line.indexOf("</span")) // less than 10? line = line.replaceFirst(">",">00"); } awayTeam = false; } else if (line.contains("<td") && line.contains("span class=\"" + SCORES_CLASS + "\"")) { line = line.replaceFirst(">\\d?OT<","><"); // hide OT/2OT/3OT text } else if (periods > 0 && !line.contains("<td")) // add up to 3 dummy OT period scores { for (int i=7;i>periods;i--) line = "<td style='border:1px dotted red;color:EEEEDD' class=\"yspscores\">00</td>\n" + line; if (periods > 4) overtime = true; periods = 0; } } } if (inScoreHeader) { line = line.replaceFirst("width=\"25\"","width=\"40\""); // resize to fit cumulative scores if (line.contains("colspan")) // minor border glitch line = line.substring(0, line.indexOf("colspan")+9) + "21" + line.substring(line.indexOf("colspan")+11); if (line.endsWith(">4</td>")) // add 3 dummy(?) OT period columns { line += "\n<td rowspan=\"5\" width=\"1\" class=\"yspwhitebg\"></td>\n<td width=\"40\" class=\"yspscores\">OT?</td>"; line += "\n<td rowspan=\"5\" width=\"1\" class=\"yspwhitebg\"></td>\n<td width=\"40\" class=\"yspscores\">2OT?</td>"; line += "\n<td rowspan=\"5\" width=\"1\" class=\"yspwhitebg\"></td>\n<td width=\"40\" class=\"yspscores\">3OT?</td>"; while (br.readLine().contains("<td")) // get to the empty line between quarters/overtimes and total continue; inScoreHeader = false; } } if (inRecapTable && line.contains("</table>")) // finished this game { printWriter.println("</tbody>\n</table>\n</td>\n</tr>\n<tr><td>\n<table>"); // additional convenience items int awayAfter3 = awayScores[0]+awayScores[1]+awayScores[2]; int homeAfter3 = homeScores[0]+homeScores[1]+homeScores[2]; int awayAfter4 = awayAfter3+awayScores[3]; int homeAfter4 = homeAfter3+homeScores[3]; boolean within8After3 = (awayAfter3 - 8 <= homeAfter3) && (homeAfter3 - 8 <= awayAfter3); boolean within8After4 = (awayAfter4 - 8 <= homeAfter4) && (homeAfter4 - 8 <= awayAfter4); printWriter.println("<tr class=\"ysptblclbg5\" style=\"background-color:F4F5F1\"><td>Within 8 after third quarter?</td><td class=\"yspscores\" style=\"font-family: 'Courier New', monospace;border:1px dotted red;color:F4F5F1\">" + (within8After3 ? "Yes" : "No&nbsp;") + "</td></tr>"); printWriter.println("<tr class=\"ysptblclbg5\" style=\"background-color:F4F5F1\"><td>Within 8 after fourth quarter?</td><td class=\"yspscores\" style=\"font-family: 'Courier New', monospace;border:1px dotted red;color:F4F5F1\">" + (within8After4 ? "Yes" : "No&nbsp;") + "</td></tr>"); printWriter.println("<tr class=\"ysptblclbg5\" style=\"background-color:F4F5F1\"><td>Overtime?</td><td class=\"yspscores\" style=\"font-family: 'Courier New', monospace;border:1px dotted red;color:F4F5F1\">" + (overtime ? "Yes" : "No&nbsp;") + "</td></tr>"); overtime = false; inRecapTable = false; awayTeam = true; homeScores = new int[]{0,0,0,0}; awayScores = new int[]{0,0,0,0}; } if (recapTableNext) { if (!awayTeam && line.contains("colspan")) // minor border glitch line = line.substring(0, line.indexOf("colspan")+9) + "21" + line.substring(line.indexOf("colspan")+11); if (line.contains("<table")) { line = line.replaceFirst("table ", "table style='border:1px dotted red' "); line += "\n<tbody style=\"visibility: hidden\">"; inRecapTable = true; recapTableNext = false; } } if (line.startsWith("<body")) inBody = true; printWriter.println(line); } br.close(); urlConnection.disconnect(); } } \ No newline at end of file
true
false
null
null
diff --git a/src/plugins/WebOfTrust/SubscriptionManager.java b/src/plugins/WebOfTrust/SubscriptionManager.java index b73eddfa..96dc5768 100644 --- a/src/plugins/WebOfTrust/SubscriptionManager.java +++ b/src/plugins/WebOfTrust/SubscriptionManager.java @@ -1,1254 +1,1254 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.WebOfTrust; import java.util.UUID; import plugins.WebOfTrust.Identity.IdentityID; import plugins.WebOfTrust.exceptions.DuplicateObjectException; import plugins.WebOfTrust.exceptions.UnknownIdentityException; import com.db4o.ObjectSet; import com.db4o.ext.ExtObjectContainer; import com.db4o.query.Query; import freenet.node.PrioRunnable; import freenet.pluginmanager.PluginRespirator; import freenet.support.Logger; import freenet.support.TrivialTicker; import freenet.support.codeshortification.IfNull; import freenet.support.io.NativeThread; /** * The subscription manager allows client application to subscribe to certain data sets of WoT and get notified on change. * For example, if you subscribe to the list of identities, you will get a notification when an identity is added or removed. * * The architecture of this class supports implementing different types of subscriptions: Currently, only FCP is implemented, but it is also technically possible to have subscriptions * which do a callback within the WoT plugin or maybe even via OSGI. * * The class/object model is as following: * - There is exactly one SubscriptionManager object running in the WOT plugin. It is the interface for clients. * - Subscribing to something yields a {@link Subscription} object which is stored by the SubscriptionManager in the database. Clients do not need to keep track of it. They only need to know its ID. * - When an event happens, a {@link Notification} object is created for each {@link Subscription} which matches the type of event. The Notification is stored in the database. * - After a delay, the SubscriptionManager deploys the notifications to the clients. * * The {@link Notification}s are deployed strictly sequential per {@link Subscription}. * If a single Notification cannot be deployed, the processing of the Notifications for that Subscription is halted until the failed * Notification can be deployed successfully. * This especially applies to the FCP-client-interface and all other client interfaces: If a client returns "ERROR!" from the callback it has received, * the notification queue is halted and the previous notification is re-sent a few times until it can be imported successfully by the client * or the connection is dropped due to too many failures. * * TODO: What to do, if the client does not support a certain message? * * This is a very important principle which makes client design easy: You do not need transaction-safety when caching things such as score values * incrementally. For example your client might need to do mandatory actions due to a score-value change, such as deleting messages from identities * which have a bad score now. If the score-value import succeeds but the message deletion fails, you can just return "ERROR!" to the WOT-callback-caller * (and maybe even keep your score-cache as is) - you will continue to receive the notification about the changed score value for which the import failed, * you will not receive change-notifications after that. This ensures that your consistency is not destroyed: There will be no missing slot * in the incremental change chain. * FIXME: AFAIK the FCP-client does not support the above yet, this is a MUST-have feature needed by Freetalk, check whether it works. * * <b>Synchronization:</b> * The locking order must be: * synchronized(instance of WebOfTrust) { * synchronized(instance of IntroductionPuzzleStore) { * synchronized(instance of IdentityFetcher) { * synchronized(instance of SubscriptionManager) { * synchronized(Persistent.transactionLock(instance of ObjectContainer)) { * * TODO: Allow out-of-order notifications if the client desires them * TODO: Optimization: Allow coalescing of notifications: If a single object changes twice, only send one notification * TODO: Optimization: Allow the client to specify filters to reduce traffic: - Context of identities, etc. * * * TODO: This should be used for powering the IntroductionClient/IntroductionServer. * * @author xor (xor@freenetproject.org) */ public final class SubscriptionManager implements PrioRunnable { /** * A subscription stores the information which client is subscribed to which content and how it is supposed * to be notified about updates. * Subscriptions are stored one per {@link Notification}-type and per way of notification: * Because we want the notification queue to block on error, a single subscription does not support * multiple ways of notifying the client. * * Notice: Even though this is an abstract class, it contains code specific <b>all</>b> types of subscription clients such as FCP and callback. * At first glance, this looks like a violation of abstraction principles. But it is not: * Subclasses of this class shall NOT be created for different types of clients such as FCP and callbacks. * Subclasses are created for different types of content to which the subscriber is subscribed: There is a subclass for subscriptions to the * list of {@link Identity}s, the list of {@link Trust}s, and so on. Each subclass has to implement the code for notifying <b>all</b> types * of clients (FCP, callback, etc.). * Therefore, this base class also contains code for <b>all</b> kinds of clients. */ @SuppressWarnings("serial") public static abstract class Subscription<NotificationType extends Notification> extends Persistent { /** * The UUID of this Subscription. Stored as String for db4o performance, but must be valid in terms of the UUID class. * * @see #getID() */ @IndexedField private final String mID; /** * The way of notifying a client */ public static enum Type { FCP, Callback }; /** * The way the client of this subscription desires notification. * * @see #getType() */ private final Type mType; /** * An ID which associates this subscription with a FCP connection if the type is FCP. * * @see #getFCP_ID() */ @IndexedField private final String mFCP_ID; /** * Each {@link Notification} is given an index upon creation. The indexes ensure sequential processing. * If an error happens when trying to process a notification to a client, we might want to retry some time later. * Therefore, the {@link Notification} queue exists per client and not globally - if a single {@link Notification} is created by WoT, * multiple {@link Notification} objects are stored - one for each Subscription. */ private long mNextNotificationIndex = 0; /** * Constructor for being used by child classes. * @param myType The type of the Subscription * @param fcpID The FCP ID of the subscription. Can be null if the type is not FCP. */ protected Subscription(Type myType, String fcpID) { mID = UUID.randomUUID().toString(); mType = myType; mFCP_ID = fcpID; } /** * {@inheritDoc} */ @Override public void startupDatabaseIntegrityTest() throws Exception { checkedActivate(1); // 1 is the maximum needed depth of all stuff we use in this function IfNull.thenThrow(mID, "mID"); UUID.fromString(mID); // Throws if invalid IfNull.thenThrow(mType, "mType"); if(mType == Type.FCP) IfNull.thenThrow(mFCP_ID, "mFCP_ID"); if(mNextNotificationIndex < 0) throw new IllegalStateException("mNextNotificationIndex==" + mNextNotificationIndex); } /** * You must call {@link #initializeTransient} before using this! */ protected final SubscriptionManager getSubscriptionManager() { return mWebOfTrust.getSubscriptionManager(); } /** * @return The UUID of this Subscription. Stored as String for db4o performance, but must be valid in terms of the UUID class. * @see #mID */ public final String getID() { checkedActivate(1); return mID; } /** * @return The {@link Type} of this Subscription. * @see #mType */ public final Type getType() { checkedActivate(1); return mType; } /** * @return An ID which associates this subscription with a FCP connection if the type is FCP. * @see #mFCP_ID */ public final String getFCP_ID() { if(getType() != Type.FCP) throw new UnsupportedOperationException("Type is not FCP:" + getType()); checkedActivate(1); return mFCP_ID; } /** * Returns the next free index for a {@link Notification} in the queue of this Subscription * and stores this Subscription object without committing the transaction. * * Schedules processing of the Notifications of the SubscriptionManger. */ protected final long takeFreeNotificationIndexWithoutCommit() { checkedActivate(1); final long index = mNextNotificationIndex++; storeWithoutCommit(); getSubscriptionManager().scheduleNotificationProcessing(); return index; } /** * ATTENTION: This does NOT delete the {@link Notification} objects associated with this Subscription! * Only use it if you delete them manually before! * * - Deletes this {@link Subscription} from the database. Does not commit the transaction and does not take care of synchronization. */ @Override protected void deleteWithoutCommit() { throw new UnsupportedOperationException("Need a SubscriptionManager"); } /** * Deletes this Subscription and - using the passed in {@link SubscriptionManager} - also deletes all * queued {@link Notification}s of it. Does not commit the transaction. * * @param manager The {@link SubscriptionManager} to which this Subscription belongs. */ protected void deleteWithoutCommit(final SubscriptionManager manager) { for(final Notification notification : manager.getAllNotifications(this)) { notification.deleteWithoutCommit(); } super.deleteWithoutCommit(); } /** * Takes the database lock to begin a transaction, stores this object and commits the transaction. * You must synchronize on the {@link SubscriptionManager} while calling this function. */ protected void storeAndCommit() { synchronized(Persistent.transactionLock(mDB)) { try { storeWithoutCommit(); checkedCommit(this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } /** * Called by this subscription when processing an {@link InitialSynchronizationNotification}. * * Upon creation of a Subscription, such a notification is stored immediately, i.e. not triggered by an event. * When real events happen, we only want to send a "diff" between the last state of the database before the event happened and the new state. * For being able to only send a diff, the subscriber must know what the <i>initial</i> state of the database was. * And thats the purpose of this function: To send the full initial state of the database to the client. * * For example, if a client subscribes to the list of identities, it must always receive a full list of all existing identities at first. * As new identities appear afterwards, the client can be kept up to date by sending each single new identity as it appears. * * @see InitialSynchronizationNotification */ protected abstract void synchronizeSubscriberByFCP() throws Exception; /** * Called by this Subscription when the type of it is FCP and a {@link Notification} shall be sent via FCP. * The implementation MUST throw a {@link RuntimeException} if the FCP message was not sent successfully: * Subscriptions are supposed to be reliable, if transmitting a {@link Notification} fails it shall * be resent. * * @param notification The {@link Notification} to send out via FCP. */ protected abstract void notifySubscriberByFCP(NotificationType notification) throws Exception; /** * Sends out the notification queue for this Subscription, in sequence. * * If a notification is sent successfully, it is deleted and the transaction is committed. * If sending a single notification fails, the transaction for the current Notification is rolled back * and an exception is thrown. * * You have to synchronize on the WoT, the SubscriptionManager and the database lock before calling this * function! * You don't have to commit the transaction after calling this function. * * @param manager The {@link SubscriptionManager} from which to query the {@link Notification}s of this Subscription. */ @SuppressWarnings("unchecked") protected void sendNotifications(SubscriptionManager manager) { switch(mType) { case FCP: for(final Notification notification : manager.getAllNotifications(this)) { try { try { if(notification instanceof InitialSynchronizationNotification) { synchronizeSubscriberByFCP(); } else { notifySubscriberByFCP((NotificationType)notification); notification.deleteWithoutCommit(); } } catch(Exception e) { // Disconnected etc. throw new RuntimeException(e); } // If processing of a single notification fails, we do not want the previous notifications // to be sent again when the failed notification is retried. Therefore, we commit after // each processed notification but do not catch RuntimeExceptions here Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } break; default: throw new UnsupportedOperationException("Unknown Type: " + mType); } } } /** * An object of type Notification is stored when an event happens to which a client is possibly subscribed. * The SubscriptionManager will wake up some time after that, pull all notifications from the database and process them. */ @SuppressWarnings("serial") public static abstract class Notification extends Persistent { /** * The {@link Subscription} to which this Notification belongs */ @IndexedField private final Subscription<? extends Notification> mSubscription; /** * The index of this Notification in the queue of its {@link Subscription}: * Notifications are supposed to be sent out in proper sequence, therefore we use incremental indices. */ @IndexedField private final long mIndex; /** * Constructs a Notification in the queue of the given subscription. * Takes a free notification index from it with {@link Subscription#takeFreeNotificationIndexWithoutCommit} * * @param mySubscription The {@link Subscription} to whose Notification queue this Notification belongs. */ protected Notification(final Subscription<? extends Notification> mySubscription) { mSubscription = mySubscription; mIndex = mySubscription.takeFreeNotificationIndexWithoutCommit(); } /** * {@inheritDoc} */ @Override public void startupDatabaseIntegrityTest() throws Exception { checkedActivate(1); // 1 is the maximum needed depth of all stuff we use in this function IfNull.thenThrow(mSubscription); if(mIndex < 0) throw new IllegalStateException("mIndex==" + mIndex); } } /** * This {@link Notification} is stored as the first Notification for all types of {@link Subscription} which require an initial synchronization of the client. * * Upon creation of a {@link Subscription}, such a notification is stored immediately, i.e. not triggered by an event. * When real events happen, we only want to send a "diff" between the last state of the database before the event happened and the new state. * For being able to only send a diff, the subscriber must know what the <i>initial</i> state of the database was. * And thats the purpose of this notification: To send the full initial state of the database to the client. * * For example, if a client subscribes to the list of identities, it must always receive a full list of all existing identities at first. * As new identities appear afterwards, the client can be kept up to date by sending each single new identity as it appears. * * @see Subscription#synchronizeSubscriberByFCP() The function which typically deploys this Notification. */ @SuppressWarnings("serial") protected static class InitialSynchronizationNotification extends Notification { /** * @param mySubscription The {@link Subscription} to whose {@link Notification} queue this {@link Notification} will belong. */ protected InitialSynchronizationNotification(Subscription<? extends Notification> mySubscription) { super(mySubscription); } } /** * This notification is issued when an {@link Identity} is added/deleted or its attributes change. * * It provides a {@link Identity#clone()} of the identity: * - before the change via {@link IdentityChangedNotification#getOldIdentity()} * - and and after the change via ({@link IdentityChangedNotification#getNewIdentity()} * - * If one of the before/after values is null, this is because the identity was added/deleted. - * If both are non-null, the identity was modified. + * If one of the before/after getters throws UnknownIdentityException, this is because the identity was added/deleted. + * If both do not throw, the identity was modified. * NOTICE: Modification can also mean that its class changed from {@link OwnIdentity} to {@link Identity} or vice versa! * * NOTICE: Both Identity objects are not stored in the database and must not be stored there to prevent duplicates! * * FIXME: The JavaDoc of this class should be used as inspiration for the JavaDoc of TrustChangedNotification / ScoreChangedNotification. * * @see IdentitiesSubscription The type of {@link Subscription} which deploys this notification. */ @SuppressWarnings("serial") protected static class IdentityChangedNotification extends Notification { /** * A serialized copy of the {@link Identity} before the change. * Null if the change was the creation of the identity. * If non-null its {@link Identity#getID()} must be equal to the one of {@link #mNewIdentity} if that member is non-null as well. * * @see Identity#serialize() * @see #getOldIdentity() The public getter for this. */ final byte[] mOldIdentity; /** * A serialized copy of the {@link Identity} after the change. * Null if the change was the deletion of the identity. * If non-null its {@link Identity#getID()} must be equal to the one of {@link #mOldIdentity} if that member is non-null as well. * * @see Identity#serialize() * @see #getNewIdentity() The public getter for this. */ final byte[] mNewIdentity; /** * @param mySubscription The {@link Subscription} to whose {@link Notification} queue this {@link Notification} belongs. * @param oldIdentity The version of the {@link Identity} before the change. * @param newIdentity The version of the {@link Identity} after the change. */ protected IdentityChangedNotification(final Subscription<? extends IdentityChangedNotification> mySubscription, final Identity oldIdentity, final Identity newIdentity) { super(mySubscription); mOldIdentity = (oldIdentity!=null ? oldIdentity.serialize() : null); mNewIdentity = (newIdentity!=null ? newIdentity.serialize() : null); assert ( (oldIdentity == null ^ newIdentity == null) || (oldIdentity != null && newIdentity != null && oldIdentity.getID().equals(newIdentity.getID())) ); } /** * {@inheritDoc} */ @Override public void startupDatabaseIntegrityTest() throws Exception { super.startupDatabaseIntegrityTest(); checkedActivate(1); // 1 is the maximum needed depth of all stuff we use in this function if(mOldIdentity == null && mNewIdentity == null) throw new NullPointerException("Only one of mOldIdentity and mNewIdentity may be null!"); final Identity oldIdentity = mOldIdentity != null ? (Identity)Persistent.deserialize(mWebOfTrust, mOldIdentity) : null; final Identity newIdentity = mNewIdentity != null ? (Identity)Persistent.deserialize(mWebOfTrust, mNewIdentity) : null; if(oldIdentity != null) oldIdentity.startupDatabaseIntegrityTest(); if(newIdentity != null) newIdentity.startupDatabaseIntegrityTest(); if(oldIdentity != null && newIdentity != null && !oldIdentity.getID().equals(newIdentity.getID())) throw new IllegalStateException("mOldIdentity and mNewIdentity must have the same ID!"); } /** * @return The {@link Identity} before the change. * @see #mOldIdentity The backend member variable of this getter. * @throws UnknownIdentityException If the change was the creation of the identity. */ protected final Identity getOldIdentity() throws UnknownIdentityException { checkedActivate(1); if(mOldIdentity == null) throw new UnknownIdentityException("The identity did not exist before."); return (Identity)Persistent.deserialize(mWebOfTrust, mOldIdentity); } /** * @return The {@link Identity} after the change. * @see #mNewIdentity The backend member variable of this getter. * @throws UnknownIdentityException If the change was the deletion of the identity. */ protected final Identity getNewIdentity() throws UnknownIdentityException { checkedActivate(1); if(mNewIdentity == null) throw new UnknownIdentityException("The was deleted."); return (Identity)Persistent.deserialize(mWebOfTrust, mNewIdentity); } } /** * This notification is issued when a {@link Trust} is added/deleted or its attributes change. * * FIXME: This should keep the ID of the trust instead of truster/trustee ID. Also, it should keep both the old and new ID, similar to {@link IdentityChangedNotification} * * @see TrustsSubscription The type of {@link Subscription} which deploys this notification. */ @SuppressWarnings("serial") protected static final class TrustChangedNotification extends Notification { /** * The ID of the truster of the changed {@link Trust}. * * @see Identity#getID() * @see Trust#getTruster() * @see #getTrusterID() */ private final String mTrusterID; /** * The ID of the trustee of the changed {@link Trust}. * * @see Identity#getID() * @see Trust#getTrustee() * @see #getTrusteeID() */ private final String mTrusteeID; /** * @param mySubscription The {@link Subscription} to whose {@link Notification} queue this {@link Notification} belongs. * @param myTrust The {@link Trust} which was added, removed or changed. */ protected TrustChangedNotification(final Subscription<TrustChangedNotification> mySubscription, Trust myTrust) { super(mySubscription); mTrusterID = myTrust.getTruster().getID(); mTrusteeID = myTrust.getTrustee().getID(); } /** * {@inheritDoc} */ @Override public void startupDatabaseIntegrityTest() throws Exception { super.startupDatabaseIntegrityTest(); checkedActivate(1); // 1 is the maximum needed depth of all stuff we use in this function IfNull.thenThrow(mTrusterID, "mTrusterID"); IfNull.thenThrow(mTrusteeID, "mTrusteeID"); } /** * The ID of the truster of the changed {@link Trust}. * * @see Identity#getID() * @see Trust#getTruster() * @see #mTrusterID */ protected final String getTrusterID() { checkedActivate(1); return mTrusterID; } /** * The ID of the trustee of the changed {@link Trust}. * * @see Identity#getID() * @see Trust#getTrustee() * @see #mTrusteeID */ protected final String getTrusteeID() { checkedActivate(1); return mTrusteeID; } } /** * This notification is issued when a score value is added/deleted or its attributes change. * * FIXME: This should keep the ID of the trust instead of truster/trustee ID. Also, it should keep both the old and new ID, similar to {@link IdentityChangedNotification} * * @see ScoresSubscription The type of {@link Subscription} which deploys this notification. */ @SuppressWarnings("serial") protected static final class ScoreChangedNotification extends Notification { /** * The ID of the truster of the changed {@link Score}. * * @see Identity#getID() * @see Score#getTruster() * @see #getTrusterID() */ private final String mTrusterID; /** * The ID of the trustee of the changed {@link Score}. * * @see Identity#getID() * @see Score#getTrustee() * @see #getTrusteeID() */ private final String mTrusteeID; /** * @param mySubscription The {@link Subscription} to whose {@link Notification} queue this {@link Notification} belongs. * @param myScore The {@link Score} which was added, deleted or changed. */ protected ScoreChangedNotification(final Subscription<ScoreChangedNotification> mySubscription, Score myScore) { super(mySubscription); mTrusterID = myScore.getTruster().getID(); mTrusteeID = myScore.getTrustee().getID(); } /** * {@inheritDoc} */ @Override public void startupDatabaseIntegrityTest() throws Exception { super.startupDatabaseIntegrityTest(); checkedActivate(1); // 1 is the maximum needed depth of all stuff we use in this function IfNull.thenThrow(mTrusterID, "mTrusterID"); IfNull.thenThrow(mTrusteeID, "mTrusteeID"); } /** * The ID of the truster of the changed {@link Score}. * * @see Identity#getID() * @see Score#getTruster() * @see #mTrusterID */ protected final String getTrusterID() { checkedActivate(1); return mTrusterID; } /** * The ID of the trustee of the changed {@link Score}. * * @see Identity#getID() * @see Score#getTrustee() * @see #mTrusteeID */ protected final String getTrusteeID() { checkedActivate(1); return mTrusteeID; } } /** * A subscription to the set of all {@link Identity} and {@link OwnIdentity} instances. * If an identity gets added/deleted or if its attributes change the subscriber is notified by a {@link IdentityChangedNotification}. * * @see IdentityChangedNotification The type of {@link Notification} which is deployed by this subscription. */ @SuppressWarnings("serial") public static final class IdentitiesSubscription extends Subscription<IdentityChangedNotification> { /** * @param fcpID See {@link Subscription#getFCP_ID()}. */ protected IdentitiesSubscription(String fcpID) { super(Subscription.Type.FCP, fcpID); } /** * {@inheritDoc} */ @Override protected void synchronizeSubscriberByFCP() throws Exception { mWebOfTrust.getFCPInterface().sendAllIdentities(getFCP_ID()); } /** * {@inheritDoc} */ @Override protected void notifySubscriberByFCP(IdentityChangedNotification notification) throws Exception { mWebOfTrust.getFCPInterface().sendIdentityChangedNotification(getFCP_ID(), notification.getOldIdentity(), notification.getNewIdentity()); } /** * Stores a {@link IdentityChangedNotification} to the {@link Notification} queue of this {@link Subscription}. * * @param identity The {@link Identity} whose attributes have changed. */ private void storeNotificationWithoutCommit(Identity oldIdentity, Identity newIdentity) { final IdentityChangedNotification notification = new IdentityChangedNotification(this, oldIdentity, newIdentity); notification.initializeTransient(mWebOfTrust); notification.storeWithoutCommit(); } } /** * A subscription to the set of all {@link Trust} instances. * If a trust gets added/deleted or if its attributes change the subscriber is notified by a {@link TrustChangedNotification}. * * @see TrustChangedNotification The type of {@link Notification} which is deployed by this subscription. */ @SuppressWarnings("serial") public static final class TrustsSubscription extends Subscription<TrustChangedNotification> { /** * @param fcpID See {@link Subscription#getFCP_ID()}. */ protected TrustsSubscription(String fcpID) { super(Subscription.Type.FCP, fcpID); } /** * {@inheritDoc} */ @Override protected void synchronizeSubscriberByFCP() throws Exception { mWebOfTrust.getFCPInterface().sendAllTrustValues(getFCP_ID()); } /** * {@inheritDoc} */ @Override protected void notifySubscriberByFCP(TrustChangedNotification notification) throws Exception { mWebOfTrust.getFCPInterface().sendTrustChangedNotification(getFCP_ID(), notification.getTrusterID(), notification.getTrusteeID()); } /** * Stores a {@link TrustChangedNotification} to the {@link Notification} queue of this {@link Subscription}. * * @param trust The {@link Trust} which was added, changed deleted. */ public void storeNotificationWithoutCommit(Trust trust) { final TrustChangedNotification notification = new TrustChangedNotification(this, trust); notification.initializeTransient(mWebOfTrust); notification.storeWithoutCommit(); } } /** * A subscription to the set of all {@link Score} instances. * If a score gets added/deleted or if its attributes change the subscriber is notified by a {@link ScoreChangedNotification}. * * @see ScoreChangedNotification The type of {@link Notification} which is deployed by this subscription. */ @SuppressWarnings("serial") public static final class ScoresSubscription extends Subscription<ScoreChangedNotification> { /** * @param fcpID See {@link Subscription#getFCP_ID()}. */ protected ScoresSubscription(String fcpID) { super(Subscription.Type.FCP, fcpID); } /** * {@inheritDoc} */ @Override protected void synchronizeSubscriberByFCP() throws Exception { mWebOfTrust.getFCPInterface().sendAllScoreValues(getFCP_ID()); } /** * {@inheritDoc} */ @Override protected void notifySubscriberByFCP(ScoreChangedNotification notification) throws Exception { mWebOfTrust.getFCPInterface().sendScoreChangedNotification(getFCP_ID(), notification.getTrusterID(), notification.getTrusteeID()); } /** * Stores a {@link ScoreChangedNotification} to the {@link Notification} queue of this {@link Subscription}. * * @param score The {@link Score} which was added, changed deleted. */ public void storeNotificationWithoutCommit(Score score) { final ScoreChangedNotification notification = new ScoreChangedNotification(this, score); notification.initializeTransient(mWebOfTrust); notification.storeWithoutCommit(); } } /** * After a {@link Notification} command is stored, we wait this amount of time before processing it. * This is to allow some coalescing when multiple notifications happen in a short interval. * This is usually the case as the import of trust lists often causes multiple changes. */ private static final long PROCESS_NOTIFICATIONS_DELAY = 60 * 1000; /** * The {@link WebOfTrust} to which this SubscriptionManager belongs. */ private final WebOfTrust mWoT; /** * The database in which to store {@link Subscription} and {@link Notification} objects. * Same as <code>mWoT.getDatabase();</code> */ private final ExtObjectContainer mDB; /** * The SubscriptionManager schedules execution of its notification deployment thread on this {@link TrivialTicker}. * The execution typically is scheduled after a delay of {@link #PROCESS_NOTIFICATIONS_DELAY}. * * Is null until {@link #start()} was called. */ private TrivialTicker mTicker = null; /** * Constructor both for regular in-node operation as well as operation in unit tests. * * @param myWoT The {@link WebOfTrust} to which this SubscriptionManager belongs. Its {@link WebOfTrust#getPluginRespirator()} may return null in unit tests. */ public SubscriptionManager(WebOfTrust myWoT) { mWoT = myWoT; mDB = mWoT.getDatabase(); } /** * Thrown when a single client tries to file a {@link Subscription} of the same class of event {@link Notification} and the same {@link Subscription.Type} of notification deployment. * * @see #throwIfSimilarSubscriptionExists */ @SuppressWarnings("serial") public static final class SubscriptionExistsAlreadyException extends Exception { public final Subscription<? extends Notification> existingSubscription; public SubscriptionExistsAlreadyException(Subscription<? extends Notification> existingSubscription) { this.existingSubscription = existingSubscription; } } /** * Thrown by various functions which query the database for a certain {@link Subscription} if none exists matching the given filters. */ @SuppressWarnings("serial") public static final class UnknownSubscriptionException extends Exception { /** * @param message A description of the filters which were set in the database query for the {@link Subscription}. */ public UnknownSubscriptionException(String message) { super(message); } } /** * Throws when a single client tries to file a {@link Subscription} which matches the attributes of the given Subscription: * - The class of the Subscription and thereby the same class of event {@link Notification} * - The {@link Subscription.Type} of notification deployment. * - For FCP connections, the ID of the FCP connection. See {@link Subscription#getID()}. * * Used to ensure that each client can only subscribe once to each type of event. * * @param subscription The new subscription which the client is trying to create. The database is checked for an existing one with similar properties as specified above. * @throws SubscriptionExistsAlreadyException If a {@link Subscription} exists which matches the attributes of the given Subscription as specified in the description of the function. */ @SuppressWarnings("unchecked") private synchronized void throwIfSimilarSubscriptionExists(final Subscription<? extends Notification> subscription) throws SubscriptionExistsAlreadyException { switch(subscription.getType()) { case FCP: try { throw new SubscriptionExistsAlreadyException( getSubscription((Class<? extends Subscription<? extends Notification>>)subscription.getClass(), subscription.getFCP_ID()) ); } catch (UnknownSubscriptionException e) { return; } default: throw new UnsupportedOperationException("Unknown type: " + subscription.getType()); } } /** * Creates an {@link InitialSynchronizationNotification} for the given subscription, stores it and the subscription and commits the transaction. * Takes care of all required synchronization. * Shall be used as back-end for all front-end functions for creating subscriptions. * * @throws SubscriptionExistsAlreadyException Thrown if a subscription of the same type for the same client exists already. See {@link #throwIfSimilarSubscriptionExists(Subscription)} */ private synchronized void storeNewSubscriptionAndCommit(final Subscription<? extends Notification> subscription) throws SubscriptionExistsAlreadyException { subscription.initializeTransient(mWoT); throwIfSimilarSubscriptionExists(subscription); final InitialSynchronizationNotification notification = new InitialSynchronizationNotification(subscription); notification.initializeTransient(mWoT); notification.storeWithoutCommit(); subscription.storeAndCommit(); } /** * The client is notified when an identity is added, changed or deleted. * FIXME: Do we also notify if internal things such as edition change? Should we? * * @param fcpID The identifier of the FCP connection of the client. Must be unique among all FCP connections! * @return The {@link IdentitiesSubscription} which is created by this function. * @see IdentityChangedNotification The type of {@link Notification} which is sent when an event happens. */ public IdentitiesSubscription subscribeToIdentities(String fcpID) throws SubscriptionExistsAlreadyException { final IdentitiesSubscription subscription = new IdentitiesSubscription(fcpID); storeNewSubscriptionAndCommit(subscription); return subscription; } /** * The client is notified when a trust value changes, is created or removed. * The client is NOT notified when the comment on a trust value changes. * * @param fcpID The identifier of the FCP connection of the client. Must be unique among all FCP connections! * @return The {@link TrustsSubscription} which is created by this function. * @see TrustChangedNotification The type of {@link Notification} which is sent when an event happens. */ public TrustsSubscription subscribeToTrusts(String fcpID) throws SubscriptionExistsAlreadyException { final TrustsSubscription subscription = new TrustsSubscription(fcpID); storeNewSubscriptionAndCommit(subscription); return subscription; } /** * The client is notified when a score value changes, is created or removed. * * @param fcpID The identifier of the FCP connection of the client. Must be unique among all FCP connections! * @return The {@link ScoresSubscription} which is created by this function. * @see ScoreChangedNotification The type of {@link Notification} which is sent when an event happens. */ public ScoresSubscription subscribeToScores(String fcpID) throws SubscriptionExistsAlreadyException { final ScoresSubscription subscription = new ScoresSubscription(fcpID); storeNewSubscriptionAndCommit(subscription); return subscription; } /** * Deletes the given {@link Subscription}. * * @param subscriptionID See {@link Subscription#getID()} * @throws UnknownSubscriptionException If no subscription with the given ID exists. */ public void unsubscribe(String subscriptionID) throws UnknownSubscriptionException { synchronized(mWoT) { // FIXME: Remove this synchronization when resolving the inner FIXME synchronized(this) { final Subscription<? extends Notification> subscription = getSubscription(subscriptionID); synchronized(Persistent.transactionLock(mDB)) { try { // FIXME: This is debug code and removing it is a critical optimization: // To make debugging easier, we also send an final InitialSynchronizationNotification when disconnecting a client // instead of only sending one at the beginning of the connection. // Sending an InitialSynchronizationNotification usually sends the full stored dataset to synchronize the client. // The client can use it to check whether the state of WOT which he received through notifications was correct. { final InitialSynchronizationNotification notification = new InitialSynchronizationNotification(subscription); notification.initializeTransient(mWoT); notification.storeWithoutCommit(); subscription.sendNotifications(this); } subscription.deleteWithoutCommit(this); Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } } } } /** * Typically used at startup by {@link #deleteAllSubscriptions()} and {@link #run()} * * @return All existing {@link Subscription}s. */ private ObjectSet<Subscription<? extends Notification>> getAllSubscriptions() { final Query q = mDB.query(); q.constrain(Subscription.class); return new Persistent.InitializingObjectSet<Subscription<? extends Notification>>(mWoT, q); } /** * Get all {@link Subscription}s to a certain {@link Notification} type. * * Typically used by the functions store*NotificationWithoutCommit() for storing the given {@link Notification} to the queues of all Subscriptions * which are subscribed to the type of the given notification. * * @param clazz The type of {@link Notification} to filter by. * @return Get all {@link Subscription}s to a certain {@link Notification} type. */ private ObjectSet<? extends Subscription<? extends Notification>> getSubscriptions(final Class<? extends Subscription<? extends Notification>> clazz) { final Query q = mDB.query(); q.constrain(clazz); return new Persistent.InitializingObjectSet<Subscription<? extends Notification>>(mWoT, q); } /** * @param id The unique identificator of the desired {@link Subscription}. See {@link Subscription#getID()}. * @return The {@link Subscription} with the given ID. Only one Subscription can exist for a single ID. * @throws UnknownSubscriptionException If no {@link Subscription} exists with the given ID. */ private Subscription<? extends Notification> getSubscription(final String id) throws UnknownSubscriptionException { final Query q = mDB.query(); q.constrain(Subscription.class); q.descend("mID").constrain(id); ObjectSet<Subscription<? extends Notification>> result = new Persistent.InitializingObjectSet<Subscription<? extends Notification>>(mWoT, q); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownSubscriptionException(id); default: throw new DuplicateObjectException(id); } } /** * Gets a {@link Subscription} which matches the given parameters: * - the given class of Subscription and thereby event {@link Notification} * - the given FCP identificator, see {@link Subscription#getFCP_ID()}. * * Only one {@link Subscription} which matches both of these can exist: Each FCP client can only subscribe once to a type of event. * * Typically used by {@link #throwIfSimilarSubscriptionExists(Subscription)}. * * @param clazz The class of the Subscription. * @param fcpID The identificator of the FCP connection. See {@link Subscription#getFCP_ID()}. * @return See description. * @throws UnknownSubscriptionException If no matching {@link Subscription} exists. */ private Subscription<? extends Notification> getSubscription(final Class<? extends Subscription<? extends Notification>> clazz, String fcpID) throws UnknownSubscriptionException { final Query q = mDB.query(); q.constrain(clazz); q.descend("mFCP_ID").constrain(fcpID); ObjectSet<Subscription<? extends Notification>> result = new Persistent.InitializingObjectSet<Subscription<? extends Notification>>(mWoT, q); switch(result.size()) { case 1: return result.next(); case 0: throw new UnknownSubscriptionException(clazz.getSimpleName().toString() + " with fcpID: " + fcpID); default: throw new DuplicateObjectException(clazz.getSimpleName().toString() + " with fcpID:" + fcpID); } } /** * Deletes all existing {@link Subscription} objects. * * As a consequence, all {@link Notification} objects associated with the notification queues of the subscriptions become useless and are also deleted. * * Typically used at {@link #start()} - we lose connection to all clients when restarting so their subscriptions are worthless. */ private synchronized final void deleteAllSubscriptions() { Logger.normal(this, "Deleting all subscriptions..."); synchronized(Persistent.transactionLock(mDB)) { try { for(Notification n : getAllNotifications()) { n.deleteWithoutCommit(); } for(Subscription<? extends Notification> s : getAllSubscriptions()) { s.deleteWithoutCommit(); } Persistent.checkedCommit(mDB, this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(mDB, this, e); } } Logger.normal(this, "Finished deleting all subscriptions."); } /** * Typically used by {@link #deleteAllSubscriptions()}. * * @return All objects of class Notification which are stored in the database. */ private ObjectSet<? extends Notification> getAllNotifications() { final Query q = mDB.query(); q.constrain(Notification.class); return new Persistent.InitializingObjectSet<Notification>(mWoT, q); } /** * Gets all {@link Notification} objects in the queue of the given {@link Subscription}. * They are ordered ascending by the time of when the event which triggered them happened. * * Precisely, they are ordered by their {@link Notification#mIndex}. * * Typically used for: * - Deploying the notification queue of a Subscription in {@link Subscription#sendNotifications(SubscriptionManager)} * - Deleting a subscription in {@link Subscription#deleteWithoutCommit(SubscriptionManager)} * * @param subscription The {@link Subscription} of whose queue to return notifications from. * @return All {@link Notification}s on the queue of the subscription, ordered ascending by time of happening of their inducing event. */ private ObjectSet<? extends Notification> getAllNotifications(final Subscription<? extends Notification> subscription) { final Query q = mDB.query(); q.constrain(Notification.class); q.descend("mSubscription").constrain(subscription).identity(); q.descend("mIndex").orderAscending(); return new Persistent.InitializingObjectSet<Notification>(mWoT, q); } /** * Interface for the core of WOT to deploy an {@link IdentityChangedNotification} to clients. * * Typically called when a {@link Identity} or {@link OwnIdentity} is added, deleted or its attributes are modified. * TODO: List the changes which do not trigger a notification here. For example we don't trigger one upon new edition hints. * * This function does not store a reference to the given identity object in the database, it only stores the ID. * You are safe to pass non-stored objects or objects which must not be stored. * * You must synchronize on this {@link SubscriptionManager} and the {@link Persistent#transactionLock(ExtObjectContainer)} when calling this function! * FIXME: Check synchronization of callers. * * @param oldIdentity A {@link Identity#clone()} of the {@link Identity} BEFORE the changes happened. In other words the old version of it. * @param newIdentity The new version of the {@link Identity} as stored in the database now. */ protected void storeIdentityChangedNotificationWithoutCommit(final Identity oldIdentity, final Identity newIdentity) { @SuppressWarnings("unchecked") final ObjectSet<IdentitiesSubscription> subscriptions = (ObjectSet<IdentitiesSubscription>)getSubscriptions(IdentitiesSubscription.class); for(IdentitiesSubscription subscription : subscriptions) { subscription.storeNotificationWithoutCommit(oldIdentity, newIdentity); } } /** * Interface for the core of WOT to deploy a {@link TrustChangedNotification} to clients. * * Typically called when a {@link Trust} is added, deleted or its attributes are modified. * * This function does not store references to the passed objects in the database, it only stores their IDs. * You are safe to pass non-stored objects or objects which must not be stored. * * You must synchronize on this {@link SubscriptionManager} and the {@link Persistent#transactionLock(ExtObjectContainer)} when calling this function! * FIXME: Check synchronization of callers. * * @param oldTrust A {@link Trust#clone()} of the {@link Trust} BEFORE the changes happened. In other words the old version of it. * @param newTrust The new version of the {@link Trust} as stored in the database now. */ protected void storeTrustChangedNotificationWithoutCommit(final Trust oldTrust, final Trust newTrust) { @SuppressWarnings("unchecked") final ObjectSet<TrustsSubscription> subscriptions = (ObjectSet<TrustsSubscription>)getSubscriptions(TrustsSubscription.class); for(TrustsSubscription subscription : subscriptions) { subscription.storeNotificationWithoutCommit(oldTrust); } } /** * Interface for the core of WOT to deploy a {@link ScoreChangedNotification} to clients. * * Typically called when a {@link Score} is added, deleted or its attributes are modified. * * This function does not store references to the passed objects in the database, it only stores their IDs. * You are safe to pass non-stored objects or objects which must not be stored. * * You must synchronize on this {@link SubscriptionManager} and the {@link Persistent#transactionLock(ExtObjectContainer)} when calling this function! * FIXME: Check synchronization of callers. * * @param oldScore A {@link Score#clone()} of the {@link Score} BEFORE the changes happened. In other words the old version of it. * @param newScore The new version of the {@link Score} as stored in the database now. */ protected void storeScoreChangedNotificationWithoutCommit(final Score oldScore, final Score newScore) { @SuppressWarnings("unchecked") final ObjectSet<ScoresSubscription> subscriptions = (ObjectSet<ScoresSubscription>)getSubscriptions(ScoresSubscription.class); for(ScoresSubscription subscription : subscriptions) { subscription.storeNotificationWithoutCommit(oldScore); } } /** * Sends out the {@link Notification} queue of each {@link Subscription} to its clients. * * Typically called by the Ticker {@link #mTicker} on a separate thread. This is triggered by {@link #scheduleNotificationProcessing()} * - the scheduling function should be called whenever a {@link Notification} is stored to the database. * * If deploying the notifications for a subscription fails, this function is scheduled to be run again after some time. * If deploying for a certain subscription fails N times, the Subscription is deleted. FIXME: Actually implement this. * * @see Subscription#sendNotifications(SubscriptionManager) This function is called on each subscription to deploy the {@link Notification} queue. */ public void run() { synchronized(mWoT) { synchronized(this) { for(Subscription<? extends Notification> subscription : getAllSubscriptions()) { try { subscription.sendNotifications(this); // Persistent.checkedCommit(mDB, this); /* sendNotifications() does this already */ } catch(Exception e) { Persistent.checkedRollback(mDB, this, e); scheduleNotificationProcessing(); } } } } } /** * {@inheritDoc} */ public int getPriority() { return NativeThread.LOW_PRIORITY; } /** * Schedules the {@link #run()} method to be executed after a delay of {@link #PROCESS_NOTIFICATIONS_DELAY} */ private void scheduleNotificationProcessing() { if(mTicker != null) mTicker.queueTimedJob(this, "WoT SubscriptionManager", PROCESS_NOTIFICATIONS_DELAY, false, true); else Logger.warning(this, "Cannot schedule notification processing: Ticker is null."); } /** * Deletes all old subscriptions and enables subscription processing. * * You must call this before any subscriptions are created, so for example before FCP is available. * * Does NOT work in unit tests - you must manually trigger subscription processing by calling {@link #run()} there. */ protected synchronized void start() { deleteAllSubscriptions(); final PluginRespirator respirator = mWoT.getPluginRespirator(); if(respirator != null) { // We are connected to a node mTicker = new TrivialTicker(respirator.getNode().executor); } else { // We are inside of a unit test mTicker = null; } } /** * Shuts down this SubscriptionManager by aborting all queued notification processing and waiting for running * processing to finish. */ protected synchronized void stop() { Logger.normal(this, "Aborting all pending notifications"); mTicker.shutdown(); Logger.normal(this, "Stopped."); } }
true
false
null
null
diff --git a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/internal/command/DirectEditingFeatureCommandWithContext.java b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/internal/command/DirectEditingFeatureCommandWithContext.java index a5ba208e..e3c72f53 100644 --- a/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/internal/command/DirectEditingFeatureCommandWithContext.java +++ b/plugins/org.eclipse.graphiti/src/org/eclipse/graphiti/internal/command/DirectEditingFeatureCommandWithContext.java @@ -1,84 +1,109 @@ /******************************************************************************* * <copyright> * * Copyright (c) 2005, 2010 SAP AG. * 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: * SAP AG - initial API, implementation and documentation * * </copyright> * *******************************************************************************/ package org.eclipse.graphiti.internal.command; import org.eclipse.graphiti.features.IDirectEditingFeature; import org.eclipse.graphiti.features.context.IDirectEditingContext; import org.eclipse.graphiti.features.impl.AbstractDirectEditingFeature; +import org.eclipse.graphiti.func.IProposal; +import org.eclipse.graphiti.func.IProposalSupport; /** * The Class DirectEditingFeatureCommandWithContext. * * @noinstantiate This class is not intended to be instantiated by clients. * @noextend This class is not intended to be subclassed by clients. */ public class DirectEditingFeatureCommandWithContext extends GenericFeatureCommandWithContext { private String newValue; + private IProposal proposal; /** * Instantiates a new direct editing feature command with context. * * @param feature * the feature * @param context * the context * @param valueObject * the value object */ - public DirectEditingFeatureCommandWithContext(IDirectEditingFeature feature, IDirectEditingContext context, String valueObject) { + public DirectEditingFeatureCommandWithContext(IDirectEditingFeature feature, IDirectEditingContext context, String valueObject, + IProposal proposal) { super(feature, context); setNewValue(valueObject); + setProposal(proposal); } private String getNewValue() { return newValue; } private void setNewValue(String newValue) { this.newValue = newValue; } /* * (non-Javadoc) * * @see * org.eclipse.graphiti.internal.command.GenericFeatureCommandWithContext * #execute() */ @Override public boolean execute() { boolean ret = false; if (getFeature() instanceof IDirectEditingFeature && getContext() instanceof IDirectEditingContext) { IDirectEditingFeature def = (IDirectEditingFeature) getFeature(); IDirectEditingContext dec = (IDirectEditingContext) getContext(); String initialValue = def.getInitialValue(dec); if (initialValue == null) { initialValue = ""; //$NON-NLS-1$ } if (!initialValue.equals(getNewValue())) { - def.setValue(getNewValue(), dec); + IProposalSupport proposalSupport = def.getProposalSupport(); + if (proposalSupport == null) { // simple mode with + // strings as proposals + def.setValue(getNewValue(), dec); + } else { + proposalSupport.setValue(getNewValue(), getProposal(), dec); + } ret = true; // Notify the feature that there really are changes if (getFeature() instanceof AbstractDirectEditingFeature) { ((AbstractDirectEditingFeature) getFeature()).setValueChanged(); } } } return ret; } + /** + * @return the proposal + */ + private IProposal getProposal() { + return proposal; + } + + /** + * @param proposal + * the proposal to set + */ + private void setProposal(IProposal proposal) { + this.proposal = proposal; + } }
false
false
null
null
diff --git a/LeafNode.java b/LeafNode.java index 5f92ff6..9ea3c66 100644 --- a/LeafNode.java +++ b/LeafNode.java @@ -1,131 +1,131 @@ /* * File: LeafNode.java * Description: An internal node in the BTree * Author: Benjamin David Mayes <bdm8233@rit.edu> */ import java.lang.reflect.Array; import java.util.Arrays; /** * A node that is a leaf of the BTree */ class LeafNode<K extends Comparable, V> extends Node<K,V> { private V[] children; /** * Constructs a LeafNode with K as the key and parent as the parent. * * @param key The initial key in this node. * @param parent The parent of this node. */ @SuppressWarnings({"unchecked"}) public LeafNode( K key, V value ) { super(key); children = (V[])(Array.newInstance( value.getClass(), numKeysPerNode + 2 )); children[0] = value; } private LeafNode( K[] keys, V[] values, Node<K,V> parent, Node<K,V> next ) { super( keys, parent ); children = Arrays.copyOf( values, numKeysPerNode + 2); this.next = next; } /** * Get the child of the given key. * * @param key The key to get the child of. * @return A node in a Union or null. */ @SuppressWarnings({"unchecked"}) public Union.Right<Node<K,V>,V> getChild( K key ) { int i = 0; // The contents of the node are sorted, iterate while lexicographically less. while( i < numKeys && keys[i].compareTo( key ) < 0 ) { ++i; } // check for equality - if( keys[i].equals( key ) ) { + if( keys[i] != null && keys[i].equals( key ) ) { return new Union.Right<Node<K,V>,V>( children[i] ); } else { return new Union.Right<Node<K,V>,V>(null); } } /** * Adds a key:value pair to the current LeafNode. * @param key The key of the value to add * @param value The value of the key to add. * @return True if success, false otherwise. */ @SuppressWarnings({"unchecked"}) public boolean addValue( K key, V value ) { // we need to insert the key:value pair in order int i = 0; while( i < numKeys && keys[i].compareTo( key ) < 0 ) { ++i; } if( i != numKeys && keys[i].compareTo( key ) == 0 ) { // we can replace the old value for this key children[i] = value; } else if( numKeys != numKeysPerNode) { // we can add a new value if and only if there is room // move everything over for( int j = numKeys; j > i; --j ) { keys[j] = keys[j-1]; children[j] = children[j-1]; } // insert the key:value pair in the correct spot keys[i] = key; children[i] = value; numKeys++; } else { return false; } return true; } /** {@inheritDoc} */ public Union.Right<InternalNode<K,V>,LeafNode<K,V>> split( K key, V value ) { // Number of children of a leaf node is the same as the number // of keys. LeafNode<K,V> newNode = new LeafNode<K,V>( Arrays.copyOfRange( this.keys, (numKeysPerNode)/2, numKeysPerNode ), Arrays.copyOfRange( this.children, numKeysPerNode/2, numKeysPerNode ), this.parent, this.next ); this.next = newNode; // Resize our key array this.numKeys = numKeysPerNode/2; newNode.numKeys = numKeysPerNode/2; if( key.compareTo( newNode.lowerBound() ) >= 0 ) { newNode.addValue( key, value ); } else { addValue( key, value ); } return new Union.Right<InternalNode<K,V>,LeafNode<K,V>>(newNode); } public String toString() { String output = "[L"; for( int i = 0; i < numKeys; ++i ) { output += " " + keys[i] + ":" + children[i] + ", "; } return output + "]"; } } diff --git a/Node.java b/Node.java index 5d4a73a..3868390 100644 --- a/Node.java +++ b/Node.java @@ -1,108 +1,108 @@ /* * Sequential B*-Tree implementation for the * Concurrent Search Tree Project for * Parallel Computing I * * Author: David C. Larsen <dcl9934@cs.rit.edu> * Author: Benjamin David Mayes <bdm8233@rit.edu> * Date: April. 12, 2011 */ import java.lang.reflect.Array; import java.util.Arrays; /** * A B-Tree node. */ public abstract class Node<K extends Comparable,V> { - protected static final int numKeysPerNode = 2; + protected static final int numKeysPerNode = 4; protected int numKeys; protected K[] keys; protected Node<K,V> parent = null; protected Node<K,V> next = null; /** * Creates a node with an intial value and the given parent. * * @param key The initial key in this node. */ @SuppressWarnings({"unchecked"}) public Node( K key ) { // Like: keys = new K[numKeysPerNode], but working around Java's // type-erasure approach to generics. // This cast will always work because Array dynamically creates the // generic array of the correct type. Still, we have to do an // "unchecked" cast, and we don't want to be warned about it, // because we've already guaranteed the type safety. keys = (K[])(Array.newInstance( key.getClass(), numKeysPerNode + + 1 )); keys[0] = key; numKeys = 1; } /** * Creates a node with the given keys and parent. * * @param keys The keys in this node. * @param parent The parent node. */ protected Node( K[] keys, Node<K,V> parent ) { this.keys = Arrays.copyOf( keys, numKeysPerNode ); numKeys = keys.length; this.parent = parent; } /** * Obtains the number of keys in this Node. * * @return The number of keys in this node. */ public int numKeys() { return numKeys; } /** * Obtains the next node on the same level as this node. * * @return The next node on the same level. */ public Node<K,V> getNext() { return next; } /** * Find the lowest number in the range of Keys in this Node. * * @return The lowerbound of the values in this node. */ public K lowerBound() { return keys[0]; } /** * Find the highest number in the range of Keys in this Node. * * @return The upperbound of the values in this node. */ public K upperUpper() { return keys[numKeys-1]; } /** * Returns a child node such that K is within its bounds. * * @param key The key of the desired child. * @return The child to search for the key or the value corresponding to * the key depending on the type of node. */ public abstract Union<Node<K,V>,V> getChild( K key ); /** * Splits a node into two nodes, returning the second node. */ //public abstract Union<InternalNode<K,V>,LeafNode<K,V>> split( K key, V value ); }
false
false
null
null
diff --git a/src/controller/game/edition/tools/AbstractAddLineElementTool.java b/src/controller/game/edition/tools/AbstractAddLineElementTool.java index f665d15..4ffcb92 100644 --- a/src/controller/game/edition/tools/AbstractAddLineElementTool.java +++ b/src/controller/game/edition/tools/AbstractAddLineElementTool.java @@ -1,249 +1,251 @@ package controller.game.edition.tools; import static controller.game.edition.ConnectionRules.canConnectLineElements; import static controller.game.edition.tools.Colors.*; import static controller.game.edition.tools.LineElementRecognizer.recognizeLineElement; import static model.production.elements.ProductionLineElement.connectLineElements; import static model.utils.StringUtils.join; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import model.game.Player; import model.production.Direction; import model.production.elements.ProductionLineElement; import model.warehouse.Position; import model.warehouse.TileElement; import controller.game.GamePanelController; import controller.game.edition.ConnectionRules; import controller.game.edition.EditionTool; public abstract class AbstractAddLineElementTool extends EditionTool { private ProductionLineElement lineElement; public AbstractAddLineElementTool(GamePanelController gamePanelController, Player game) { this(gamePanelController, game, null); } - + public AbstractAddLineElementTool(GamePanelController gamePanelController, Player game, ProductionLineElement startElement) { super(gamePanelController, game); this.lineElement = startElement; } @Override public void reset() { this.lineElement = createLineElement(); } @Override public void paint(Graphics2D graphics) { Position mousePosition = this.getGroundPanel() .getCurrentMousePosition(); if (mousePosition != null) { List<String> warnings = new ArrayList<String>(); boolean canPutElement = canPutElementAt(mousePosition, warnings); boolean enoughMoney = haveEnoughMoney(); Color color = canPutElement && enoughMoney ? OK_COLOR : BAD_COLOR; if (!enoughMoney) warnings.add("Not enough money!"); drawWarnings(graphics, warnings); drawElementRectagle(graphics, mousePosition, color); drawInputArrow(graphics, mousePosition, color); drawOutputArrow(graphics, mousePosition, color); } } @Override public void mouseClicked(Position position) { if (canPutElementAt(position) && haveEnoughMoney()) { putLineElementAt(position, this.lineElement); tryConnectInput(position); tryConnectOutput(position); this.lineElement = createLineElement(); } } - protected void putLineElementAt(Position position, ProductionLineElement element) { + protected void putLineElementAt(Position position, + ProductionLineElement element) { getPlayer().buyAndAddProductionLineElement(element, position); } protected abstract ProductionLineElement createLineElement(); private void drawWarnings(Graphics2D graphics, List<String> warnings) { if (!warnings.isEmpty()) getGroundPanel().drawNotificationBesideMouse(join(warnings, " - "), graphics); } private void drawElementRectagle(Graphics2D graphics, Position mousePosition, Color color) { int width = this.lineElement.getWidth(); int height = this.lineElement.getHeight(); getGroundPanel().drawRectangle(graphics, mousePosition, width, height, color); } private void drawInputArrow(Graphics2D graphics, Position mousePosition, Color color) { if (this.lineElement.canHavePreviousLineElement()) { Position inPos = getInputConnectionPosition(mousePosition); Direction inDir = this.lineElement.getInputConnectionDirection(); getGroundPanel().drawInputArrow(inPos, inDir, color, graphics); } } private void drawOutputArrow(Graphics2D graphics, Position mousePosition, Color color) { if (this.lineElement.canHaveNextLineElement()) { Position outPos = getOutputConnectionPosition(mousePosition); Direction outDir = this.lineElement.getOutputConnectionDirection(); getGroundPanel().drawOutputArrow(outPos, outDir, color, graphics); } } private void tryConnectInput(Position position) { if (this.lineElement.canHavePreviousLineElement()) { ProductionLineElement inputLineElement = searchForInputElement(position); if (inputLineElement != null) connectLineElements(inputLineElement, this.lineElement, ConnectionRules.getInstance()); } } private void tryConnectOutput(Position position) { if (this.lineElement.canHaveNextLineElement()) { ProductionLineElement outputLineElement = searchForOutputElement(position); if (outputLineElement != null) connectLineElements(this.lineElement, outputLineElement, ConnectionRules.getInstance()); } } private boolean canPutElementAt(Position position) { return canPutElementAt(position, null); } private boolean canPutElementAt(Position position, List<String> whyNot) { int width = this.lineElement.getWidth(); int height = this.lineElement.getHeight(); boolean insideBounds = getGround().isAreaInsideBounds(width, height, position); if (!insideBounds && whyNot != null) whyNot.add("Out of bounds"); boolean canPutElement = getGround().canAddTileElementByDimension(width, height, position); if (!canPutElement && insideBounds && whyNot != null) whyNot.add("Area not empty"); return canPutElement && canPutInput(position, whyNot) && canPutOutput(position, whyNot); } private boolean canPutInput(Position position, List<String> whyNot) { if (!this.lineElement.canHavePreviousLineElement()) return true; Position inputPos = getInputConnectionPosition(position); boolean emptyArea = getGround().canAddTileElementByDimension(1, 1, inputPos); boolean canConnect = canConnectInput(position); boolean canPutInput = emptyArea || canConnect; if (!canPutInput && whyNot != null) whyNot.add("Cannot connect input"); return canPutInput; } private boolean canPutOutput(Position position, List<String> whyNot) { if (!this.lineElement.canHaveNextLineElement()) return true; Position outputPos = getOutputConnectionPosition(position); boolean emptyArea = getGround().canAddTileElementByDimension(1, 1, outputPos); boolean canConnect = canConnectOutput(position); boolean canPutOutput = emptyArea || canConnect; if (!canPutOutput && whyNot != null) whyNot.add("Cannot connect output"); return canPutOutput; } private Position getInputConnectionPosition(Position position) { return position.add(this.lineElement .getInputConnectionRelativePosition()); } private Position getOutputConnectionPosition(Position position) { return position.add(this.lineElement .getOutputConnectionRelativePosition()); } private boolean canConnectInput(Position position) { return searchForInputElement(position) != null; } private boolean canConnectOutput(Position position) { return searchForOutputElement(position) != null; } private ProductionLineElement searchForInputElement(Position position) { Position inputPos = getInputConnectionPosition(position); Direction inputDir = this.lineElement.getInputConnectionDirection(); TileElement tileElement = getGround().getTileElementAt(inputPos); ProductionLineElement inputElement = recognizeLineElement(tileElement); boolean canConnectByRule = canConnectLineElements(inputElement, this.lineElement); - if (inputElement == null || inputElement.hasNextLineElement() - || !canConnectByRule) { + if (inputElement == null || !inputElement.canHaveNextLineElement() + || inputElement.hasNextLineElement() || !canConnectByRule) { inputElement = null; } else { Position expectedOutputPos = inputPos.subtract(inputDir .getAssociatedPosition()); boolean canConnect = inputElement.getOutputConnectionPosition() .equals(expectedOutputPos); if (!canConnect) inputElement = null; } return inputElement; } private ProductionLineElement searchForOutputElement(Position position) { Position outputPos = getOutputConnectionPosition(position); Direction outputDir = this.lineElement.getOutputConnectionDirection(); TileElement tileElement = getGround().getTileElementAt(outputPos); ProductionLineElement outputElement = recognizeLineElement(tileElement); boolean canConnectByRule = canConnectLineElements(this.lineElement, outputElement); - if (outputElement == null || outputElement.hasPreviousLineElement() - || !canConnectByRule) { + if (outputElement == null + || !outputElement.canHavePreviousLineElement() + || outputElement.hasPreviousLineElement() || !canConnectByRule) { outputElement = null; } else { Position expectedInputPos = outputPos.subtract(outputDir .getAssociatedPosition()); boolean canConnect = outputElement.getInputConnectionPosition() .equals(expectedInputPos); if (!canConnect) outputElement = null; } return outputElement; } protected boolean haveEnoughMoney() { return this.getPlayer().canAfford(this.lineElement.getPurchasePrice()); } } diff --git a/src/view/game/TileElementImageRecognizer.java b/src/view/game/TileElementImageRecognizer.java index 47f03d7..acc54a8 100644 --- a/src/view/game/TileElementImageRecognizer.java +++ b/src/view/game/TileElementImageRecognizer.java @@ -1,96 +1,98 @@ package view.game; import java.awt.Image; import java.awt.image.BufferedImage; import view.ImageLoader; import model.production.elements.Conveyor; import model.production.elements.InputProductionLineElement; import model.production.elements.OutputProductionLineElement; import model.production.elements.ProductionLineElement; import model.production.elements.machine.MachineType; import model.production.elements.machine.ProductionMachine; import model.production.elements.machine.QualityControlMachine; import model.warehouse.TileElement; import model.warehouse.TileElementVisitor; import model.warehouse.Wall; public abstract class TileElementImageRecognizer extends TileElementVisitor { protected static final String IMG_WALL = "Wall.png"; - private static final String CONVEYOR_IMG_PREFIX = "conveyor_"; + private static final String CONVEYOR_IMG_PREFIX = "conveyor/conveyor_"; private static final String IMG_EXTENSION = ".png"; - private static final String INPUT_ELEMENT_PREFIX = "input_"; - private static final String OUTPUT_ELEMENT_PREFIX = "output_"; + private static final String INPUT_ELEMENT_PREFIX = "input/input_"; + private static final String OUTPUT_ELEMENT_PREFIX = "output/output_"; + + private static final String MACHINE_IMG_PREFIX = "machines/"; protected abstract void onLineElmentVisited(ProductionLineElement element, BufferedImage image); protected abstract void onWallVisited(Wall wall, BufferedImage image); @Override public void visitProductionMachine(ProductionMachine machine) { BufferedImage image = getMachineImage(machine.getMachineType()); this.onLineElmentVisited(machine, image); } @Override public void visitQualityControlMachine(QualityControlMachine machine) { BufferedImage image = getMachineImage(machine.getMachineType()); this.onLineElmentVisited(machine, image); } @Override public void visitWall(Wall wall) { this.onWallVisited(wall, ImageLoader.getImage(IMG_WALL)); } @Override public void visitConveyor(Conveyor conveyor) { this.onLineElmentVisited(conveyor, getConveyorImage(conveyor)); } @Override public void visitInputProductionLineElement( InputProductionLineElement inputElement) { BufferedImage image = getInputElementImage(inputElement); this.onLineElmentVisited(inputElement, image); } @Override public void visitOutputProductionLineElement( OutputProductionLineElement outputElement) { BufferedImage image = getOutputElementImage(outputElement); this.onLineElmentVisited(outputElement, image); } public static BufferedImage getInputElementImage( InputProductionLineElement inputElement) { char symbol = inputElement.getOutputConnectionDirection().getSymbol(); String imgName = INPUT_ELEMENT_PREFIX + symbol + IMG_EXTENSION; return ImageLoader.getImage(imgName); } public static BufferedImage getOutputElementImage( OutputProductionLineElement outputElement) { char symbol = outputElement.getInputConnectionDirection().getSymbol(); String imgName = OUTPUT_ELEMENT_PREFIX + symbol + IMG_EXTENSION; return ImageLoader.getImage(imgName); } public static BufferedImage getConveyorImage(Conveyor conveyor) { char prevSymbol = conveyor.getInputConnectionDirection().getSymbol(); char nextSymbol = conveyor.getOutputConnectionDirection().getSymbol(); String imgName = CONVEYOR_IMG_PREFIX + prevSymbol + nextSymbol + IMG_EXTENSION; return ImageLoader.getImage(imgName); } public static BufferedImage getMachineImage(MachineType mtype) { - String imgName = mtype.getName() + IMG_EXTENSION; + String imgName = MACHINE_IMG_PREFIX + mtype.getName() + IMG_EXTENSION; return ImageLoader.getImage(imgName); } }
false
false
null
null
diff --git a/src/util/TwoComplement.java b/src/util/TwoComplement.java index 1404702..7b0fd88 100644 --- a/src/util/TwoComplement.java +++ b/src/util/TwoComplement.java @@ -1,22 +1,29 @@ package util; public class TwoComplement { public static double to2complement(byte b) { if(b < 0) - //return (double) (0x00FF & b); - return (double) ((short) b + (short) 256); - return (double) b; + return (b + (short) 256); + + return b; } - + public static byte from2complement(double d) { - short s = (short) d; + if(d > 256.0) + d = 256.0; + + if(d < 0.0) + d = 0.0; + + short s = (short) Math.round(d); if(s < 128) - //return (byte) (s - 127); - //return (byte) (~(0x00FF & s) + 1); return (byte) s; + return (byte) (s - 256); - - + + } } + +// <TITLE> \ No newline at end of file
false
false
null
null
diff --git a/proj/DFSServer.java b/proj/DFSServer.java index 5dc1dde..0275a25 100644 --- a/proj/DFSServer.java +++ b/proj/DFSServer.java @@ -1,357 +1,366 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.Vector; import edu.washington.cs.cse490h.lib.PersistentStorageReader; import edu.washington.cs.cse490h.lib.PersistentStorageWriter; import edu.washington.cs.cse490h.lib.Utility; public class DFSServer extends DFSComponent { public static final String tempFileName = ".temp"; - private HashMap<Integer, DFSClient.RequestWrapper> issuedCommands; private HashMap<Integer, LinkedList<DFSMessage>> queuedResponses; private HashMap<String, Vector<Integer>> readCheckOuts; private HashMap<String, Integer> whoOwns; private PersistentStorageCache cache; public DFSServer(DFSNode parent) { super(parent); } public void start() { - issuedCommands = new HashMap<Integer, DFSClient.RequestWrapper>(); queuedResponses = new HashMap<Integer, LinkedList<DFSMessage>>(); readCheckOuts = new HashMap<String, Vector<Integer>>(); cache = new PersistentStorageCache(parent, this, true); System.out.println("Starting the DFSNode..."); // Check for a temp file. if (Utility.fileExists(parent, tempFileName)) { try { PersistentStorageReader tempReader = this.getReader(tempFileName); PersistentStorageWriter tempDeleter = this.getWriter(tempFileName, false); if (tempReader.ready()) { String filename = tempReader.readLine(); String oldContent = readRemainingContentsToString(tempReader); PersistentStorageWriter writer = this.getWriter(filename, false); writer.write(oldContent); writer.close(); } tempDeleter.delete(); } catch(FileNotFoundException fnfe) { // File must have been deleted since the check. } catch(IOException ioe) { // AUDIT(andrew): Shouldn't we at least error here? } } } @Override public void onRIOReceive(Integer from, DFSMessage msg) { String filename = ((FileNameMessage) msg).getFileName(); DFSMessage response; // Demux on the message type and dispatch accordingly. switch (msg.getMessageType()) { case Create: response = handleCreateRequest(filename); break; case Get: response = handleGetRequest(filename); break; case Put: response = handlePutRequest(filename, (PutMessage) msg); break; case Append: response = handleAppendRequest(filename, (AppendMessage) msg); break; case Delete: response = handleDeleteRequest(filename); break; case SyncRequest: response = handleSyncRequest(from, filename, (SyncRequestMessage) msg); break; case SyncData: response = handleSyncData(filename, (SyncDataMessage) msg); break; default: // TODO: Exception fixit. Giving error code 1 so the bitch'll compile. response = new ResponseMessage(5); } System.out.println("Server (addr " + this.addr + ") sending: " + response.toString()); RIOSend(from, Protocol.DATA, response.pack()); } private DFSMessage handleSyncRequest(Integer from, String filename, SyncRequestMessage msg) { DFSMessage response; Flags f = msg.getFlags(); if (f.isSet(SyncFlags.TransferOwnership)) { response = handleTransferOwnershipRequest(from, filename, msg); } if (f.isSet(SyncFlags.Create)) { response = handleCreateSyncRequest(from, filename, msg); } if (f.isSet(SyncFlags.ReadOnly)) { response = handleReadOnlySyncRequest(from, filename, msg); } return response; } private DFSMessage handleTransferOwnershipRequest(Integer from, String filename, SyncRequestMessage msg) { DFSMessage response; Integer i = whoOwns.get(filename); LinkedList<DFSMessage> responses = queuedResponses.get(from); //in case the write request has to wait if (i == null) { //nobody owns + try { whoOwns.put(filename, from); - Flags f = new Flags(SyncFlags.TransferOwnershipGranted); + Flags f = new Flags(); response = new SyncDataMessage(filename, msg.version, f, readFileToString(filename)); + } catch (IOException ioe) { + response = new ResponseMessage(5); + } - } else if (i != parent.addr) { //somebody else owns + } else { //somebody else owns - //add command to queuedResponses - if (responses == null) { - responses = new LinkedList<DFSMessage>(); - responses.add(msg); - queuedResponses.put(from, responses); - } else { // server owns - responses.add(msg); //server must relinquish control first - } + //add command to queuedResponses + addQueuedResponse(from, filename, msg, responses); + + Flags f = new Flags(SyncFlags.TransferOwnership); + response = new SyncRequestMessage(filename, msg.version, f); } return response; } + private void addQueuedResponse(Integer from, String filename, SyncRequestMessage msg, LinkedList<DFSMessage> responses) { + if (responses == null) { + responses = new LinkedList<DFSMessage>(); + responses.add(msg); + queuedResponses.put(from, responses); + } else { + responses.add(msg); + } + } + private DFSMessage handleCreateSyncRequest(Integer from, String filename, SyncRequestMessage mgs) { return null; } private DFSMessage handleReadOnlySyncRequest(Integer from, String filename, SyncRequestMessage msg) { DFSMessage response; if(!Utility.fileExists(parent, filename)) { response = new ResponseMessage(10); } else { if (msg.version < cache.get(new DFSFilename(filename)).getVersion()) { //server has most recent version try { Flags f = new Flags(0); response = new SyncDataMessage(filename, msg.version, null, readFileToString(filename)); // checkOutForRead(from, filename); } catch (FileNotFoundException fnfe) { response = new ResponseMessage(10); } catch (IOException ioe) { response = new ResponseMessage(5); } } else { //client had the most recent version response = new SyncRequestMessage(filename, cache.get(new DFSFilename(filename)) .getVersion(), msg.flags); } } return response; } private void checkOutForRead(Integer from, String filename) { //add to readCheckOuts Vector<Integer> v = readCheckOuts.get(filename); if(v == null) { v = new Vector<Integer>(); v.add(from); readCheckOuts.put(filename, v); } else { v.add(from); } } private ResponseMessage handleSyncData(String filename, SyncDataMessage msg) { DFSMessage response; handleDeleteRequest(filename); handleCreateRequest(filename); handlePutRequest(filename, (FileMessage) msg); response = new SyncRequestMessage(filename, cache.get(filename).getVersion(), msg.flags); } /** * Creates the target file. * * Generates and returns a response containing the appropriate error code. * * @param filename * The name of the file to create. * @return A ResponseMessage containing the appropriate error code. */ private DFSMessage handleCreateRequest(String filename) { ResponseMessage response; PersistentStorageWriter writer; // Test existence of filename. if (Utility.fileExists(parent, filename)) { response = new ResponseMessage(11); } else { try { writer = this.getWriter(filename, false); writer.close(); // File created properly, so we respond with happy error code. response = new ResponseMessage(0); } catch (IOException ioe) { // TODO: Exception fixit. response = new ResponseMessage(5); } } return response; } /** * Gets the contents of the target file. * * @param filename * The name of the file of which to get contents. * @return A ResponseMessage containing error code and (hopefully) * contents of the target file. */ private ResponseMessage handleGetRequest(String filename) { ResponseMessage response; if (!Utility.fileExists(parent, filename)) { response = new ResponseMessage(10); } else { try { response = new DataResponseMessage(0, readFileToString(filename)); } catch (FileNotFoundException fnfe) { response = new ResponseMessage(10); } catch (IOException ioe) { // TODO: Exception fixit. response = new ResponseMessage(5); } } return response; } /** * Writes data to a file. * * @param filename The name of the file to which to write. * @param * @return A ResponseMessage containing the appropriate error code. */ private ResponseMessage handlePutRequest(String filename, FileMessage putmessage) { ResponseMessage response; PersistentStorageWriter tempWriter; PersistentStorageWriter writer; if (Utility.fileExists(parent, filename)) { try { tempWriter = this.getWriter(tempFileName, false); String existingContent = readFileToString(filename); tempWriter.write(filename + "\n"); tempWriter.write(existingContent); tempWriter.close(); // Write to target file. writer = this.getWriter(filename, false); System.out.println("String to write to " + filename + " in put request: " + putmessage.getData()); writer.write(putmessage.getData()); // Delete temp file. // TODO: Should probably use File.delete() here. See HandleDeleteRequest. PersistentStorageWriter tempDeleter = this.getWriter(tempFileName, false); if (!tempDeleter.delete()) System.out.println(filename + " failed to delete"); response = new ResponseMessage(0); } catch(IOException ioe) { ioe.printStackTrace(); response = new ResponseMessage(5); } } else { response = new ResponseMessage(10); } return response; } /** * Appends data to the end of afile. * * @param filename The name of the file to which to append. * @param * @return A ResponseMessage containing the appropriate error code. */ private ResponseMessage handleAppendRequest(String filename, AppendMessage appendmessage) { ResponseMessage response; PersistentStorageWriter writer; if (Utility.fileExists(parent, filename)) { try { // Working on the write file. writer = this.getWriter(filename, true); writer.write(appendmessage.getData()); writer.close(); response = new ResponseMessage(0); } catch(IOException ioe) { ioe.printStackTrace(); response = new ResponseMessage(5); } } else { response = new ResponseMessage(10); } return response; } /** * Attempts to delete the target file. * * @param filename * The name of the file to delete * @return A ResponseMessage containing the appropriate error code. */ private ResponseMessage handleDeleteRequest(String filename) { ResponseMessage response; if (!Utility.fileExists(parent, filename)) { // File doesn't exist, so we return appropriate error code. response = new ResponseMessage(10); } else { File f = new File("storage/" + this.addr + "/" + filename); try { if (f.delete()) { response = new ResponseMessage(0); } else { // Delete failed, so return a generic error. // TODO: Exception fixit. response = new ResponseMessage(1); } } catch (SecurityException se) { response = new ResponseMessage(5); } } return response; } }
false
false
null
null
diff --git a/plexus-container-default.old/src/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java b/plexus-container-default.old/src/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java index 689f8188..655116d0 100644 --- a/plexus-container-default.old/src/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java +++ b/plexus-container-default.old/src/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java @@ -1,86 +1,93 @@ package org.codehaus.plexus.service.repository.instance; import org.codehaus.plexus.service.repository.ComponentHousing; /** * This ensures only a single instance of a a component exists. Once no * more connections for this component exists it is disposed. * * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @author <a href="mailto:bert@tuaworks.co.nz">Bert van Brakel</a> * * @version $Id$ */ public class ClassicSingletonInstanceManager extends AbstractInstanceManager { private ComponentHousing singleton; /** Number of clients using this component */ private int connections = 0; /** * */ public ClassicSingletonInstanceManager() { super(); } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#release(java.lang.Object) */ public void release( Object component ) { //Only accept it if it is the same instance. + + System.out.println( "singleton = " + singleton ); + System.out.println( "connections = " + connections ); + if ( singleton.getComponent() == component ) { connections--; + if ( connections == 0 ) { endComponentLifecycle( singleton ); + singleton = null; } - singleton = null; } else { getLogger().warn( "Component returned which is not the same instance. Ignored. component=" + component ); } } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#dispose() */ public void dispose() { //wait for all the clients to return all the components //Do we do this in a seperate thread? or block the current thread?? //TODO if ( singleton != null ) { endComponentLifecycle( singleton ); } } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#getComponent() */ public Object getComponent() throws Exception { if ( singleton == null ) { singleton = newHousingInstance(); } + connections++; + return singleton.getComponent(); } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#getConnections() */ public int getConnections() { return connections; } } \ No newline at end of file diff --git a/plexus-container-new.old/src/main/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java b/plexus-container-new.old/src/main/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java index 689f8188..655116d0 100644 --- a/plexus-container-new.old/src/main/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java +++ b/plexus-container-new.old/src/main/java/org/codehaus/plexus/service/repository/instance/ClassicSingletonInstanceManager.java @@ -1,86 +1,93 @@ package org.codehaus.plexus.service.repository.instance; import org.codehaus.plexus.service.repository.ComponentHousing; /** * This ensures only a single instance of a a component exists. Once no * more connections for this component exists it is disposed. * * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @author <a href="mailto:bert@tuaworks.co.nz">Bert van Brakel</a> * * @version $Id$ */ public class ClassicSingletonInstanceManager extends AbstractInstanceManager { private ComponentHousing singleton; /** Number of clients using this component */ private int connections = 0; /** * */ public ClassicSingletonInstanceManager() { super(); } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#release(java.lang.Object) */ public void release( Object component ) { //Only accept it if it is the same instance. + + System.out.println( "singleton = " + singleton ); + System.out.println( "connections = " + connections ); + if ( singleton.getComponent() == component ) { connections--; + if ( connections == 0 ) { endComponentLifecycle( singleton ); + singleton = null; } - singleton = null; } else { getLogger().warn( "Component returned which is not the same instance. Ignored. component=" + component ); } } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#dispose() */ public void dispose() { //wait for all the clients to return all the components //Do we do this in a seperate thread? or block the current thread?? //TODO if ( singleton != null ) { endComponentLifecycle( singleton ); } } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#getComponent() */ public Object getComponent() throws Exception { if ( singleton == null ) { singleton = newHousingInstance(); } + connections++; + return singleton.getComponent(); } /** * @see org.codehaus.plexus.service.repository.instance.InstanceManager#getConnections() */ public int getConnections() { return connections; } } \ No newline at end of file
false
false
null
null
diff --git a/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java b/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java index 9862b8de..fe5fb2d8 100644 --- a/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java +++ b/tests/appsecurity-tests/src/com/android/cts/appsecurity/AppSecurityTests.java @@ -1,314 +1,317 @@ /* * 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.cts.appsecurity; import java.io.File; import java.io.IOException; import junit.framework.Test; import com.android.ddmlib.Log; import com.android.ddmlib.testrunner.ITestRunListener; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; import com.android.ddmlib.testrunner.TestIdentifier; import com.android.hosttest.DeviceTestCase; import com.android.hosttest.DeviceTestSuite; /** * Set of tests that verify various security checks involving multiple apps are properly enforced. */ public class AppSecurityTests extends DeviceTestCase { // testSharedUidDifferentCerts constants private static final String SHARED_UI_APK = "CtsSharedUidInstall.apk"; private static final String SHARED_UI_PKG = "com.android.cts.shareuidinstall"; private static final String SHARED_UI_DIFF_CERT_APK = "CtsSharedUidInstallDiffCert.apk"; private static final String SHARED_UI_DIFF_CERT_PKG = "com.android.cts.shareuidinstalldiffcert"; // testAppUpgradeDifferentCerts constants private static final String SIMPLE_APP_APK = "CtsSimpleAppInstall.apk"; private static final String SIMPLE_APP_PKG = "com.android.cts.simpleappinstall"; private static final String SIMPLE_APP_DIFF_CERT_APK = "CtsSimpleAppInstallDiffCert.apk"; // testAppFailAccessPrivateData constants private static final String APP_WITH_DATA_APK = "CtsAppWithData.apk"; private static final String APP_WITH_DATA_PKG = "com.android.cts.appwithdata"; private static final String APP_ACCESS_DATA_APK = "CtsAppAccessData.apk"; private static final String APP_ACCESS_DATA_PKG = "com.android.cts.appaccessdata"; // testInstrumentationDiffCert constants private static final String TARGET_INSTRUMENT_APK = "CtsTargetInstrumentationApp.apk"; private static final String TARGET_INSTRUMENT_PKG = "com.android.cts.targetinstrumentationapp"; private static final String INSTRUMENT_DIFF_CERT_APK = "CtsInstrumentationAppDiffCert.apk"; private static final String INSTRUMENT_DIFF_CERT_PKG = "com.android.cts.instrumentationdiffcertapp"; // testPermissionDiffCert constants private static final String DECLARE_PERMISSION_APK = "CtsPermissionDeclareApp.apk"; private static final String DECLARE_PERMISSION_PKG = "com.android.cts.permissiondeclareapp"; private static final String PERMISSION_DIFF_CERT_APK = "CtsUsePermissionDiffCert.apk"; private static final String PERMISSION_DIFF_CERT_PKG = "com.android.cts.usespermissiondiffcertapp"; private static final String LOG_TAG = "AppSecurityTests"; @Override protected void setUp() throws Exception { super.setUp(); // ensure apk path has been set before test is run assertNotNull(getTestAppPath()); } /** * Test that an app that declares the same shared uid as an existing app, cannot be installed * if it is signed with a different certificate. */ public void testSharedUidDifferentCerts() throws IOException { Log.i(LOG_TAG, "installing apks with shared uid, but different certs"); try { // cleanup test apps that might be installed from previous partial test run getDevice().uninstallPackage(SHARED_UI_PKG); getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG); String installResult = getDevice().installPackage(getTestAppFilePath(SHARED_UI_APK), false); assertNull("failed to install shared uid app", installResult); installResult = getDevice().installPackage(getTestAppFilePath(SHARED_UI_DIFF_CERT_APK), false); assertNotNull("shared uid app with different cert than existing app installed " + "successfully", installResult); assertEquals("INSTALL_FAILED_UPDATE_INCOMPATIBLE", installResult); } finally { getDevice().uninstallPackage(SHARED_UI_PKG); getDevice().uninstallPackage(SHARED_UI_DIFF_CERT_PKG); } } /** * Test that an app update cannot be installed over an existing app if it has a different * certificate. */ public void testAppUpgradeDifferentCerts() throws IOException { Log.i(LOG_TAG, "installing app upgrade with different certs"); try { // cleanup test app that might be installed from previous partial test run getDevice().uninstallPackage(SIMPLE_APP_PKG); String installResult = getDevice().installPackage(getTestAppFilePath(SIMPLE_APP_APK), false); assertNull("failed to install simple app", installResult); installResult = getDevice().installPackage(getTestAppFilePath(SIMPLE_APP_DIFF_CERT_APK), true /* reinstall */); assertNotNull("app upgrade with different cert than existing app installed " + "successfully", installResult); assertEquals("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES", installResult); } finally { getDevice().uninstallPackage(SIMPLE_APP_PKG); } } /** * Test that an app cannot access another app's private data. */ public void testAppFailAccessPrivateData() throws IOException { Log.i(LOG_TAG, "installing app that attempts to access another app's private data"); try { // cleanup test app that might be installed from previous partial test run getDevice().uninstallPackage(APP_WITH_DATA_PKG); getDevice().uninstallPackage(APP_ACCESS_DATA_PKG); String installResult = getDevice().installPackage(getTestAppFilePath(APP_WITH_DATA_APK), false); assertNull("failed to install app with data", installResult); // run appwithdata's tests to create private data assertTrue("failed to create app's private data", runDeviceTests(APP_WITH_DATA_PKG)); installResult = getDevice().installPackage(getTestAppFilePath(APP_ACCESS_DATA_APK), false); assertNull("failed to install app access data", installResult); // run appaccessdata's tests which attempt to access appwithdata's private data assertTrue("could access app's private data", runDeviceTests(APP_ACCESS_DATA_PKG)); } finally { getDevice().uninstallPackage(APP_WITH_DATA_PKG); getDevice().uninstallPackage(APP_ACCESS_DATA_PKG); } } /** * Test that an app cannot instrument another app that is signed with different certificate. */ public void testInstrumentationDiffCert() throws IOException { Log.i(LOG_TAG, "installing app that attempts to instrument another app"); try { // cleanup test app that might be installed from previous partial test run getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG); getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG); String installResult = getDevice().installPackage( getTestAppFilePath(TARGET_INSTRUMENT_APK), false); assertNull("failed to install target instrumentation app", installResult); // the app will install, but will get error at runtime installResult = getDevice().installPackage(getTestAppFilePath(INSTRUMENT_DIFF_CERT_APK), false); assertNull("failed to install instrumentation app with diff cert", installResult); // run INSTRUMENT_DIFF_CERT_PKG tests - expect the test run to fail String runResults = runDeviceTestsWithRunResult(INSTRUMENT_DIFF_CERT_PKG); assertNotNull("running instrumentation with diff cert unexpectedly succeeded", runResults); String msg = String.format("Unexpected error message result from %s. Received %s", "instrumentation with diff cert. Expected starts with Permission Denial", runResults); assertTrue(msg, runResults.startsWith("Permission Denial")); } finally { getDevice().uninstallPackage(TARGET_INSTRUMENT_PKG); getDevice().uninstallPackage(INSTRUMENT_DIFF_CERT_PKG); } } /** * Test that an app cannot use a signature-enforced permission if it is signed with a different * certificate than the app that declared the permission. */ public void testPermissionDiffCert() throws IOException { Log.i(LOG_TAG, "installing app that attempts to use permission of another app"); try { // cleanup test app that might be installed from previous partial test run getDevice().uninstallPackage(DECLARE_PERMISSION_PKG); getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG); String installResult = getDevice().installPackage( getTestAppFilePath(DECLARE_PERMISSION_APK), false); assertNull("failed to install declare permission app", installResult); // the app will install, but will get error at runtime installResult = getDevice().installPackage(getTestAppFilePath(PERMISSION_DIFF_CERT_APK), false); assertNull("failed to install permission app with diff cert", installResult); // run PERMISSION_DIFF_CERT_PKG tests which try to access the permission assertTrue("unexpected result when running permission tests", runDeviceTests(PERMISSION_DIFF_CERT_PKG)); } finally { getDevice().uninstallPackage(DECLARE_PERMISSION_PKG); getDevice().uninstallPackage(PERMISSION_DIFF_CERT_PKG); } } /** * Get the absolute file system location of test app with given filename * @param fileName the file name of the test app apk * @return {@link String} of absolute file path */ private String getTestAppFilePath(String fileName) { return String.format("%s%s%s", getTestAppPath(), File.separator, fileName); } /** * Helper method that will the specified packages tests on device. * * @param pkgName Android application package for tests * @return <code>true</code> if all tests passed. + * @throws IOException if connection to device was lost */ - private boolean runDeviceTests(String pkgName) { + private boolean runDeviceTests(String pkgName) throws IOException { CollectingTestRunListener listener = doRunTests(pkgName); return listener.didAllTestsPass(); } /** * Helper method to run tests and return the listener that collected the results. * @param pkgName Android application package for tests * @return the {@link CollectingTestRunListener} + * @throws IOException if connection to device was lost */ - private CollectingTestRunListener doRunTests(String pkgName) { + private CollectingTestRunListener doRunTests(String pkgName) throws IOException { RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner(pkgName, getDevice()); CollectingTestRunListener listener = new CollectingTestRunListener(); testRunner.run(listener); return listener; } /** * Helper method to run the specified packages tests, and return the test run error message. * * @param pkgName Android application package for tests * @return the test run error message or <code>null</code> if test run completed. + * @throws IOException if connection to device was lost */ - private String runDeviceTestsWithRunResult(String pkgName) { + private String runDeviceTestsWithRunResult(String pkgName) throws IOException { CollectingTestRunListener listener = doRunTests(pkgName); return listener.getTestRunErrorMessage(); } private static class CollectingTestRunListener implements ITestRunListener { private boolean mAllTestsPassed = true; private String mTestRunErrorMessage = null; public void testEnded(TestIdentifier test) { // ignore } public void testFailed(TestFailure status, TestIdentifier test, String trace) { Log.w(LOG_TAG, String.format("%s#%s failed: %s", test.getClassName(), test.getTestName(), trace)); mAllTestsPassed = false; } public void testRunEnded(long elapsedTime) { // ignore } public void testRunFailed(String errorMessage) { Log.w(LOG_TAG, String.format("test run failed: %s", errorMessage)); mAllTestsPassed = false; mTestRunErrorMessage = errorMessage; } public void testRunStarted(int testCount) { // ignore } public void testRunStopped(long elapsedTime) { // ignore } public void testStarted(TestIdentifier test) { // ignore } boolean didAllTestsPass() { return mAllTestsPassed; } /** * Get the test run failure error message. * @return the test run failure error message or <code>null</code> if test run completed. */ String getTestRunErrorMessage() { return mTestRunErrorMessage; } } public static Test suite() { return new DeviceTestSuite(AppSecurityTests.class); } }
false
false
null
null
diff --git a/rxjava-core/src/test/java/rx/ZipTests.java b/rxjava-core/src/test/java/rx/ZipTests.java index 97928a509..262f7dcb7 100644 --- a/rxjava-core/src/test/java/rx/ZipTests.java +++ b/rxjava-core/src/test/java/rx/ZipTests.java @@ -1,114 +1,141 @@ /** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx; +import static org.junit.Assert.*; + +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.Test; import rx.CovarianceTest.CoolRating; import rx.CovarianceTest.ExtendedResult; import rx.CovarianceTest.HorrorMovie; import rx.CovarianceTest.Media; import rx.CovarianceTest.Movie; import rx.CovarianceTest.Rating; import rx.CovarianceTest.Result; import rx.EventStream.Event; import rx.functions.Action1; import rx.functions.Func1; import rx.functions.Func2; +import rx.functions.FuncN; import rx.observables.GroupedObservable; public class ZipTests { @Test public void testZipObservableOfObservables() { EventStream.getEventStream("HTTP-ClusterB", 20) .groupBy(new Func1<Event, String>() { @Override public String call(Event e) { return e.instanceId; } // now we have streams of cluster+instanceId }).flatMap(new Func1<GroupedObservable<String, Event>, Observable<Map<String, String>>>() { @Override public Observable<Map<String, String>> call(final GroupedObservable<String, Event> ge) { return ge.scan(new HashMap<String, String>(), new Func2<Map<String, String>, Event, Map<String, String>>() { @Override public Map<String, String> call(Map<String, String> accum, Event perInstanceEvent) { accum.put("instance", ge.getKey()); return accum; } }); } }) .take(10) .toBlockingObservable().forEach(new Action1<Map<String, String>>() { @Override public void call(Map<String, String> v) { System.out.println(v); } }); System.out.println("**** finished"); } /** * This won't compile if super/extends isn't done correctly on generics */ @Test public void testCovarianceOfZip() { Observable<HorrorMovie> horrors = Observable.from(new HorrorMovie()); Observable<CoolRating> ratings = Observable.from(new CoolRating()); Observable.<Movie, CoolRating, Result> zip(horrors, ratings, combine).toBlockingObservable().forEach(action); Observable.<Movie, CoolRating, Result> zip(horrors, ratings, combine).toBlockingObservable().forEach(action); Observable.<Media, Rating, ExtendedResult> zip(horrors, ratings, combine).toBlockingObservable().forEach(extendedAction); Observable.<Media, Rating, Result> zip(horrors, ratings, combine).toBlockingObservable().forEach(action); Observable.<Media, Rating, ExtendedResult> zip(horrors, ratings, combine).toBlockingObservable().forEach(action); Observable.<Movie, CoolRating, Result> zip(horrors, ratings, combine); } + /** + * Occasionally zip may be invoked with 0 observables. This blocks indefinitely instead + * of immediately invoking zip with 0 argument. + */ + @Test(timeout = 5000) + public void nonBlockingObservable() { + + final Object invoked = new Object(); + + Collection<Observable<Object>> observables = Collections.emptyList(); + + Observable<Object> result = Observable.zip(observables, new FuncN<Object>() { + @Override + public Object call(final Object... args) { + assertEquals("No argument should have been passed", 0, args.length); + return invoked; + } + }); + + assertSame(invoked, result.toBlockingObservable().last()); + } + Func2<Media, Rating, ExtendedResult> combine = new Func2<Media, Rating, ExtendedResult>() { @Override public ExtendedResult call(Media m, Rating r) { return new ExtendedResult(); } }; Action1<Result> action = new Action1<Result>() { @Override public void call(Result t1) { System.out.println("Result: " + t1); } }; Action1<ExtendedResult> extendedAction = new Action1<ExtendedResult>() { @Override public void call(ExtendedResult t1) { System.out.println("Result: " + t1); } }; }
false
false
null
null
diff --git a/src/main/java/org/thymeleaf/standard/fragment/StandardFragment.java b/src/main/java/org/thymeleaf/standard/fragment/StandardFragment.java index 4e462c16..a4435f4a 100755 --- a/src/main/java/org/thymeleaf/standard/fragment/StandardFragment.java +++ b/src/main/java/org/thymeleaf/standard/fragment/StandardFragment.java @@ -1,228 +1,231 @@ /* * ============================================================================= * * Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.standard.fragment; import java.util.Collections; import java.util.List; import java.util.Map; import org.thymeleaf.Arguments; import org.thymeleaf.Configuration; import org.thymeleaf.Template; import org.thymeleaf.TemplateProcessingParameters; import org.thymeleaf.TemplateRepository; import org.thymeleaf.context.IProcessingContext; import org.thymeleaf.dom.NestableAttributeHolderNode; import org.thymeleaf.dom.Node; import org.thymeleaf.exceptions.TemplateProcessingException; import org.thymeleaf.fragment.IFragmentSpec; import org.thymeleaf.standard.expression.FragmentSignature; import org.thymeleaf.standard.expression.StandardExpressionProcessor; import org.thymeleaf.util.Validate; /** * <p> * Object modelling the result of resolving a standard fragment specification, after all its expressions * have been evaluated, its parameters parsed, etc. * </p> * <p> * Note that the specified template can be null, in which case the fragment will * be considered to be executed on the current template (obtained from the * IProcessingContext argument in * {@link #extractFragment(org.thymeleaf.Configuration, org.thymeleaf.context.IProcessingContext, * org.thymeleaf.TemplateRepository, java.lang.String)}, * which will therefore need to be an instance of * {@link org.thymeleaf.Arguments}). * </p> * * @author Daniel Fern&aacute;ndez * * @since 2.1.0 * */ public final class StandardFragment { private final String templateName; private final IFragmentSpec fragmentSpec; private final Map<String,Object> parameters; /** * <p> * Create a new instance of this class. * </p> * * @param templateName the name of the template that will be resolved and parsed, null if * fragment is to be executed on the current template. * @param fragmentSpec the fragment spec that will be applied to the template, once parsed. * @param parameters the parameters to be applied to the fragment, when processed. */ public StandardFragment(final String templateName, final IFragmentSpec fragmentSpec, final Map<String, Object> parameters) { super(); // templateName can be null if target template is the current one Validate.notNull(fragmentSpec, "Fragment spec cannot be null or empty"); this.templateName = templateName; this.fragmentSpec = fragmentSpec; this.parameters = parameters; } /** * <p> * Returns the name of the template that will be resolved and parsed. * </p> * * @return the template name. */ public String getTemplateName() { return this.templateName; } /** * <p> * Returns the {@link org.thymeleaf.fragment.IFragmentSpec} that will be applied to the template. * </p> * * @return the fragment spec. */ public IFragmentSpec getFragmentSpec() { return this.fragmentSpec; } /** * <p> * Returns the parameters that will be applied to the fragment. * </p> * - * @return the map of parameters. + * @return the map of parameters. May return null if no parameters exist. */ public Map<String,Object> getParameters() { + if (this.parameters == null) { + return null; + } return Collections.unmodifiableMap(this.parameters); } /** * <p> * Read the specified template from {@link org.thymeleaf.TemplateRepository}, and then apply * the {@link org.thymeleaf.fragment.IFragmentSpec} to the result of parsing it (the template). * </p> * <p> * Fragment parameters will also be processed and applied as local variables of the returned nodes. * </p> * <p> * In order to execute on the current template (templateName == null), the <tt>context</tt> * argument will need to be an {@link org.thymeleaf.Arguments} object. * </p> * * @param configuration the configuration to be used for resolving the template and * processing the fragment spec. * @param context the processing context to be used for resolving and parsing the template. * @param templateRepository the template repository to be asked for the template. * @param fragmentSignatureAttributeName the name of the attribute in which we could expect to find a * fragment * @return the result of parsing + applying the fragment spec. */ public List<Node> extractFragment( final Configuration configuration, final IProcessingContext context, final TemplateRepository templateRepository, final String fragmentSignatureAttributeName) { String targetTemplateName = getTemplateName(); if (targetTemplateName == null) { if (context != null && context instanceof Arguments) { targetTemplateName = ((Arguments)context).getTemplateName(); } else { throw new TemplateProcessingException( "In order to extract fragment from current template (templateName == null), processing context " + "must be a non-null instance of the Arguments class (but is: " + (context == null? null : context.getClass().getName()) + ")"); } } final TemplateProcessingParameters fragmentTemplateProcessingParameters = new TemplateProcessingParameters(configuration, targetTemplateName, context); final Template parsedFragmentTemplate = templateRepository.getTemplate(fragmentTemplateProcessingParameters); final List<Node> nodes = this.fragmentSpec.extractFragment(configuration, parsedFragmentTemplate.getDocument().getChildren()); /* * CHECK RETURNED NODES: if there is only one node, check whether it contains a fragment signature (normally, * a "th:fragment" attribute). If so, let the signature process the parameters before being applied. If no * signature is found, then just apply the parameters to every returning node. */ if (nodes == null) { return null; } // Detach nodes from their parents, before returning them. This might help the GC. for (final Node node : nodes) { if (node.hasParent()) { node.getParent().clearChildren(); } } // Check whether this is a node specifying a fragment signature. If it is, process its parameters. if (nodes.size() == 1 && fragmentSignatureAttributeName != null) { final Node node = nodes.get(0); if (node instanceof NestableAttributeHolderNode) { final NestableAttributeHolderNode attributeHolderNode = (NestableAttributeHolderNode)node; if (attributeHolderNode.hasNormalizedAttribute(fragmentSignatureAttributeName)) { final String attributeValue = attributeHolderNode.getAttributeValue(fragmentSignatureAttributeName); if (attributeValue != null) { final FragmentSignature fragmentSignature = StandardExpressionProcessor.parseFragmentSignature(configuration, attributeValue); if (fragmentSignature != null) { final Map<String,Object> processedParameters = fragmentSignature.processParameters(this.parameters); applyParameters(nodes, processedParameters); return nodes; } } } } } applyParameters(nodes, this.parameters); return nodes; } private static void applyParameters(final List<Node> nodes, final Map<String,Object> parameters) { for (final Node node : nodes) { node.setAllNodeLocalVariables(parameters); } } }
false
false
null
null
diff --git a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java index 81a4793..270ad08 100644 --- a/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java +++ b/src/main/java/com/brotherlogic/booser/servlets/APIEndpoint.java @@ -1,246 +1,245 @@ package com.brotherlogic.booser.servlets; import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.brotherlogic.booser.Config; import com.brotherlogic.booser.atom.Atom; import com.brotherlogic.booser.atom.Beer; import com.brotherlogic.booser.atom.Drink; import com.brotherlogic.booser.atom.FoursquareVenue; import com.brotherlogic.booser.atom.User; import com.brotherlogic.booser.atom.Venue; import com.brotherlogic.booser.storage.AssetManager; import com.brotherlogic.booser.storage.db.Database; import com.brotherlogic.booser.storage.db.DatabaseFactory; import com.brotherlogic.booser.storage.web.Downloader; import com.brotherlogic.booser.storage.web.WebLayer; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class APIEndpoint extends UntappdBaseServlet { - private static final String baseURL = "http://localhost:8080/"; - // private static final String baseURL = - // "http://booser-beautiful.rhcloud.com/"; + // private static final String baseURL = "http://localhost:8080/"; + private static final String baseURL = "http://booser-beautiful.rhcloud.com/"; private static final int COOKIE_AGE = 60 * 60 * 24 * 365; private static final String COOKIE_NAME = "untappdpicker_cookie"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String token = getUserToken(req, resp); System.out.println("Got the user token"); // If we're not logged in, server will redirect if (token != "not_logged_in") { AssetManager manager = AssetManager.getManager(token); String action = req.getParameter("action"); if (action == null) { resp.sendRedirect("/"); return; } if (action.equals("getVenue")) { double lat = Double.parseDouble(req.getParameter("lat")); double lon = Double.parseDouble(req.getParameter("lon")); List<Atom> venues = getFoursquareVenues(lat, lon); processJson(resp, venues); } else if (action.equals("getNumberOfDrinks")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); User u = manager.getUser(); List<Drink> beers = u.getDrinks(); JsonObject obj = new JsonObject(); obj.add("drinks", new JsonPrimitive(beers.size())); obj.add("username", new JsonPrimitive(u.getId())); write(resp, obj); System.out.println("CALLS = " + db.getNumberOfCalls()); } else if (action.equals("getDrinks")) { User u = manager.getUser(); List<Drink> drinks = u.getDrinks(); Map<Beer, Integer> counts = new TreeMap<Beer, Integer>(); Map<Beer, Double> beers = new TreeMap<Beer, Double>(); for (Drink d : drinks) { if (!counts.containsKey(d.getBeer())) counts.put(d.getBeer(), 1); else counts.put(d.getBeer(), counts.get(d.getBeer()) + 1); beers.put(d.getBeer(), d.getRating_score()); } Gson gson = new Gson(); JsonArray arr = new JsonArray(); for (Beer b : beers.keySet()) { JsonObject obj = gson.toJsonTree(b).getAsJsonObject(); obj.add("rating", new JsonPrimitive(beers.get(b))); obj.add("drunkcount", new JsonPrimitive(counts.get(b))); arr.add(obj); } write(resp, arr); } else if (action.equals("users")) { Database db = DatabaseFactory.getInstance().getDatabase(); db.reset(); List<Atom> users = manager.getUsers(); JsonArray arr = new JsonArray(); for (Atom user : users) arr.add(new JsonPrimitive(user.getId())); write(resp, arr); System.out.println("CALLS = " + db.getNumberOfCalls()); } } } public List<Atom> getFoursquareVenues(double lat, double lon) { try { WebLayer layer = new WebLayer(); List<Atom> atoms = layer.getLocal(FoursquareVenue.class, new URL("https://api.foursquare.com/v2/venues/search?ll=" + lat + "," + lon + "&client_id=" + Config.getFoursquareClientId() + "&" + "client_secret=" + Config.getFoursquareSecret() + "&v=20130118")); return atoms; } catch (MalformedURLException e) { e.printStackTrace(); } return new LinkedList<Atom>(); } public String getUserDetails(String userToken) throws IOException { User u = AssetManager.getManager(userToken).getUser(); return u.getJson(); } /** * Gets the user token from the request * * @param req * The servlet request object * @return The User Token */ private String getUserToken(final HttpServletRequest req, final HttpServletResponse resp) { if (req.getCookies() != null) for (Cookie cookie : req.getCookies()) if (cookie.getName().equals(COOKIE_NAME)) return cookie.getValue(); // Forward the thingy on to the login point try { // Check we're not in the login process if (req.getParameter("code") != null) { Thread.dumpStack(); String response = Downloader.getInstance().download( new URL("https://untappd.com/oauth/authorize/?client_id=" + Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret() + "&response_type=code&redirect_url=" + baseURL + "API&code=" + req.getParameter("code"))); System.out.println("RESP = " + response); // Get the access token JsonParser parser = new JsonParser(); String nToken = parser.parse(response).getAsJsonObject().get("response") .getAsJsonObject().get("access_token").getAsString(); // Set the cookie Cookie cookie = new Cookie(COOKIE_NAME, nToken); cookie.setMaxAge(COOKIE_AGE); cookie.setPath("/"); resp.addCookie(cookie); System.out.println("RETURNING"); return nToken; } else resp.sendRedirect("http://untappd.com/oauth/authenticate/?client_id=" + Config.getUntappdClient() + "&client_secret=" + Config.getUntappdSecret() + "&response_type=code&redirect_url=" + baseURL + "API"); } catch (IOException e) { e.printStackTrace(); } return "not_logged_in"; } public List<Venue> getVenues(String userToken, double latitude, double longitude) { List<Atom> fsVenues = getFoursquareVenues(latitude, longitude); List<Venue> venues = new LinkedList<Venue>(); for (Atom fsVenue : fsVenues) venues.add(AssetManager.getManager(userToken).getVenue(fsVenue.getId())); return venues; } private void processJson(HttpServletResponse resp, List<Atom> atoms) throws IOException { StringBuffer ret = new StringBuffer("["); ret.append(atoms.get(0).toString()); for (Atom atom : atoms) ret.append("," + atom.getJson()); ret.append("]"); write(resp, ret.toString()); } private void write(HttpServletResponse resp, JsonElement obj) throws IOException { write(resp, obj.toString()); } private void write(HttpServletResponse resp, String jsonString) throws IOException { resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); out.print(jsonString); out.close(); } }
true
false
null
null
diff --git a/jmdns/src/javax/jmdns/impl/JmDNSImpl.java b/jmdns/src/javax/jmdns/impl/JmDNSImpl.java index 78826c8..0b3cfdf 100644 --- a/jmdns/src/javax/jmdns/impl/JmDNSImpl.java +++ b/jmdns/src/javax/jmdns/impl/JmDNSImpl.java @@ -1,1980 +1,1984 @@ ///Copyright 2003-2005 Arthur van Hoff, Rick Blair //Licensed under Apache License version 2.0 //Original license LGPL package javax.jmdns.impl; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.SocketException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import javax.jmdns.ServiceTypeListener; import javax.jmdns.ServiceInfo.Fields; import javax.jmdns.impl.constants.DNSConstants; import javax.jmdns.impl.constants.DNSRecordClass; import javax.jmdns.impl.constants.DNSRecordType; import javax.jmdns.impl.constants.DNSState; import javax.jmdns.impl.tasks.DNSTask; import javax.jmdns.impl.tasks.RecordReaper; import javax.jmdns.impl.tasks.Responder; import javax.jmdns.impl.tasks.resolver.ServiceInfoResolver; import javax.jmdns.impl.tasks.resolver.ServiceResolver; import javax.jmdns.impl.tasks.resolver.TypeResolver; import javax.jmdns.impl.tasks.state.Announcer; import javax.jmdns.impl.tasks.state.Canceler; import javax.jmdns.impl.tasks.state.Prober; import javax.jmdns.impl.tasks.state.Renewer; // REMIND: multiple IP addresses /** * mDNS implementation in Java. * * @version %I%, %G% * @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis */ public class JmDNSImpl extends JmDNS implements DNSStatefulObject { private static Logger logger = Logger.getLogger(JmDNSImpl.class.getName()); public enum Operation { Remove, Update, Add, RegisterServiceType, Noop } /** * This is the multicast group, we are listening to for multicast DNS messages. */ private volatile InetAddress _group; /** * This is our multicast socket. */ private volatile MulticastSocket _socket; /** * Used to fix live lock problem on unregister. */ private volatile boolean _closed = false; /** * Holds instances of JmDNS.DNSListener. Must by a synchronized collection, because it is updated from concurrent threads. */ private final List<DNSListener> _listeners; /** * Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's. */ private final ConcurrentMap<String, List<ServiceListener>> _serviceListeners; /** * Holds instances of ServiceTypeListener's. */ private final Set<ServiceTypeListener> _typeListeners; /** * Cache for DNSEntry's. */ private DNSCache _cache; /** * This hashtable holds the services that have been registered. Keys are instances of String which hold an all lower-case version of the fully qualified service name. Values are instances of ServiceInfo. */ private final ConcurrentMap<String, ServiceInfo> _services; /** * This hashtable holds the service types that have been registered or that have been received in an incoming datagram. Keys are instances of String which hold an all lower-case version of the fully qualified service type. Values hold the fully * qualified service type. */ private final ConcurrentMap<String, Set<String>> _serviceTypes; /** * This is the shutdown hook, we registered with the java runtime. */ protected Thread _shutdown; /** * Handle on the local host */ private HostInfo _localHost; private Thread _incomingListener; /** * Throttle count. This is used to count the overall number of probes sent by JmDNS. When the last throttle increment happened . */ private int _throttle; /** * Last throttle increment. */ private long _lastThrottleIncrement; // // 2009-09-16 ldeck: adding docbug patch with slight ammendments // 'Fixes two deadlock conditions involving JmDNS.close() - ID: 1473279' // // --------------------------------------------------- /** * The timer that triggers our announcements. We can't use the main timer object, because that could cause a deadlock where Prober waits on JmDNS.this lock held by close(), close() waits for us to finish, and we wait for Prober to give us back * the timer thread so we can announce. (Patch from docbug in 2006-04-19 still wasn't patched .. so I'm doing it!) */ // private final Timer _cancelerTimer; // --------------------------------------------------- /** * The timer is used to dispatch all outgoing messages of JmDNS. It is also used to dispatch maintenance tasks for the DNS cache. */ private final Timer _timer; /** * The timer is used to dispatch maintenance tasks for the DNS cache. */ private final Timer _stateTimer; /** * The source for random values. This is used to introduce random delays in responses. This reduces the potential for collisions on the network. */ private final static Random _random = new Random(); /** * This lock is used to coordinate processing of incoming and outgoing messages. This is needed, because the Rendezvous Conformance Test does not forgive race conditions. */ private final ReentrantLock _ioLock = new ReentrantLock(); /** * If an incoming package which needs an answer is truncated, we store it here. We add more incoming DNSRecords to it, until the JmDNS.Responder timer picks it up.<br/> * FIXME [PJYF June 8 2010]: This does not work well with multiple planned answers for packages that came in from different clients. */ private DNSIncoming _plannedAnswer; // State machine /** * This hashtable is used to maintain a list of service types being collected by this JmDNS instance. The key of the hashtable is a service type name, the value is an instance of JmDNS.ServiceCollector. * * @see #list */ private final ConcurrentMap<String, ServiceCollector> _serviceCollectors; private final String _name; /** * Create an instance of JmDNS and bind it to a specific network interface given its IP-address. * * @param address * IP address to bind to. * @param name * name of the newly created JmDNS * @throws IOException */ public JmDNSImpl(InetAddress address, String name) throws IOException { super(); logger.finer("JmDNS instance created"); _cache = new DNSCache(100); _listeners = Collections.synchronizedList(new ArrayList<DNSListener>()); _serviceListeners = new ConcurrentHashMap<String, List<ServiceListener>>(); _typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListener>()); _serviceCollectors = new ConcurrentHashMap<String, ServiceCollector>(); _services = new ConcurrentHashMap<String, ServiceInfo>(20); _serviceTypes = new ConcurrentHashMap<String, Set<String>>(20); _localHost = HostInfo.newHostInfo(address, this); _name = (name != null ? name : _localHost.getName()); _timer = new Timer("JmDNS(" + _name + ").Timer", true); _stateTimer = new Timer("JmDNS(" + _name + ").State.Timer", false); // _cancelerTimer = new Timer("JmDNS.cancelerTimer"); // (ldeck 2.1.1) preventing shutdown blocking thread // ------------------------------------------------- // _shutdown = new Thread(new Shutdown(), "JmDNS.Shutdown"); // Runtime.getRuntime().addShutdownHook(_shutdown); // ------------------------------------------------- // Bind to multicast socket this.openMulticastSocket(this.getLocalHost()); this.start(this.getServices().values()); new RecordReaper(this).start(_timer); } private void start(Collection<? extends ServiceInfo> serviceInfos) { if (_incomingListener == null) { _incomingListener = new Thread(new SocketListener(this), "JmDNS(" + _name + ").SocketListener"); _incomingListener.setDaemon(true); _incomingListener.start(); } this.startProber(); for (ServiceInfo info : serviceInfos) { try { this.registerService(new ServiceInfoImpl(info)); } catch (final Exception exception) { logger.log(Level.WARNING, "start() Registration exception ", exception); } } } private void openMulticastSocket(HostInfo hostInfo) throws IOException { if (_group == null) { _group = InetAddress.getByName(DNSConstants.MDNS_GROUP); } if (_socket != null) { this.closeMulticastSocket(); } _socket = new MulticastSocket(DNSConstants.MDNS_PORT); if ((hostInfo != null) && (hostInfo.getInterface() != null)) { try { _socket.setNetworkInterface(hostInfo.getInterface()); } catch (SocketException e) { logger.fine("openMulticastSocket() Set network interface exception: " + e.getMessage()); } } _socket.setTimeToLive(255); _socket.joinGroup(_group); } private void closeMulticastSocket() { // jP: 20010-01-18. See below. We'll need this monitor... // assert (Thread.holdsLock(this)); logger.finer("closeMulticastSocket()"); if (_socket != null) { // close socket try { try { _socket.leaveGroup(_group); } catch (SocketException exception) { // } _socket.close(); // jP: 20010-01-18. It isn't safe to join() on the listener // thread - it attempts to lock the IoLock object, and deadlock // ensues. Per issue #2933183, changed this to wait on the JmDNS // monitor, checking on each notify (or timeout) that the // listener thread has stopped. // while (_incomingListener != null && _incomingListener.isAlive()) { synchronized (this) { try { // wait time is arbitrary, we're really expecting notification. logger.finer("closeMulticastSocket(): waiting for jmDNS monitor"); this.wait(1000); } catch (InterruptedException ignored) { // Ignored } } } _incomingListener = null; } catch (final Exception exception) { logger.log(Level.WARNING, "closeMulticastSocket() Close socket exception ", exception); } _socket = null; } } // State machine /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#advanceState(javax.jmdns.impl.tasks.DNSTask) */ @Override public boolean advanceState(DNSTask task) { return this._localHost.advanceState(task); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#revertState() */ @Override public boolean revertState() { return this._localHost.revertState(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#cancel() */ @Override public boolean cancelState() { return this._localHost.cancelState(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#recover() */ @Override public boolean recoverState() { return this._localHost.recoverState(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#getDns() */ @Override public JmDNSImpl getDns() { return this; } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#associateWithTask(javax.jmdns.impl.tasks.DNSTask, javax.jmdns.impl.constants.DNSState) */ @Override public void associateWithTask(DNSTask task, DNSState state) { this._localHost.associateWithTask(task, state); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#removeAssociationWithTask(javax.jmdns.impl.tasks.DNSTask) */ @Override public void removeAssociationWithTask(DNSTask task) { this._localHost.removeAssociationWithTask(task); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isAssociatedWithTask(javax.jmdns.impl.tasks.DNSTask, javax.jmdns.impl.constants.DNSState) */ @Override public boolean isAssociatedWithTask(DNSTask task, DNSState state) { return this._localHost.isAssociatedWithTask(task, state); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isProbing() */ @Override public boolean isProbing() { return this._localHost.isProbing(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isAnnouncing() */ @Override public boolean isAnnouncing() { return this._localHost.isAnnouncing(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isAnnounced() */ @Override public boolean isAnnounced() { return this._localHost.isAnnounced(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isCanceling() */ @Override public boolean isCanceling() { return this._localHost.isCanceling(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#isCanceled() */ @Override public boolean isCanceled() { return this._localHost.isCanceled(); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#waitForAnnounced(long) */ @Override public boolean waitForAnnounced(long timeout) { return this._localHost.waitForAnnounced(timeout); } /* * (non-Javadoc) * * @see javax.jmdns.impl.DNSStatefulObject#waitForCanceled(long) */ @Override public boolean waitForCanceled(long timeout) { return this._localHost.waitForCanceled(timeout); } /** * Return the DNSCache associated with the cache variable * * @return DNS cache */ public DNSCache getCache() { return _cache; } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getName() */ @Override public String getName() { return _name; } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getHostName() */ @Override public String getHostName() { return _localHost.getName(); } /** * Returns the local host info * * @return local host info */ public HostInfo getLocalHost() { return _localHost; } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getInterface() */ @Override public InetAddress getInterface() throws IOException { return _socket.getInterface(); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String) */ @Override public ServiceInfo getServiceInfo(String type, String name) { return this.getServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String) */ @Override public ServiceInfo getServiceInfo(String type, String name, long timeout) { return this.getServiceInfo(type, name, false, timeout); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String) */ @Override public ServiceInfo getServiceInfo(String type, String name, boolean persistent) { return this.getServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, int) */ @Override public ServiceInfo getServiceInfo(String type, String name, boolean persistent, long timeout) { final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent); this.waitForInfoData(info, timeout); return (info.hasData() ? info : null); } ServiceInfoImpl resolveServiceInfo(String type, String name, String subtype, boolean persistent) { String lotype = type.toLowerCase(); this.registerServiceType(lotype); if (_serviceCollectors.putIfAbsent(lotype, new ServiceCollector(lotype)) == null) { this.addServiceListener(lotype, _serviceCollectors.get(lotype)); } // Check if the answer is in the cache. final ServiceInfoImpl info = this.getServiceInfoFromCache(type, name, subtype, persistent); // We still run the resolver to do the dispatch but if the info is already there it will quit immediately new ServiceInfoResolver(this, info).start(_timer); return info; } ServiceInfoImpl getServiceInfoFromCache(String type, String name, String subtype, boolean persistent) { // Check if the answer is in the cache. ServiceInfoImpl info = new ServiceInfoImpl(type, name, subtype, 0, 0, 0, persistent, (byte[]) null); DNSEntry pointerEntry = this.getCache().getDNSEntry(new DNSRecord.Pointer(type, DNSRecordClass.CLASS_ANY, false, 0, info.getQualifiedName())); if (pointerEntry instanceof DNSRecord) { ServiceInfoImpl cachedInfo = (ServiceInfoImpl) ((DNSRecord) pointerEntry).getServiceInfo(persistent); if (cachedInfo != null) { // To get a complete info record we need to retrieve the service, address and the text bytes. Map<Fields, String> map = cachedInfo.getQualifiedNameMap(); byte[] srvBytes = null; String server = ""; DNSEntry serviceEntry = this.getCache().getDNSEntry(info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_ANY); if (serviceEntry instanceof DNSRecord) { ServiceInfo cachedServiceEntryInfo = ((DNSRecord) serviceEntry).getServiceInfo(persistent); if (cachedServiceEntryInfo != null) { cachedInfo = new ServiceInfoImpl(map, cachedServiceEntryInfo.getPort(), cachedServiceEntryInfo.getWeight(), cachedServiceEntryInfo.getPriority(), persistent, (byte[]) null); srvBytes = cachedServiceEntryInfo.getTextBytes(); server = cachedServiceEntryInfo.getServer(); } } DNSEntry addressEntry = this.getCache().getDNSEntry(server, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_ANY); if (addressEntry instanceof DNSRecord) { ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent); if (cachedAddressInfo != null) { cachedInfo.setAddress(cachedAddressInfo.getInet4Address()); cachedInfo._setText(cachedAddressInfo.getTextBytes()); } } addressEntry = this.getCache().getDNSEntry(server, DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_ANY); if (addressEntry instanceof DNSRecord) { ServiceInfo cachedAddressInfo = ((DNSRecord) addressEntry).getServiceInfo(persistent); if (cachedAddressInfo != null) { cachedInfo.setAddress(cachedAddressInfo.getInet6Address()); cachedInfo._setText(cachedAddressInfo.getTextBytes()); } } DNSEntry textEntry = this.getCache().getDNSEntry(cachedInfo.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_ANY); if (textEntry instanceof DNSRecord) { ServiceInfo cachedTextInfo = ((DNSRecord) textEntry).getServiceInfo(persistent); if (cachedTextInfo != null) { cachedInfo._setText(cachedTextInfo.getTextBytes()); } } if (cachedInfo.getTextBytes().length == 0) { cachedInfo._setText(srvBytes); } if (cachedInfo.hasData()) { info = cachedInfo; } } } return info; } private void waitForInfoData(ServiceInfo info, long timeout) { synchronized (info) { long loops = (timeout / 200L); if (loops < 1) { loops = 1; } for (int i = 0; i < loops; i++) { + if (info.hasData()) + { + break; + } try { info.wait(200); } catch (final InterruptedException e) { /* Stub */ } - if (info.hasData()) - { - break; - } } } } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String) */ @Override public void requestServiceInfo(String type, String name) { this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean) */ @Override public void requestServiceInfo(String type, String name, boolean persistent) { this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, int) */ @Override public void requestServiceInfo(String type, String name, long timeout) { this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, int) */ @Override public void requestServiceInfo(String type, String name, boolean persistent, long timeout) { final ServiceInfoImpl info = this.resolveServiceInfo(type, name, "", persistent); this.waitForInfoData(info, timeout); } void handleServiceResolved(ServiceEvent event) { List<ServiceListener> list = _serviceListeners.get(event.getType().toLowerCase()); List<ServiceListener> listCopy = Collections.emptyList(); if ((list != null) && (!list.isEmpty())) { if ((event.getInfo() != null) && event.getInfo().hasData()) { synchronized (list) { listCopy = new ArrayList<ServiceListener>(list); } for (ServiceListener listener : listCopy) { listener.serviceResolved(event); } } } } /** * @see javax.jmdns.JmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener ) */ @Override public void addServiceTypeListener(ServiceTypeListener listener) throws IOException { _typeListeners.add(listener); // report cached service types for (String type : _serviceTypes.keySet()) { listener.serviceTypeAdded(new ServiceEventImpl(this, type, "", null)); } new TypeResolver(this).start(_timer); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener) */ @Override public void removeServiceTypeListener(ServiceTypeListener listener) { _typeListeners.remove(listener); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void addServiceListener(String type, ServiceListener listener) { final String lotype = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(lotype); if (list == null) { if (_serviceListeners.putIfAbsent(lotype, new LinkedList<ServiceListener>()) == null) { if (_serviceCollectors.putIfAbsent(lotype, new ServiceCollector(lotype)) == null) { this.addServiceListener(lotype, _serviceCollectors.get(lotype)); } } list = _serviceListeners.get(lotype); } synchronized (list) { if (!list.contains(listener)) { list.add(listener); } } // report cached service types final List<ServiceEvent> serviceEvents = new ArrayList<ServiceEvent>(); Collection<DNSEntry> dnsEntryLits = this.getCache().allValues(); for (DNSEntry entry : dnsEntryLits) { final DNSRecord record = (DNSRecord) entry; if (record.getRecordType() == DNSRecordType.TYPE_SRV) { if (record.getName().endsWith(type)) { // Do not used the record embedded method for generating event this will not work. // serviceEvents.add(record.getServiceEvent(this)); serviceEvents.add(new ServiceEventImpl(this, type, toUnqualifiedName(type, record.getName()), record.getServiceInfo())); } } } // Actually call listener with all service events added above for (ServiceEvent serviceEvent : serviceEvents) { listener.serviceAdded(serviceEvent); } // Create/start ServiceResolver new ServiceResolver(this, type).start(_timer); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener) */ @Override public void removeServiceListener(String type, ServiceListener listener) { String aType = type.toLowerCase(); List<ServiceListener> list = _serviceListeners.get(aType); if (list != null) { synchronized (list) { list.remove(listener); if (list.isEmpty()) { _serviceListeners.remove(aType, list); } } } } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#registerService(javax.jmdns.ServiceInfo) */ @Override public void registerService(ServiceInfo infoAbstract) throws IOException { final ServiceInfoImpl info = (ServiceInfoImpl) infoAbstract; if ((info.getDns() != null) && (info.getDns() != this)) { throw new IllegalStateException("This service information is already registered with another DNS."); } info.setDns(this); this.registerServiceType(info.getTypeWithSubtype()); // bind the service to this address info.setServer(_localHost.getName()); info.setAddress(_localHost.getInet4Address()); info.setAddress(_localHost.getInet6Address()); this.waitForAnnounced(0); this.makeServiceNameUnique(info); while (_services.putIfAbsent(info.getQualifiedName().toLowerCase(), info) != null) { this.makeServiceNameUnique(info); } new /* Service */Prober(this).start(_stateTimer); info.waitForAnnounced(0); logger.fine("registerService() JmDNS registered service as " + info); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#unregisterService(javax.jmdns.ServiceInfo) */ @Override public void unregisterService(ServiceInfo infoAbstract) { final ServiceInfoImpl info = (ServiceInfoImpl) infoAbstract; _services.remove(info.getQualifiedName().toLowerCase()); info.cancelState(); this.startCanceler(); // Remind: We get a deadlock here, if the Canceler does not run! info.waitForCanceled(0); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#unregisterAllServices() */ @Override public void unregisterAllServices() { logger.finer("unregisterAllServices()"); for (String name : _services.keySet()) { ServiceInfoImpl info = (ServiceInfoImpl) _services.get(name); if (info != null) { logger.finer("Cancelling service info: " + info); info.cancelState(); } } this.startCanceler(); for (String name : _services.keySet()) { ServiceInfoImpl info = (ServiceInfoImpl) _services.get(name); if (info != null) { logger.finer("Wait for service info cancel: " + info); info.waitForCanceled(DNSConstants.CLOSE_TIMEOUT); _services.remove(name, info); } } } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#registerServiceType(java.lang.String) */ @Override public boolean registerServiceType(String type) { boolean typeAdded = false; Map<Fields, String> map = ServiceInfoImpl.decodeQualifiedNameMapForType(type); String domain = map.get(Fields.Domain); String protocol = map.get(Fields.Protocol); String application = map.get(Fields.Application); String subtype = map.get(Fields.Subtype); String name = (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + "."; logger.fine(this.getName() + ".registering service type: " + type + " as: " + name + (subtype.length() > 0 ? " subtype: " + subtype : "")); if (!_serviceTypes.containsKey(name) && !application.equals("dns-sd") && !domain.endsWith("in-addr.arpa") && !domain.endsWith("ip6.arpa")) { typeAdded = _serviceTypes.putIfAbsent(name, new HashSet<String>()) == null; if (typeAdded) { final ServiceTypeListener[] list = _typeListeners.toArray(new ServiceTypeListener[_typeListeners.size()]); final ServiceEvent event = new ServiceEventImpl(this, name, "", null); for (ServiceTypeListener listener : list) { listener.serviceTypeAdded(event); } } } if (subtype.length() > 0) { Set<String> subtypes = _serviceTypes.get(name); if (!subtypes.contains(subtype)) { synchronized (subtypes) { if (!subtypes.contains(subtype)) { typeAdded = true; subtypes.add(subtype); final ServiceTypeListener[] list = _typeListeners.toArray(new ServiceTypeListener[_typeListeners.size()]); final ServiceEvent event = new ServiceEventImpl(this, "_" + subtype + "._sub." + name, "", null); for (ServiceTypeListener listener : list) { listener.subTypeForServiceTypeAdded(event); } } } } } return typeAdded; } /** * Generate a possibly unique name for a service using the information we have in the cache. * * @return returns true, if the name of the service info had to be changed. */ private boolean makeServiceNameUnique(ServiceInfoImpl info) { final String originalQualifiedName = info.getQualifiedName(); final long now = System.currentTimeMillis(); boolean collision; do { collision = false; // Check for collision in cache Collection<? extends DNSEntry> entryList = this.getCache().getDNSEntryList(info.getQualifiedName().toLowerCase()); if (entryList != null) { for (DNSEntry dnsEntry : entryList) { if (DNSRecordType.TYPE_SRV.equals(dnsEntry.getRecordType()) && !dnsEntry.isExpired(now)) { final DNSRecord.Service s = (DNSRecord.Service) dnsEntry; if (s.getPort() != info.getPort() || !s.getServer().equals(_localHost.getName())) { logger.finer("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:" + dnsEntry + " s.server=" + s.getServer() + " " + _localHost.getName() + " equals:" + (s.getServer().equals(_localHost.getName()))); info.setName(incrementName(info.getName())); collision = true; break; } } } } // Check for collision with other service infos published by JmDNS final ServiceInfo selfService = _services.get(info.getQualifiedName().toLowerCase()); if (selfService != null && selfService != info) { info.setName(incrementName(info.getName())); collision = true; } } while (collision); return !(originalQualifiedName.equals(info.getQualifiedName())); } String incrementName(String name) { String aName = name; try { final int l = aName.lastIndexOf('('); final int r = aName.lastIndexOf(')'); if ((l >= 0) && (l < r)) { aName = aName.substring(0, l) + "(" + (Integer.parseInt(aName.substring(l + 1, r)) + 1) + ")"; } else { aName += " (2)"; } } catch (final NumberFormatException e) { aName += " (2)"; } return aName; } /** * Add a listener for a question. The listener will receive updates of answers to the question as they arrive, or from the cache if they are already available. * * @param listener * DSN listener * @param question * DNS query */ public void addListener(DNSListener listener, DNSQuestion question) { final long now = System.currentTimeMillis(); // add the new listener _listeners.add(listener); // report existing matched records if (question != null) { Collection<? extends DNSEntry> entryList = this.getCache().getDNSEntryList(question.getName().toLowerCase()); if (entryList != null) { synchronized (entryList) { for (DNSEntry dnsEntry : entryList) { if (question.answeredBy(dnsEntry) && !dnsEntry.isExpired(now)) { listener.updateRecord(this.getCache(), now, dnsEntry); } } } } } } /** * Remove a listener from all outstanding questions. The listener will no longer receive any updates. * * @param listener * DSN listener */ public void removeListener(DNSListener listener) { _listeners.remove(listener); } /** * Renew a service when the record become stale. If there is no service collector for the type this method does nothing. * * @param record * DNS record */ public void renewServiceCollector(DNSRecord record) { ServiceInfo info = record.getServiceInfo(); if (_serviceCollectors.containsKey(info.getType().toLowerCase())) { // Create/start ServiceResolver new ServiceResolver(this, info.getType()).start(_timer); } } // Remind: Method updateRecord should receive a better name. /** * Notify all listeners that a record was updated. * * @param now * update date * @param rec * DNS record * @param operation * DNS cache operation */ public void updateRecord(long now, DNSRecord rec, Operation operation) { // We do not want to block the entire DNS while we are updating the record for each listener (service info) { List<DNSListener> listenerList = null; synchronized (_listeners) { listenerList = new ArrayList<DNSListener>(_listeners); } for (DNSListener listener : listenerList) { listener.updateRecord(this.getCache(), now, rec); } } if (DNSRecordType.TYPE_PTR.equals(rec.getRecordType())) // if (DNSRecordType.TYPE_PTR.equals(rec.getRecordType()) || DNSRecordType.TYPE_SRV.equals(rec.getRecordType())) { ServiceEvent event = rec.getServiceEvent(this); if ((event.getInfo() == null) || !event.getInfo().hasData()) { // We do not care about the subtype because teh info is only used if complete and the subtype will tehn be included. ServiceInfo info = this.getServiceInfoFromCache(event.getType(), event.getName(), "", false); if (info.hasData()) { event = new ServiceEventImpl(this, event.getType(), event.getName(), info); } } List<ServiceListener> list = _serviceListeners.get(event.getType()); List<ServiceListener> serviceListenerList = Collections.emptyList(); if (list != null) { synchronized (list) { serviceListenerList = new ArrayList<ServiceListener>(list); } } logger.finest(this.getName() + ".updating record for event: " + event + " list " + serviceListenerList + " operation: " + operation); if (!serviceListenerList.isEmpty()) { switch (operation) { case Add: for (ServiceListener listener : serviceListenerList) { listener.serviceAdded(event); } break; case Remove: for (ServiceListener listener : serviceListenerList) { listener.serviceRemoved(event); } break; default: break; } } } } /** * Handle an incoming response. Cache answers, and pass them on to the appropriate questions. * * @throws IOException */ void handleResponse(DNSIncoming msg) throws IOException { final long now = System.currentTimeMillis(); boolean hostConflictDetected = false; boolean serviceConflictDetected = false; for (DNSRecord newRecord : msg.getAllAnswers()) { Operation cacheOperation = Operation.Noop; final boolean expired = newRecord.isExpired(now); // update the cache final DNSRecord cachedRecord = (DNSRecord) this.getCache().getDNSEntry(newRecord); logger.fine(this.getName() + ".handle response: " + newRecord + "\ncached recod: " + cachedRecord); if (cachedRecord != null) { if (expired) { cacheOperation = Operation.Remove; this.getCache().removeDNSEntry(cachedRecord); } else { // If the record content has changed we need to inform our listeners. if (!newRecord.sameValue(cachedRecord) || (!newRecord.sameSubtype(cachedRecord) && (newRecord.getSubtype().length() > 0))) { cacheOperation = Operation.Update; this.getCache().replaceDNSEntry(newRecord, cachedRecord); } else { cachedRecord.resetTTL(newRecord); newRecord = cachedRecord; } } } else { if (!expired) { cacheOperation = Operation.Add; this.getCache().addDNSEntry(newRecord); } } switch (newRecord.getRecordType()) { case TYPE_PTR: // handle DNSConstants.DNS_META_QUERY records boolean typeAdded = false; if (newRecord.isServicesDiscoveryMetaQuery()) { // The service names are in the alias. if (!expired) { typeAdded = this.registerServiceType(((DNSRecord.Pointer) newRecord).getAlias()); } continue; } typeAdded |= this.registerServiceType(newRecord.getName()); if (typeAdded && (cacheOperation == Operation.Noop)) cacheOperation = Operation.RegisterServiceType; break; default: break; } if (DNSRecordType.TYPE_A.equals(newRecord.getRecordType()) || DNSRecordType.TYPE_AAAA.equals(newRecord.getRecordType())) { hostConflictDetected |= newRecord.handleResponse(this); } else { serviceConflictDetected |= newRecord.handleResponse(this); } // notify the listeners if (cacheOperation != Operation.Noop) { this.updateRecord(now, newRecord, cacheOperation); } } if (hostConflictDetected || serviceConflictDetected) { this.startProber(); } } /** * Handle an incoming query. See if we can answer any part of it given our service infos. * * @param in * @param addr * @param port * @throws IOException */ void handleQuery(DNSIncoming in, InetAddress addr, int port) throws IOException { logger.fine(this.getName() + ".handle query: " + in); // Track known answers boolean conflictDetected = false; final long expirationTime = System.currentTimeMillis() + DNSConstants.KNOWN_ANSWER_TTL; for (DNSRecord answer : in.getAllAnswers()) { conflictDetected |= answer.handleQuery(this, expirationTime); } if (_plannedAnswer != null) { _plannedAnswer.append(in); } else { if (in.isTruncated()) { _plannedAnswer = in; } new Responder(this, in, port).start(_timer); } if (conflictDetected) { this.startProber(); } } /** * Add an answer to a question. Deal with the case when the outgoing packet overflows * * @param in * @param addr * @param port * @param out * @param rec * @return outgoing answer * @throws IOException */ public DNSOutgoing addAnswer(DNSIncoming in, InetAddress addr, int port, DNSOutgoing out, DNSRecord rec) throws IOException { DNSOutgoing newOut = out; if (newOut == null) { newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload()); } try { newOut.addAnswer(in, rec); } catch (final IOException e) { newOut.setFlags(newOut.getFlags() | DNSConstants.FLAGS_TC); newOut.setId(in.getId()); send(newOut); newOut = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, false, in.getSenderUDPPayload()); newOut.addAnswer(in, rec); } return newOut; } /** * Send an outgoing multicast DNS message. * * @param out * @throws IOException */ public void send(DNSOutgoing out) throws IOException { if (!out.isEmpty()) { byte[] message = out.data(); final DatagramPacket packet = new DatagramPacket(message, message.length, _group, DNSConstants.MDNS_PORT); if (logger.isLoggable(Level.FINEST)) { try { final DNSIncoming msg = new DNSIncoming(packet); logger.finest("send(" + this.getName() + ") JmDNS out:" + msg.print(true)); } catch (final IOException e) { logger.throwing(getClass().toString(), "send(" + this.getName() + ") - JmDNS can not parse what it sends!!!", e); } } final MulticastSocket ms = _socket; if (ms != null && !ms.isClosed()) ms.send(packet); } } public void startProber() { new Prober(this).start(_stateTimer); } public void startAnnouncer() { new Announcer(this).start(_stateTimer); } public void startRenewer() { new Renewer(this).start(_stateTimer); } public void startCanceler() { new Canceler(this).start(_stateTimer); } // REMIND: Why is this not an anonymous inner class? /** * Shutdown operations. */ protected class Shutdown implements Runnable { + @Override public void run() { try { _shutdown = null; close(); } catch (Throwable exception) { System.err.println("Error while shuting down. " + exception); } } } /** * Recover jmdns when there is an error. */ public void recover() { logger.finer("recover()"); // We have an IO error so lets try to recover if anything happens lets close it. // This should cover the case of the IP address changing under our feet if (this.isCanceling() || this.isCanceled()) return; // Stop JmDNS // This protects against recursive calls if (this.cancelState()) { // Synchronize only if we are not already in process to prevent dead locks // logger.finer("recover() Cleanning up"); // Purge the timer _timer.purge(); // We need to keep a copy for reregistration final Collection<ServiceInfo> oldServiceInfos = new ArrayList<ServiceInfo>(getServices().values()); // Cancel all services this.unregisterAllServices(); this.disposeServiceCollectors(); this.waitForCanceled(0); // Purge the canceler timer _stateTimer.purge(); // // close multicast socket this.closeMulticastSocket(); // this.getCache().clear(); logger.finer("recover() All is clean"); // // All is clear now start the services // for (ServiceInfo info : oldServiceInfos) { ((ServiceInfoImpl) info).recoverState(); } this.recoverState(); try { this.openMulticastSocket(this.getLocalHost()); this.start(oldServiceInfos); } catch (final Exception exception) { logger.log(Level.WARNING, "recover() Start services exception ", exception); } logger.log(Level.WARNING, "recover() We are back!"); } } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#close() */ @Override public void close() { if (this.isCanceling() || this.isCanceled()) return; logger.finer("Cancelling JmDNS: " + this); // Stop JmDNS // This protects against recursive calls if (this.cancelState()) { // We got the tie break now clean up // Stop the timer _timer.cancel(); // Cancel all services this.unregisterAllServices(); this.disposeServiceCollectors(); logger.finer("Wait for JmDNS cancel: " + this); this.waitForCanceled(DNSConstants.CLOSE_TIMEOUT); // Stop the canceler timer _stateTimer.cancel(); // close socket this.closeMulticastSocket(); // remove the shutdown hook if (_shutdown != null) { Runtime.getRuntime().removeShutdownHook(_shutdown); } } } /** * List cache entries, for debugging only. */ void print() { System.out.println(_cache.toString()); System.out.println(); } /** * @see javax.jmdns.JmDNS#printServices() */ @Override public void printServices() { System.err.println(toString()); } @Override public String toString() { final StringBuilder aLog = new StringBuilder(2048); aLog.append("\t---- Local Host -----"); aLog.append("\n\t" + _localHost); aLog.append("\n\t---- Services -----"); for (String key : _services.keySet()) { aLog.append("\n\t\tService: " + key + ": " + _services.get(key)); } aLog.append("\n"); aLog.append("\t---- Types ----"); for (String key : _serviceTypes.keySet()) { Set<String> subtypes = _serviceTypes.get(key); aLog.append("\n\t\tType: " + key + ": " + (subtypes.isEmpty() ? "no subtypes" : subtypes)); } aLog.append("\n"); aLog.append(_cache.toString()); aLog.append("\n"); aLog.append("\t---- Service Collectors ----"); for (String key : _serviceCollectors.keySet()) { aLog.append("\n\t\tService Collector: " + key + ": " + _serviceCollectors.get(key)); } aLog.append("\n"); aLog.append("\t---- Service Listeners ----"); for (String key : _serviceListeners.keySet()) { aLog.append("\n\t\tService Listener: " + key + ": " + _serviceListeners.get(key)); } return aLog.toString(); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#list(java.lang.String) */ @Override public ServiceInfo[] list(String type) { return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#list(java.lang.String, int) */ @Override public ServiceInfo[] list(String type, long timeout) { // Implementation note: The first time a list for a given type is // requested, a ServiceCollector is created which collects service // infos. This greatly speeds up the performance of subsequent calls // to this method. The caveats are, that 1) the first call to this // method for a given type is slow, and 2) we spawn a ServiceCollector // instance for each service type which increases network traffic a // little. String aType = type.toLowerCase(); boolean newCollectorCreated = false; if (this.isCanceling() || this.isCanceled()) { return new ServiceInfo[0]; } ServiceCollector collector = _serviceCollectors.get(aType); if (collector == null) { newCollectorCreated = _serviceCollectors.putIfAbsent(aType, new ServiceCollector(aType)) == null; collector = _serviceCollectors.get(aType); if (newCollectorCreated) { this.addServiceListener(aType, collector); } } logger.finer(this.getName() + ".collector: " + collector); return collector.list(timeout); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#listBySubtype(java.lang.String) */ @Override public Map<String, ServiceInfo[]> listBySubtype(String type) { return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT); } /* * (non-Javadoc) * * @see javax.jmdns.JmDNS#listBySubtype(java.lang.String, long) */ @Override public Map<String, ServiceInfo[]> listBySubtype(String type, long timeout) { Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5); for (ServiceInfo info : this.list(type, timeout)) { String subtype = info.getSubtype(); if (!map.containsKey(subtype)) { map.put(subtype, new ArrayList<ServiceInfo>(10)); } map.get(subtype).add(info); } Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size()); for (String subtype : map.keySet()) { List<ServiceInfo> infoForSubType = map.get(subtype); result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()])); } return result; } /** * This method disposes all ServiceCollector instances which have been created by calls to method <code>list(type)</code>. * * @see #list */ private void disposeServiceCollectors() { logger.finer("disposeServiceCollectors()"); for (String type : _serviceCollectors.keySet()) { ServiceCollector collector = _serviceCollectors.get(type); if (collector != null) { this.removeServiceListener(type, collector); } _serviceCollectors.remove(type, collector); } } /** * Instances of ServiceCollector are used internally to speed up the performance of method <code>list(type)</code>. * * @see #list */ private static class ServiceCollector implements ServiceListener { // private static Logger logger = Logger.getLogger(ServiceCollector.class.getName()); /** * A set of collected service instance names. */ private final ConcurrentMap<String, ServiceInfo> _infos; /** * A set of collected service event waiting to be resolved. */ private final ConcurrentMap<String, ServiceEvent> _events; private final String _type; /** * This is used to force a wait on the first invocation of list. */ private volatile boolean _needToWaitForInfos; public ServiceCollector(String type) { super(); _infos = new ConcurrentHashMap<String, ServiceInfo>(); _events = new ConcurrentHashMap<String, ServiceEvent>(); _type = type; _needToWaitForInfos = true; } /** * A service has been added. * * @param event * service event */ + @Override public void serviceAdded(ServiceEvent event) { synchronized (this) { ServiceInfo info = event.getInfo(); if ((info != null) && (info.hasData())) { _infos.put(event.getName(), info); } else { String subtype = (info != null ? info.getSubtype() : ""); info = ((JmDNSImpl) event.getDNS()).resolveServiceInfo(event.getType(), event.getName(), subtype, true); if (info != null) { _infos.put(event.getName(), info); } else { _events.put(event.getName(), event); } } } } /** * A service has been removed. * * @param event * service event */ + @Override public void serviceRemoved(ServiceEvent event) { synchronized (this) { _infos.remove(event.getName()); _events.remove(event.getName()); } } /** * A service has been resolved. Its details are now available in the ServiceInfo record. * * @param event * service event */ + @Override public void serviceResolved(ServiceEvent event) { synchronized (this) { _infos.put(event.getName(), event.getInfo()); _events.remove(event.getName()); } } /** * Returns an array of all service infos which have been collected by this ServiceCollector. * * @param timeout * timeout if the info list is empty. * * @return Service Info array */ public ServiceInfo[] list(long timeout) { if (_infos.isEmpty() || !_events.isEmpty() || _needToWaitForInfos) { long loops = (timeout / 200L); if (loops < 1) { loops = 1; } for (int i = 0; i < loops; i++) { try { Thread.sleep(200); } catch (final InterruptedException e) { /* Stub */ } if (_events.isEmpty() && !_infos.isEmpty() && !_needToWaitForInfos) { break; } } } _needToWaitForInfos = false; return _infos.values().toArray(new ServiceInfo[_infos.size()]); } @Override public String toString() { final StringBuffer aLog = new StringBuffer(); aLog.append("\n\tType: " + _type); if (_infos.isEmpty()) { aLog.append("\n\tNo services collected."); } else { aLog.append("\n\tServices"); for (String key : _infos.keySet()) { aLog.append("\n\t\tService: " + key + ": " + _infos.get(key)); } } if (_events.isEmpty()) { aLog.append("\n\tNo event queued."); } else { aLog.append("\n\tEvents"); for (String key : _events.keySet()) { aLog.append("\n\t\tEvent: " + key + ": " + _events.get(key)); } } return aLog.toString(); } } static String toUnqualifiedName(String type, String qualifiedName) { if (qualifiedName.endsWith(type) && !(qualifiedName.equals(type))) { return qualifiedName.substring(0, qualifiedName.length() - type.length() - 1); } return qualifiedName; } public Map<String, ServiceInfo> getServices() { return _services; } public void setLastThrottleIncrement(long lastThrottleIncrement) { this._lastThrottleIncrement = lastThrottleIncrement; } public long getLastThrottleIncrement() { return _lastThrottleIncrement; } public void setThrottle(int throttle) { this._throttle = throttle; } public int getThrottle() { return _throttle; } public static Random getRandom() { return _random; } public void ioLock() { _ioLock.lock(); } public void ioUnlock() { _ioLock.unlock(); } public void setPlannedAnswer(DNSIncoming plannedAnswer) { this._plannedAnswer = plannedAnswer; } public DNSIncoming getPlannedAnswer() { return _plannedAnswer; } void setLocalHost(HostInfo localHost) { this._localHost = localHost; } public Map<String, Set<String>> getServiceTypes() { return _serviceTypes; } public void setClosed(boolean closed) { this._closed = closed; } public boolean isClosed() { return _closed; } public MulticastSocket getSocket() { return _socket; } public InetAddress getGroup() { return _group; } } diff --git a/jmdns/test/javax/jmdns/test/TextUpdateTest.java b/jmdns/test/javax/jmdns/test/TextUpdateTest.java index 5c4a10e..06312a1 100644 --- a/jmdns/test/javax/jmdns/test/TextUpdateTest.java +++ b/jmdns/test/javax/jmdns/test/TextUpdateTest.java @@ -1,349 +1,349 @@ /** * */ package javax.jmdns.test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import javax.jmdns.impl.constants.DNSConstants; import javax.jmdns.impl.tasks.state.DNSStateTask; import org.junit.Before; import org.junit.Test; /** * */ public class TextUpdateTest { private ServiceInfo service; private ServiceInfo printer; private MockListener serviceListenerMock; private final static String serviceKey = "srvname"; // Max 9 chars public static class MockListener implements ServiceListener { private final List<ServiceEvent> _serviceAdded = Collections.synchronizedList(new ArrayList<ServiceEvent>(2)); private final List<ServiceEvent> _serviceRemoved = Collections.synchronizedList(new ArrayList<ServiceEvent>(2)); private final List<ServiceEvent> _serviceResolved = Collections.synchronizedList(new ArrayList<ServiceEvent>(2)); /* * (non-Javadoc) * * @see javax.jmdns.ServiceListener#serviceAdded(javax.jmdns.ServiceEvent) */ @Override public void serviceAdded(ServiceEvent event) { try { _serviceAdded.add((ServiceEvent) event.clone()); } catch (CloneNotSupportedException exception) { // } } /* * (non-Javadoc) * * @see javax.jmdns.ServiceListener#serviceRemoved(javax.jmdns.ServiceEvent) */ @Override public void serviceRemoved(ServiceEvent event) { try { _serviceRemoved.add((ServiceEvent) event.clone()); } catch (CloneNotSupportedException exception) { // } } /* * (non-Javadoc) * * @see javax.jmdns.ServiceListener#serviceResolved(javax.jmdns.ServiceEvent) */ @Override public void serviceResolved(ServiceEvent event) { try { _serviceResolved.add((ServiceEvent) event.clone()); } catch (CloneNotSupportedException exception) { // } } public List<ServiceEvent> servicesAdded() { return _serviceAdded; } public List<ServiceEvent> servicesRemoved() { return _serviceRemoved; } public List<ServiceEvent> servicesResolved() { return _serviceResolved; } public synchronized void reset() { _serviceAdded.clear(); _serviceRemoved.clear(); _serviceResolved.clear(); } @Override public String toString() { StringBuilder aLog = new StringBuilder(); aLog.append("Services Added: " + _serviceAdded.size()); for (ServiceEvent event : _serviceAdded) { aLog.append("\n\tevent name: '"); aLog.append(event.getName()); aLog.append("' type: '"); aLog.append(event.getType()); aLog.append("' info: '"); aLog.append(event.getInfo()); } aLog.append("\nServices Removed: " + _serviceRemoved.size()); for (ServiceEvent event : _serviceRemoved) { aLog.append("\n\tevent name: '"); aLog.append(event.getName()); aLog.append("' type: '"); aLog.append(event.getType()); aLog.append("' info: '"); aLog.append(event.getInfo()); } aLog.append("\nServices Resolved: " + _serviceResolved.size()); for (ServiceEvent event : _serviceResolved) { aLog.append("\n\tevent name: '"); aLog.append(event.getName()); aLog.append("' type: '"); aLog.append(event.getType()); aLog.append("' info: '"); aLog.append(event.getInfo()); } return aLog.toString(); } } @Before public void setup() { boolean log = false; if (log) { ConsoleHandler handler = new ConsoleHandler(); handler.setLevel(Level.FINEST); for (Enumeration<String> enumerator = LogManager.getLogManager().getLoggerNames(); enumerator.hasMoreElements();) { String loggerName = enumerator.nextElement(); Logger logger = Logger.getLogger(loggerName); logger.addHandler(handler); logger.setLevel(Level.FINEST); } } String text = "Test hypothetical web server"; Map<String, byte[]> properties = new HashMap<String, byte[]>(); properties.put(serviceKey, text.getBytes()); service = ServiceInfo.create("_html._tcp.local.", "apache-someuniqueid", 80, 0, 0, true, properties); text = "Test hypothetical print server"; properties.clear(); properties.put(serviceKey, text.getBytes()); printer = ServiceInfo.create("_html._tcp.local.", "printer-someuniqueid", "_printer", 80, 0, 0, true, properties); serviceListenerMock = new MockListener(); } @Test public void testListenForTextUpdateOnOtherRegistry() throws IOException, InterruptedException { JmDNS registry = null; JmDNS newServiceRegistry = null; try { registry = JmDNS.create("Listener"); registry.addServiceListener(service.getType(), serviceListenerMock); // newServiceRegistry = JmDNS.create("Registry"); newServiceRegistry.registerService(service); // We get the service added event when we register the service. However the service has not been resolved at this point. // The info associated with the event only has the minimum information i.e. name and type. List<ServiceEvent> servicesAdded = serviceListenerMock.servicesAdded(); assertEquals("We did not get the service added event.", 1, servicesAdded.size()); ServiceInfo info = servicesAdded.get(servicesAdded.size() - 1).getInfo(); assertEquals("We did not get the right name for the resolved service:", service.getName(), info.getName()); assertEquals("We did not get the right type for the resolved service:", service.getType(), info.getType()); // We get the service added event when we register the service. However the service has not been resolved at this point. // The info associated with the event only has the minimum information i.e. name and type. List<ServiceEvent> servicesResolved = serviceListenerMock.servicesResolved(); assertEquals("We did not get the service resolved event.", 1, servicesResolved.size()); ServiceInfo result = servicesResolved.get(servicesResolved.size() - 1).getInfo(); assertNotNull("Did not get the expected service info: ", result); assertEquals("Did not get the expected service info: ", service, result); assertEquals("Did not get the expected service info text: ", service.getPropertyString(serviceKey), result.getPropertyString(serviceKey)); serviceListenerMock.reset(); String text = "Test improbable web server"; Map<String, byte[]> properties = new HashMap<String, byte[]>(); properties.put(serviceKey, text.getBytes()); service.setText(properties); - Thread.sleep(2000); + Thread.sleep(3000); servicesResolved = serviceListenerMock.servicesResolved(); assertEquals("We did not get the service text updated event.", 1, servicesResolved.size()); result = servicesResolved.get(servicesResolved.size() - 1).getInfo(); assertEquals("Did not get the expected service info text: ", text, result.getPropertyString(serviceKey)); serviceListenerMock.reset(); text = "Test more improbable web server"; properties = new HashMap<String, byte[]>(); properties.put(serviceKey, text.getBytes()); service.setText(properties); - Thread.sleep(2000); + Thread.sleep(3000); servicesResolved = serviceListenerMock.servicesResolved(); assertEquals("We did not get the service text updated event.", 1, servicesResolved.size()); result = servicesResolved.get(servicesResolved.size() - 1).getInfo(); assertEquals("Did not get the expected service info text: ", text, result.getPropertyString(serviceKey)); serviceListenerMock.reset(); text = "Test even more improbable web server"; properties = new HashMap<String, byte[]>(); properties.put(serviceKey, text.getBytes()); service.setText(properties); - Thread.sleep(2000); + Thread.sleep(3000); servicesResolved = serviceListenerMock.servicesResolved(); assertEquals("We did not get the service text updated event.", 1, servicesResolved.size()); result = servicesResolved.get(servicesResolved.size() - 1).getInfo(); assertEquals("Did not get the expected service info text: ", text, result.getPropertyString(serviceKey)); } finally { if (registry != null) registry.close(); if (newServiceRegistry != null) newServiceRegistry.close(); } } @Test public void testRenewExpiringRequests() throws IOException, InterruptedException { JmDNS registry = null; JmDNS newServiceRegistry = null; try { // To test for expiring TTL DNSStateTask.setDefaultTTL(1 * 60); registry = JmDNS.create("Listener"); registry.addServiceListener(service.getType(), serviceListenerMock); // newServiceRegistry = JmDNS.create("Registry"); newServiceRegistry.registerService(service); List<ServiceEvent> servicesAdded = serviceListenerMock.servicesAdded(); assertTrue("We did not get the service added event.", servicesAdded.size() == 1); ServiceInfo[] services = registry.list(service.getType()); assertEquals("We should see the service we just registered: ", 1, services.length); assertEquals(service, services[0]); // wait for the TTL Thread.sleep(2 * 60 * 1000); services = registry.list(service.getType()); assertEquals("We should see the service after the renewal: ", 1, services.length); assertEquals(service, services[0]); } finally { if (registry != null) registry.close(); if (newServiceRegistry != null) newServiceRegistry.close(); DNSStateTask.setDefaultTTL(DNSConstants.DNS_TTL); } } @Test public void testSubtype() throws IOException { JmDNS registry = null; JmDNS newServiceRegistry = null; try { registry = JmDNS.create("Listener"); registry.addServiceListener(service.getType(), serviceListenerMock); // newServiceRegistry = JmDNS.create("Registry"); newServiceRegistry.registerService(printer); // We get the service added event when we register the service. However the service has not been resolved at this point. // The info associated with the event only has the minimum information i.e. name and type. List<ServiceEvent> servicesAdded = serviceListenerMock.servicesAdded(); assertEquals("We did not get the service added event.", 1, servicesAdded.size()); ServiceInfo info = servicesAdded.get(servicesAdded.size() - 1).getInfo(); assertEquals("We did not get the right name for the resolved service:", printer.getName(), info.getName()); assertEquals("We did not get the right type for the resolved service:", printer.getType(), info.getType()); // We get the service added event when we register the service. However the service has not been resolved at this point. // The info associated with the event only has the minimum information i.e. name and type. List<ServiceEvent> servicesResolved = serviceListenerMock.servicesResolved(); assertEquals("We did not get the service resolved event.", 1, servicesResolved.size()); ServiceInfo result = servicesResolved.get(servicesResolved.size() - 1).getInfo(); assertNotNull("Did not get the expected service info: ", result); assertEquals("Did not get the expected service info: ", printer, result); assertEquals("Did not get the expected service info subtype: ", printer.getSubtype(), result.getSubtype()); assertEquals("Did not get the expected service info text: ", printer.getPropertyString(serviceKey), result.getPropertyString(serviceKey)); serviceListenerMock.reset(); } finally { if (registry != null) registry.close(); if (newServiceRegistry != null) newServiceRegistry.close(); } } }
false
false
null
null
diff --git a/modules/RadioController.java b/modules/RadioController.java index 7522928..d531edb 100644 --- a/modules/RadioController.java +++ b/modules/RadioController.java @@ -1,160 +1,168 @@ package team035.modules; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Vector; import team035.messages.MessageAddress; import team035.messages.MessageWrapper; import team035.messages.RobotMessage; import team035.robots.BaseRobot; import battlecode.common.GameActionException; import battlecode.common.Message; public class RadioController { protected static final String salt = "a23fo9anaewvaln32faln3falf3"; protected BaseRobot r; protected int numMessagesInQueue = 0; protected MessageWrapper[] outgoingMessageQueue; public static final int MAX_MESSAGES_PER_TURN = 20; // there's one of these for each message type, which has N objects that // want to be notified about messages of that type. protected HashMap<String, Vector<RadioListener>> listeners = new HashMap<String, Vector<RadioListener>>(); public RadioController(BaseRobot r) { this.r = r; this.newRound(); } public void addListener(RadioListener listener, String messageClass) { String[] classes = new String[1]; classes[0] = messageClass; this.addListener(listener, classes); } public void addListener(RadioListener listener, String[] messageClasses) { Vector<RadioListener> listenersForClass; System.out.println("adding listener: " + listener + " for classes: " + messageClasses); for(String c : messageClasses) { if(c==null) break; System.out.println("adding listener for class: " + c); if(listeners.get(c)==null) { listenersForClass = new Vector<RadioListener>(); } else { listenersForClass = listeners.get(c); } listenersForClass.add(listener); listeners.put(c, listenersForClass); } } public void addMessageToTransmitQueue(MessageAddress adr, RobotMessage m) { outgoingMessageQueue[numMessagesInQueue] = new MessageWrapper(adr, m); numMessagesInQueue++; } // Sends the messages we've queued up over the course of this turn. public void transmit() { try { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytesOut); int messagesWritten = 0; for(MessageWrapper wrapper : this.outgoingMessageQueue) { if(wrapper==null) { break; } System.out.println("about to send: " + wrapper); out.writeObject(wrapper); messagesWritten++; } Message outgoingMessage = new Message(); String[] s = {new String(bytesOut.toByteArray())}; outgoingMessage.strings = s; if(messagesWritten > 0) { this.r.getRc().broadcast(outgoingMessage); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GameActionException e) { // TODO Auto-generated catch block e.printStackTrace(); } // clean out the queue this.newRound(); } private void newRound() { this.outgoingMessageQueue = new MessageWrapper[MAX_MESSAGES_PER_TURN]; numMessagesInQueue=0; } // Handles any incoming messages we received this turn. // If they pass basic validation, are addressed to us, and we have // any listeners on that message type, alert the listeners to the // existence of the message. public void receive() { Message[] messages = this.r.getRc().getAllMessages(); System.out.println("received " + messages.length + " messages"); for(Message m : messages) { + + // skip invalid messages + if(!this.validMessage(m)) continue; + ByteArrayInputStream byteIn = new ByteArrayInputStream(m.strings[0].getBytes()); try { ObjectInputStream in = new ObjectInputStream(byteIn); Object nextObject = in.readObject(); - + if(nextObject.getClass() == MessageWrapper.class) { MessageWrapper msg = (MessageWrapper)nextObject; if(msg.isForThisRobot()) { for(RadioListener l : this.listeners.get(msg.msg.getType())) { l.handleMessage(msg); } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } + protected boolean validMessage(Message msg) { // these tests ensure that the number of fields is right // to make this a probable message from our team. + if(msg.ints==null) return false; + if(msg.strings==null) return false; + if(msg.locations != null) return false; + if(msg.ints.length!=1) return false; if(msg.strings.length != 1) return false; - if(msg.locations != null) return false; // now do the more rigorous check - does the hashcode of the message string // match the int in the ints field? StringBuilder builder = new StringBuilder(); builder.append(msg.strings[0]); builder.append(RadioController.salt); if(builder.toString().hashCode()!=msg.ints[0]) return false; return true; } }
false
false
null
null
diff --git a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/SonarEngine.java b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/SonarEngine.java index 2fbdde1ed4..961b085bf4 100644 --- a/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/SonarEngine.java +++ b/plugins/sonar-cpd-plugin/src/main/java/org/sonar/plugins/cpd/SonarEngine.java @@ -1,216 +1,218 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.cpd; import com.google.common.collect.Iterables; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.SensorContext; import org.sonar.api.database.model.ResourceModel; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Measure; import org.sonar.api.resources.*; import org.sonar.api.utils.SonarException; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.BlockChunker; import org.sonar.duplications.detector.suffixtree.SuffixTreeCloneDetectionAlgorithm; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; import org.sonar.duplications.index.ClonePart; import org.sonar.duplications.java.JavaStatementBuilder; import org.sonar.duplications.java.JavaTokenProducer; import org.sonar.duplications.statement.Statement; import org.sonar.duplications.statement.StatementChunker; import org.sonar.duplications.token.TokenChunker; import org.sonar.plugins.cpd.index.IndexFactory; import org.sonar.plugins.cpd.index.SonarDuplicationsIndex; +import javax.annotation.Nullable; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.Reader; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.*; public class SonarEngine extends CpdEngine { private static final Logger LOG = LoggerFactory.getLogger(SonarEngine.class); private static final int BLOCK_SIZE = 10; /** * Limit of time to analyse one file (in seconds). */ private static final int TIMEOUT = 5 * 60; private final IndexFactory indexFactory; public SonarEngine(IndexFactory indexFactory) { this.indexFactory = indexFactory; } @Override public boolean isLanguageSupported(Language language) { return Java.INSTANCE.equals(language); } static String getFullKey(Project project, Resource resource) { return new StringBuilder(ResourceModel.KEY_SIZE) .append(project.getKey()) .append(':') .append(resource.getKey()) .toString(); } @Override public void analyse(Project project, SensorContext context) { List<InputFile> inputFiles = project.getFileSystem().mainFiles(project.getLanguageKey()); if (inputFiles.isEmpty()) { return; } SonarDuplicationsIndex index = createIndex(project, inputFiles); detect(index, context, project, inputFiles); } private SonarDuplicationsIndex createIndex(Project project, List<InputFile> inputFiles) { final SonarDuplicationsIndex index = indexFactory.create(project); TokenChunker tokenChunker = JavaTokenProducer.build(); StatementChunker statementChunker = JavaStatementBuilder.build(); BlockChunker blockChunker = new BlockChunker(BLOCK_SIZE); for (InputFile inputFile : inputFiles) { LOG.debug("Populating index from {}", inputFile.getFile()); Resource resource = getResource(inputFile); String resourceKey = getFullKey(project, resource); List<Statement> statements; Reader reader = null; try { reader = new InputStreamReader(new FileInputStream(inputFile.getFile()), project.getFileSystem().getSourceCharset()); statements = statementChunker.chunk(tokenChunker.chunk(reader)); } catch (FileNotFoundException e) { throw new SonarException(e); } finally { IOUtils.closeQuietly(reader); } List<Block> blocks = blockChunker.chunk(resourceKey, statements); index.insert(resource, blocks); } return index; } private void detect(SonarDuplicationsIndex index, SensorContext context, Project project, List<InputFile> inputFiles) { ExecutorService executorService = Executors.newSingleThreadExecutor(); try { for (InputFile inputFile : inputFiles) { LOG.debug("Detection of duplications for {}", inputFile.getFile()); Resource resource = getResource(inputFile); String resourceKey = getFullKey(project, resource); Collection<Block> fileBlocks = index.getByResource(resource, resourceKey); List<CloneGroup> clones; try { clones = executorService.submit(new Task(index, fileBlocks)).get(TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException e) { clones = null; LOG.warn("Timeout during detection of duplications for " + inputFile.getFile(), e); } catch (InterruptedException e) { throw new SonarException(e); } catch (ExecutionException e) { throw new SonarException(e); } save(context, resource, clones); } } finally { executorService.shutdown(); } } private static class Task implements Callable<List<CloneGroup>> { private final CloneIndex index; private final Collection<Block> fileBlocks; public Task(CloneIndex index, Collection<Block> fileBlocks) { this.index = index; this.fileBlocks = fileBlocks; } public List<CloneGroup> call() { return SuffixTreeCloneDetectionAlgorithm.detect(index, fileBlocks); } } private Resource getResource(InputFile inputFile) { return JavaFile.fromRelativePath(inputFile.getRelativePath(), false); } - static void save(SensorContext context, Resource resource, Iterable<CloneGroup> duplications) { - if (Iterables.isEmpty(duplications)) { + static void save(SensorContext context, Resource resource, @Nullable Iterable<CloneGroup> duplications) { + if (duplications == null || Iterables.isEmpty(duplications)) { return; } // Calculate number of lines and blocks Set<Integer> duplicatedLines = new HashSet<Integer>(); double duplicatedBlocks = 0; for (CloneGroup clone : duplications) { ClonePart origin = clone.getOriginPart(); for (ClonePart part : clone.getCloneParts()) { if (part.getResourceId().equals(origin.getResourceId())) { duplicatedBlocks++; for (int duplicatedLine = part.getStartLine(); duplicatedLine < part.getStartLine() + part.getLines(); duplicatedLine++) { duplicatedLines.add(duplicatedLine); } } } } // Save context.saveMeasure(resource, CoreMetrics.DUPLICATED_FILES, 1.0); context.saveMeasure(resource, CoreMetrics.DUPLICATED_LINES, (double) duplicatedLines.size()); context.saveMeasure(resource, CoreMetrics.DUPLICATED_BLOCKS, duplicatedBlocks); context.saveMeasure(resource, new Measure(CoreMetrics.DUPLICATIONS_DATA, toXml(duplications))); } private static String toXml(Iterable<CloneGroup> duplications) { StringBuilder xml = new StringBuilder(); xml.append("<duplications>"); for (CloneGroup duplication : duplications) { xml.append("<g>"); for (ClonePart part : duplication.getCloneParts()) { xml.append("<b s=\"").append(part.getStartLine()) .append("\" l=\"").append(part.getLines()) .append("\" r=\"").append(part.getResourceId()) .append("\"/>"); } xml.append("</g>"); } xml.append("</duplications>"); return xml.toString(); } }
false
false
null
null
diff --git a/src/java/org/infoglue/deliver/controllers/kernel/impl/simple/ExtranetController.java b/src/java/org/infoglue/deliver/controllers/kernel/impl/simple/ExtranetController.java index 18be4968b..b227a4b36 100755 --- a/src/java/org/infoglue/deliver/controllers/kernel/impl/simple/ExtranetController.java +++ b/src/java/org/infoglue/deliver/controllers/kernel/impl/simple/ExtranetController.java @@ -1,652 +1,655 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.deliver.controllers.kernel.impl.simple; import java.security.Principal; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.log4j.Logger; import org.exolab.castor.jdo.Database; import org.infoglue.cms.controllers.kernel.impl.simple.GroupPropertiesController; import org.infoglue.cms.controllers.kernel.impl.simple.RolePropertiesController; import org.infoglue.cms.controllers.kernel.impl.simple.SiteNodeController; import org.infoglue.cms.controllers.kernel.impl.simple.UserControllerProxy; import org.infoglue.cms.controllers.kernel.impl.simple.UserPropertiesController; import org.infoglue.cms.entities.content.DigitalAsset; import org.infoglue.cms.entities.management.GroupProperties; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.entities.management.RoleProperties; import org.infoglue.cms.entities.management.UserProperties; import org.infoglue.cms.entities.structure.SiteNode; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.security.AuthenticationModule; import org.infoglue.cms.security.InfoGlueAuthenticationFilter; import org.infoglue.cms.security.InfoGlueGroup; import org.infoglue.cms.security.InfoGluePrincipal; import org.infoglue.cms.security.InfoGlueRole; import org.infoglue.deliver.applications.databeans.DeliveryContext; /** * @author Mattias Bogeblad * * This class is the controller for extranet functionality. Authentication, authorization and stuff like that * is what it does best! */ public class ExtranetController extends BaseDeliveryController { private final static Logger logger = Logger.getLogger(ExtranetController.class.getName()); /** * Private constructor to enforce factory-use */ private ExtranetController() { } /** * Factory method */ public static ExtranetController getController() { return new ExtranetController(); } /** * This method autenticates a user. It takes a username and checks first that it is defined as a * infoglue extranet user. */ public Principal getAuthenticatedPrincipal(Database db, Map request) throws Exception { Principal principal = null; try { String authenticatorClass = InfoGlueAuthenticationFilter.authenticatorClass; String authorizerClass = InfoGlueAuthenticationFilter.authorizerClass; String invalidLoginUrl = InfoGlueAuthenticationFilter.invalidLoginUrl; String loginUrl = InfoGlueAuthenticationFilter.loginUrl; String serverName = InfoGlueAuthenticationFilter.serverName; Properties extraProperties = InfoGlueAuthenticationFilter.extraProperties; String casRenew = InfoGlueAuthenticationFilter.casRenew; String casServiceUrl = InfoGlueAuthenticationFilter.casServiceUrl; String casValidateUrl = InfoGlueAuthenticationFilter.casValidateUrl; AuthenticationModule authenticationModule = (AuthenticationModule)Class.forName(authenticatorClass).newInstance(); authenticationModule.setAuthenticatorClass(authenticatorClass); authenticationModule.setAuthorizerClass(authorizerClass); authenticationModule.setInvalidLoginUrl(invalidLoginUrl); authenticationModule.setLoginUrl(loginUrl); authenticationModule.setServerName(serverName); authenticationModule.setExtraProperties(extraProperties); authenticationModule.setCasRenew(casRenew); authenticationModule.setCasServiceUrl(casServiceUrl); authenticationModule.setCasValidateUrl(casValidateUrl); authenticationModule.setTransactionObject(db); String authenticatedUserName = authenticationModule.authenticateUser(request); logger.info("authenticatedUserName:" + authenticatedUserName); principal = UserControllerProxy.getController(db).getUser(authenticatedUserName); logger.info("principal:" + principal); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException("The login process failed: " + e.getMessage(), e); } return principal; } /** * This method autenticates a user. It takes a username and checks first that it is defined as a * infoglue extranet user. */ public Principal getAuthenticatedPrincipal(Map request) throws Exception { Principal principal = null; try { String authenticatedUserName = AuthenticationModule.getAuthenticationModule(null, null).authenticateUser(request); logger.info("authenticatedUserName:" + authenticatedUserName); - principal = UserControllerProxy.getController().getUser(authenticatedUserName); - logger.info("principal:" + principal); + if(authenticatedUserName != null) + { + principal = UserControllerProxy.getController().getUser(authenticatedUserName); + logger.info("principal:" + principal); + } } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException("The login process failed: " + e.getMessage(), e); } return principal; } /** * This method checks if a user has access to an entity. It takes name and id of the entity. */ /* public boolean getIsPrincipalAuthorized(Principal principal, String name, String value, NodeDeliveryController nodeDeliveryController) throws Exception { boolean isPrincipalAuthorized = false; //UserVO userVO = UserController.getController().getUserVO(principal.getName()); List extranetAccessVOList = ExtranetAccessController.getController().getExtranetAccessVOList(name, value); if(extranetAccessVOList != null && extranetAccessVOList.size() > 0) { Iterator extranetAccessVOListIterator = extranetAccessVOList.iterator(); outer: while(extranetAccessVOListIterator.hasNext()) { ExtranetAccessVO extranetAccessVO = (ExtranetAccessVO)extranetAccessVOListIterator.next(); List roles = ((InfoGluePrincipal)principal).getRoles(); logger.info("ExtranetAccessVO:" + extranetAccessVO.getRoleId()); logger.info("name:" + extranetAccessVO.getName()); logger.info("value:" + extranetAccessVO.getValue()); Iterator rolesIterator = roles.iterator(); while(rolesIterator.hasNext()) { RoleVO roleVO = (RoleVO)rolesIterator.next(); logger.info("roleVO:" + roleVO.getRoleId()); if(roleVO.getRoleId().intValue() == extranetAccessVO.getRoleId().intValue() && extranetAccessVO.getHasReadAccess().booleanValue()) { isPrincipalAuthorized = true; break outer; } } } } else { if(name.equals("SiteNode")) { SiteNodeVO parentSiteNodeVO = nodeDeliveryController.getParentSiteNode(new Integer(value)); if(parentSiteNodeVO != null) isPrincipalAuthorized = getIsPrincipalAuthorized(principal, name, parentSiteNodeVO.getSiteNodeId().toString(), nodeDeliveryController); } } logger.info("isPrincipalAuthorized:" + isPrincipalAuthorized); return isPrincipalAuthorized; } */ /** * This method checks if a user has write access to an entity. It takes name and id of the entity. */ /* public boolean getIsPrincipalAuthorizedForWriteAccess(Principal principal, String name, String value, NodeDeliveryController nodeDeliveryController) throws Exception { boolean isPrincipalAuthorized = false; //UserVO userVO = UserController.getController().getUserVO(principal.getName()); List extranetAccessVOList = ExtranetAccessController.getController().getExtranetAccessVOList(name, value); if(extranetAccessVOList != null && extranetAccessVOList.size() > 0) { Iterator extranetAccessVOListIterator = extranetAccessVOList.iterator(); outer: while(extranetAccessVOListIterator.hasNext()) { ExtranetAccessVO extranetAccessVO = (ExtranetAccessVO)extranetAccessVOListIterator.next(); List roles = ((InfoGluePrincipal)principal).getRoles(); logger.info("ExtranetAccessVO:" + extranetAccessVO.getRoleId()); logger.info("name:" + extranetAccessVO.getName()); logger.info("value:" + extranetAccessVO.getValue()); Iterator rolesIterator = roles.iterator(); while(rolesIterator.hasNext()) { RoleVO roleVO = (RoleVO)rolesIterator.next(); logger.info("roleVO:" + roleVO.getRoleId()); if(roleVO.getRoleId().intValue() == extranetAccessVO.getRoleId().intValue() && extranetAccessVO.getHasWriteAccess().booleanValue()) { isPrincipalAuthorized = true; break outer; } } } } else { if(name.equals("SiteNode")) { SiteNodeVO parentSiteNodeVO = nodeDeliveryController.getParentSiteNode(new Integer(value)); if(parentSiteNodeVO != null) isPrincipalAuthorized = getIsPrincipalAuthorizedForWriteAccess(principal, name, parentSiteNodeVO.getSiteNodeId().toString(), nodeDeliveryController); } } logger.info("isPrincipalAuthorized:" + isPrincipalAuthorized); return isPrincipalAuthorized; } */ /** * Getting a property for a Principal - used for personalisation. * This method starts with getting the property on the user and if it does not exist we check out the * group-properties as well. */ /* public String getPrincipalPropertyValue(Database db, InfoGluePrincipal infoGluePrincipal, String propertyName, Integer languageId, Integer siteNodeId, boolean useLanguageFallback, boolean escapeSpecialCharacters) throws Exception { String value = ""; if(infoGluePrincipal == null || propertyName == null) return null; Collection userPropertiesList = UserPropertiesController.getController().getUserPropertiesList(infoGluePrincipal.getName(), languageId, db); Iterator userPropertiesListIterator = userPropertiesList.iterator(); while(userPropertiesListIterator.hasNext()) { UserProperties userProperties = (UserProperties)userPropertiesListIterator.next(); if(userProperties != null && userProperties.getLanguage().getLanguageId().equals(languageId) && userProperties.getValue() != null && propertyName != null) { String propertyXML = userProperties.getValue(); DOMBuilder domBuilder = new DOMBuilder(); Document document = domBuilder.getDocument(propertyXML); Node node = document.getRootElement().selectSingleNode("attributes/" + propertyName); if(node != null) { value = node.getStringValue(); logger.info("Getting value: " + value); if(value != null && escapeSpecialCharacters) value = new VisualFormatter().escapeHTML(value); break; } } } if(value.equals("")) { List roles = infoGluePrincipal.getRoles(); Iterator rolesIterator = roles.iterator(); while(rolesIterator.hasNext()) { InfoGlueRole role = (InfoGlueRole)rolesIterator.next(); Collection rolePropertiesList = RolePropertiesController.getController().getRolePropertiesList(role.getName(), languageId, db); Iterator rolePropertiesListIterator = rolePropertiesList.iterator(); while(rolePropertiesListIterator.hasNext()) { RoleProperties roleProperties = (RoleProperties)rolePropertiesListIterator.next(); if(roleProperties != null && roleProperties.getLanguage().getLanguageId().equals(languageId) && roleProperties.getValue() != null && propertyName != null) { String propertyXML = roleProperties.getValue(); DOMBuilder domBuilder = new DOMBuilder(); Document document = domBuilder.getDocument(propertyXML); Node node = document.getRootElement().selectSingleNode("attributes/" + propertyName); if(node != null) { value = node.getStringValue(); logger.info("Getting value: " + value); if(value != null && escapeSpecialCharacters) value = new VisualFormatter().escapeHTML(value); break; } } } } if(value.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalPropertyValue(db, infoGluePrincipal, propertyName, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, escapeSpecialCharacters); } } if(value.equals("")) { List groups = infoGluePrincipal.getGroups(); Iterator groupsIterator = groups.iterator(); while(groupsIterator.hasNext()) { InfoGlueGroup group = (InfoGlueGroup)groupsIterator.next(); Collection groupPropertiesList = GroupPropertiesController.getController().getGroupPropertiesList(group.getName(), languageId, db); Iterator groupPropertiesListIterator = groupPropertiesList.iterator(); while(groupPropertiesListIterator.hasNext()) { GroupProperties groupProperties = (GroupProperties)groupPropertiesListIterator.next(); if(groupProperties != null && groupProperties.getLanguage().getLanguageId().equals(languageId) && groupProperties.getValue() != null && propertyName != null) { String propertyXML = groupProperties.getValue(); DOMBuilder domBuilder = new DOMBuilder(); Document document = domBuilder.getDocument(propertyXML); Node node = document.getRootElement().selectSingleNode("attributes/" + propertyName); if(node != null) { value = node.getStringValue(); logger.info("Getting value: " + value); if(value != null && escapeSpecialCharacters) value = new VisualFormatter().escapeHTML(value); break; } } } } if(value.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalPropertyValue(db, infoGluePrincipal, propertyName, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, escapeSpecialCharacters); } } return value; } */ /** * Getting a digitalAsset for a Principal - used for personalisation. * This method starts with getting the asset on the user and if it does not exist we check out the * group-properties as well. */ public String getPrincipalAssetUrl(Database db, InfoGluePrincipal infoGluePrincipal, String assetKey, Integer languageId, Integer siteNodeId, boolean useLanguageFallback, DeliveryContext deliveryContext) throws Exception { String assetUrl = ""; if(infoGluePrincipal == null || assetKey == null) return null; Collection userPropertiesList = UserPropertiesController.getController().getUserPropertiesList(infoGluePrincipal.getName(), languageId, db, true); logger.info("userProperties:" + userPropertiesList.size()); Iterator userPropertiesListIterator = userPropertiesList.iterator(); while(userPropertiesListIterator.hasNext()) { UserProperties userProperties = (UserProperties)userPropertiesListIterator.next(); //logger.info("userProperties:" + userProperties.getValue()); //logger.info("propertyName:" + propertyName); logger.info("userProperties:" + userProperties.getValue()); logger.info("assetKey:" + assetKey); if(userProperties != null && userProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = userProperties.getDigitalAssets(); logger.info("assets:" + assets.size()); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); logger.info("digitalAsset:" + digitalAsset.getAssetKey()); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetUrl(digitalAsset, siteNode.getRepository(), deliveryContext); logger.info("assetUrl:" + assetUrl); break; } } } } if(assetUrl.equals("")) { List roles = infoGluePrincipal.getRoles(); Iterator rolesIterator = roles.iterator(); while(rolesIterator.hasNext()) { InfoGlueRole role = (InfoGlueRole)rolesIterator.next(); Collection rolePropertiesList = RolePropertiesController.getController().getRolePropertiesList(role.getName(), languageId, db, true); Iterator rolePropertiesListIterator = rolePropertiesList.iterator(); while(rolePropertiesListIterator.hasNext()) { RoleProperties roleProperties = (RoleProperties)rolePropertiesListIterator.next(); if(roleProperties != null && roleProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = roleProperties.getDigitalAssets(); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetUrl(digitalAsset, siteNode.getRepository(), deliveryContext); break; } } } } } if(assetUrl.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalAssetUrl(db, infoGluePrincipal, assetKey, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, deliveryContext); } } if(assetUrl.equals("")) { List groups = infoGluePrincipal.getGroups(); Iterator groupsIterator = groups.iterator(); while(groupsIterator.hasNext()) { InfoGlueGroup group = (InfoGlueGroup)groupsIterator.next(); Collection groupPropertiesList = GroupPropertiesController.getController().getGroupPropertiesList(group.getName(), languageId, db, true); Iterator groupPropertiesListIterator = groupPropertiesList.iterator(); while(groupPropertiesListIterator.hasNext()) { GroupProperties groupProperties = (GroupProperties)groupPropertiesListIterator.next(); if(groupProperties != null && groupProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = groupProperties.getDigitalAssets(); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetUrl(digitalAsset, siteNode.getRepository(), deliveryContext); break; } } } } } if(assetUrl.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalAssetUrl(db, infoGluePrincipal, assetKey, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, deliveryContext); } } return assetUrl; } /** * Getting a digitalAsset for a Principal - used for personalisation. * This method starts with getting the asset on the user and if it does not exist we check out the * group-properties as well. */ public String getPrincipalThumbnailAssetUrl(Database db, InfoGluePrincipal infoGluePrincipal, String assetKey, Integer languageId, Integer siteNodeId, boolean useLanguageFallback, int width, int height, DeliveryContext deliveryContext) throws Exception { String assetUrl = ""; if(infoGluePrincipal == null || assetKey == null) return null; Collection userPropertiesList = UserPropertiesController.getController().getUserPropertiesList(infoGluePrincipal.getName(), languageId, db, true); Iterator userPropertiesListIterator = userPropertiesList.iterator(); while(userPropertiesListIterator.hasNext()) { UserProperties userProperties = (UserProperties)userPropertiesListIterator.next(); if(userProperties != null && userProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = userProperties.getDigitalAssets(); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetThumbnailUrl(digitalAsset, siteNode.getRepository(), width, height, deliveryContext); break; } } } } if(assetUrl.equals("")) { List roles = infoGluePrincipal.getRoles(); Iterator rolesIterator = roles.iterator(); while(rolesIterator.hasNext()) { InfoGlueRole role = (InfoGlueRole)rolesIterator.next(); Collection rolePropertiesList = RolePropertiesController.getController().getRolePropertiesList(role.getName(), languageId, db, true); Iterator rolePropertiesListIterator = rolePropertiesList.iterator(); while(rolePropertiesListIterator.hasNext()) { RoleProperties roleProperties = (RoleProperties)rolePropertiesListIterator.next(); if(roleProperties != null && roleProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = roleProperties.getDigitalAssets(); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetThumbnailUrl(digitalAsset, siteNode.getRepository(), width, height, deliveryContext); break; } } } } } if(assetUrl.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalThumbnailAssetUrl(db, infoGluePrincipal, assetKey, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, width, height, deliveryContext); } } if(assetUrl.equals("")) { List groups = infoGluePrincipal.getGroups(); Iterator groupsIterator = groups.iterator(); while(groupsIterator.hasNext()) { InfoGlueGroup group = (InfoGlueGroup)groupsIterator.next(); Collection groupPropertiesList = GroupPropertiesController.getController().getGroupPropertiesList(group.getName(), languageId, db, true); Iterator groupPropertiesListIterator = groupPropertiesList.iterator(); while(groupPropertiesListIterator.hasNext()) { GroupProperties groupProperties = (GroupProperties)groupPropertiesListIterator.next(); if(groupProperties != null && groupProperties.getLanguage().getLanguageId().equals(languageId)) { Collection assets = groupProperties.getDigitalAssets(); Iterator assetsIterator = assets.iterator(); while(assetsIterator.hasNext()) { DigitalAsset digitalAsset = (DigitalAsset)assetsIterator.next(); if(digitalAsset.getAssetKey().equalsIgnoreCase(assetKey)) { SiteNode siteNode = SiteNodeController.getController().getSiteNodeWithId(siteNodeId, db); assetUrl = DigitalAssetDeliveryController.getDigitalAssetDeliveryController().getAssetThumbnailUrl(digitalAsset, siteNode.getRepository(), width, height, deliveryContext); break; } } } } } if(assetUrl.equals("") && useLanguageFallback) { LanguageVO masterLanguageVO = LanguageDeliveryController.getLanguageDeliveryController().getMasterLanguageForSiteNode(db, siteNodeId); if(!masterLanguageVO.getLanguageId().equals(languageId)) return getPrincipalThumbnailAssetUrl(db, infoGluePrincipal, assetKey, masterLanguageVO.getLanguageId(), siteNodeId, useLanguageFallback, width, height, deliveryContext); } } return assetUrl; } /** * Getting a property for a Principal - used for personalisation. * This method starts with getting the property on the user and if it does not exist we check out the * group-properties as well. The value in question is a map - name-value. */ /* public Map getPrincipalPropertyHashValues(Database db, InfoGluePrincipal infoGluePrincipal, String propertyName, Integer languageId, Integer siteNodeId, boolean useLanguageFallback, boolean escapeSpecialCharacters) throws Exception { Properties properties = new Properties(); String attributeValue = getPrincipalPropertyValue(db, infoGluePrincipal, propertyName, languageId, siteNodeId, useLanguageFallback, escapeSpecialCharacters); ByteArrayInputStream is = new ByteArrayInputStream(attributeValue.getBytes("UTF-8")); properties.load(is); return properties; } */ }
true
false
null
null
diff --git a/src/AnnotationTester.java b/src/AnnotationTester.java index ca59913..1f7cb25 100644 --- a/src/AnnotationTester.java +++ b/src/AnnotationTester.java @@ -1,128 +1,128 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * prints the annotations for all classes and their methods * * @author Thomas * */ @Creator(name = "Thomas", lastUpdate = "08.12.2012") public class AnnotationTester implements Tester{ @Override @Creator(name = "Thomas", lastUpdate = "08.12.2012") public void runTests() { System.out.println("=== " + Bauernhof.class.getName() + " ==="); displayAnnotations(Bauernhof.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Bauernhof.class.getDeclaredMethods()); System.out.println("\n\n=== " + Traktor.class.getName() + " ==="); displayAnnotations(Traktor.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Traktor.class.getDeclaredMethods()); System.out.println("\n\n=== " + BiogasTraktor.class.getName() + " ==="); displayAnnotations(BiogasTraktor.class.getAnnotations()); System.out.println(); displayMethodAnnotations(BiogasTraktor.class.getDeclaredMethods()); System.out.println("\n\n=== " + DieselTraktor.class.getName() + " ==="); displayAnnotations(DieselTraktor.class.getAnnotations()); System.out.println(); displayMethodAnnotations(DieselTraktor.class.getDeclaredMethods()); System.out.println("\n\n=== " + TraktorGeraet.class.getName() + " ==="); displayAnnotations(TraktorGeraet.class.getAnnotations()); System.out.println(); displayMethodAnnotations(TraktorGeraet.class.getDeclaredMethods()); System.out.println("\n\n=== " + Drillmaschine.class.getName() + " ==="); displayAnnotations(Drillmaschine.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Drillmaschine.class.getDeclaredMethods()); System.out.println("\n\n=== " + Duengerstreuer.class.getName() + " ==="); displayAnnotations(Duengerstreuer.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Duengerstreuer.class.getDeclaredMethods()); System.out.println("\n\n=== " + MyIterator.class.getName() + " ==="); displayAnnotations(MyIterator.class.getAnnotations()); System.out.println(); displayMethodAnnotations(MyIterator.class.getDeclaredMethods()); System.out.println("\n\n=== " + Liste.class.getName() + " ==="); displayAnnotations(Liste.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Liste.class.getDeclaredMethods()); System.out.println("\n\n=== " + Liste.class.getDeclaredClasses()[0].getName() + " ==="); displayAnnotations(Liste.class.getDeclaredClasses()[0].getAnnotations()); System.out.println(); displayMethodAnnotations(Liste.class.getDeclaredClasses()[0].getDeclaredMethods()); // nested iterator System.out.println("\n\n=== " + Tester.class.getName() + " ==="); displayAnnotations(Tester.class.getAnnotations()); System.out.println(); displayMethodAnnotations(Tester.class.getDeclaredMethods()); System.out.println("\n\n=== " + AnnotationTester.class.getName() + " ==="); displayAnnotations(AnnotationTester.class.getAnnotations()); System.out.println(); displayMethodAnnotations(AnnotationTester.class.getDeclaredMethods()); } /** * prints the annotations in a pretty manner * * @param a * annotation-array (ALLOWED!) */ @Creator(name = "Thomas", lastUpdate = "08.12.2012") private void displayAnnotations(Annotation[] a) { if (a != null) { for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } } } /** * prints the annotations of all methods passed as arg * * @param m * method-array (ALLOWED!) */ @Creator(name = "Thomas", lastUpdate = "08.12.2012") private void displayMethodAnnotations(Method[] m) { if (m != null) { for (int i = 0; i < m.length; i++) { if (m[i].getAnnotations().length != 0) { System.out.print("Method: " + m[i].getName() + "("); for (int k = 0; k < m[i].getParameterTypes().length; k++) { System.out.print(m[i].getParameterTypes()[k].getName()); if (k != m[i].getParameterTypes().length - 1) { - System.out.print(" "); + System.out.print(", "); } } System.out.print("):\n"); displayAnnotations(m[i].getAnnotations()); System.out.println(); } } } } }
true
false
null
null
diff --git a/source/src/ca/idi/tekla/ime/TeclaIME.java b/source/src/ca/idi/tekla/ime/TeclaIME.java index 85168cf..3bb3b9c 100644 --- a/source/src/ca/idi/tekla/ime/TeclaIME.java +++ b/source/src/ca/idi/tekla/ime/TeclaIME.java @@ -1,2378 +1,2381 @@ /* * Copyright (C) 2008-2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package ca.idi.tekla.ime; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.inputmethodservice.InputMethodService; import android.inputmethodservice.Keyboard; import android.inputmethodservice.Keyboard.Key; import android.inputmethodservice.KeyboardView; import android.media.AudioManager; import android.media.ToneGenerator; import android.os.Debug; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import android.speech.RecognizerIntent; import android.text.AutoText; import android.text.ClipboardManager; import android.text.TextUtils; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.PopupWindow; import ca.idi.tecla.sdk.SepManager; import ca.idi.tecla.sdk.SwitchEvent; import ca.idi.tekla.R; import ca.idi.tekla.TeclaApp; import ca.idi.tekla.TeclaPrefs; import ca.idi.tekla.sep.SwitchEventProvider; import ca.idi.tekla.util.Highlighter; import ca.idi.tekla.util.Persistence; /** * Input method implementation for Qwerty'ish keyboard. */ public class TeclaIME extends InputMethodService implements KeyboardView.OnKeyboardActionListener { static final boolean TRACE = false; private static final String PREF_VIBRATE_ON = "vibrate_on"; private static final String PREF_SOUND_ON = "sound_on"; private static final String PREF_AUTO_CAP = "auto_cap"; private static final String PREF_QUICK_FIXES = "quick_fixes"; private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions"; private static final String PREF_AUTO_COMPLETE = "auto_complete"; private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_START_TUTORIAL = 1; private static final int MSG_UPDATE_SHIFT_STATE = 2; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; // Weight added to a user picking a new word from the suggestion strip static final int FREQUENCY_FOR_PICKED = 3; // Weight added to a user typing a new word that doesn't get corrected (or is reverted) static final int FREQUENCY_FOR_TYPED = 1; // A word that is frequently typed and get's promoted to the user dictionary, uses this // frequency. static final int FREQUENCY_FOR_AUTO_ADD = 250; static final int KEYCODE_ENTER = '\n'; static final int KEYCODE_SPACE = ' '; // Contextual menu positions private static final int POS_SETTINGS = 0; private static final int POS_METHOD = 1; private TeclaKeyboardView mIMEView; private CandidateViewContainer mCandidateViewContainer; private CandidateView mCandidateView; private Suggest mSuggest; private CompletionInfo[] mCompletions; private AlertDialog mOptionsDialog; KeyboardSwitcher mKeyboardSwitcher; // Morse variables private TeclaMorse mTeclaMorse; private Keyboard.Key mSpaceKey; private Keyboard.Key mCapsLockKey; private int mCapsLockKeyIndex; private int mSpaceKeyIndex; private int mRepeatedKey; private long mMorseStartTime; // Morse caps lock key private static final int CAPS_LOCK_OFF = 0; private static final int CAPS_LOCK_NEXT = 1; private static final int CAPS_LOCK_ALL = 2; private Integer mCapsLockState = CAPS_LOCK_OFF; //Morse key modes public static final int TRIPLE_KEY_MODE = 0; public static final int DOUBLE_KEY_MODE = 1; public static final int SINGLE_KEY_MODE = 2; + + //Morse typing error margin (single-key mode) + private static final float ERROR_MARGIN = 1.15f; private UserDictionary mUserDictionary; private ContactsDictionary mContactsDictionary; private ExpandableDictionary mAutoDictionary; private String mLocale; private StringBuilder mComposing = new StringBuilder(); private WordComposer mWord = new WordComposer(); private int mCommittedLength; private boolean mPredicting; private CharSequence mBestWord; private boolean mPredictionOn; private boolean mCompletionOn; private boolean mAutoSpace; private boolean mAutoCorrectOn; private boolean mCapsLock; private boolean mVibrateOn; private boolean mSoundOn; private boolean mAutoCap; private boolean mQuickFixes; private boolean mShowSuggestions; private int mCorrectionMode; private int mOrientation; // Indicates whether the suggestion strip is to be on in landscape private boolean mJustAccepted; private CharSequence mJustRevertedSeparator; private int mDeleteCount; private long mLastKeyTime; private Tutorial mTutorial; private Vibrator mVibrator; private long mVibrateDuration; private AudioManager mAudioManager; // Align sound effect volume on music volume private final float FX_VOLUME = -1.0f; private boolean mSilentMode; private ToneGenerator mTone = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 80); private int mToneType = ToneGenerator.TONE_CDMA_DIAL_TONE_LITE; private String mWordSeparators; private String mSentenceSeparators; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: updateSuggestions(); break; case MSG_START_TUTORIAL: if (mTutorial == null) { if (mIMEView.isShown()) { mTutorial = new Tutorial(TeclaIME.this, mIMEView); mTutorial.start(); } else { // Try again soon if the view is not yet showing sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100); } } break; case MSG_UPDATE_SHIFT_STATE: updateShiftKeyState(getCurrentInputEditorInfo()); break; } } }; @Override public void onCreate() { super.onCreate(); mTeclaMorse = new TeclaMorse(this); // Setup Debugging //if (TeclaApp.DEBUG) android.os.Debug.waitForDebugger(); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Creating IME..."); //setStatusIcon(R.drawable.ime_qwerty); mKeyboardSwitcher = new KeyboardSwitcher(this); final Configuration conf = getResources().getConfiguration(); initSuggest(conf.locale.toString()); mOrientation = conf.orientation; mVibrateDuration = getResources().getInteger(R.integer.vibrate_duration_ms); // register to receive ringer mode changes for silent mode registerReceiver(mReceiver, new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION)); initTeclaA11y(); } private void initSuggest(String locale) { mLocale = locale; mSuggest = new Suggest(this, R.raw.main); mSuggest.setCorrectionMode(mCorrectionMode); mUserDictionary = new UserDictionary(this); mContactsDictionary = new ContactsDictionary(this); mAutoDictionary = new AutoDictionary(this); mSuggest.setUserDictionary(mUserDictionary); mSuggest.setContactsDictionary(mContactsDictionary); mSuggest.setAutoDictionary(mAutoDictionary); mWordSeparators = getResources().getString(R.string.word_separators); mSentenceSeparators = getResources().getString(R.string.sentence_separators); } @Override public void onDestroy() { super.onDestroy(); mUserDictionary.close(); mContactsDictionary.close(); unregisterReceiver(mReceiver); TeclaApp.highlighter.stopSelfScanning(); SepManager.stop(this); } @Override public void onConfigurationChanged(Configuration conf) { if (!TextUtils.equals(conf.locale.toString(), mLocale)) { initSuggest(conf.locale.toString()); } // If orientation changed while predicting, commit the change if (conf.orientation != mOrientation) { commitTyped(getCurrentInputConnection()); mOrientation = conf.orientation; // If the fullscreen switch is enabled, change its size to match screen if(isFullScreenShowing()) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, "Changing size of fullscreen overlay."); Display display = getDisplay(); mSwitchPopup.update(display.getWidth(), display.getHeight()); } } if (mKeyboardSwitcher == null) { mKeyboardSwitcher = new KeyboardSwitcher(this); } mKeyboardSwitcher.makeKeyboards(true); super.onConfigurationChanged(conf); if (mKeyboardSwitcher.isMorseMode()) { mTeclaMorse.getMorseChart().configChanged(conf); mIMEView.invalidate(); updateSpaceKey(true); updateCapsLockKey(true); } } @Override public View onCreateInputView() { mIMEView = (TeclaKeyboardView) getLayoutInflater().inflate( R.xml.input, null); mKeyboardSwitcher.setInputView(mIMEView); mKeyboardSwitcher.makeKeyboards(true); mIMEView.setOnKeyboardActionListener(this); mIMEView.setTeclaMorse(mTeclaMorse); mIMEView.setService(this); if (TeclaApp.persistence.isMorseModeEnabled()) mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_MORSE, 0); else mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_NAV, 0); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Soft IME view created."); TeclaApp.highlighter.setIMEView(mIMEView); return mIMEView; } @Override public View onCreateCandidatesView() { // No candidates view in Morse mode if (!TeclaApp.persistence.isMorseModeEnabled()) { mKeyboardSwitcher.makeKeyboards(true); mCandidateViewContainer = (CandidateViewContainer) getLayoutInflater().inflate( R.layout.candidates, null); mCandidateViewContainer.initViews(); mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates); mCandidateView.setService(this); setCandidatesViewShown(true); // TODO: Tecla - uncomment to enable suggestions //return mCandidateViewContainer; } return null; } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { // In landscape mode, this method gets called without the input view being created. if (mIMEView == null) { return; } mKeyboardSwitcher.makeKeyboards(false); TextEntryState.newSession(this); boolean disableAutoCorrect = false; mPredictionOn = false; mCompletionOn = false; mCompletions = null; mCapsLock = false; switch (attribute.inputType&EditorInfo.TYPE_MASK_CLASS) { case EditorInfo.TYPE_CLASS_NUMBER: case EditorInfo.TYPE_CLASS_DATETIME: if (TeclaApp.persistence.isMorseModeEnabled()) mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_MORSE, attribute.imeOptions); else mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_SYMBOLS, attribute.imeOptions); break; case EditorInfo.TYPE_CLASS_PHONE: if (TeclaApp.persistence.isMorseModeEnabled()) mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_MORSE, attribute.imeOptions); else mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE, attribute.imeOptions); break; case EditorInfo.TYPE_CLASS_TEXT: if (TeclaApp.persistence.isMorseModeEnabled()) mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_MORSE, attribute.imeOptions); else { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute.imeOptions); //startPrediction(); mPredictionOn = true; // Make sure that passwords are not displayed in candidate view int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION; if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD || variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) { mPredictionOn = false; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) { mAutoSpace = false; } else { mAutoSpace = true; } if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL, attribute.imeOptions); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) { mPredictionOn = false; mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL, attribute.imeOptions); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM, attribute.imeOptions); } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) { mPredictionOn = false; } else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) { // If it's a browser edit field and auto correct is not ON explicitly, then // disable auto correction, but keep suggestions on. if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) { disableAutoCorrect = true; } } // If NO_SUGGESTIONS is set, don't do prediction. if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) { mPredictionOn = false; disableAutoCorrect = true; } // If it's not multiline and the autoCorrect flag is not set, then don't correct if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 && (attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) { disableAutoCorrect = true; } if ((attribute.inputType&EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) { mPredictionOn = false; mCompletionOn = true && isFullscreenMode(); } updateShiftKeyState(attribute); } break; case EditorInfo.TYPE_NULL: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_NAV, attribute.imeOptions); updateShiftKeyState(attribute); break; default: if (TeclaApp.persistence.isMorseModeEnabled()) mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_MORSE, attribute.imeOptions); else { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT, attribute.imeOptions); updateShiftKeyState(attribute); } } mIMEView.closing(); mComposing.setLength(0); mPredicting = false; mDeleteCount = 0; setCandidatesViewShown(false); if (mCandidateView != null) mCandidateView.setSuggestions(null, false, false, false); loadSettings(); // Override auto correct if (disableAutoCorrect) { mAutoCorrectOn = false; if (mCorrectionMode == Suggest.CORRECTION_FULL) { mCorrectionMode = Suggest.CORRECTION_BASIC; } } mIMEView.setProximityCorrectionEnabled(true); if (mSuggest != null) { mSuggest.setCorrectionMode(mCorrectionMode); } mPredictionOn = mPredictionOn && mCorrectionMode > 0; checkTutorial(attribute.privateImeOptions); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); int thisKBMode = mKeyboardSwitcher.getKeyboardMode(); if(mLastKeyboardMode != thisKBMode) { mLastKeyboardMode = thisKBMode; evaluateStartScanning(); } initMorseKeyboard(); if (mKeyboardSwitcher.isMorseMode() && TeclaApp.persistence.isMorseHudEnabled()) { mTeclaMorse.getMorseChart().restore(); mIMEView.invalidate(); } evaluateNavKbdTimeout(); } @Override public void onFinishInput() { super.onFinishInput(); if (mIMEView != null) { mIMEView.closing(); } } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); // If the current selection in the text view changes, we should // clear whatever candidate text we have. if (mComposing.length() > 0 && mPredicting && (newSelStart != candidatesEnd || newSelEnd != candidatesEnd)) { mComposing.setLength(0); mPredicting = false; updateSuggestions(); TextEntryState.reset(); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } } else if (!mPredicting && !mJustAccepted && TextEntryState.getState() == TextEntryState.STATE_ACCEPTED_DEFAULT) { TextEntryState.reset(); } mJustAccepted = false; postUpdateShiftKeyState(); } @Override public void hideWindow() { if (TeclaApp.highlighter.isSoftIMEShowing()) { TeclaApp.highlighter.stopSelfScanning(); TeclaApp.highlighter.clear(); } if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } if (mTutorial != null) { mTutorial.close(); mTutorial = null; } super.hideWindow(); TextEntryState.endSession(); } @Override public boolean onEvaluateFullscreenMode() { // never go to fullscreen mode //return super.onEvaluateFullscreenMode(); return false; } @Override public void onDisplayCompletions(CompletionInfo[] completions) { if (false) { Log.i("foo", "Received completions:"); for (int i=0; i<(completions != null ? completions.length : 0); i++) { Log.i("foo", " #" + i + ": " + completions[i]); } } if (mCompletionOn) { mCompletions = completions; if (completions == null) { mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = new ArrayList<CharSequence>(); for (int i=0; i<(completions != null ? completions.length : 0); i++) { CompletionInfo ci = completions[i]; if (ci != null) stringList.add(ci.getText()); } //CharSequence typedWord = mWord.getTypedWord(); mCandidateView.setSuggestions(stringList, true, true, true); mBestWord = null; setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } } @Override public void setCandidatesViewShown(boolean shown) { // TODO: Remove this if we support candidates with hard keyboard if (onEvaluateInputViewShown()) { super.setCandidatesViewShown(shown); } } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); if (!isFullscreenMode()) { outInsets.contentTopInsets = outInsets.visibleTopInsets; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: // FIXME: Tecla - Prevent soft input method from consuming the back key /*if (event.getRepeatCount() == 0 && mInputView != null) { if (mInputView.handleBack()) { return true; } else if (mTutorial != null) { mTutorial.close(); mTutorial = null; } } break;*/ return false; case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // If tutorial is visible, don't allow dpad to work if (mTutorial != null) { return true; } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // If tutorial is visible, don't allow dpad to work if (mTutorial != null) { return true; } // Enable shift key and DPAD to do selections if (TeclaApp.highlighter.isSoftIMEShowing() && mIMEView.isShifted()) { event = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(event); return true; } break; } return super.onKeyUp(keyCode, event); } /** * This is called every time the soft IME window is hidden from the user. */ @Override public void onWindowHidden() { super.onWindowHidden(); if (shouldShowIME() && !mIsNavKbdTimedOut) { showIMEView(); if (TeclaApp.highlighter.isSoftIMEShowing()) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_NAV, 0); evaluateStartScanning(); } } } @Override public boolean onEvaluateInputViewShown() { return shouldShowIME()? true:super.onEvaluateInputViewShown(); } private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) // receive ringer mode changes to detect silent mode updateRingerMode(); if (action.equals(SwitchEvent.ACTION_SWITCH_EVENT_RECEIVED)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received switch event intent."); handleSwitchEvent(new SwitchEvent(intent.getExtras())); } if (action.equals(SwitchEventProvider.ACTION_SHIELD_CONNECTED)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received Shield connected intent."); if (!mShieldConnected) mShieldConnected = true; showIMEView(); evaluateStartScanning(); } if (action.equals(SwitchEventProvider.ACTION_SHIELD_DISCONNECTED)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received Shield disconnected intent."); if (mShieldConnected) mShieldConnected = false; evaluateStartScanning(); } if (action.equals(TeclaApp.ACTION_SHOW_IME)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received show IME intent."); showIMEView(); evaluateStartScanning(); evaluateNavKbdTimeout(); //TODO: Assume/force persistent keyboard preference } if (action.equals(TeclaApp.ACTION_HIDE_IME)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received hide IME intent."); hideSoftIME(); } if (action.equals(TeclaApp.ACTION_START_FS_SWITCH_MODE)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received start fullscreen switch mode intent."); startFullScreenSwitchMode(500); } if (action.equals(TeclaApp.ACTION_STOP_FS_SWITCH_MODE)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received stop fullscreen switch mode intent."); stopFullScreenSwitchMode(); } if (action.equals(Highlighter.ACTION_START_SCANNING)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received start scanning IME intent."); evaluateStartScanning(); } if (action.equals(Highlighter.ACTION_STOP_SCANNING)) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received stop scanning IME intent."); evaluateStartScanning(); } if (action.equals(TeclaApp.ACTION_INPUT_STRING)) { String input_string = intent.getExtras().getString(TeclaApp.EXTRA_INPUT_STRING); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received input string intent."); typeInputString(input_string); } if (action.equals(TeclaApp.ACTION_ENABLE_MORSE)) { if (TeclaApp.highlighter.isSoftIMEShowing()) { hideSoftIME(); } if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received enable morse intent."); mLastFullKeyboardMode = KeyboardSwitcher.MODE_MORSE; } if (action.equals(TeclaApp.ACTION_DISABLE_MORSE)) { if (TeclaApp.highlighter.isSoftIMEShowing()) { hideSoftIME(); } if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Received disable morse intent."); mLastFullKeyboardMode = KeyboardSwitcher.MODE_TEXT; } } }; private void commitTyped(InputConnection inputConnection) { if (mPredicting) { mPredicting = false; if (mComposing.length() > 0) { if (inputConnection != null) { inputConnection.commitText(mComposing, 1); } mCommittedLength = mComposing.length(); TextEntryState.acceptedTyped(mComposing); mAutoDictionary.addWord(mComposing.toString(), FREQUENCY_FOR_TYPED); } updateSuggestions(); } } private void postUpdateShiftKeyState() { mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE); mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SHIFT_STATE), 300); } public void updateShiftKeyState(EditorInfo attr) { InputConnection ic = getCurrentInputConnection(); if (attr != null && mIMEView != null && mKeyboardSwitcher.isAlphabetMode() && ic != null) { int caps = 0; EditorInfo ei = getCurrentInputEditorInfo(); if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) { caps = ic.getCursorCapsMode(attr.inputType); } mIMEView.setShifted(mCapsLock || caps != 0); } } private void swapPunctuationAndSpace() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == KEYCODE_SPACE && isSentenceSeparator(lastTwo.charAt(1))) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } private void doubleSpace() { //if (!mAutoPunctuate) return; if (mCorrectionMode == Suggest.CORRECTION_NONE) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Character.isLetterOrDigit(lastThree.charAt(0)) && lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) { ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); } } public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); return true; } private boolean isAlphabet(int code) { if (Character.isLetter(code)) { return true; } else { return false; } } // Implementation of KeyboardViewListener public void onKey(int primaryCode, int[] keyCodes) { long when = SystemClock.uptimeMillis(); if (TeclaApp.DEBUG) { if (keyCodes != null && keyCodes.length > 0) { Log.d(TeclaApp.TAG, CLASS_TAG + "Keycode: " + keyCodes[0]); } } if (primaryCode != Keyboard.KEYCODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; switch (primaryCode) { case Keyboard.KEYCODE_DELETE: handleBackspace(); mDeleteCount++; break; case Keyboard.KEYCODE_SHIFT: handleShift(); break; case Keyboard.KEYCODE_CANCEL: if (mOptionsDialog == null || !mOptionsDialog.isShowing()) { handleClose(); } break; case TeclaKeyboardView.KEYCODE_OPTIONS: showOptionsMenu(); break; case TeclaKeyboardView.KEYCODE_SHIFT_LONGPRESS: if (mCapsLock) { handleShift(); } else { toggleCapsLock(); } break; case Keyboard.KEYCODE_MODE_CHANGE: changeKeyboardMode(); break; default: if (isMorseKeyboardKey(primaryCode)) { onKeyMorse(primaryCode); } else if (isWordSeparator(primaryCode)) { handleSeparator(primaryCode); } else if (isSpecialKey(primaryCode)) { handleSpecialKey(primaryCode); } else { handleCharacter(primaryCode, keyCodes); } // Cancel the just reverted state mJustRevertedSeparator = null; } if (mKeyboardSwitcher.onKey(primaryCode)) { changeKeyboardMode(); } evaluateNavKbdTimeout(); } /** * Handles key input on the Morse Code keyboard * @param primaryCode */ public void onKeyMorse(int primaryCode) { initMorseKeyboard(); switch (primaryCode) { case TeclaKeyboard.KEYCODE_MORSE_DIT: case TeclaKeyboard.KEYCODE_MORSE_DAH: // Set a limit to the Morse sequence length if (mTeclaMorse.getCurrentChar().length() < mTeclaMorse.getMorseDictionary().getMaxCodeLength()) { if(primaryCode == TeclaKeyboard.KEYCODE_MORSE_DIT) mTeclaMorse.addDit(); else mTeclaMorse.addDah(); evaluateEndOfChar(); } break; // Space button ends the current ditdah sequence // Space twice in a row sends through a standard space character case TeclaKeyboard.KEYCODE_MORSE_SPACEKEY: if (TeclaApp.persistence.getMorseKeyMode() != SINGLE_KEY_MODE) handleMorseSpaceKey(); break; case TeclaKeyboard.KEYCODE_MORSE_DELKEY: handleMorseBackspace(true); break; case TeclaKeyboard.KEYCODE_MORSE_CAPSKEY: switch (mCapsLockState) { case CAPS_LOCK_OFF: mCapsLockState = CAPS_LOCK_NEXT; break; case CAPS_LOCK_NEXT: mCapsLockState = CAPS_LOCK_ALL; break; default: mCapsLockState = CAPS_LOCK_OFF; } updateCapsLockKey(true); break; } updateSpaceKey(true); mIMEView.invalidate(); } private void clearCharInProgress() { mTeclaMorse.clearCharInProgress(); } private void handleMorseSpaceKey() { String curCharMatch = mTeclaMorse.morseToChar(mTeclaMorse.getCurrentChar()); if (mTeclaMorse.getCurrentChar().length() == 0) { getCurrentInputConnection().commitText(" ", 1); } else { if (curCharMatch != null) { if (curCharMatch.contentEquals("↵")) { sendDownUpKeyEvents(KeyEvent.KEYCODE_ENTER); } else if (curCharMatch.contentEquals("DEL")) { handleMorseBackspace(false); } else if (curCharMatch.contentEquals("✓")) { hideSoftIME(); } else if (curCharMatch.contentEquals("SP")) { getCurrentInputConnection().commitText(" ", 1); } else if (curCharMatch.contentEquals("\\n")) { getCurrentInputConnection().commitText("\n", 1); } else { boolean upperCase = false; if (mCapsLockState == CAPS_LOCK_NEXT) { upperCase = true; mCapsLockState = CAPS_LOCK_OFF; updateCapsLockKey(true); } else if (mCapsLockState == CAPS_LOCK_ALL) { upperCase = true; } if (upperCase) { curCharMatch = curCharMatch.toUpperCase(); } getCurrentInputConnection().commitText(curCharMatch, curCharMatch.length()); } } } clearCharInProgress(); } /** * Handles the backspace event (Morse keyboard only) * @param clearEnabled */ private void handleMorseBackspace(boolean clearEnabled) { // If there's a character in progress, clear it // otherwise, send through a backspace keypress if (mTeclaMorse.getCurrentChar().length() > 0 && clearEnabled) { clearCharInProgress(); }else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); clearCharInProgress(); updateSpaceKey(true); if (mCapsLockState == CAPS_LOCK_NEXT) { // If you've hit delete and you were in caps_next state, // then caps_off mCapsLockState = CAPS_LOCK_OFF; updateCapsLockKey(true); } } } /** * Updates the state of the Space key (Morse keyboard only) * @param refreshScreen */ private void updateSpaceKey(boolean refreshScreen) { String sequence = mTeclaMorse.getCurrentChar(); String charac = mTeclaMorse.morseToChar(sequence); if (charac == null && sequence.length() > 0) mSpaceKey.label = sequence; else if (!sequence.equals("") && sequence.length() <= mTeclaMorse.getMorseDictionary().getMaxCodeLength()) { //Update the key label according the current character mSpaceKey.label = (mCapsLockState == CAPS_LOCK_OFF ? charac : charac.toUpperCase()) + " " + sequence; mSpaceKey.icon = null; } else { //Icon should take precedence over label, but it is not the case, //so set label to null mSpaceKey.label = null; mSpaceKey.icon = TeclaApp.getInstance().getResources().getDrawable(R.drawable.sym_keyboard_space); } if (refreshScreen) mIMEView.invalidateKey(mSpaceKeyIndex); } /** * Updates the state of the Caps Lock key (Morse keyboard only) * @param refreshScreen */ private void updateCapsLockKey(boolean refreshScreen) { Context context = this.getApplicationContext(); switch (mCapsLockState) { case CAPS_LOCK_OFF: mCapsLockKey.on = false; mCapsLockKey.label = context.getText(R.string.caps_lock_off); break; case CAPS_LOCK_NEXT: mCapsLockKey.on = false; mCapsLockKey.label = context.getText(R.string.caps_lock_next); break; case CAPS_LOCK_ALL: mCapsLockKey.on = true; mCapsLockKey.label = context.getText(R.string.caps_lock_all); break; } if (refreshScreen) mIMEView.invalidateKey(mCapsLockKeyIndex); } public void onText(CharSequence text) { InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); if (mPredicting) { commitTyped(ic); } ic.commitText(text, 1); ic.endBatchEdit(); updateShiftKeyState(getCurrentInputEditorInfo()); mJustRevertedSeparator = null; } private void handleBackspace() { boolean deleteChar = false; InputConnection ic = getCurrentInputConnection(); if (ic == null) return; if (mPredicting) { final int length = mComposing.length(); if (length > 0) { mComposing.delete(length - 1, length); mWord.deleteLast(); ic.setComposingText(mComposing, 1); if (mComposing.length() == 0) { mPredicting = false; } postUpdateSuggestions(); } else { ic.deleteSurroundingText(1, 0); } } else { deleteChar = true; } postUpdateShiftKeyState(); TextEntryState.backspace(); if (TextEntryState.getState() == TextEntryState.STATE_UNDO_COMMIT) { revertLastWord(deleteChar); return; } else if (deleteChar) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); if (mDeleteCount > DELETE_ACCELERATE_AT) { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); } } mJustRevertedSeparator = null; } private void handleShift() { //Keyboard currentKeyboard = mIMEView.getKeyboard(); if (mKeyboardSwitcher.isAlphabetMode()) { // Alphabet keyboard checkToggleCapsLock(); mIMEView.setShifted(mCapsLock || !mIMEView.isShifted()); } else { mKeyboardSwitcher.toggleShift(); } } private void handleCharacter(int primaryCode, int[] keyCodes) { CharSequence variants = null; TeclaKeyboard keyboard = mIMEView.getKeyboard(); Key key = keyboard.getKeyFromCode(primaryCode); if (key != null) variants = key.popupCharacters; if (TeclaApp.persistence.isVariantsOn() && variants != null && variants.length() > 0) { // Key has variants! mWasSymbols = mKeyboardSwitcher.isSymbols(); mWasShifted = keyboard.isShifted(); TeclaApp.persistence.setVariantsShowing(true); switch (variants.length()) { case 1: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X3); break; case 2: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X4); break; case 3: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X5); break; case 4: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X6); break; case 5: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X7); break; case 6: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X8); break; case 7: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X9); break; case 8: mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_1X10); break; } populateVariants(key.label, variants); mIMEView.getKeyboard().setShifted(mWasShifted); evaluateStartScanning(); } else { if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) { if (!mPredicting) { mPredicting = true; mComposing.setLength(0); mWord.reset(); } } if (mIMEView.isShifted()) { // TODO: This doesn't work with ß, need to fix it in the next release. if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT || keyCodes[0] > Character.MAX_CODE_POINT) { return; } primaryCode = new String(keyCodes, 0, 1).toUpperCase().charAt(0); } if (mPredicting) { if (mIMEView.isShifted() && mComposing.length() == 0) { mWord.setCapitalized(true); } mComposing.append((char) primaryCode); mWord.add(primaryCode, keyCodes); InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.setComposingText(mComposing, 1); } postUpdateSuggestions(); } else { sendKeyChar((char)primaryCode); } updateShiftKeyState(getCurrentInputEditorInfo()); measureCps(); TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode)); if (mKeyboardSwitcher.isVariants()) { doVariantsExit(primaryCode); evaluateStartScanning(); } } } private void handleSeparator(int primaryCode) { boolean pickedDefault = false; // Handle separator InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mPredicting) { // In certain languages where single quote is a separator, it's better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the elision // requires the last vowel to be removed. if (mAutoCorrectOn && primaryCode != '\'' && (mJustRevertedSeparator == null || mJustRevertedSeparator.length() == 0 || mJustRevertedSeparator.charAt(0) != primaryCode)) { pickDefaultSuggestion(); pickedDefault = true; } else { commitTyped(ic); } } sendKeyChar((char)primaryCode); TextEntryState.typedCharacter((char) primaryCode, true); if (TextEntryState.getState() == TextEntryState.STATE_PUNCTUATION_AFTER_ACCEPTED && primaryCode != KEYCODE_ENTER) { swapPunctuationAndSpace(); } else if (isPredictionOn() && primaryCode == ' ') { //else if (TextEntryState.STATE_SPACE_AFTER_ACCEPTED) { doubleSpace(); } if (pickedDefault && mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); } updateShiftKeyState(getCurrentInputEditorInfo()); if (ic != null) { ic.endBatchEdit(); } } private void handleClose() { commitTyped(getCurrentInputConnection()); requestHideSelf(0); mIMEView.closing(); TextEntryState.endSession(); } private void checkToggleCapsLock() { if (mIMEView.getKeyboard().isShifted()) { toggleCapsLock(); } } private void toggleCapsLock() { mCapsLock = !mCapsLock; if (mKeyboardSwitcher.isAlphabetMode()) { mIMEView.getKeyboard().setShiftLocked(mCapsLock); } } private void postUpdateSuggestions() { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100); } private boolean isPredictionOn() { boolean predictionOn = mPredictionOn; //if (isFullscreenMode()) predictionOn &= mPredictionLandscape; return predictionOn; } private boolean isCandidateStripVisible() { return isPredictionOn() && mShowSuggestions; } private void updateSuggestions() { // Check if we have a suggestion engine attached. if (mSuggest == null || !isPredictionOn()) { return; } if (!mPredicting) { mCandidateView.setSuggestions(null, false, false, false); return; } List<CharSequence> stringList = mSuggest.getSuggestions(mIMEView, mWord, false); boolean correctionAvailable = mSuggest.hasMinimalCorrection(); //|| mCorrectionMode == mSuggest.CORRECTION_FULL; CharSequence typedWord = mWord.getTypedWord(); // If we're in basic correct boolean typedWordValid = mSuggest.isValidWord(typedWord); if (mCorrectionMode == Suggest.CORRECTION_FULL) { correctionAvailable |= typedWordValid; } // Don't auto-correct words with multiple capital letter correctionAvailable &= !mWord.isMostlyCaps(); mCandidateView.setSuggestions(stringList, false, typedWordValid, correctionAvailable); if (stringList.size() > 0) { if (correctionAvailable && !typedWordValid && stringList.size() > 1) { mBestWord = stringList.get(1); } else { mBestWord = typedWord; } } else { mBestWord = null; } setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn); } private void pickDefaultSuggestion() { // Complete any pending candidate query first if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) { mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS); updateSuggestions(); } if (mBestWord != null) { TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord); mJustAccepted = true; pickSuggestion(mBestWord); } } public void pickSuggestionManually(int index, CharSequence suggestion) { if (mCompletionOn && mCompletions != null && index >= 0 && index < mCompletions.length) { CompletionInfo ci = mCompletions[index]; InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitCompletion(ci); } mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.clear(); } updateShiftKeyState(getCurrentInputEditorInfo()); return; } pickSuggestion(suggestion); TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion); // Follow it with a space if (mAutoSpace) { sendSpace(); } // Fool the state watcher so that a subsequent backspace will not do a revert TextEntryState.typedCharacter((char) KEYCODE_SPACE, true); } private void pickSuggestion(CharSequence suggestion) { if (mCapsLock) { suggestion = suggestion.toString().toUpperCase(); } else if (preferCapitalization() || (mKeyboardSwitcher.isAlphabetMode() && mIMEView.isShifted())) { suggestion = suggestion.toString().toUpperCase().charAt(0) + suggestion.subSequence(1, suggestion.length()).toString(); } InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.commitText(suggestion, 1); } // Add the word to the auto dictionary if it's not a known word if (mAutoDictionary.isValidWord(suggestion) || !mSuggest.isValidWord(suggestion)) { mAutoDictionary.addWord(suggestion.toString(), FREQUENCY_FOR_PICKED); } mPredicting = false; mCommittedLength = suggestion.length(); if (mCandidateView != null) { mCandidateView.setSuggestions(null, false, false, false); } updateShiftKeyState(getCurrentInputEditorInfo()); } private boolean isCursorTouchingWord() { InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !isWordSeparator(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !isWordSeparator(toRight.charAt(0))) { return true; } return false; } public void revertLastWord(boolean deleteChar) { final int length = mComposing.length(); if (!mPredicting && length > 0) { final InputConnection ic = getCurrentInputConnection(); mPredicting = true; ic.beginBatchEdit(); mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0); if (deleteChar) ic.deleteSurroundingText(1, 0); int toDelete = mCommittedLength; CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0); if (toTheLeft != null && toTheLeft.length() > 0 && isWordSeparator(toTheLeft.charAt(0))) { toDelete--; } ic.deleteSurroundingText(toDelete, 0); ic.setComposingText(mComposing, 1); TextEntryState.backspace(); ic.endBatchEdit(); postUpdateSuggestions(); } else { sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL); mJustRevertedSeparator = null; } } protected String getWordSeparators() { return mWordSeparators; } public boolean isWordSeparator(int code) { String separators = getWordSeparators(); return separators.contains(String.valueOf((char)code)); } public boolean isSentenceSeparator(int code) { return mSentenceSeparators.contains(String.valueOf((char)code)); } private void sendSpace() { sendKeyChar((char)KEYCODE_SPACE); updateShiftKeyState(getCurrentInputEditorInfo()); //onKey(KEY_SPACE[0], KEY_SPACE); } public boolean preferCapitalization() { return mWord.isCapitalized(); } public void swipeRight() { if (TeclaKeyboardView.DEBUG_AUTO_PLAY) { ClipboardManager cm = ((ClipboardManager)getSystemService(CLIPBOARD_SERVICE)); CharSequence text = cm.getText(); if (!TextUtils.isEmpty(text)) { mIMEView.startPlaying(text.toString()); } } } public void swipeLeft() { //handleBackspace(); } public void swipeDown() { handleClose(); } public void swipeUp() { //launchSettings(); } public void onPress(int primaryCode) { if (primaryCode == TeclaKeyboard.KEYCODE_MORSE_SPACEKEY) { if (TeclaApp.persistence.getMorseKeyMode() == SINGLE_KEY_MODE) { evaluateMorsePress(); } } else { vibrate(); playKeyClick(primaryCode); } } public void onRelease(int primaryCode) { if (primaryCode == TeclaKeyboard.KEYCODE_MORSE_SPACEKEY) { if (TeclaApp.persistence.getMorseKeyMode() == SINGLE_KEY_MODE) { stopRepeating(); evaluateEndOfChar(); } } //vibrate(); } // update flags for silent mode private void updateRingerMode() { if (mAudioManager == null) { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } if (mAudioManager != null) { mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL); } } private void checkRingerMode() { // if mAudioManager is null, we don't have the ringer state yet // mAudioManager will be set by updateRingerMode if (mAudioManager == null) { if (mIMEView != null) { updateRingerMode(); } } } private void playKeyClick(int primaryCode) { checkRingerMode(); if (mSoundOn && !mSilentMode) { // FIXME: Volume and enable should come from UI settings // FIXME: These should be triggered after auto-repeat logic int sound = AudioManager.FX_KEYPRESS_STANDARD; int duration = TeclaApp.persistence.getMorseTimeUnit(); switch (primaryCode) { case Keyboard.KEYCODE_DELETE: sound = AudioManager.FX_KEYPRESS_DELETE; mAudioManager.playSoundEffect(sound, FX_VOLUME); break; case KEYCODE_ENTER: sound = AudioManager.FX_KEYPRESS_RETURN; mAudioManager.playSoundEffect(sound, FX_VOLUME); break; case KEYCODE_SPACE: sound = AudioManager.FX_KEYPRESS_SPACEBAR; mAudioManager.playSoundEffect(sound, FX_VOLUME); break; case TeclaKeyboard.KEYCODE_MORSE_DIT: mTone.startTone(mToneType, duration); break; case TeclaKeyboard.KEYCODE_MORSE_DAH: mTone.startTone(mToneType, duration * 3); break; } } } private void vibrate() { if (!mVibrateOn) { return; } if (mVibrator == null) { mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); } mVibrator.vibrate(mVibrateDuration); } private void checkTutorial(String privateImeOptions) { if (privateImeOptions == null) return; if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) { if (mTutorial == null) startTutorial(); } else if (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) { if (mTutorial != null) { if (mTutorial.close()) { mTutorial = null; } } } } private void startTutorial() { mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500); } void tutorialDone() { mTutorial = null; } void promoteToUserDictionary(String word, int frequency) { if (mUserDictionary.isValidWord(word)) return; mUserDictionary.addWord(word, frequency); } private void launchSettings() { handleClose(); Intent intent = new Intent(); intent.setClass(getApplicationContext(), TeclaPrefs.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void loadSettings() { // Get the settings preferences SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false); mSoundOn = sp.getBoolean(PREF_SOUND_ON, false); mAutoCap = sp.getBoolean(PREF_AUTO_CAP, true); mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true); // If there is no auto text data, then quickfix is forced to "on", so that the other options // will continue to work if (AutoText.getSize(mIMEView) < 1) mQuickFixes = true; //TODO: Tecla - changed default show_suggestions to false // need to change back when the dictionary is ready! //mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, true) & mQuickFixes; mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, false) & mQuickFixes; boolean autoComplete = sp.getBoolean(PREF_AUTO_COMPLETE, getResources().getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions; mAutoCorrectOn = mSuggest != null && (autoComplete || mQuickFixes); mCorrectionMode = autoComplete ? Suggest.CORRECTION_FULL : (mQuickFixes ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE); } private void showOptionsMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(R.drawable.ic_dialog_keyboard); builder.setNegativeButton(android.R.string.cancel, null); CharSequence itemSettings = getString(R.string.english_ime_settings); CharSequence itemInputMethod = getString(R.string.inputMethod); builder.setItems(new CharSequence[] { itemSettings, itemInputMethod}, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case POS_SETTINGS: launchSettings(); break; case POS_METHOD: ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .showInputMethodPicker(); break; } } }); builder.setTitle(getResources().getString(R.string.english_ime_name)); mOptionsDialog = builder.create(); Window window = mOptionsDialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.token = mIMEView.getWindowToken(); lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; window.setAttributes(lp); window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); mOptionsDialog.show(); } private void changeKeyboardMode() { mKeyboardSwitcher.toggleSymbols(); if (mCapsLock && mKeyboardSwitcher.isAlphabetMode()) { mIMEView.getKeyboard().setShiftLocked(mCapsLock); } updateShiftKeyState(getCurrentInputEditorInfo()); } @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("TeclaIME state :"); p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode()); p.println(" mCapsLock=" + mCapsLock); p.println(" mComposing=" + mComposing.toString()); p.println(" mPredictionOn=" + mPredictionOn); p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" mPredicting=" + mPredicting); p.println(" mAutoCorrectOn=" + mAutoCorrectOn); p.println(" mAutoSpace=" + mAutoSpace); p.println(" mCompletionOn=" + mCompletionOn); p.println(" TextEntryState.state=" + TextEntryState.getState()); p.println(" mSoundOn=" + mSoundOn); p.println(" mVibrateOn=" + mVibrateOn); } // Characters per second measurement private static final boolean PERF_DEBUG = false; private long mLastCpsTime; private static final int CPS_BUFFER_SIZE = 16; private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE]; private int mCpsIndex; private void measureCps() { if (!TeclaIME.PERF_DEBUG) return; long now = System.currentTimeMillis(); if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial mCpsIntervals[mCpsIndex] = now - mLastCpsTime; mLastCpsTime = now; mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE; long total = 0; for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i]; System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total)); } class AutoDictionary extends ExpandableDictionary { // If the user touches a typed word 2 times or more, it will become valid. private static final int VALIDITY_THRESHOLD = 2 * FREQUENCY_FOR_PICKED; // If the user touches a typed word 5 times or more, it will be added to the user dict. private static final int PROMOTION_THRESHOLD = 5 * FREQUENCY_FOR_PICKED; public AutoDictionary(Context context) { super(context); } @Override public boolean isValidWord(CharSequence word) { final int frequency = getWordFrequency(word); return frequency > VALIDITY_THRESHOLD; } @Override public void addWord(String word, int addFrequency) { final int length = word.length(); // Don't add very short or very long words. if (length < 2 || length > getMaxWordLength()) return; super.addWord(word, addFrequency); final int freq = getWordFrequency(word); if (freq > PROMOTION_THRESHOLD) { TeclaIME.this.promoteToUserDictionary(word, FREQUENCY_FOR_AUTO_ADD); } } } //TECLA CONSTANTS AND VARIABLES /** * Tag used for logging in this class */ private static final String CLASS_TAG = "IME: "; //TODO: Try moving these variables to TeclaApp class private String mVoiceInputString; private int mLastKeyboardMode, mLastFullKeyboardMode; private boolean mShieldConnected, mRepeating; private PopupWindow mSwitchPopup; private View mSwitch; private Handler mTeclaHandler; private int[] mKeyCodes; private boolean mIsNavKbdTimedOut; private boolean mWasSymbols, mWasShifted; private void initTeclaA11y() { // register to receive switch events from Tecla shield registerReceiver(mReceiver, new IntentFilter(SwitchEventProvider.ACTION_SHIELD_CONNECTED)); registerReceiver(mReceiver, new IntentFilter(SwitchEventProvider.ACTION_SHIELD_DISCONNECTED)); registerReceiver(mReceiver, new IntentFilter(SwitchEvent.ACTION_SWITCH_EVENT_RECEIVED)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_SHOW_IME)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_HIDE_IME)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_ENABLE_MORSE)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_DISABLE_MORSE)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_START_FS_SWITCH_MODE)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_STOP_FS_SWITCH_MODE)); registerReceiver(mReceiver, new IntentFilter(Highlighter.ACTION_START_SCANNING)); registerReceiver(mReceiver, new IntentFilter(Highlighter.ACTION_STOP_SCANNING)); registerReceiver(mReceiver, new IntentFilter(TeclaApp.ACTION_INPUT_STRING)); mLastFullKeyboardMode = TeclaApp.persistence.isMorseModeEnabled() ? KeyboardSwitcher.MODE_MORSE : KeyboardSwitcher.MODE_TEXT; mTeclaHandler = new Handler(); mShieldConnected = false; mRepeating = false; mWasSymbols = false; mWasShifted = false; if (TeclaApp.persistence.isPersistentKeyboardEnabled()) { TeclaApp.getInstance().queueSplash(); } } private void initMorseKeyboard() { if (mKeyboardSwitcher.isMorseMode()) { //Initialize Space and Caps Lock key objects mSpaceKey = mIMEView.getKeyboard().getSpaceKey(); mCapsLockKey = mIMEView.getKeyboard().getCapsLockKey(); List<Keyboard.Key> keys = mIMEView.getKeyboard().getKeys(); mSpaceKeyIndex = keys.indexOf(mSpaceKey); mCapsLockKeyIndex = keys.indexOf(mCapsLockKey); } } private void typeInputString(String input_string) { Log.d(TeclaApp.TAG, CLASS_TAG + "Received input string: " + input_string); mVoiceInputString = input_string; mTeclaHandler.removeCallbacks(mAutoPlayRunnable); mTeclaHandler.postDelayed(mAutoPlayRunnable, 1000); } public Runnable mAutoPlayRunnable = new Runnable() { public void run() { //mIMEView.startPlaying(mVoiceInputString); onText(mVoiceInputString); } }; private void startTimer() { mMorseStartTime = System.currentTimeMillis(); } public void startRepeating(long delay) { pauseRepeating(); mTeclaHandler.postDelayed(mStartRepeatRunnable, delay); } public void evaluateMorsePress() { switch(TeclaApp.persistence.getMorseKeyMode()) { case TRIPLE_KEY_MODE: startRepeating(0); break; case DOUBLE_KEY_MODE: emulateMorseKey(mRepeatedKey); break; case SINGLE_KEY_MODE: startTimer(); checkRingerMode(); if (mSoundOn && !mSilentMode) mTone.startTone(mToneType); break; } } private void handleSingleKeyUp() { mTone.stopTone(); long duration = System.currentTimeMillis() - mMorseStartTime; if (mTeclaMorse.getCurrentChar().length() < mTeclaMorse.getMorseDictionary().getMaxCodeLength()) { - if (duration < TeclaApp.persistence.getMorseTimeUnit()) { + if (duration < TeclaApp.persistence.getMorseTimeUnit() * ERROR_MARGIN) { mTeclaMorse.addDit(); } - else if (duration < TeclaApp.persistence.getMorseTimeUnit() * 3) + else if (duration < (TeclaApp.persistence.getMorseTimeUnit() * 3) * ERROR_MARGIN) mTeclaMorse.addDah(); } updateSpaceKey(true); mIMEView.invalidate(); } public void pauseRepeating() { mTeclaHandler.removeCallbacks(mRepeatRunnable); mTeclaHandler.removeCallbacks(mStartRepeatRunnable); mTeclaHandler.removeCallbacks(mEndOfCharRunnable); } public void stopRepeating() { pauseRepeating(); } /** * Runnable used to repeat an occurence of a Morse key */ private Runnable mRepeatRunnable = new Runnable() { public void run() { final long start = SystemClock.uptimeMillis(); emulateMorseKey(mRepeatedKey); mTeclaHandler.postAtTime(this, start + TeclaApp.persistence.getRepeatFrequency()); } }; /** * Runnable used to start the Morse key repetition process */ private Runnable mStartRepeatRunnable = new Runnable() { public void run() { emulateMorseKey(mRepeatedKey); int frequency = TeclaApp.persistence.getRepeatFrequency(); if (frequency != Persistence.NEVER_REPEAT) mTeclaHandler.postDelayed(mRepeatRunnable, frequency); } }; private Runnable mEndOfCharRunnable = new Runnable() { public void run() { handleMorseSpaceKey(); updateSpaceKey(true); mIMEView.invalidate(); } }; private void evaluateEndOfChar() { if (TeclaApp.persistence.getMorseKeyMode() == TRIPLE_KEY_MODE) return; if (TeclaApp.persistence.getMorseKeyMode() == SINGLE_KEY_MODE) { handleSingleKeyUp(); } mTeclaHandler.removeCallbacks(mEndOfCharRunnable); mTeclaHandler.postDelayed(mEndOfCharRunnable, 3 * TeclaApp.persistence.getMorseTimeUnit()); } private void handleMorseSwitch(SwitchEvent switchEvent, int action) { switch(action) { case 1: //Add a dit to the current Morse sequence (repeatable) if (switchEvent.isPressed(switchEvent.getSwitchChanges())) { mRepeatedKey = TeclaKeyboard.KEYCODE_MORSE_DIT; evaluateMorsePress(); } if (switchEvent.isReleased(switchEvent.getSwitchChanges())) { stopRepeating(); evaluateEndOfChar(); } break; case 2: //Add a dah to the current Morse sequence (repeatable) if (switchEvent.isPressed(switchEvent.getSwitchChanges())) { mRepeatedKey = TeclaKeyboard.KEYCODE_MORSE_DAH; evaluateMorsePress(); } if (switchEvent.isReleased(switchEvent.getSwitchChanges())) { stopRepeating(); evaluateEndOfChar(); } break; case 3: //Send through a space key event: acts as an end of char signal //if the current sequence represents a valid character, otherwise //inserts a simple space if (switchEvent.isPressed(switchEvent.getSwitchChanges())) emulateMorseKey(TeclaKeyboard.KEYCODE_MORSE_SPACEKEY); break; case 4: //Send through a backspace event (repeatable) if (switchEvent.isPressed(switchEvent.getSwitchChanges())) { mRepeatedKey = TeclaKeyboard.KEYCODE_MORSE_DELKEY; evaluateMorsePress(); } if (switchEvent.isReleased(switchEvent.getSwitchChanges())) { stopRepeating(); } break; case 5: //Hide the Morse IME view if (switchEvent.isPressed(switchEvent.getSwitchChanges())) emulateMorseKey(Keyboard.KEYCODE_DONE); break; default: break; } } private void handleSwitchEvent(SwitchEvent switchEvent) { //Emulator issue (temporary fix): if typing too fast, or holding a long press //while in auto-release mode, some switch events are null if (switchEvent.toString() == null) { Log.d(TeclaApp.TAG, "Captured null switch event"); return; } cancelNavKbdTimeout(); if (!TeclaApp.highlighter.isSoftIMEShowing() && TeclaApp.persistence.isPersistentKeyboardEnabled()) { showIMEView(); TeclaApp.highlighter.startSelfScanning(); } else { //Collect the mapped actions of the current switch String[] switchActions = TeclaApp.persistence.getSwitchMap().get(switchEvent.toString()); if (mKeyboardSwitcher.isMorseMode()) { //Switches have different actions when Morse keyboard is showing handleMorseSwitch(switchEvent, Integer.parseInt(switchActions[1])); } else { String action_tecla = switchActions[0]; switch(Integer.parseInt(action_tecla)) { case 1: if (switchEvent.isPressed(switchEvent.getSwitchChanges())) TeclaApp.highlighter.move(Highlighter.HIGHLIGHT_NEXT); break; case 2: if (switchEvent.isPressed(switchEvent.getSwitchChanges())) TeclaApp.highlighter.move(Highlighter.HIGHLIGHT_PREV); break; case 3: if (switchEvent.isPressed(switchEvent.getSwitchChanges())) TeclaApp.highlighter.stepOut(); break; case 4: if (switchEvent.isPressed(switchEvent.getSwitchChanges())) { if (TeclaApp.persistence.isInverseScanningEnabled()) { TeclaApp.highlighter.resumeSelfScanning(); } else { selectHighlighted(true); } } if (switchEvent.isReleased(switchEvent.getSwitchChanges())) { if (TeclaApp.persistence.isInverseScanningEnabled()) { if (TeclaApp.persistence.isInverseScanningChanged()) { //Ignore event right after Inverse Scanning is Enabled stopRepeatingKey(); TeclaApp.persistence.unsetInverseScanningChanged(); Log.w(TeclaApp.TAG, CLASS_TAG + "Ignoring switch event because Inverse Scanning was just enabled"); } else { selectHighlighted(false); } } else { stopRepeatingKey(); } } break; default: break; } } if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Switch event received: " + TeclaApp.getInstance().byte2Hex(switchEvent.getSwitchChanges()) + ":" + TeclaApp.getInstance().byte2Hex(switchEvent.getSwitchStates())); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Byte handled: " + TeclaApp.getInstance().byte2Hex(switchEvent.getSwitchStates()) + " at " + SystemClock.uptimeMillis()); } evaluateNavKbdTimeout(); } private void emulateMorseKey(int key) { int[] keyCode = new int[1]; keyCode[0] = key; emulateKeyPress(keyCode); playKeyClick(key); } /** * Determine weather the current keyboard should auto-hide. */ private void evaluateNavKbdTimeout() { if(mKeyboardSwitcher.isNavigation()) { resetNavKbdTimeout(); } else { cancelNavKbdTimeout(); } } /** * Cancel any currently active calls to auto-hide the keyboard. */ private void cancelNavKbdTimeout() { mIsNavKbdTimedOut = false; mTeclaHandler.removeCallbacks(hideNavKbdRunnable); } /** * Do not use this method, use {@link #evaluateNavKbdTimeout()} instead. */ private void resetNavKbdTimeout() { cancelNavKbdTimeout(); int navKbdTimeout = TeclaApp.persistence.getNavigationKeyboardTimeout(); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Navigation keyboard timeout in: " + navKbdTimeout + " seconds"); if (navKbdTimeout != Persistence.NEVER_AUTOHIDE) mTeclaHandler.postDelayed(hideNavKbdRunnable, navKbdTimeout * 1000); } private Runnable hideNavKbdRunnable = new Runnable() { public void run() { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Navigation keyboard timed out!"); mIsNavKbdTimedOut = true; hideSoftIME(); } }; /** * Select the currently highlighted item. * @param repeat true if a key should be repeated on hold, false otherwise. */ private void selectHighlighted(Boolean repeat) { //FIXME: Repeat key should be re-implemented as repeat switch action on hold on the SEP // will disable it here for now. repeat = false; TeclaApp.highlighter.pauseSelfScanning(); if (TeclaApp.highlighter.getScanDepth() == Highlighter.DEPTH_KEY) { //Selected item is a key mKeyCodes = TeclaApp.highlighter.getCurrentKey().codes; if (repeat && isRepeatableWithTecla(mKeyCodes[0])) { mTeclaHandler.post(mRepeatKeyRunnable); } else { emulateKeyPress(mKeyCodes); TeclaApp.highlighter.doSelectKey(mKeyCodes[0]); } } else { //Selected item is a row TeclaApp.highlighter.doSelectRow(); } } private boolean isMorseKeyboardKey(int keycode) { return (keycode == TeclaKeyboard.KEYCODE_MORSE_DIT) || (keycode == TeclaKeyboard.KEYCODE_MORSE_DAH) || (keycode == TeclaKeyboard.KEYCODE_MORSE_SPACEKEY) || (keycode == TeclaKeyboard.KEYCODE_MORSE_DELKEY) || (keycode == TeclaKeyboard.KEYCODE_MORSE_CAPSKEY); } private boolean isSpecialKey(int keycode) { return ((keycode>=KeyEvent.KEYCODE_DPAD_UP) && (keycode<=KeyEvent.KEYCODE_DPAD_CENTER)) || (keycode == KeyEvent.KEYCODE_BACK) || (keycode == Keyboard.KEYCODE_DONE) || (keycode == TeclaKeyboard.KEYCODE_VOICE) || (keycode == TeclaKeyboard.KEYCODE_VARIANTS); } private void handleSpecialKey(int keyEventCode) { if (keyEventCode == Keyboard.KEYCODE_DONE) { if (!mKeyboardSwitcher.isNavigation() && !mKeyboardSwitcher.isVariants()) { if (mKeyboardSwitcher.isMorseMode() && TeclaApp.persistence.isMorseHudEnabled()) { mTeclaMorse.getMorseChart().hide(); } // Closing mLastFullKeyboardMode = mKeyboardSwitcher.getKeyboardMode(); mWasShifted = mIMEView.getKeyboard().isShifted(); hideSoftIME(); } else { // Opening if (mKeyboardSwitcher.isVariants()) { doVariantsExit(keyEventCode); } else { mKeyboardSwitcher.setKeyboardMode(mLastFullKeyboardMode); mIMEView.getKeyboard().setShifted(mWasShifted); } initMorseKeyboard(); if (mKeyboardSwitcher.isMorseMode() && TeclaApp.persistence.isMorseHudEnabled()) { mTeclaMorse.getMorseChart().restore(); mIMEView.invalidate(); } evaluateStartScanning(); } } else if (keyEventCode == TeclaKeyboard.KEYCODE_VOICE) { if (mKeyboardSwitcher.isNavigation()) { TeclaApp.getInstance().broadcastVoiceCommand(); } else { TeclaApp.getInstance().startVoiceInput(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); } } else if (keyEventCode == TeclaKeyboard.KEYCODE_VARIANTS) { Key key = mIMEView.getKeyboard().getVariantsKey(); if (key != null) { Log.d(TeclaApp.TAG, CLASS_TAG + "Variants key code is " + key.codes[0]); if (TeclaApp.persistence.isVariantsOn()) { TeclaApp.persistence.setVariantsOff(); key.on = false; } else { TeclaApp.persistence.setVariantsOn(); key.on = true; } mIMEView.invalidateAllKeys(); } } else { keyDownUp(keyEventCode); } } /** * Helper to send a key down / key up pair to the current editor. */ private void keyDownUp(int keyEventCode) { getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_DOWN, keyEventCode)); getCurrentInputConnection().sendKeyEvent( new KeyEvent(KeyEvent.ACTION_UP, keyEventCode)); } private boolean isRepeatableWithTecla(int code) { if (code == TeclaKeyboard.KEYCODE_DONE || code == TeclaKeyboard.KEYCODE_VOICE || code == TeclaKeyboard.KEYCODE_VARIANTS) { return false; } return true; } private void stopRepeatingKey() { if (mRepeating) { mTeclaHandler.removeCallbacks(mRepeatKeyRunnable); mRepeating = false; TeclaApp.highlighter.doSelectKey(mKeyCodes[0]); } } private Runnable mRepeatKeyRunnable = new Runnable() { public void run() { emulateKeyPress(mKeyCodes); if (mRepeating) { mTeclaHandler.postDelayed(mRepeatKeyRunnable, Math.round(0.5 * TeclaApp.persistence.getScanDelay())); } else { // First key repeat takes a bit longer mTeclaHandler.postDelayed(mRepeatKeyRunnable, TeclaApp.persistence.getScanDelay()); mRepeating = true; } } }; private void emulateKeyPress(int[] key_codes) { // Process key as if it had been pressed onKey(key_codes[0], key_codes); } private void startFullScreenSwitchMode(int delay) { mTeclaHandler.removeCallbacks(mCreateSwitchRunnable); mTeclaHandler.postDelayed(mCreateSwitchRunnable, delay); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Sent delayed broadcast to show fullscreen switch"); } /** * Runnable used to create full-screen switch overlay */ private Runnable mCreateSwitchRunnable = new Runnable () { public void run() { if (TeclaApp.highlighter.isSoftIMEShowing()) { Display display = getDisplay(); if (mSwitchPopup == null) { //Create single-switch pop-up mSwitch = getLayoutInflater().inflate(R.layout.popup_fullscreen_transparent, null); mSwitch.setOnTouchListener(mSwitchTouchListener); mSwitch.setOnClickListener(mSwitchClickListener); mSwitch.setOnLongClickListener(mSwitchLongPressListener); mSwitchPopup = new PopupWindow(mSwitch); } if (mSwitchPopup.isShowing()) mSwitchPopup.dismiss(); mSwitchPopup.setWidth(display.getWidth()); mSwitchPopup.setHeight(display.getHeight()); mSwitchPopup.showAtLocation(mIMEView, Gravity.NO_GRAVITY, 0, 0); TeclaApp.getInstance().showToast(R.string.fullscreen_enabled); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Fullscreen switch shown"); evaluateStartScanning(); } else { startFullScreenSwitchMode(1000); } } }; /** * Listener for full-screen single switch long press */ private View.OnLongClickListener mSwitchLongPressListener = new View.OnLongClickListener() { public boolean onLongClick(View v) { if (!TeclaApp.persistence.isInverseScanningEnabled()) { launchSettings(); //Doing this here again because the ACTION_UP event in the onTouch listener doesn't always work. mSwitch.setBackgroundResource(android.R.color.transparent); return true; } return false; } }; /** * Listener for full-screen switch actions */ private View.OnTouchListener mSwitchTouchListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Fullscreen switch down!"); mSwitch.setBackgroundResource(R.color.switch_pressed); vibrate(); playKeyClick(KEYCODE_ENTER); if (TeclaApp.persistence.isInverseScanningEnabled()) { TeclaApp.highlighter.resumeSelfScanning(); } else { selectHighlighted(false); } break; case MotionEvent.ACTION_UP: if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Fullscreen switch up!"); mSwitch.setBackgroundResource(android.R.color.transparent); if (TeclaApp.persistence.isInverseScanningEnabled()) { if (TeclaApp.persistence.isInverseScanningChanged()) { //Ignore event right after Inverse Scanning is Enabled TeclaApp.persistence.unsetInverseScanningChanged(); Log.w(TeclaApp.TAG, CLASS_TAG + "Ignoring switch event because Inverse Scanning was just enabled"); } else { vibrate(); playKeyClick(KEYCODE_ENTER); selectHighlighted(false); } } break; default: break; } return false; } }; private View.OnClickListener mSwitchClickListener = new View.OnClickListener() { public void onClick(View v) { //Doing this here again because the ACTION_UP event in the onTouch listener doesn't always work. mSwitch.setBackgroundResource(android.R.color.transparent); } }; private void stopFullScreenSwitchMode() { if (isFullScreenShowing()) { mSwitchPopup.dismiss(); } evaluateStartScanning(); TeclaApp.getInstance().showToast(R.string.fullscreen_disabled); } private boolean isFullScreenShowing() { if (mSwitchPopup != null) { if (mSwitchPopup.isShowing()) return true; } return false; } private void evaluateStartScanning() { if (TeclaApp.highlighter.isSoftIMEShowing()) { if (mShieldConnected || isFullScreenShowing()) { TeclaApp.highlighter.startSelfScanning(0); } else { TeclaApp.highlighter.stopSelfScanning(); } } else { Log.w(TeclaApp.TAG, CLASS_TAG + "Could not reset scanning, InputView is not ready!"); } } private Display getDisplay() { return ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); } private boolean shouldShowIME() { return TeclaApp.persistence.isPersistentKeyboardEnabled(); } private void showIMEView() { if (TeclaApp.highlighter.isSoftIMEShowing()) { if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Soft IME is already showing"); } else { showWindow(true); updateInputViewShown(); initMorseKeyboard(); // Fixes https://github.com/jorgesilva/TeclaAccess/issues/3 if (TeclaApp.highlighter.isSoftIMEShowing()) { mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_NAV); } // This call causes a looped intent call until the IME View is created callShowSoftIMEWatchDog(350); } } private void callShowSoftIMEWatchDog(int delay) { mTeclaHandler.removeCallbacks(mShowSoftIMEWatchdog); mTeclaHandler.postDelayed(mShowSoftIMEWatchdog, delay); } private Runnable mShowSoftIMEWatchdog = new Runnable () { public void run() { if (!TeclaApp.highlighter.isSoftIMEShowing()) { // If IME View still not showing... // We are force-openning the soft IME through an intent since //it seems to be the only way to make it work TeclaApp.getInstance().requestShowIMEView(); } } }; private void hideSoftIME() { hideWindow(); updateInputViewShown(); } // TODO: Consider moving to TeclaKeyboardView or TeclaKeyboard private void populateVariants (CharSequence keyLabel, CharSequence popupChars) { List<Key> keyList = mIMEView.getKeyboard().getKeys(); Key key = keyList.get(1); CharSequence sequence; key.label = keyLabel; key.codes = new int[1]; key.codes[0] = (int) keyLabel.charAt(0); for (int i=0; i < popupChars.length(); i++) { key = keyList.get(i+2); sequence = popupChars.subSequence(i, i+1); key.label = sequence; key.codes = new int[1]; key.codes[0] = (int) sequence.charAt(0); if (TeclaApp.DEBUG) Log.d(TeclaApp.TAG, CLASS_TAG + "Populating char: " + sequence.toString()); } } private void doVariantsExit(int keyCode) { TeclaApp.persistence.setVariantsShowing(false); mKeyboardSwitcher.setKeyboardMode(mLastFullKeyboardMode); if (mWasSymbols && !mKeyboardSwitcher.isSymbols()) { mKeyboardSwitcher.toggleSymbols(); } if (mWasShifted && mWasSymbols) { handleShift(); } else { mIMEView.setShifted(mWasShifted); } if (keyCode != TeclaKeyboard.KEYCODE_DONE) { TeclaApp.persistence.setVariantsOff(); Key key = mIMEView.getKeyboard().getVariantsKey(); key.on = false; } } public KeyboardSwitcher getKeyboardSwitcher() { return mKeyboardSwitcher; } }
false
false
null
null
diff --git a/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java b/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java index 5102136a..48095cfd 100644 --- a/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java +++ b/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java @@ -1,136 +1,139 @@ /* * Copyright 2012-2013 Sergey Ignatov * * 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.intellij.erlang.formatter; import com.intellij.formatting.Indent; import com.intellij.lang.ASTNode; import com.intellij.psi.formatter.FormatterUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.intellij.erlang.ErlangParserDefinition; import org.intellij.erlang.formatter.settings.ErlangCodeStyleSettings; import org.intellij.erlang.psi.ErlangArgumentDefinition; import org.intellij.erlang.psi.ErlangExpression; import org.intellij.erlang.psi.ErlangListOpExpression; import org.intellij.erlang.psi.ErlangParenthesizedExpression; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; import static org.intellij.erlang.ErlangTypes.*; public class ErlangIndentProcessor { private static final Set<IElementType> BIN_OPERATORS = ContainerUtil.set( ERL_OP_PLUS, ERL_OP_MINUS, ERL_OP_AR_MUL, ERL_OP_AR_DIV, ERL_REM, ERL_OR, ERL_XOR, ERL_BOR, ERL_BXOR, ERL_BSL, ERL_BSR, ERL_AND, ERL_BAND, ERL_OP_EQ_EQ, ERL_OP_DIV_EQ, ERL_OP_EQ_COL_EQ, ERL_OP_EQ_DIV_EQ, ERL_OP_LT, ERL_OP_EQ_LT, ERL_OP_GT, ERL_OP_GT_EQ, ERL_OP_LT_EQ, ERL_OP_EQ, ERL_OP_EXL, ERL_OP_LT_MINUS, ERL_ANDALSO, ERL_ORELSE ); private final ErlangCodeStyleSettings myErlangSettings; public ErlangIndentProcessor(@NotNull ErlangCodeStyleSettings erlangSettings) { myErlangSettings = erlangSettings; } public Indent getChildIndent(ASTNode node) { IElementType elementType = node.getElementType(); ASTNode parent = node.getTreeParent(); IElementType parentType = parent != null ? parent.getElementType() : null; ASTNode grandfather = parent != null ? parent.getTreeParent() : null; IElementType grandfatherType = grandfather != null ? grandfather.getElementType() : null; ASTNode prevSibling = FormatterUtil.getPreviousNonWhitespaceSibling(node); IElementType prevSiblingElementType = prevSibling != null ? prevSibling.getElementType() : null; if (parent == null || parent.getTreeParent() == null) { return Indent.getNoneIndent(); } if (elementType == ERL_CATCH || elementType == ERL_AFTER) { return Indent.getNoneIndent(); } if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_DEFINITION_LIST || parentType == ERL_FUN_TYPE || parentType == ERL_FUN_TYPE_ARGUMENTS) { if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) return Indent.getNoneIndent(); return Indent.getContinuationIndent(); } if (parentType == ERL_ARGUMENT_LIST) { if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) return Indent.getNoneIndent(); return Indent.getNormalIndent(); } if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS || parentType == ERL_RECORD_LIKE_TYPE) { if (elementType == ERL_CURLY_LEFT || elementType == ERL_CURLY_RIGHT) return Indent.getNoneIndent(); return Indent.getNormalIndent(); } if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS || parentType == ERL_EXPORT_TYPES) { if (elementType == ERL_BRACKET_LEFT || elementType == ERL_BRACKET_RIGHT || elementType == ERL_BIN_START || elementType == ERL_BIN_END || elementType == ERL_LC_EXPRS) { return Indent.getNoneIndent(); } return Indent.getNormalIndent(); } if ((parentType == ERL_GUARD || (parentType == ERL_CLAUSE_GUARD && elementType == ERL_WHEN)) && grandfatherType != ERL_IF_CLAUSE) { return Indent.getNormalIndent(); } if (parentType == ERL_LC_EXPRS) { return Indent.getNormalIndent(); } if (parentType == ERL_RECORD_FIELDS) { // todo: not a smart solution //noinspection unchecked boolean insideCall = PsiTreeUtil.getParentOfType(node.getPsi(), ErlangArgumentDefinition.class, ErlangParenthesizedExpression.class) != null; return insideCall ? Indent.getNormalIndent() : Indent.getNoneIndent(); } + if (parentType == ERL_MAP_ENTRIES) { + return Indent.getNormalIndent(); + } if (parentType == ERL_BEGIN_END_BODY) { return Indent.getNoneIndent(); } if (parentType == ERL_CASE_EXPRESSION || parentType == ERL_RECEIVE_EXPRESSION || parentType == ERL_TRY_EXPRESSION || parentType == ERL_BEGIN_END_EXPRESSION || parentType == ERL_IF_EXPRESSION) { if (elementType == ERL_CR_CLAUSE || elementType == ERL_IF_CLAUSE || elementType == ERL_BEGIN_END_BODY) { return Indent.getNormalIndent(myErlangSettings.INDENT_RELATIVE); } if (elementType == ERL_END || elementType == ERL_TRY_CATCH || elementType == ERL_AFTER_CLAUSE) { return myErlangSettings.INDENT_RELATIVE ? Indent.getSpaceIndent(0, true) : Indent.getNoneIndent(); } } if (ErlangParserDefinition.COMMENTS.contains(elementType) && (parentType == ERL_TRY_CATCH || parentType == ERL_TRY_EXPRESSION)) { return Indent.getNormalIndent(); } if (needIndent(parentType)) { return Indent.getNormalIndent(); } if (node.getPsi() instanceof ErlangListOpExpression) { return Indent.getNoneIndent(); } if (parent.getPsi() instanceof ErlangListOpExpression && (grandfather == null || grandfather.getPsi() instanceof ErlangExpression)) { return node.getPsi() instanceof ErlangListOpExpression ? Indent.getNoneIndent() : Indent.getNormalIndent(); } if (parentType == ERL_PREFIX_EXPRESSION) { return Indent.getNoneIndent(); } if (parent.getPsi() instanceof ErlangExpression && (BIN_OPERATORS.contains(elementType) || BIN_OPERATORS.contains(prevSiblingElementType))) { return Indent.getNormalIndent(); } return Indent.getNoneIndent(); } private static boolean needIndent(@Nullable IElementType type) { return type != null && ErlangFormattingBlock.BLOCKS_TOKEN_SET.contains(type); } } diff --git a/tests/org/intellij/erlang/formatting/ErlangFormattingTest.java b/tests/org/intellij/erlang/formatting/ErlangFormattingTest.java index 02951c07..a417e35f 100644 --- a/tests/org/intellij/erlang/formatting/ErlangFormattingTest.java +++ b/tests/org/intellij/erlang/formatting/ErlangFormattingTest.java @@ -1,257 +1,258 @@ /* * Copyright 2012-2013 Sergey Ignatov * * 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.intellij.erlang.formatting; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import junit.framework.Assert; import org.intellij.erlang.ErlangFileType; import org.intellij.erlang.ErlangLanguage; import org.intellij.erlang.formatter.settings.ErlangCodeStyleSettings; import org.intellij.erlang.utils.ErlangLightPlatformCodeInsightFixtureTestCase; import java.io.File; import java.io.IOException; public class ErlangFormattingTest extends ErlangLightPlatformCodeInsightFixtureTestCase { public static final boolean OVERRIDE_TEST_DATA = false; private CodeStyleSettings myTemporarySettings; public void doTest() throws Exception { doTest(true); } public void doEnterTest() throws Exception { doTest(false); } public void doTest(boolean format) throws Exception { final String testName = getTestName(true); myFixture.configureByFile(testName + ".erl"); String after = doTest(format, testName); myFixture.checkResultByFile(after); } public void doEnterParasiteTest() throws Exception { doParasiteTest(false); } public void doParasiteTest(boolean format) throws Exception { String appendix = "\nfoo() -> ok."; final String testName = getTestName(true).replace("Parasite", ""); String text = FileUtil.loadFile(new File(getTestDataPath() + testName + ".erl")) + appendix; myFixture.configureByText(testName + ".erl", text); String after = doTest(format, testName); String afterText = FileUtil.loadFile(new File(getTestDataPath() + after), true) + appendix; myFixture.checkResult(afterText); } private String doTest(boolean format, String testName) throws IOException { if (format) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CodeStyleManager.getInstance(getProject()).reformat(myFixture.getFile()); } }); } else { myFixture.type('\n'); } String after = String.format("%s-after.erl", testName); if (OVERRIDE_TEST_DATA) { FileUtil.writeToFile(new File(myFixture.getTestDataPath() + "/" + after), myFixture.getFile().getText()); } return after; } public void test48() throws Exception { doTest(); } public void test52() throws Exception { doTest(); } public void test53() throws Exception { doTest(); } public void test67() throws Exception { doTest(); } public void test71() throws Exception { doTest(); } public void test75() throws Exception { doTest(); } public void test82() throws Exception { doTest(); } public void test95() throws Exception { doTest(); } public void test116() throws Exception { doTest(); } public void test118() throws Exception { doTest(); } public void test136() throws Exception { doTest(); } public void test137() throws Exception { doTest(); } public void test141() throws Exception { doTest(); } public void test125() throws Exception { doTest(); } public void test171() throws Exception { doTest(); } public void test191() throws Exception { doTest(); } public void testSimple() throws Exception { doTest(); } public void testCaseEx() throws Exception { doTest(); } public void test288() throws Exception { doTest(); } public void test299() throws Exception { doTest(); } public void test305() throws Exception { doTest(); } public void test350() throws Exception { doTest(); } public void test351() throws Exception { getErlangSettings().INDENT_RELATIVE = true; doTest(); } public void test222_1() throws Exception { getErlangSettings().INDENT_RELATIVE = true; doTest(); } public void test222_2() throws Exception { getErlangSettings().INDENT_RELATIVE = false; doTest(); } public void test273() throws Exception { getErlangSettings().ALIGN_GUARDS = true; doTest(); } public void test379() throws Exception { setUpCommaFirst(); doTest(); } public void test433() throws Exception { getErlangSettings().ALIGN_FUN_CLAUSES = true; doTest(); } + public void test434() throws Exception { doTest(); } public void test292() throws Exception { ErlangCodeStyleSettings erlangSettings = getErlangSettings(); erlangSettings.ALIGN_MULTILINE_BLOCK = true; erlangSettings.NEW_LINE_BEFORE_COMMA = true; erlangSettings.SPACE_AROUND_OR_IN_LISTS = false; doTest(); } public void testAligned() throws Exception { getErlangSettings().ALIGN_MULTILINE_BLOCK = true; doTest(); } public void testFunctionClausesAligned() throws Exception { getErlangSettings().ALIGN_FUNCTION_CLAUSES = true; doTest(); } public void testKeepCommentAtTheFirstLine() throws Exception { getCommonSettings().KEEP_FIRST_COLUMN_COMMENT = true; doTest(); } public void testNotKeepCommentAtTheFirstLine() throws Exception { getCommonSettings().KEEP_FIRST_COLUMN_COMMENT = false; doTest(); } public void testFunctionClause() throws Exception { doEnterTest(); } public void testIf1() throws Exception { doEnterTest(); } public void testIf2() throws Exception { doEnterTest(); } public void testIf3() throws Exception { doEnterTest(); } public void testTry1() throws Exception { doEnterTest(); } public void testTry2() throws Exception { doEnterTest(); } public void testTry3() throws Exception { doEnterTest(); } public void testTry4() throws Exception { doEnterTest(); } public void testTry5() throws Exception { doEnterTest(); } public void testCase1() throws Exception { doEnterTest(); } public void testCase2() throws Exception { doEnterTest(); } public void testCase3() throws Exception { doEnterTest(); } public void testCase4() throws Exception { doEnterTest(); } public void testReceive() throws Exception { doTest(); } // public void testReceive1() throws Exception { doEnterTest(); } public void testReceive2() throws Exception { doEnterTest(); } public void testReceive3() throws Exception { doEnterTest(); } public void testReceive4() throws Exception { doEnterTest(); } public void testReceive5() throws Exception { doEnterTest(); } public void testReceive6() throws Exception { doEnterTest(); } public void testReceive7() throws Exception { doEnterTest(); } public void testBegin1() throws Exception { doEnterTest(); } public void testBegin2() throws Exception { doEnterTest(); } public void testBegin3() throws Exception { doEnterTest(); } public void testRecordFields1() throws Exception { doEnterTest(); } public void testRecordFields2() throws Exception { doEnterTest(); } public void testFunExpression() throws Exception { doTest(); } // public void testFunExpression1() throws Exception { doEnterTest(); } public void testFunExpression2() throws Exception { doEnterTest(); } public void testFunExpression3() throws Exception { doEnterTest(); } public void testFunExpression4() throws Exception { doEnterTest(); } public void testIfParasite1() throws Exception { doEnterParasiteTest(); } public void testIfParasite2() throws Exception { doEnterParasiteTest(); } public void testIfParasite3() throws Exception { doEnterParasiteTest(); } public void testTryParasite1() throws Exception { doEnterParasiteTest(); } public void testTryParasite2() throws Exception { doEnterParasiteTest(); } public void testTryParasite3() throws Exception { doEnterParasiteTest(); } public void testTryParasite4() throws Exception { doEnterParasiteTest(); } public void testTryParasite5() throws Exception { doEnterParasiteTest(); } public void testCaseParasite1() throws Exception { doEnterParasiteTest(); } public void testCaseParasite2() throws Exception { doEnterParasiteTest(); } public void testCaseParasite3() throws Exception { doEnterParasiteTest(); } public void testCaseParasite4() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite1() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite2() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite3() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite4() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite5() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite6() throws Exception { doEnterParasiteTest(); } public void testReceiveParasite7() throws Exception { doEnterParasiteTest(); } public void testBeginParasite1() throws Exception { doEnterParasiteTest(); } public void testBeginParasite2() throws Exception { doEnterParasiteTest(); } public void testBeginParasite3() throws Exception { doEnterParasiteTest(); } public void testFunExpressionParasite1() throws Exception { doEnterParasiteTest(); } public void testFunExpressionParasite2() throws Exception { doEnterParasiteTest(); } public void testFunExpressionParasite3() throws Exception { doEnterParasiteTest(); } public void testFunExpressionParasite4() throws Exception { doEnterParasiteTest(); } public void testCommaFirstEnter() throws Exception { setUpCommaFirst(); doEnterTest(); } public void testCommaFirstEnter2() throws Exception { setUpCommaFirst(); doEnterTest(); } private void setUpCommaFirst() { getErlangSettings().NEW_LINE_BEFORE_COMMA = true; getErlangSettings().ALIGN_MULTILINE_BLOCK = true; } private ErlangCodeStyleSettings getErlangSettings() { return myTemporarySettings.getCustomSettings(ErlangCodeStyleSettings.class); } private CommonCodeStyleSettings getCommonSettings() { return myTemporarySettings.getCommonSettings(ErlangLanguage.INSTANCE); } @Override protected String getTestDataPath() { return "testData/formatter/"; } @Override protected void setUp() throws Exception { System.setProperty("idea.platform.prefix", "Idea"); super.setUp(); setTestStyleSettings(); } @Override public void tearDown() throws Exception { restoreStyleSettings(); super.tearDown(); } private void setTestStyleSettings() { CodeStyleSettingsManager settingsManager = CodeStyleSettingsManager.getInstance(getProject()); CodeStyleSettings currSettings = settingsManager.getCurrentSettings(); Assert.assertNotNull(currSettings); myTemporarySettings = currSettings.clone(); CodeStyleSettings.IndentOptions indentOptions = myTemporarySettings.getIndentOptions(ErlangFileType.MODULE); Assert.assertNotNull(indentOptions); settingsManager.setTemporarySettings(myTemporarySettings); } private void restoreStyleSettings() { CodeStyleSettingsManager.getInstance(getProject()).dropTemporarySettings(); } } \ No newline at end of file
false
false
null
null
diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java index 668bfa654..753bfd365 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java @@ -1,1293 +1,1293 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text.source.projection; import org.eclipse.core.runtime.NullProgressMonitor; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Layout; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.FindReplaceDocumentAdapter; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentInformationMappingExtension; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ISlaveDocumentManager; import org.eclipse.jface.text.ITextViewerExtension5; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.projection.ProjectionDocument; import org.eclipse.jface.text.projection.ProjectionDocumentEvent; import org.eclipse.jface.text.projection.ProjectionDocumentManager; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModelEvent; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; import org.eclipse.jface.text.source.IAnnotationModelListener; import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.IVerticalRulerColumn; import org.eclipse.jface.text.source.SourceViewer; /** * A projection source viewer is a source viewer which does not support the * concept of a single visible region. Instead it supports multiple visible * regions which can dynamically be changed. * <p> * A projection source viewer uses a <code>ProjectionDocumentManager</code> * for the management of the visible document. * <p> * API in progress. Do not yet use. * * @since 3.0 */ public class ProjectionViewer extends SourceViewer implements ITextViewerExtension5 { private static final int BASE= INFORMATION; // see ISourceViewer.INFORMATION /** Operation constant for the expand operation. */ public static final int EXPAND= BASE + 1; /** Operation constant for the collapse operation. */ public static final int COLLAPSE= BASE + 2; /** Operation constant for the toggle projection operation. */ public static final int TOGGLE= BASE + 3; /** Operation constant for the expand all operation. */ public static final int EXPAND_ALL= BASE + 4; /** * Internal listener to changes of the annotation model. */ private class AnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension { /* * @see org.eclipse.jface.text.source.IAnnotationModelListener#modelChanged(org.eclipse.jface.text.source.IAnnotationModel) */ public void modelChanged(IAnnotationModel model) { processModelChanged(model, null); } /* * @see org.eclipse.jface.text.source.IAnnotationModelListenerExtension#modelChanged(org.eclipse.jface.text.source.AnnotationModelEvent) */ public void modelChanged(AnnotationModelEvent event) { processModelChanged(event.getAnnotationModel(), event); } private void processModelChanged(IAnnotationModel model, AnnotationModelEvent event) { if (model == fProjectionAnnotationModel) { if (fProjectionSummary != null) fProjectionSummary.updateSummaries(new NullProgressMonitor()); processCatchupRequest(event); } else if (model == getAnnotationModel() && fProjectionSummary != null) fProjectionSummary.updateSummaries(new NullProgressMonitor()); } } /** * Executes the 'replaceVisibleDocument' operation when called the first time. Self-destructs afterwards. */ private class ReplaceVisibleDocumentExecutor implements IDocumentListener { private IDocument fSlaveDocument; private IDocument fExecutionTrigger; public ReplaceVisibleDocumentExecutor(IDocument slaveDocument) { fSlaveDocument= slaveDocument; } public void install(IDocument executionTrigger) { if (executionTrigger != null && fSlaveDocument != null) { fExecutionTrigger= executionTrigger; fExecutionTrigger.addDocumentListener(this); } } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { fExecutionTrigger.removeDocumentListener(this); executeReplaceVisibleDocument(fSlaveDocument); } } /** * Internal listener to find the document onto which to hook the replace-visible-document command. */ private class DocumentListener implements IDocumentListener { /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { fReplaceVisibleDocumentExecutionTrigger= event.getDocument(); fRememberedTopIndex= getTopIndex(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { fReplaceVisibleDocumentExecutionTrigger= null; fRememberedTopIndex= -1; } } /** The projection annotation model used by this viewer. */ private ProjectionAnnotationModel fProjectionAnnotationModel; /** The annotation model listener */ private IAnnotationModelListener fAnnotationModelListener= new AnnotationModelListener(); /** The projection summary. */ private ProjectionSummary fProjectionSummary; /** Indication that an annotation world change has not yet been processed. */ private boolean fPendingAnnotationWorldChange= false; /** Indication whether projection changes in the visible document should be considered. */ private boolean fHandleProjectionChanges= true; /** The list of projection listeners. */ private List fProjectionListeners; /** Internal lock for protecting the list of pending requests */ private Object fLock= new Object(); /** The list of pending requests */ private List fPendingRequests= new ArrayList(); /** The replace-visible-document execution trigger */ private IDocument fReplaceVisibleDocumentExecutionTrigger; /** Internal document listener */ private IDocumentListener fDocumentListener= new DocumentListener(); /** Remembered top index when the master document changes*/ private int fRememberedTopIndex= -1; /** <code>true</code> if projection was on the last time we switched to segmented mode. */ private boolean fWasProjectionEnabled; /** * Creates a new projection source viewer. * * @param parent the SWT parent control * @param ruler the vertical ruler * @param overviewRuler the overview ruler * @param showsAnnotationOverview <code>true</code> if the overview ruler should be shown * @param styles the SWT style bits */ public ProjectionViewer(Composite parent, IVerticalRuler ruler, IOverviewRuler overviewRuler, boolean showsAnnotationOverview, int styles) { super(parent, ruler, overviewRuler, showsAnnotationOverview, styles); } /* * @see org.eclipse.jface.text.source.SourceViewer#createLayout() */ protected Layout createLayout() { return new RulerLayout(1); } /** * Sets the projection summary for this viewer. * * @param projectionSummary the projection summary. */ public void setProjectionSummary(ProjectionSummary projectionSummary) { fProjectionSummary= projectionSummary; } /** * Adds the projection annotation model to the given annotation model. * * @param model the model to which the projection annotation model is added */ private void addProjectionAnnotationModel(IAnnotationModel model) { if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension extension= (IAnnotationModelExtension) model; extension.addAnnotationModel(ProjectionSupport.PROJECTION, fProjectionAnnotationModel); model.addAnnotationModelListener(fAnnotationModelListener); } } /** * Removes the projection annotation model from the given annotation model. * * @param model the mode from which the projection annotation model is removed */ private IAnnotationModel removeProjectionAnnotationModel(IAnnotationModel model) { if (model instanceof IAnnotationModelExtension) { model.removeAnnotationModelListener(fAnnotationModelListener); IAnnotationModelExtension extension= (IAnnotationModelExtension) model; return extension.removeAnnotationModel(ProjectionSupport.PROJECTION); } return null; } /* * @see org.eclipse.jface.text.source.SourceViewer#setDocument(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.source.IAnnotationModel, int, int) */ public void setDocument(IDocument document, IAnnotationModel annotationModel, int modelRangeOffset, int modelRangeLength) { boolean wasProjectionEnabled= false; if (fProjectionAnnotationModel != null) { wasProjectionEnabled= removeProjectionAnnotationModel(getVisualAnnotationModel()) != null; fProjectionAnnotationModel= null; } super.setDocument(document, annotationModel, modelRangeOffset, modelRangeLength); if (wasProjectionEnabled) enableProjection(); } /* * @see org.eclipse.jface.text.source.SourceViewer#createVisualAnnotationModel(org.eclipse.jface.text.source.IAnnotationModel) */ protected IAnnotationModel createVisualAnnotationModel(IAnnotationModel annotationModel) { IAnnotationModel model= super.createVisualAnnotationModel(annotationModel); fProjectionAnnotationModel= new ProjectionAnnotationModel(); return model; } /** * Returns the projection annotation model. * * @return the projection annotation model */ public ProjectionAnnotationModel getProjectionAnnotationModel() { IAnnotationModel model= getVisualAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension extension= (IAnnotationModelExtension) model; return (ProjectionAnnotationModel) extension.getAnnotationModel(ProjectionSupport.PROJECTION); } return null; } /* * @see org.eclipse.jface.text.TextViewer#createSlaveDocumentManager() */ protected ISlaveDocumentManager createSlaveDocumentManager() { return new ProjectionDocumentManager(); } /* * @see org.eclipse.jface.text.TextViewer#updateSlaveDocument(org.eclipse.jface.text.IDocument, int, int) */ protected boolean updateSlaveDocument(IDocument slaveDocument, int modelRangeOffset, int modelRangeLength) throws BadLocationException { if (slaveDocument instanceof ProjectionDocument) { ProjectionDocument projection= (ProjectionDocument) slaveDocument; int offset= modelRangeOffset; int length= modelRangeLength; if (!isProjectionMode()) { // mimic original TextViewer behavior IDocument master= projection.getMasterDocument(); int line= master.getLineOfOffset(modelRangeOffset); offset= master.getLineOffset(line); length= (modelRangeOffset - offset) + modelRangeLength; } try { fHandleProjectionChanges= false; projection.replaceMasterDocumentRanges(offset, length); } finally { fHandleProjectionChanges= true; } return true; } return false; } public void addProjectionListener(IProjectionListener listener) { Assert.isNotNull(listener); if (fProjectionListeners == null) fProjectionListeners= new ArrayList(); if (!fProjectionListeners.contains(listener)) fProjectionListeners.add(listener); } public void removeProjectionListener(IProjectionListener listener) { Assert.isNotNull(listener); if (fProjectionListeners != null) { fProjectionListeners.remove(listener); if (fProjectionListeners.size() == 0) fProjectionListeners= null; } } protected void fireProjectionEnabled() { if (fProjectionListeners != null) { Iterator e= new ArrayList(fProjectionListeners).iterator(); while (e.hasNext()) { IProjectionListener l= (IProjectionListener) e.next(); l.projectionEnabled(); } } } protected void fireProjectionDisabled() { if (fProjectionListeners != null) { Iterator e= new ArrayList(fProjectionListeners).iterator(); while (e.hasNext()) { IProjectionListener l= (IProjectionListener) e.next(); l.projectionDisabled(); } } } /** * Returns whether this viewer is in projection mode. * * @return <code>true</code> if this viewer is in projection mode, * <code>false</code> otherwise */ private boolean isProjectionMode() { return getProjectionAnnotationModel() != null; } /** * Disables the projection mode. */ private void disableProjection() { if (isProjectionMode()) { removeProjectionAnnotationModel(getVisualAnnotationModel()); fProjectionAnnotationModel.removeAllAnnotations(); fFindReplaceDocumentAdapter= null; fireProjectionDisabled(); } } /** * Enables the projection mode. */ private void enableProjection() { if (!isProjectionMode()) { addProjectionAnnotationModel(getVisualAnnotationModel()); fFindReplaceDocumentAdapter= null; fireProjectionEnabled(); } } private void expandAll() { int offset= 0; IDocument doc= getDocument(); int length= doc == null ? 0 : doc.getLength(); if (isProjectionMode()) { fProjectionAnnotationModel.expandAll(offset, length); } } private void expand() { if (isProjectionMode()) { Position found= null; Annotation bestMatch= null; Point selection= getSelectedRange(); for (Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); // take the first most fine grained match if (position != null && touches(selection, position)) if (found == null || position.includes(found.offset) && position.includes(found.offset + found.length)) { found= position; bestMatch= annotation; } } } if (bestMatch != null) fProjectionAnnotationModel.expand(bestMatch); } } private boolean touches(Point selection, Position position) { return position.overlapsWith(selection.x, selection.y) || selection.y == 0 && position.offset + position.length == selection.x + selection.y; } private void collapse() { if (isProjectionMode()) { Position found= null; Annotation bestMatch= null; Point selection= getSelectedRange(); for (Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (!annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); // take the first most fine grained match if (position != null && touches(selection, position)) if (found == null || found.includes(position.offset) && found.includes(position.offset + position.length)) { found= position; bestMatch= annotation; } } } if (bestMatch != null) fProjectionAnnotationModel.collapse(bestMatch); } } /** * Remembers whether to listen to projection changes of the visible * document. * * @see ProjectionDocument#addMasterDocumentRange(int, int) */ private void addMasterDocumentRange(ProjectionDocument projection, int offset, int length) throws BadLocationException { try { fHandleProjectionChanges= false; projection.addMasterDocumentRange(offset, length); } finally { fHandleProjectionChanges= true; } } /** * Remembers whether to listen to projection changes of the visible * document. * * @see ProjectionDocument#removeMasterDocumentRange(int, int) */ private void removeMasterDocumentRange(ProjectionDocument projection, int offset, int length) throws BadLocationException { try { fHandleProjectionChanges= false; projection.removeMasterDocumentRange(offset, length); } finally { fHandleProjectionChanges= true; } } /* * @see org.eclipse.jface.text.TextViewer#setVisibleRegion(int, int) */ public void setVisibleRegion(int start, int length) { if (!isSegmented()) fWasProjectionEnabled= isProjectionMode(); disableProjection(); super.setVisibleRegion(start, length); } /* * @see org.eclipse.jface.text.TextViewer#resetVisibleRegion() */ public void resetVisibleRegion() { super.resetVisibleRegion(); if (fWasProjectionEnabled) enableProjection(); } /* * @see org.eclipse.jface.text.ITextViewer#getVisibleRegion() */ public IRegion getVisibleRegion() { disableProjection(); return getModelCoverage(); } /* * @see org.eclipse.jface.text.ITextViewer#overlapsWithVisibleRegion(int,int) */ public boolean overlapsWithVisibleRegion(int offset, int length) { disableProjection(); IRegion coverage= getModelCoverage(); if (coverage == null) return false; boolean appending= (offset == coverage.getOffset() + coverage.getLength()) && length == 0; return appending || TextUtilities.overlaps(coverage, new Region(offset, length)); } /** * Replace the visible document with the given document. Maintains the * scroll offset and the selection. * * @param visibleDocument the visible document */ private void replaceVisibleDocument(IDocument slave) { if (fReplaceVisibleDocumentExecutionTrigger != null) { ReplaceVisibleDocumentExecutor executor= new ReplaceVisibleDocumentExecutor(slave); executor.install(fReplaceVisibleDocumentExecutionTrigger); } else executeReplaceVisibleDocument(slave); } private void executeReplaceVisibleDocument(IDocument visibleDocument) { StyledText textWidget= getTextWidget(); try { if (textWidget != null && !textWidget.isDisposed()) textWidget.setRedraw(false); int topIndex= getTopIndex(); Point selection= getSelectedRange(); setVisibleDocument(visibleDocument); setSelectedRange(selection.x, selection.y); setTopIndex(topIndex); } finally { if (textWidget != null && !textWidget.isDisposed()) textWidget.setRedraw(true); } } /** * Hides the given range by collapsing it. If requested, a redraw request is issued. * * @param offset the offset of the range to hide * @param length the length of the range to hide * @param fireRedraw <code>true</code> if a redraw request should be issued, <code>false</code> otherwise * @throws BadLocationException in case the range is invalid */ private void collapse(int offset, int length, boolean fireRedraw) throws BadLocationException { ProjectionDocument projection= null; StyledText textWidget= getTextWidget(); try { if (textWidget != null && !textWidget.isDisposed()) textWidget.setRedraw(false); IDocument visibleDocument= getVisibleDocument(); if (visibleDocument instanceof ProjectionDocument) projection= (ProjectionDocument) visibleDocument; else { IDocument master= getDocument(); IDocument slave= createSlaveDocument(getDocument()); if (slave instanceof ProjectionDocument) { projection= (ProjectionDocument) slave; addMasterDocumentRange(projection, 0, master.getLength()); replaceVisibleDocument(projection); } } if (projection != null) removeMasterDocumentRange(projection, offset, length); } finally { if (textWidget != null && !textWidget.isDisposed()) { if (fRememberedTopIndex != -1) setTopIndex(fRememberedTopIndex); textWidget.setRedraw(true); } } if (projection != null && fireRedraw) { // repaint line above IDocument document= getDocument(); int line= document.getLineOfOffset(offset); if (line > 0) { IRegion info= document.getLineInformation(line - 1); invalidateTextPresentation(info.getOffset(), info.getLength()); } } } /** * Makes the given range visible again while keeping the given collapsed * ranges. If requested, a redraw request is issued. * * @param expanded the range to be expanded * @param collapsed a sequence of collapsed ranges completely contained by * the expanded range * @param fireRedraw <code>true</code> if a redraw request should be * issued, <code>false</code> otherwise * @throws BadLocationException in case the range is invalid */ private void expand(Position expanded, Position[] collapsed, boolean fireRedraw) throws BadLocationException { IDocument slave= getVisibleDocument(); if (slave instanceof ProjectionDocument) { ProjectionDocument projection= (ProjectionDocument) slave; StyledText textWidget= getTextWidget(); try { if (textWidget != null && !textWidget.isDisposed()) textWidget.setRedraw(false); // expand addMasterDocumentRange(projection, expanded.getOffset(), expanded.getLength()); // collapse contained regions if (collapsed != null) { for (int i= 0; i < collapsed.length; i++) { IRegion p= computeCollapsedRegion(collapsed[i]); removeMasterDocumentRange(projection, p.getOffset(), p.getLength()); } } } finally { if (textWidget != null && !textWidget.isDisposed()) { if (fRememberedTopIndex != -1) setTopIndex(fRememberedTopIndex); textWidget.setRedraw(true); } } IDocument master= getDocument(); if (slave.getLength() == master.getLength()) { replaceVisibleDocument(master); } else if (fireRedraw){ invalidateTextPresentation(expanded.getOffset(), expanded.getLength()); } } } /** * Processes the request for catch up with the annotation model in the UI thread. If the current * thread is not the UI thread or there are pending catch up requests, a new request is posted. * * @param event the annotation model event */ protected final void processCatchupRequest(AnnotationModelEvent event) { if (Display.getCurrent() != null) { boolean run= false; synchronized (fLock) { run= fPendingRequests.isEmpty(); } if (run) { try { catchupWithProjectionAnnotationModel(event); } catch (BadLocationException x) { throw new IllegalArgumentException(); } } else postCatchupRequest(event); } else { postCatchupRequest(event); } } /** * Posts the request for catch up with the annotation model into the UI thread. * * @param event the annotation model event */ protected final void postCatchupRequest(final AnnotationModelEvent event) { synchronized (fLock) { fPendingRequests.add(event); if (fPendingRequests.size() == 1) { StyledText widget= getTextWidget(); if (widget != null) { Display display= widget.getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { Iterator e= fPendingRequests.iterator(); try { while (true) { AnnotationModelEvent ame= null; synchronized (fLock) { if (e.hasNext()) { ame= (AnnotationModelEvent) e.next(); } else { fPendingRequests.clear(); return; } } catchupWithProjectionAnnotationModel(ame); } } catch (BadLocationException x) { try { catchupWithProjectionAnnotationModel(null); } catch (BadLocationException x1) { throw new IllegalArgumentException(); } finally { synchronized (fLock) { fPendingRequests.clear(); } } } } }); } } } } } /** * Adapts the slave visual document of this viewer to the changes described * in the annotation model event. When the event is <code>null</code>, * this is identical to a world change event. * * @param event the annotation model event or <code>null</code> * @exception BadLocationException in case the annotation model event is no longer in sync with the document */ private void catchupWithProjectionAnnotationModel(AnnotationModelEvent event) throws BadLocationException { if (event == null) { fPendingAnnotationWorldChange= false; reinitializeProjection(); } else if (event.isWorldChange()) { if (event.isValid()) { fPendingAnnotationWorldChange= false; reinitializeProjection(); } else fPendingAnnotationWorldChange= true; } else { if (fPendingAnnotationWorldChange) { if (event.isValid()) { fPendingAnnotationWorldChange= false; reinitializeProjection(); } } else { boolean fireRedraw= true; processDeletions(event, fireRedraw); processAdditions(event, fireRedraw); processModifications(event, fireRedraw); if (!fireRedraw) { //TODO compute minimal scope for invalidation invalidateTextPresentation(); } } } } private boolean includes(Position expanded, Position position) { if (!expanded.equals(position) && !position.isDeleted()) return expanded.getOffset() <= position.getOffset() && position.getOffset() + position.getLength() <= expanded.getOffset() + expanded.getLength(); return false; } private Position[] computeCollapsedRanges(Position expanded) { List positions= new ArrayList(5); Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); while (e.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); if (position == null) { // annotation might already be deleted, we will be informed later on about this deletion continue; } if (includes(expanded, position)) positions.add(position); } } if (positions.size() > 0) { Position[] result= new Position[positions.size()]; positions.toArray(result); return result; } return null; } private void processDeletions(AnnotationModelEvent event, boolean fireRedraw) throws BadLocationException { Annotation[] annotations= event.getRemovedAnnotations(); for (int i= 0; i < annotations.length; i++) { ProjectionAnnotation annotation= (ProjectionAnnotation) annotations[i]; if (annotation.isCollapsed()) { Position expanded= event.getPositionOfRemovedAnnotation(annotation); Position[] collapsed= computeCollapsedRanges(expanded); expand(expanded, collapsed, false); if (fireRedraw) invalidateTextPresentation(expanded.getOffset(), expanded.getLength()); } } } public IRegion computeCollapsedRegion(Position position) { try { IDocument document= getDocument(); int line= document.getLineOfOffset(position.getOffset()); int offset= document.getLineOffset(line + 1); int length= position.getLength() - (offset - position.getOffset()); if (length > 0) return new Region(offset, length); } catch (BadLocationException x) { } return null; } public Position computeCollapsedRegionAnchor(Position position) { try { IDocument document= getDocument(); IRegion lineInfo= document.getLineInformationOfOffset(position.getOffset()); return new Position(lineInfo.getOffset() + lineInfo.getLength(), 0); } catch (BadLocationException x) { } return null; } private void processAdditions(AnnotationModelEvent event, boolean fireRedraw) throws BadLocationException { Annotation[] annotations= event.getAddedAnnotations(); for (int i= 0; i < annotations.length; i++) { ProjectionAnnotation annotation= (ProjectionAnnotation) annotations[i]; if (annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); if (position != null) { IRegion region= computeCollapsedRegion(position); if (region != null) collapse(region.getOffset(), region.getLength(), fireRedraw); } } } } private void processModifications(AnnotationModelEvent event, boolean fireRedraw) throws BadLocationException { Annotation[] annotations= event.getChangedAnnotations(); for (int i= 0; i < annotations.length; i++) { ProjectionAnnotation annotation= (ProjectionAnnotation) annotations[i]; Position position= fProjectionAnnotationModel.getPosition(annotation); if (position == null) { // we are potentially processing in a different thread, i.e. the annotation might already be // deleted which will be indicated with one of the subsequent events continue; } if (annotation.isCollapsed()) { IRegion region= computeCollapsedRegion(position); if (region != null) collapse(region.getOffset(), region.getLength(), fireRedraw); } else { Position[] collapsed= computeCollapsedRanges(position); expand(position, collapsed, false); if (fireRedraw) invalidateTextPresentation(position.getOffset(), position.getLength()); } } } private void reinitializeProjection() throws BadLocationException { ProjectionDocument projection= null; ISlaveDocumentManager manager= getSlaveDocumentManager(); if (manager != null) { IDocument master= getDocument(); if (master != null) { IDocument slave= manager.createSlaveDocument(master); if (slave instanceof ProjectionDocument) { projection= (ProjectionDocument) slave; addMasterDocumentRange(projection, 0, master.getLength()); } } } if (projection != null) { Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); while (e.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); if (position != null) { IRegion region= computeCollapsedRegion(position); if (region != null) removeMasterDocumentRange(projection, region.getOffset(), region.getLength()); } } } } replaceVisibleDocument(projection); } /* * @see org.eclipse.jface.text.TextViewer#handleVerifyEvent(org.eclipse.swt.events.VerifyEvent) */ protected void handleVerifyEvent(VerifyEvent e) { IRegion modelRange= event2ModelRange(e); if (exposeModelRange(modelRange)) e.doit= false; else super.handleVerifyEvent(e); } /** * Adds the give column as last column to this viewer's vertical ruler. * * @param column the column to be added */ public void addVerticalRulerColumn(IVerticalRulerColumn column) { IVerticalRuler ruler= getVerticalRuler(); if (ruler instanceof CompositeRuler) { CompositeRuler compositeRuler= (CompositeRuler) ruler; compositeRuler.addDecorator(99, column); } } /** * Removes the give column from this viewer's vertical ruler. * * @param column the column to be removed */ public void removeVerticalRulerColumn(IVerticalRulerColumn column) { IVerticalRuler ruler= getVerticalRuler(); if (ruler instanceof CompositeRuler) { CompositeRuler compositeRuler= (CompositeRuler) ruler; compositeRuler.removeDecorator(column); } } /* * @see org.eclipse.jface.text.ITextViewerExtension5#exposeModelRange(org.eclipse.jface.text.IRegion) */ public boolean exposeModelRange(IRegion modelRange) { if (isProjectionMode()) return fProjectionAnnotationModel.expandAll(modelRange.getOffset(), modelRange.getLength()); if (!overlapsWithVisibleRegion(modelRange.getOffset(), modelRange.getLength())) { resetVisibleRegion(); return true; } return false; } /* * @see org.eclipse.jface.text.source.SourceViewer#setRangeIndication(int, int, boolean) */ public void setRangeIndication(int start, int length, boolean moveCursor) { // TODO experimental code if (moveCursor) exposeModelRange(new Region(start, length)); super.setRangeIndication(start, length, moveCursor); } /* * @see org.eclipse.jface.text.TextViewer#inputChanged(java.lang.Object, java.lang.Object) */ protected void inputChanged(Object newInput, Object oldInput) { if (oldInput instanceof IDocument) { IDocument previous= (IDocument) oldInput; previous.removeDocumentListener(fDocumentListener); } super.inputChanged(newInput, oldInput); if (newInput instanceof IDocument) { IDocument current= (IDocument) newInput; current.addDocumentListener(fDocumentListener); } } /* * @see org.eclipse.jface.text.TextViewer#handleVisibleDocumentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ protected void handleVisibleDocumentChanged(DocumentEvent event) { if (fHandleProjectionChanges && event instanceof ProjectionDocumentEvent && isProjectionMode()) { ProjectionDocumentEvent e= (ProjectionDocumentEvent) event; if (ProjectionDocumentEvent.PROJECTION_CHANGE == e.getChangeType() && e.getLength() == 0 && e.getText().length() != 0) fProjectionAnnotationModel.expandAll(e.getMasterOffset(), e.getMasterLength()); } } /* * @see org.eclipse.jface.text.ITextViewerExtension5#getCoveredModelRanges(org.eclipse.jface.text.IRegion) */ public IRegion[] getCoveredModelRanges(IRegion modelRange) { if (fInformationMapping == null) return new IRegion[] { new Region(modelRange.getOffset(), modelRange.getLength()) }; if (fInformationMapping instanceof IDocumentInformationMappingExtension) { IDocumentInformationMappingExtension extension= (IDocumentInformationMappingExtension) fInformationMapping; try { return extension.getExactCoverage(modelRange); } catch (BadLocationException x) { } } return null; } /* * @see org.eclipse.jface.text.ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { switch (operation) { case TOGGLE: if (canDoOperation(TOGGLE)) { if (!isProjectionMode()) { enableProjection(); } else { expandAll(); disableProjection(); } return; } } if (!isProjectionMode()) { super.doOperation(operation); return; } StyledText textWidget= getTextWidget(); if (textWidget == null) return; Point selection= null; switch (operation) { case CUT: if (redraws()) { selection= getSelectedRange(); if (selection.y == 0) copyMarkedRegion(true); else copyToClipboard(selection.x, selection.y, true, textWidget); selection= textWidget.getSelectionRange(); fireSelectionChanged(selection.x, selection.y); } break; case COPY: if (redraws()) { selection= getSelectedRange(); if (selection.y == 0) copyMarkedRegion(false); else copyToClipboard(selection.x, selection.y, false, textWidget); } break; case EXPAND_ALL: if (redraws()) expandAll(); break; case EXPAND: if (redraws()) { expand(); } break; case COLLAPSE: if (redraws()) { collapse(); } break; default: super.doOperation(operation); } } /* * @see org.eclipse.jface.text.source.SourceViewer#canDoOperation(int) */ public boolean canDoOperation(int operation) { switch (operation) { case COLLAPSE: case EXPAND: case EXPAND_ALL: return isProjectionMode(); case TOGGLE: return !isSegmented(); } return super.canDoOperation(operation); } private boolean isSegmented() { IDocument document= getDocument(); int length= document == null ? 0 : document.getLength(); IRegion visible= getModelCoverage(); boolean isSegmented= visible != null && !visible.equals(new Region(0, length)); return isSegmented; } /* * @see org.eclipse.jface.text.TextViewer#copyMarkedRegion(boolean) */ protected void copyMarkedRegion(boolean delete) { StyledText textWidget= getTextWidget(); if (textWidget == null) return; if (fMarkPosition == null || fMarkPosition.isDeleted()) return; int start= fMarkPosition.getOffset(); int end= getSelectedRange().x; if (start > end) { start= start + end; end= start - end; start= start - end; } copyToClipboard(start, end - start, delete, textWidget); } private void copyToClipboard(int offset, int length, boolean delete, StyledText textWidget) { IDocument document= getDocument(); Clipboard clipboard= new Clipboard(textWidget.getDisplay()); try { Transfer[] dataTypes= new Transfer[] { TextTransfer.getInstance() }; Object[] data= new Object[] { document.get(offset, length) }; clipboard.setContents(data, dataTypes); if (delete) { int widgetCaret= modelOffset2WidgetOffset(offset); textWidget.setSelection(widgetCaret); document.replace(offset, length, null); } } catch (BadLocationException x) { } finally { clipboard.dispose(); } } /** * Adapts the behavior to line based folding. */ protected Point widgetSelection2ModelSelection(Point widgetSelection) { if (!isProjectionMode()) return super.widgetSelection2ModelSelection(widgetSelection); IRegion modelSelection= widgetRange2ModelRange(new Region(widgetSelection.x, widgetSelection.y)); if (modelSelection == null) return null; int modelOffset= modelSelection.getOffset(); int modelLength= modelSelection.getLength(); int widgetSelectionExclusiveEnd= widgetSelection.x + widgetSelection.y; int modelExclusiveEnd= widgetOffset2ModelOffset(widgetSelectionExclusiveEnd); if (modelOffset + modelLength < modelExclusiveEnd) return new Point(modelOffset, modelExclusiveEnd - modelOffset); if (widgetSelectionExclusiveEnd == getVisibleDocument().getLength()) return new Point(modelOffset, getDocument().getLength() - modelOffset); return new Point(modelOffset, modelLength); } /* * @see org.eclipse.jface.text.TextViewer#getFindReplaceDocumentAdapter() */ protected FindReplaceDocumentAdapter getFindReplaceDocumentAdapter() { if (fFindReplaceDocumentAdapter == null) { IDocument document= isProjectionMode() ? getDocument() : getVisibleDocument(); fFindReplaceDocumentAdapter= new FindReplaceDocumentAdapter(document); } return fFindReplaceDocumentAdapter; } /* * @see org.eclipse.jface.text.TextViewer#findAndSelect(int, java.lang.String, boolean, boolean, boolean, boolean) */ protected int findAndSelect(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) { if (!isProjectionMode()) return super.findAndSelect(startPosition, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); StyledText textWidget= getTextWidget(); if (textWidget == null) return -1; try { IRegion matchRegion= getFindReplaceDocumentAdapter().find(startPosition, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); if (matchRegion != null) { exposeModelRange(matchRegion); setSelectedRange(matchRegion.getOffset(), matchRegion.getLength()); textWidget.showSelection(); return matchRegion.getOffset(); } } catch (BadLocationException x) { } return -1; } /* * @see org.eclipse.jface.text.TextViewer#findAndSelectInRange(int, java.lang.String, boolean, boolean, boolean, int, int, boolean) */ protected int findAndSelectInRange(int startPosition, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, int rangeOffset, int rangeLength, boolean regExSearch) { if (!isProjectionMode()) return super.findAndSelect(startPosition, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); StyledText textWidget= getTextWidget(); if (textWidget == null) return -1; try { int modelOffset= startPosition; if (forwardSearch && (startPosition == -1 || startPosition < rangeOffset)) { modelOffset= rangeOffset; } else if (!forwardSearch && (startPosition == -1 || startPosition > rangeOffset + rangeLength)) { modelOffset= rangeOffset + rangeLength; } IRegion matchRegion= getFindReplaceDocumentAdapter().find(modelOffset, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); if (matchRegion != null) { int offset= matchRegion.getOffset(); int length= matchRegion.getLength(); - if (rangeOffset <= offset || offset + length <= rangeOffset + rangeLength) { + if (rangeOffset <= offset && offset + length <= rangeOffset + rangeLength) { exposeModelRange(matchRegion); setSelectedRange(offset, length); textWidget.showSelection(); return offset; } } } catch (BadLocationException x) { } return -1; } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java index 7747ee25d..551c33f64 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java @@ -1,1814 +1,1802 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ui.texteditor; import java.text.BreakIterator; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.contentassist.SubjectControlContentAssistant; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.resource.JFaceColors; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IFindReplaceTarget; import org.eclipse.jface.text.IFindReplaceTargetExtension; import org.eclipse.jface.text.IFindReplaceTargetExtension3; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.contentassist.ContentAssistHandler; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.internal.texteditor.TextEditorPlugin; /** * Find/Replace dialog. The dialog is opened on a particular * target but can be re-targeted. Internally used by the <code>FindReplaceAction</code> */ class FindReplaceDialog extends Dialog { /** * Updates the find replace dialog on activation changes. */ class ActivationListener extends ShellAdapter { /* * @see ShellListener#shellActivated(ShellEvent) */ public void shellActivated(ShellEvent e) { String oldText= fFindField.getText(); // XXX workaround for 10766 List oldList= new ArrayList(); oldList.addAll(fFindHistory); readConfiguration(); fFindField.removeModifyListener(fFindModifyListener); updateCombo(fFindField, fFindHistory); if (!fFindHistory.equals(oldList) && !fFindHistory.isEmpty()) fFindField.setText((String) fFindHistory.get(0)); else fFindField.setText(oldText); if (findFieldHadFocus()) fFindField.setSelection(new Point(0, fFindField.getText().length())); fFindField.addModifyListener(fFindModifyListener); fActiveShell= (Shell)e.widget; updateButtonState(); if (findFieldHadFocus() && getShell() == fActiveShell && !fFindField.isDisposed()) fFindField.setFocus(); } /** * Returns <code>true</code> if the find field had focus, * <code>false</code> if it did not. * * @return <code>true</code> if the find field had focus, * <code>false</code> if it did not */ private boolean findFieldHadFocus() { /* * See bug 45447. Under GTK and Motif, the focus of the find field * is already gone when shellDeactivated is called. On the other * hand focus has already been restored when shellActivated is * called. * * Therefore, we select and give focus if either * fGiveFocusToFindField is true or the find field has focus. */ return fGiveFocusToFindField || okToUse(fFindField) && fFindField.isFocusControl(); } /* * @see ShellListener#shellDeactivated(ShellEvent) */ public void shellDeactivated(ShellEvent e) { fGiveFocusToFindField= fFindField.isFocusControl(); storeSettings(); fGlobalRadioButton.setSelection(true); fSelectedRangeRadioButton.setSelection(false); fUseSelectedLines= false; if (fTarget != null && (fTarget instanceof IFindReplaceTargetExtension)) ((IFindReplaceTargetExtension) fTarget).setScope(null); fOldScope= null; fActiveShell= null; updateButtonState(); } } /** * Modify listener to update the search result in case of incremental search. * @since 2.0 */ private class FindModifyListener implements ModifyListener { /* * @see ModifyListener#modifyText(ModifyEvent) */ public void modifyText(ModifyEvent e) { if (isIncrementalSearch() && !isRegExSearchAvailableAndChecked()) { if (fFindField.getText().equals("") && fTarget != null) { //$NON-NLS-1$ // empty selection at base location int offset= fIncrementalBaseLocation.x; if (isForwardSearch() && !fNeedsInitialFindBeforeReplace || !isForwardSearch() && fNeedsInitialFindBeforeReplace) offset= offset + fIncrementalBaseLocation.y; fNeedsInitialFindBeforeReplace= false; findAndSelect(offset, "", isForwardSearch(), isCaseSensitiveSearch(), isWholeWordSearch(), isRegExSearchAvailableAndChecked()); //$NON-NLS-1$ } else { performSearch(false); } } updateButtonState(!isIncrementalSearch()); } } /** The size of the dialogs search history. */ private static final int HISTORY_SIZE= 5; private Point fLocation; private Point fIncrementalBaseLocation; private boolean fWrapInit, fCaseInit, fWholeWordInit, fForwardInit, fGlobalInit, fIncrementalInit; /** * Tells whether an initial find operation is needed * before the replace operation. * @since 3.0 */ private boolean fNeedsInitialFindBeforeReplace; /** * Initial value for telling whether the search string is a regular expression. * @since 3.0 */ boolean fIsRegExInit; private List fFindHistory; private List fReplaceHistory; private IRegion fOldScope; private boolean fIsTargetEditable; private IFindReplaceTarget fTarget; private Shell fParentShell; private Shell fActiveShell; private final ActivationListener fActivationListener= new ActivationListener(); private final ModifyListener fFindModifyListener= new FindModifyListener(); private Label fReplaceLabel, fStatusLabel; private Button fForwardRadioButton, fGlobalRadioButton, fSelectedRangeRadioButton; private Button fCaseCheckBox, fWrapCheckBox, fWholeWordCheckBox, fIncrementalCheckBox; /** * Checkbox for selecting whether the search string is a regular expression. * @since 3.0 */ private Button fIsRegExCheckBox; private Button fReplaceSelectionButton, fReplaceFindButton, fFindNextButton, fReplaceAllButton; Combo fFindField, fReplaceField; private Rectangle fDialogPositionInit; private IDialogSettings fDialogSettings; /** * Tells whether the target supports regular expressions. * <code>true</code> if the target supports regular expressions * @since 3.0 */ private boolean fIsTargetSupportingRegEx; /** * Tells whether fUseSelectedLines radio is checked. * @since 3.0 */ private boolean fUseSelectedLines; /** * The content assist handler for the find combo. * @since 3.0 */ private ContentAssistHandler fFindContentAssistHandler; /** * The content assist handler for the replace combo. * @since 3.0 */ private ContentAssistHandler fReplaceContentAssistHandler; /** * Content assist's proposal popup background color. * @since 3.0 */ private Color fProposalPopupBackgroundColor; /** * Content assist's proposal popup foreground color. * @since 3.0 */ private Color fProposalPopupForegroundColor; /** * <code>true</code> if the find field should receive focus the next time * the dialog is activated, <code>false</code> otherwise. * @since 3.0 */ private boolean fGiveFocusToFindField= true; /** * Creates a new dialog with the given shell as parent. * @param parentShell the parent shell */ public FindReplaceDialog(Shell parentShell) { super(parentShell); fParentShell= null; fTarget= null; fDialogPositionInit= null; fFindHistory= new ArrayList(HISTORY_SIZE - 1); fReplaceHistory= new ArrayList(HISTORY_SIZE - 1); fWrapInit= false; fCaseInit= false; fIsRegExInit= false; fWholeWordInit= false; fIncrementalInit= false; fGlobalInit= true; fForwardInit= true; readConfiguration(); setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE); setBlockOnOpen(false); } /** * Returns this dialog's parent shell. * @return the dialog's parent shell */ public Shell getParentShell() { return super.getParentShell(); } /** * Returns <code>true</code> if control can be used. * * @param control the control to be checked * @return <code>true</code> if control can be used */ private boolean okToUse(Control control) { return control != null && !control.isDisposed(); } /* * @see org.eclipse.jface.window.Window#create() */ public void create() { super.create(); Shell shell= getShell(); shell.addShellListener(fActivationListener); if (fLocation != null) shell.setLocation(fLocation); // set help context WorkbenchHelp.setHelp(shell, IAbstractTextEditorHelpContextIds.FIND_REPLACE_DIALOG); // fill in combo contents fFindField.removeModifyListener(fFindModifyListener); updateCombo(fFindField, fFindHistory); fFindField.addModifyListener(fFindModifyListener); updateCombo(fReplaceField, fReplaceHistory); // get find string initFindStringFromSelection(); // set dialog position if (fDialogPositionInit != null) shell.setBounds(fDialogPositionInit); shell.setText(EditorMessages.getString("FindReplace.title")); //$NON-NLS-1$ // shell.setImage(null); } /** * Create the button section of the find/replace dialog. * * @param parent the parent composite * @return the button section */ private Composite createButtonSection(Composite parent) { Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= -2; layout.makeColumnsEqualWidth= true; panel.setLayout(layout); fFindNextButton= makeButton(panel, "FindReplace.FindNextButton.label", 102, true, new SelectionAdapter() { //$NON-NLS-1$ public void widgetSelected(SelectionEvent e) { if (isIncrementalSearch() && !isRegExSearchAvailableAndChecked()) initIncrementalBaseLocation(); fNeedsInitialFindBeforeReplace= false; performSearch(); updateFindHistory(); fFindNextButton.setFocus(); } }); setGridData(fFindNextButton, GridData.FILL, true, GridData.FILL, false); fReplaceFindButton= makeButton(panel, "FindReplace.ReplaceFindButton.label", 103, false, new SelectionAdapter() { //$NON-NLS-1$ public void widgetSelected(SelectionEvent e) { if (fNeedsInitialFindBeforeReplace) performSearch(); if (performReplaceSelection()) performSearch(); updateFindAndReplaceHistory(); fReplaceFindButton.setFocus(); } }); setGridData(fReplaceFindButton, GridData.FILL, true, GridData.FILL, false); fReplaceSelectionButton= makeButton(panel, "FindReplace.ReplaceSelectionButton.label", 104, false, new SelectionAdapter() { //$NON-NLS-1$ public void widgetSelected(SelectionEvent e) { if (fNeedsInitialFindBeforeReplace) performSearch(); performReplaceSelection(); updateFindAndReplaceHistory(); fFindNextButton.setFocus(); } }); setGridData(fReplaceSelectionButton, GridData.FILL, true, GridData.FILL, false); fReplaceAllButton= makeButton(panel, "FindReplace.ReplaceAllButton.label", 105, false, new SelectionAdapter() { //$NON-NLS-1$ public void widgetSelected(SelectionEvent e) { performReplaceAll(); updateFindAndReplaceHistory(); fFindNextButton.setFocus(); } }); setGridData(fReplaceAllButton, GridData.FILL, true, GridData.FILL, false); // Make the all the buttons the same size as the Remove Selection button. fReplaceAllButton.setEnabled(isEditable()); return panel; } /** * Creates the options configuration section of the find replace dialog. * * @param parent the parent composite * @return the options configuration section */ private Composite createConfigPanel(Composite parent) { Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.makeColumnsEqualWidth= true; panel.setLayout(layout); Composite directionGroup= createDirectionGroup(panel); setGridData(directionGroup, GridData.FILL, true, GridData.FILL, false); Composite scopeGroup= createScopeGroup(panel); setGridData(scopeGroup, GridData.FILL, true, GridData.FILL, false); Composite optionsGroup= createOptionsGroup(panel); setGridData(optionsGroup, GridData.FILL, true, GridData.FILL, false); GridData data= (GridData) optionsGroup.getLayoutData(); data.horizontalSpan= 2; optionsGroup.setLayoutData(data); return panel; } /* * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.Composite) */ protected Control createContents(Composite parent) { Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 1; layout.makeColumnsEqualWidth= true; panel.setLayout(layout); Composite inputPanel= createInputPanel(panel); setGridData(inputPanel, GridData.FILL, true, GridData.CENTER, false); Composite configPanel= createConfigPanel(panel); setGridData(configPanel, GridData.FILL, true, GridData.CENTER, true); Composite buttonPanelB= createButtonSection(panel); setGridData(buttonPanelB, GridData.FILL, true, GridData.CENTER, false); Composite statusBar= createStatusAndCloseButton(panel); setGridData(statusBar, GridData.FILL, true, GridData.CENTER, false); updateButtonState(); applyDialogFont(panel); // Setup content assistants for find and replace combos fProposalPopupBackgroundColor= new Color(getShell().getDisplay(), new RGB(254, 241, 233)); fProposalPopupForegroundColor= new Color(getShell().getDisplay(), new RGB(0, 0, 0)); return panel; } private void setContentAssistsEnablement(boolean enable) { if (enable) { if (fFindContentAssistHandler == null) { fFindContentAssistHandler= ContentAssistHandler.createHandlerForCombo(fFindField, createContentAssistant()); fReplaceContentAssistHandler= ContentAssistHandler.createHandlerForCombo(fReplaceField, createContentAssistant()); } fFindContentAssistHandler.setEnabled(true); fReplaceContentAssistHandler.setEnabled(true); } else { if (fFindContentAssistHandler == null) return; fFindContentAssistHandler.setEnabled(false); fReplaceContentAssistHandler.setEnabled(false); } } /** * Creates the direction defining part of the options defining section * of the find replace dialog. * * @param parent the parent composite * @return the direction defining part */ private Composite createDirectionGroup(Composite parent) { Composite panel= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; panel.setLayout(layout); Group group= new Group(panel, SWT.SHADOW_ETCHED_IN); group.setText(EditorMessages.getString("FindReplace.Direction")); //$NON-NLS-1$ GridLayout groupLayout= new GridLayout(); group.setLayout(groupLayout); group.setLayoutData(new GridData(GridData.FILL_BOTH)); SelectionListener selectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (isIncrementalSearch() && !isRegExSearchAvailableAndChecked()) initIncrementalBaseLocation(); } public void widgetDefaultSelected(SelectionEvent e) { } }; fForwardRadioButton= new Button(group, SWT.RADIO | SWT.LEFT); fForwardRadioButton.setText(EditorMessages.getString("FindReplace.ForwardRadioButton.label")); //$NON-NLS-1$ setGridData(fForwardRadioButton, GridData.BEGINNING, false, GridData.CENTER, false); fForwardRadioButton.addSelectionListener(selectionListener); Button backwardRadioButton= new Button(group, SWT.RADIO | SWT.LEFT); backwardRadioButton.setText(EditorMessages.getString("FindReplace.BackwardRadioButton.label")); //$NON-NLS-1$ setGridData(backwardRadioButton, GridData.BEGINNING, false, GridData.CENTER, false); backwardRadioButton.addSelectionListener(selectionListener); backwardRadioButton.setSelection(!fForwardInit); fForwardRadioButton.setSelection(fForwardInit); return panel; } /** * Creates the scope defining part of the find replace dialog. * * @param parent the parent composite * @return the scope defining part * @since 2.0 */ private Composite createScopeGroup(Composite parent) { Composite panel= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; panel.setLayout(layout); Group group= new Group(panel, SWT.SHADOW_ETCHED_IN); group.setText(EditorMessages.getString("FindReplace.Scope")); //$NON-NLS-1$ GridLayout groupLayout= new GridLayout(); group.setLayout(groupLayout); group.setLayoutData(new GridData(GridData.FILL_BOTH)); fGlobalRadioButton= new Button(group, SWT.RADIO | SWT.LEFT); fGlobalRadioButton.setText(EditorMessages.getString("FindReplace.GlobalRadioButton.label")); //$NON-NLS-1$ setGridData(fGlobalRadioButton, GridData.BEGINNING, false, GridData.CENTER, false); fGlobalRadioButton.setSelection(fGlobalInit); fGlobalRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (!fGlobalRadioButton.getSelection() || !fUseSelectedLines) return; fUseSelectedLines= false; useSelectedLines(false); } public void widgetDefaultSelected(SelectionEvent e) { } }); fSelectedRangeRadioButton= new Button(group, SWT.RADIO | SWT.LEFT); fSelectedRangeRadioButton.setText(EditorMessages.getString("FindReplace.SelectedRangeRadioButton.label")); //$NON-NLS-1$ setGridData(fSelectedRangeRadioButton, GridData.BEGINNING, false, GridData.CENTER, false); fSelectedRangeRadioButton.setSelection(!fGlobalInit); fUseSelectedLines= !fGlobalInit; fSelectedRangeRadioButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (!fSelectedRangeRadioButton.getSelection() || fUseSelectedLines) return; fUseSelectedLines= true; useSelectedLines(true); } public void widgetDefaultSelected(SelectionEvent e) { } }); return panel; } /** * Tells the dialog to perform searches only in the scope given by the actually selected lines. * @param selectedLines <code>true</code> if selected lines should be used * @since 2.0 */ private void useSelectedLines(boolean selectedLines) { if (isIncrementalSearch() && !isRegExSearchAvailableAndChecked()) initIncrementalBaseLocation(); if (fTarget == null || !(fTarget instanceof IFindReplaceTargetExtension)) return; IFindReplaceTargetExtension extensionTarget= (IFindReplaceTargetExtension) fTarget; if (selectedLines) { IRegion scope; if (fOldScope == null) { Point lineSelection= extensionTarget.getLineSelection(); scope= new Region(lineSelection.x, lineSelection.y); } else { scope= fOldScope; fOldScope= null; } int offset= isForwardSearch() ? scope.getOffset() : scope.getOffset() + scope.getLength(); extensionTarget.setSelection(offset, 0); extensionTarget.setScope(scope); } else { fOldScope= extensionTarget.getScope(); extensionTarget.setScope(null); } } /** * Creates the panel where the user specifies the text to search * for and the optional replacement text. * * @param parent the parent composite * @return the input panel */ private Composite createInputPanel(Composite parent) { ModifyListener listener= new ModifyListener() { public void modifyText(ModifyEvent e) { updateButtonState(); } }; Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; panel.setLayout(layout); Label findLabel= new Label(panel, SWT.LEFT); findLabel.setText(EditorMessages.getString("FindReplace.Find.label")); //$NON-NLS-1$ setGridData(findLabel, GridData.BEGINNING, false, GridData.CENTER, false); fFindField= new Combo(panel, SWT.DROP_DOWN | SWT.BORDER); setGridData(fFindField, GridData.FILL, true, GridData.CENTER, false); fFindField.addModifyListener(fFindModifyListener); fReplaceLabel= new Label(panel, SWT.LEFT); fReplaceLabel.setText(EditorMessages.getString("FindReplace.Replace.label")); //$NON-NLS-1$ setGridData(fReplaceLabel, GridData.BEGINNING, false, GridData.CENTER, false); fReplaceField= new Combo(panel, SWT.DROP_DOWN | SWT.BORDER); setGridData(fReplaceField, GridData.FILL, true, GridData.CENTER, false); fReplaceField.addModifyListener(listener); return panel; } /** * Creates the functional options part of the options defining * section of the find replace dialog. * * @param parent the parent composite * @return the options group */ private Composite createOptionsGroup(Composite parent) { Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; panel.setLayout(layout); Group group= new Group(panel, SWT.SHADOW_NONE); group.setText(EditorMessages.getString("FindReplace.Options")); //$NON-NLS-1$ GridLayout groupLayout= new GridLayout(); groupLayout.numColumns= 2; groupLayout.makeColumnsEqualWidth= true; group.setLayout(groupLayout); group.setLayoutData(new GridData(GridData.FILL_BOTH)); SelectionListener selectionListener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { storeSettings(); } public void widgetDefaultSelected(SelectionEvent e) { } }; fCaseCheckBox= new Button(group, SWT.CHECK | SWT.LEFT); fCaseCheckBox.setText(EditorMessages.getString("FindReplace.CaseCheckBox.label")); //$NON-NLS-1$ setGridData(fCaseCheckBox, GridData.BEGINNING, false, GridData.CENTER, false); fCaseCheckBox.setSelection(fCaseInit); fCaseCheckBox.addSelectionListener(selectionListener); fWrapCheckBox= new Button(group, SWT.CHECK | SWT.LEFT); fWrapCheckBox.setText(EditorMessages.getString("FindReplace.WrapCheckBox.label")); //$NON-NLS-1$ setGridData(fWrapCheckBox, GridData.BEGINNING, false, GridData.CENTER, false); fWrapCheckBox.setSelection(fWrapInit); fWrapCheckBox.addSelectionListener(selectionListener); fWholeWordCheckBox= new Button(group, SWT.CHECK | SWT.LEFT); fWholeWordCheckBox.setText(EditorMessages.getString("FindReplace.WholeWordCheckBox.label")); //$NON-NLS-1$ setGridData(fWholeWordCheckBox, GridData.BEGINNING, false, GridData.CENTER, false); fWholeWordCheckBox.setSelection(fWholeWordInit); fWholeWordCheckBox.addSelectionListener(selectionListener); fIncrementalCheckBox= new Button(group, SWT.CHECK | SWT.LEFT); fIncrementalCheckBox.setText(EditorMessages.getString("FindReplace.IncrementalCheckBox.label")); //$NON-NLS-1$ setGridData(fIncrementalCheckBox, GridData.BEGINNING, false, GridData.CENTER, false); fIncrementalCheckBox.setSelection(fIncrementalInit); fIncrementalCheckBox.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (isIncrementalSearch() && !isRegExSearch()) initIncrementalBaseLocation(); storeSettings(); } public void widgetDefaultSelected(SelectionEvent e) { } }); fIsRegExCheckBox= new Button(group, SWT.CHECK | SWT.LEFT); fIsRegExCheckBox.setText(EditorMessages.getString("FindReplace.RegExCheckbox.label")); //$NON-NLS-1$ setGridData(fIsRegExCheckBox, GridData.BEGINNING, false, GridData.CENTER, false); ((GridData)fIsRegExCheckBox.getLayoutData()).horizontalSpan= 2; fIsRegExCheckBox.setSelection(fIsRegExInit); fIsRegExCheckBox.addSelectionListener(new SelectionAdapter() { /* * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { boolean newState= fIsRegExCheckBox.getSelection(); fIncrementalCheckBox.setEnabled(!newState); fWholeWordCheckBox.setEnabled(!newState); updateButtonState(); storeSettings(); setContentAssistsEnablement(newState); } }); fWholeWordCheckBox.setEnabled(!isRegExSearchAvailableAndChecked()); fWholeWordCheckBox.addSelectionListener(new SelectionAdapter() { /* * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) */ public void widgetSelected(SelectionEvent e) { updateButtonState(); } }); fIncrementalCheckBox.setEnabled(!isRegExSearchAvailableAndChecked()); return panel; } /** * Creates the status and close section of the dialog. * * @param parent the parent composite * @return the status and close button */ private Composite createStatusAndCloseButton(Composite parent) { Composite panel= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginWidth= 0; layout.marginHeight= 0; panel.setLayout(layout); fStatusLabel= new Label(panel, SWT.LEFT); setGridData(fStatusLabel, GridData.FILL, true, GridData.CENTER, false); String label= EditorMessages.getString("FindReplace.CloseButton.label"); //$NON-NLS-1$ Button closeButton= createButton(panel, 101, label, false); setGridData(closeButton, GridData.END, false, GridData.END, false); return panel; } /* * @see Dialog#buttonPressed */ protected void buttonPressed(int buttonID) { if (buttonID == 101) close(); } // ------- action invocation --------------------------------------- /** * Returns the position of the specified search string, or <code>-1</code> if the string can * not be found when searching using the given options. * * @param findString the string to search for * @param startPosition the position at which to start the search * @param forwardSearch the direction of the search * @param caseSensitive should the search be case sensitive * @param wrapSearch should the search wrap to the start/end if arrived at the end/start * @param wholeWord does the search string represent a complete word * @param regExSearch if <code>true</code> findString represents a regular expression * @return the occurrence of the find string following the options or <code>-1</code> if nothing found * @since 3.0 */ private int findIndex(String findString, int startPosition, boolean forwardSearch, boolean caseSensitive, boolean wrapSearch, boolean wholeWord, boolean regExSearch) { if (forwardSearch) { if (wrapSearch) { int index= findAndSelect(startPosition, findString, true, caseSensitive, wholeWord, regExSearch); if (index == -1) { if (okToUse(getShell()) && !isIncrementalSearch()) getShell().getDisplay().beep(); index= findAndSelect(-1, findString, true, caseSensitive, wholeWord, regExSearch); } return index; } return findAndSelect(startPosition, findString, true, caseSensitive, wholeWord, regExSearch); } // backward if (wrapSearch) { int index= findAndSelect(startPosition - 1, findString, false, caseSensitive, wholeWord, regExSearch); if (index == -1) { if (okToUse(getShell()) && !isIncrementalSearch()) getShell().getDisplay().beep(); index= findAndSelect(-1, findString, false, caseSensitive, wholeWord, regExSearch); } return index; } return findAndSelect(startPosition - 1, findString, false, caseSensitive, wholeWord, regExSearch); } /** * Searches for a string starting at the given offset and using the specified search * directives. If a string has been found it is selected and its start offset is * returned. * * @param offset the offset at which searching starts * @param findString the string which should be found * @param forwardSearch the direction of the search * @param caseSensitive <code>true</code> performs a case sensitive search, <code>false</code> an insensitive search * @param wholeWord if <code>true</code> only occurrences are reported in which the findString stands as a word by itself * @param regExSearch if <code>true</code> findString represents a regular expression * @return the position of the specified string, or -1 if the string has not been found * @since 3.0 */ private int findAndSelect(int offset, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) { if (fTarget instanceof IFindReplaceTargetExtension3) return ((IFindReplaceTargetExtension3)fTarget).findAndSelect(offset, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); else return fTarget.findAndSelect(offset, findString, forwardSearch, caseSensitive, wholeWord); } /** * Replaces the selection with <code>replaceString</code>. If * <code>regExReplace</code> is <code>true</code>, * <code>replaceString</code> is a regex replace pattern which will get * expanded if the underlying target supports it. Returns the region of the * inserted text; note that the returned selection covers the expanded * pattern in case of regex replace. * * @param replaceString the replace string (or a regex pattern) * @param regExReplace <code>true</code> if <code>replaceString</code> * is a pattern * @return the selection after replacing, i.e. the inserted text * @since 3.0 */ Point replaceSelection(String replaceString, boolean regExReplace) { if (fTarget instanceof IFindReplaceTargetExtension3) ((IFindReplaceTargetExtension3)fTarget).replaceSelection(replaceString, regExReplace); else fTarget.replaceSelection(replaceString); return fTarget.getSelection(); } /** * Returns whether the specified search string can be found using the given options. * * @param findString the string to search for * @param forwardSearch the direction of the search * @param caseSensitive should the search be case sensitive * @param wrapSearch should the search wrap to the start/end if arrived at the end/start * @param wholeWord does the search string represent a complete word * @param incremental is this an incremental search - * @param global is the search scope the whole document * @param regExSearch if <code>true</code> findString represents a regular expression * @return <code>true</code> if the search string can be found using the given options + * * @since 3.0 */ - private boolean findNext(String findString, boolean forwardSearch, boolean caseSensitive, boolean wrapSearch, boolean wholeWord, boolean incremental, boolean global, boolean regExSearch) { + private boolean findNext(String findString, boolean forwardSearch, boolean caseSensitive, boolean wrapSearch, boolean wholeWord, boolean incremental, boolean regExSearch) { if (fTarget == null) return false; Point r= null; if (incremental) r= fIncrementalBaseLocation; else r= fTarget.getSelection(); int findReplacePosition= r.x; if (forwardSearch && !fNeedsInitialFindBeforeReplace || !forwardSearch && fNeedsInitialFindBeforeReplace) findReplacePosition += r.y; fNeedsInitialFindBeforeReplace= false; int index= findIndex(findString, findReplacePosition, forwardSearch, caseSensitive, wrapSearch, wholeWord, regExSearch); if (index != -1) return true; return false; } /** * Returns the dialog's boundaries. * @return the dialog's boundaries */ private Rectangle getDialogBoundaries() { if (okToUse(getShell())) { return getShell().getBounds(); } else { return fDialogPositionInit; } } /** * Returns the dialog's history. * @return the dialog's history */ private List getFindHistory() { return fFindHistory; } // ------- accessors --------------------------------------- /** * Retrieves the string to search for from the appropriate text input field and returns it. * @return the search string */ private String getFindString() { if (okToUse(fFindField)) { return fFindField.getText(); } return ""; //$NON-NLS-1$ } /** * Returns the dialog's replace history. * @return the dialog's replace history */ private List getReplaceHistory() { return fReplaceHistory; } /** * Retrieves the replacement string from the appropriate text input field and returns it. * @return the replacement string */ private String getReplaceString() { if (okToUse(fReplaceField)) { return fReplaceField.getText(); } return ""; //$NON-NLS-1$ } // ------- init / close --------------------------------------- /** * Returns the actual selection of the find replace target. * @return the selection of the target */ private String getSelectionString() { String selection= fTarget.getSelectionText(); if (selection != null && selection.length() > 0) { int[] info= TextUtilities.indexOf(TextUtilities.DELIMITERS, selection, 0); if (info[0] > 0) return selection.substring(0, info[0]); else if (info[0] == -1) return selection; } return null; } /** * @see org.eclipse.jface.window.Window#close() */ public boolean close() { handleDialogClose(); return super.close(); } /** * Removes focus changed listener from browser and stores settings for re-open. */ private void handleDialogClose() { // remove listeners if (okToUse(fFindField)) { fFindField.removeModifyListener(fFindModifyListener); } if (fParentShell != null) { fParentShell.removeShellListener(fActivationListener); fParentShell= null; } getShell().removeShellListener(fActivationListener); // store current settings in case of re-open storeSettings(); if (fTarget != null && fTarget instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) fTarget).endSession(); setContentAssistsEnablement(false); fFindContentAssistHandler= null; fReplaceContentAssistHandler= null; fProposalPopupBackgroundColor.dispose(); fProposalPopupForegroundColor.dispose(); // prevent leaks fActiveShell= null; fTarget= null; } /** * Writes the current selection to the dialog settings. * @since 3.0 */ private void writeSelection() { if (fTarget == null) return; String selection= fTarget.getSelectionText(); if (selection == null) selection= ""; //$NON-NLS-1$ IDialogSettings s= getDialogSettings(); s.put("selection", selection); //$NON-NLS-1$ } /** * Stores the current state in the dialog settings. * @since 2.0 */ private void storeSettings() { fDialogPositionInit= getDialogBoundaries(); fWrapInit= isWrapSearch(); fWholeWordInit= isWholeWordSearch(); fCaseInit= isCaseSensitiveSearch(); fIsRegExInit= isRegExSearch(); fIncrementalInit= isIncrementalSearch(); fForwardInit= isForwardSearch(); writeConfiguration(); } /** * Initializes the string to search for and the appropriate * text inout field based on the selection found in the * action's target. */ private void initFindStringFromSelection() { if (fTarget != null && okToUse(fFindField)) { String selection= getSelectionString(); fFindField.removeModifyListener(fFindModifyListener); if (selection != null) { fFindField.setText(selection); if (!selection.equals(fTarget.getSelectionText())) { useSelectedLines(true); fGlobalRadioButton.setSelection(false); fSelectedRangeRadioButton.setSelection(true); fUseSelectedLines= true; } } else { if ("".equals(fFindField.getText())) { //$NON-NLS-1$ if (fFindHistory.size() > 0) fFindField.setText((String) fFindHistory.get(0)); else fFindField.setText(""); //$NON-NLS-1$ } } fFindField.setSelection(new Point(0, fFindField.getText().length())); fFindField.addModifyListener(fFindModifyListener); } } /** * Initializes the anchor used as starting point for incremental searching. * @since 2.0 */ private void initIncrementalBaseLocation() { if (fTarget != null && isIncrementalSearch() && !isRegExSearchAvailableAndChecked()) { fIncrementalBaseLocation= fTarget.getSelection(); } else { fIncrementalBaseLocation= new Point(0, 0); } } // ------- history --------------------------------------- /** * Retrieves and returns the option case sensitivity from the appropriate check box. * @return <code>true</code> if case sensitive */ private boolean isCaseSensitiveSearch() { if (okToUse(fCaseCheckBox)) { return fCaseCheckBox.getSelection(); } return fCaseInit; } /** * Retrieves and returns the regEx option from the appropriate check box. * * @return <code>true</code> if case sensitive * @since 3.0 */ private boolean isRegExSearch() { if (okToUse(fIsRegExCheckBox)) { return fIsRegExCheckBox.getSelection(); } return fIsRegExInit; } /** * If the target supports regular expressions search retrieves and returns * regEx option from appropriate check box. * * @return <code>true</code> if regEx is available and checked * @since 3.0 */ private boolean isRegExSearchAvailableAndChecked() { if (okToUse(fIsRegExCheckBox)) { return fIsTargetSupportingRegEx && fIsRegExCheckBox.getSelection(); } return fIsRegExInit; } /** * Retrieves and returns the option search direction from the appropriate check box. * @return <code>true</code> if searching forward */ private boolean isForwardSearch() { if (okToUse(fForwardRadioButton)) { return fForwardRadioButton.getSelection(); } return fForwardInit; } /** - * Retrieves and returns the option global scope from the appropriate check box. - * @return <code>true</code> if searching globally - * @since 2.0 - */ - private boolean isGlobalSearch() { - if (okToUse(fGlobalRadioButton)) { - return fGlobalRadioButton.getSelection(); - } - return fGlobalInit; - } - - /** * Retrieves and returns the option search whole words from the appropriate check box. * @return <code>true</code> if searching for whole words */ private boolean isWholeWordSearch() { if (okToUse(fWholeWordCheckBox)) { return fWholeWordCheckBox.getSelection(); } return fWholeWordInit; } /** * Retrieves and returns the option wrap search from the appropriate check box. * @return <code>true</code> if wrapping while searching */ private boolean isWrapSearch() { if (okToUse(fWrapCheckBox)) { return fWrapCheckBox.getSelection(); } return fWrapInit; } /** * Retrieves and returns the option incremental search from the appropriate check box. * @return <code>true</code> if incremental search * @since 2.0 */ private boolean isIncrementalSearch() { if (okToUse(fIncrementalCheckBox)) { return fIncrementalCheckBox.getSelection(); } return fIncrementalInit; } /** * Creates a button. * @param parent the parent control * @param key the key to lookup the button label * @param id the button id * @param dfltButton is this button the default button * @param listener a button pressed listener * @return the new button */ private Button makeButton(Composite parent, String key, int id, boolean dfltButton, SelectionListener listener) { String label= EditorMessages.getString(key); Button b= createButton(parent, id, label, dfltButton); b.addSelectionListener(listener); return b; } /** * Returns the status line manager of the active editor or <code>null</code> if there is no such editor. * @return the status line manager of the active editor */ private IEditorStatusLine getStatusLineManager() { IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window == null) return null; IWorkbenchPage page= window.getActivePage(); if (page == null) return null; IEditorPart editor= page.getActiveEditor(); if (editor == null) return null; return (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class); } /** * Sets the given status message in the status line. * * @param error <code>true</code> if it is an error * @param message the error message */ private void statusMessage(boolean error, String message) { fStatusLabel.setText(message); if (error) fStatusLabel.setForeground(JFaceColors.getErrorText(fStatusLabel.getDisplay())); else fStatusLabel.setForeground(null); IEditorStatusLine statusLine= getStatusLineManager(); if (statusLine != null) statusLine.setMessage(error, message, null); if (error) getShell().getDisplay().beep(); } /** * Sets the given error message in the status line. * @param message the message */ private void statusError(String message) { statusMessage(true, message); } /** * Sets the given message in the status line. * @param message the message */ private void statusMessage(String message) { statusMessage(false, message); } /** * Replaces all occurrences of the user's findString with * the replace string. Indicate to the user the number of replacements * that occur. */ private void performReplaceAll() { int replaceCount= 0; final String replaceString= getReplaceString(); final String findString= getFindString(); if (findString != null && findString.length() > 0) { class ReplaceAllRunnable implements Runnable { public int numberOfOccurrences; public void run() { - numberOfOccurrences= replaceAll(findString, replaceString == null ? "" : replaceString, isForwardSearch(), isCaseSensitiveSearch(), isWrapSearch(), isWholeWordSearch() && !isRegExSearchAvailableAndChecked(), isGlobalSearch(), isRegExSearchAvailableAndChecked()); //$NON-NLS-1$ + numberOfOccurrences= replaceAll(findString, replaceString == null ? "" : replaceString, isForwardSearch(), isCaseSensitiveSearch(), isWrapSearch(), isWholeWordSearch() && !isRegExSearchAvailableAndChecked(), isRegExSearchAvailableAndChecked()); //$NON-NLS-1$ } } try { ReplaceAllRunnable runnable= new ReplaceAllRunnable(); BusyIndicator.showWhile(fActiveShell.getDisplay(), runnable); replaceCount= runnable.numberOfOccurrences; if (replaceCount != 0) { if (replaceCount == 1) { // not plural statusMessage(EditorMessages.getString("FindReplace.Status.replacement.label")); //$NON-NLS-1$ } else { String msg= EditorMessages.getString("FindReplace.Status.replacements.label"); //$NON-NLS-1$ msg= MessageFormat.format(msg, new Object[] {String.valueOf(replaceCount)}); statusMessage(msg); } } else { statusMessage(EditorMessages.getString("FindReplace.Status.noMatch.label")); //$NON-NLS-1$ } } catch (PatternSyntaxException ex) { statusError(ex.getLocalizedMessage()); } catch (IllegalStateException ex) { // we don't keep state in this dialog } } writeSelection(); updateButtonState(); } /** * Validates the state of the find/replace target. * @return <code>true</code> if target can be changed, <code>false</code> otherwise * @since 2.1 */ private boolean validateTargetState() { if (fTarget instanceof IFindReplaceTargetExtension2) { IFindReplaceTargetExtension2 extension= (IFindReplaceTargetExtension2) fTarget; if (!extension.validateTargetState()) { statusError(EditorMessages.getString("FindReplaceDialog.read_only")); //$NON-NLS-1$ updateButtonState(); return false; } } return isEditable(); } /** * Replaces the current selection of the target with the user's * replace string. * * @return <code>true</code> if the operation was successful */ private boolean performReplaceSelection() { if (!validateTargetState()) return false; String replaceString= getReplaceString(); if (replaceString == null) replaceString= ""; //$NON-NLS-1$ boolean replaced; try { replaceSelection(replaceString, isRegExSearchAvailableAndChecked()); replaced= true; writeSelection(); } catch (PatternSyntaxException ex) { statusError(ex.getLocalizedMessage()); replaced= false; } catch (IllegalStateException ex) { replaced= false; } updateButtonState(); return replaced; } /** * Locates the user's findString in the text of the target. */ private void performSearch() { performSearch(isIncrementalSearch() && !isRegExSearchAvailableAndChecked()); } /** * Locates the user's findString in the text of the target. * * @param mustInitIncrementalBaseLocation <code>true</code> if base location must be initialized * @since 3.0 */ private void performSearch(boolean mustInitIncrementalBaseLocation) { if (mustInitIncrementalBaseLocation) initIncrementalBaseLocation(); String findString= getFindString(); if (findString != null && findString.length() > 0) { try { - boolean somethingFound= findNext(findString, isForwardSearch(), isCaseSensitiveSearch(), isWrapSearch(), isWholeWordSearch() && !isRegExSearchAvailableAndChecked(), isIncrementalSearch() && !isRegExSearchAvailableAndChecked(), isGlobalSearch(), isRegExSearchAvailableAndChecked()); + boolean somethingFound= findNext(findString, isForwardSearch(), isCaseSensitiveSearch(), isWrapSearch(), isWholeWordSearch() && !isRegExSearchAvailableAndChecked(), isIncrementalSearch() && !isRegExSearchAvailableAndChecked(), isRegExSearchAvailableAndChecked()); if (somethingFound) { statusMessage(""); //$NON-NLS-1$ } else { statusMessage(EditorMessages.getString("FindReplace.Status.noMatch.label")); //$NON-NLS-1$ } } catch (PatternSyntaxException ex) { statusError(ex.getLocalizedMessage()); } catch (IllegalStateException ex) { // we don't keep state in this dialog } } writeSelection(); updateButtonState(); } /** * Replaces all occurrences of the user's findString with * the replace string. Returns the number of replacements * that occur. * * @param findString the string to search for * @param replaceString the replacement string * @param forwardSearch the search direction * @param caseSensitive should the search be case sensitive * @param wrapSearch should search wrap to start/end if end/start is reached * @param wholeWord does the search string represent a complete word - * @param global is the search performed globally * @param regExSearch if <code>true</code> findString represents a regular expression * @return the number of occurrences + * * @since 3.0 */ - private int replaceAll(String findString, String replaceString, boolean forwardSearch, boolean caseSensitive, boolean wrapSearch, boolean wholeWord, boolean global, boolean regExSearch) { + private int replaceAll(String findString, String replaceString, boolean forwardSearch, boolean caseSensitive, boolean wrapSearch, boolean wholeWord, boolean regExSearch) { int replaceCount= 0; int findReplacePosition= 0; if (wrapSearch) { // search the whole text findReplacePosition= 0; forwardSearch= true; } else if (fTarget.getSelectionText() != null) { // the cursor is set to the end or beginning of the selected text Point selection= fTarget.getSelection(); findReplacePosition= selection.x; } if (!validateTargetState()) return replaceCount; if (fTarget instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) fTarget).setReplaceAllMode(true); try { int index= 0; while (index != -1) { index= findAndSelect(findReplacePosition, findString, forwardSearch, caseSensitive, wholeWord, regExSearch); if (index != -1) { // substring not contained from current position Point selection= replaceSelection(replaceString, regExSearch); replaceCount++; if (forwardSearch) findReplacePosition= selection.x + selection.y; else { findReplacePosition= selection.x; if (findReplacePosition == -1) break; } } } } finally { if (fTarget instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) fTarget).setReplaceAllMode(false); } return replaceCount; } // ------- UI creation --------------------------------------- /** * Attaches the given layout specification to the <code>component</code>. * * @param component the component * @param horizontalAlignment horizontal alignment * @param grabExcessHorizontalSpace grab excess horizontal space * @param verticalAlignment vertical alignment * @param grabExcessVerticalSpace grab excess vertical space */ private void setGridData(Control component, int horizontalAlignment, boolean grabExcessHorizontalSpace, int verticalAlignment, boolean grabExcessVerticalSpace) { GridData gd= new GridData(); gd.horizontalAlignment= horizontalAlignment; gd.grabExcessHorizontalSpace= grabExcessHorizontalSpace; gd.verticalAlignment= verticalAlignment; gd.grabExcessVerticalSpace= grabExcessVerticalSpace; component.setLayoutData(gd); } /** * Updates the enabled state of the buttons. */ private void updateButtonState() { updateButtonState(false); } /** * Updates the enabled state of the buttons. * * @param disableReplace <code>true</code> if replace button must be disabled * @since 3.0 */ private void updateButtonState(boolean disableReplace) { if (okToUse(getShell()) && okToUse(fFindNextButton)) { String selectedText= null; if (fTarget != null) { selectedText= fTarget.getSelectionText(); } boolean selection= (selectedText != null && selectedText.length() > 0); boolean enable= fTarget != null && (fActiveShell == fParentShell || fActiveShell == getShell()); String str= getFindString(); boolean findString= str != null && str.length() > 0 && (isRegExSearchAvailableAndChecked() || !isWholeWordSearch() || isWord(str)); fFindNextButton.setEnabled(enable && findString); fReplaceSelectionButton.setEnabled(!disableReplace && enable && isEditable() && selection && (!fNeedsInitialFindBeforeReplace || !isRegExSearchAvailableAndChecked())); fReplaceFindButton.setEnabled(!disableReplace && enable && isEditable() && findString && selection && (!fNeedsInitialFindBeforeReplace || !isRegExSearchAvailableAndChecked())); fReplaceAllButton.setEnabled(enable && isEditable() && findString); } } /** * Tests whether each character in the given * string is a letter. * * @param str * @return <code>true</code> if the given string is a word * @since 3.0 */ private boolean isWord(String str) { if (str == null) return false; BreakIterator wordIterator= BreakIterator.getWordInstance(); wordIterator.setText(str); int first= wordIterator.first(); if (first > 0) return false; return wordIterator.next() == str.length(); } /** * Updates the given combo with the given content. * @param combo combo to be updated * @param content to be put into the combo */ private void updateCombo(Combo combo, List content) { combo.removeAll(); for (int i= 0; i < content.size(); i++) { combo.add(content.get(i).toString()); } } // ------- open / reopen --------------------------------------- /** * Called after executed find/replace action to update the history. */ private void updateFindAndReplaceHistory() { updateFindHistory(); if (okToUse(fReplaceField)) { updateHistory(fReplaceField, fReplaceHistory); } } /** * Called after executed find action to update the history. */ private void updateFindHistory() { if (okToUse(fFindField)) { fFindField.removeModifyListener(fFindModifyListener); updateHistory(fFindField, fFindHistory); fFindField.addModifyListener(fFindModifyListener); } } /** * Updates the combo with the history. * @param combo to be updated * @param history to be put into the combo */ private void updateHistory(Combo combo, List history) { String findString= combo.getText(); int index= history.indexOf(findString); if (index != 0) { if (index != -1) { history.remove(index); } history.add(0, findString); updateCombo(combo, history); combo.setText(findString); } } /** * Returns whether the target is editable. * @return <code>true</code> if target is editable */ private boolean isEditable() { boolean isEditable= (fTarget == null ? false : fTarget.isEditable()); return fIsTargetEditable && isEditable; } /** * Updates this dialog because of a different target. * @param target the new target * @param isTargetEditable <code>true</code> if the new target can be modifed * @since 2.0 */ public void updateTarget(IFindReplaceTarget target, boolean isTargetEditable) { fIsTargetEditable= isTargetEditable; fNeedsInitialFindBeforeReplace= true; if (target != fTarget) { if (fTarget != null && fTarget instanceof IFindReplaceTargetExtension) ((IFindReplaceTargetExtension) fTarget).endSession(); fTarget= target; if (target != null) fIsTargetSupportingRegEx= target instanceof IFindReplaceTargetExtension3; if (fTarget != null && fTarget instanceof IFindReplaceTargetExtension) { ((IFindReplaceTargetExtension) fTarget).beginSession(); fGlobalInit= true; fGlobalRadioButton.setSelection(fGlobalInit); fSelectedRangeRadioButton.setSelection(!fGlobalInit); fUseSelectedLines= !fGlobalInit; } } if (okToUse(fIsRegExCheckBox)) fIsRegExCheckBox.setEnabled(fIsTargetSupportingRegEx); if (okToUse(fWholeWordCheckBox)) fWholeWordCheckBox.setEnabled(!isRegExSearchAvailableAndChecked()); if (okToUse(fIncrementalCheckBox)) fIncrementalCheckBox.setEnabled(!isRegExSearchAvailableAndChecked()); if (okToUse(fReplaceLabel)) { fReplaceLabel.setEnabled(isEditable()); fReplaceField.setEnabled(isEditable()); initFindStringFromSelection(); initIncrementalBaseLocation(); updateButtonState(); } // see pr 51073 fGiveFocusToFindField= true; setContentAssistsEnablement(isRegExSearchAvailableAndChecked()); } /** * Sets the parent shell of this dialog to be the given shell. * * @param shell the new parent shell */ public void setParentShell(Shell shell) { if (shell != fParentShell) { if (fParentShell != null) fParentShell.removeShellListener(fActivationListener); fParentShell= shell; fParentShell.addShellListener(fActivationListener); } fActiveShell= shell; } //--------------- configuration handling -------------- /** * Returns the dialog settings object used to share state * between several find/replace dialogs. * * @return the dialog settings to be used */ private IDialogSettings getDialogSettings() { IDialogSettings settings= TextEditorPlugin.getDefault().getDialogSettings(); fDialogSettings= settings.getSection(getClass().getName()); if (fDialogSettings == null) fDialogSettings= settings.addNewSection(getClass().getName()); return fDialogSettings; } /** * Initializes itself from the dialog settings with the same state * as at the previous invocation. */ private void readConfiguration() { IDialogSettings s= getDialogSettings(); try { int x= s.getInt("x"); //$NON-NLS-1$ int y= s.getInt("y"); //$NON-NLS-1$ fLocation= new Point(x, y); } catch (NumberFormatException e) { fLocation= null; } fWrapInit= s.getBoolean("wrap"); //$NON-NLS-1$ fCaseInit= s.getBoolean("casesensitive"); //$NON-NLS-1$ fWholeWordInit= s.getBoolean("wholeword"); //$NON-NLS-1$ fIncrementalInit= s.getBoolean("incremental"); //$NON-NLS-1$ fIsRegExInit= s.getBoolean("isRegEx"); //$NON-NLS-1$ String[] findHistory= s.getArray("findhistory"); //$NON-NLS-1$ if (findHistory != null) { List history= getFindHistory(); history.clear(); for (int i= 0; i < findHistory.length; i++) history.add(findHistory[i]); } String[] replaceHistory= s.getArray("replacehistory"); //$NON-NLS-1$ if (replaceHistory != null) { List history= getReplaceHistory(); history.clear(); for (int i= 0; i < replaceHistory.length; i++) history.add(replaceHistory[i]); } } /** * Stores its current configuration in the dialog store. */ private void writeConfiguration() { IDialogSettings s= getDialogSettings(); Point location= getShell().getLocation(); s.put("x", location.x); //$NON-NLS-1$ s.put("y", location.y); //$NON-NLS-1$ s.put("wrap", fWrapInit); //$NON-NLS-1$ s.put("casesensitive", fCaseInit); //$NON-NLS-1$ s.put("wholeword", fWholeWordInit); //$NON-NLS-1$ s.put("incremental", fIncrementalInit); //$NON-NLS-1$ s.put("isRegEx", fIsRegExInit); //$NON-NLS-1$ List history= getFindHistory(); while (history.size() > 8) history.remove(8); String[] names= new String[history.size()]; history.toArray(names); s.put("findhistory", names); //$NON-NLS-1$ history= getReplaceHistory(); while (history.size() > 8) history.remove(8); names= new String[history.size()]; history.toArray(names); s.put("replacehistory", names); //$NON-NLS-1$ } // ------------- content assistant ----------------- /** * Create a new regex content assistant. * * @return a new configured content assistant * @since 3.0 */ private SubjectControlContentAssistant createContentAssistant() { final SubjectControlContentAssistant contentAssistant= new SubjectControlContentAssistant(); contentAssistant.setRestoreCompletionProposalSize(getSettings("FindReplaceDialog.completion_proposal_size")); //$NON-NLS-1$ IContentAssistProcessor processor= new RegExContentAssistProcessor(); contentAssistant.setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); contentAssistant.enableAutoActivation(isRegExSearchAvailableAndChecked()); contentAssistant.setProposalSelectorBackground(fProposalPopupBackgroundColor); contentAssistant.setProposalSelectorForeground(fProposalPopupForegroundColor); contentAssistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE); contentAssistant.setInformationControlCreator(new IInformationControlCreator() { /* * @see org.eclipse.jface.text.IInformationControlCreator#createInformationControl(org.eclipse.swt.widgets.Shell) */ public IInformationControl createInformationControl(Shell parent) { return new DefaultInformationControl(parent); }}); return contentAssistant; } private IDialogSettings getSettings(String sectionName) { IDialogSettings pluginDialogSettings= TextEditorPlugin.getDefault().getDialogSettings(); IDialogSettings settings= pluginDialogSettings.getSection(sectionName); if (settings == null) settings= pluginDialogSettings.addNewSection(sectionName); return settings; } }
false
false
null
null
diff --git a/src/be/ibridge/kettle/trans/step/databaselookup/DatabaseLookupMeta.java b/src/be/ibridge/kettle/trans/step/databaselookup/DatabaseLookupMeta.java index 85bf4870..ab2493d1 100644 --- a/src/be/ibridge/kettle/trans/step/databaselookup/DatabaseLookupMeta.java +++ b/src/be/ibridge/kettle/trans/step/databaselookup/DatabaseLookupMeta.java @@ -1,916 +1,921 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** info@kettle.be ** ** ** **********************************************************************/ /* * Created on 26-apr-2003 * */ package be.ibridge.kettle.trans.step.databaselookup; import java.util.ArrayList; import java.util.Hashtable; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.CheckResult; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.trans.DatabaseImpact; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStepMeta; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepDialogInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; public class DatabaseLookupMeta extends BaseStepMeta implements StepMetaInterface { /** what's the lookup schema name? */ private String schemaName; /** what's the lookup table? */ private String tablename; /** database connection */ private DatabaseMeta databaseMeta; /** which field in input stream to compare with? */ private String streamKeyField1[]; /** Extra field for between... */ private String streamKeyField2[]; /** Comparator: =, <>, BETWEEN, ... */ private String keyCondition[]; /** field in table */ private String tableKeyField[]; /** return these field values after lookup */ private String returnValueField[]; /** new name for value ... */ private String returnValueNewName[]; /** default value in case not found... */ private String returnValueDefault[]; /** type of default value */ private int returnValueDefaultType[]; /** order by clause... */ private String orderByClause; /** Cache values we look up --> faster */ private boolean cached; /** Limit the cache size to this! */ private int cacheSize; /** Have the lookup fail if multiple results were found, renders the orderByClause useless */ private boolean failingOnMultipleResults; /** Have the lookup eat the incoming row when nothing gets found */ private boolean eatingRowOnLookupFailure; public DatabaseLookupMeta() { super(); // allocate BaseStepMeta } /** * @return Returns the cached. */ public boolean isCached() { return cached; } /** * @param cached The cached to set. */ public void setCached(boolean cached) { this.cached = cached; } /** * @return Returns the cacheSize. */ public int getCacheSize() { return cacheSize; } /** * @param cacheSize The cacheSize to set. */ public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } /** * @return Returns the database. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * @param database The database to set. */ public void setDatabaseMeta(DatabaseMeta database) { this.databaseMeta = database; } /** * @return Returns the keyCondition. */ public String[] getKeyCondition() { return keyCondition; } /** * @param keyCondition The keyCondition to set. */ public void setKeyCondition(String[] keyCondition) { this.keyCondition = keyCondition; } /** * @return Returns the orderByClause. */ public String getOrderByClause() { return orderByClause; } /** * @param orderByClause The orderByClause to set. */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * @return Returns the returnValueDefault. */ public String[] getReturnValueDefault() { return returnValueDefault; } /** * @param returnValueDefault The returnValueDefault to set. */ public void setReturnValueDefault(String[] returnValueDefault) { this.returnValueDefault = returnValueDefault; } /** * @return Returns the returnValueDefaultType. */ public int[] getReturnValueDefaultType() { return returnValueDefaultType; } /** * @param returnValueDefaultType The returnValueDefaultType to set. */ public void setReturnValueDefaultType(int[] returnValueDefaultType) { this.returnValueDefaultType = returnValueDefaultType; } /** * @return Returns the returnValueField. */ public String[] getReturnValueField() { return returnValueField; } /** * @param returnValueField The returnValueField to set. */ public void setReturnValueField(String[] returnValueField) { this.returnValueField = returnValueField; } /** * @return Returns the returnValueNewName. */ public String[] getReturnValueNewName() { return returnValueNewName; } /** * @param returnValueNewName The returnValueNewName to set. */ public void setReturnValueNewName(String[] returnValueNewName) { this.returnValueNewName = returnValueNewName; } /** * @return Returns the streamKeyField1. */ public String[] getStreamKeyField1() { return streamKeyField1; } /** * @param streamKeyField1 The streamKeyField1 to set. */ public void setStreamKeyField1(String[] streamKeyField1) { this.streamKeyField1 = streamKeyField1; } /** * @return Returns the streamKeyField2. */ public String[] getStreamKeyField2() { return streamKeyField2; } /** * @param streamKeyField2 The streamKeyField2 to set. */ public void setStreamKeyField2(String[] streamKeyField2) { this.streamKeyField2 = streamKeyField2; } /** * @return Returns the tableKeyField. */ public String[] getTableKeyField() { return tableKeyField; } /** * @param tableKeyField The tableKeyField to set. */ public void setTableKeyField(String[] tableKeyField) { this.tableKeyField = tableKeyField; } /** * @return Returns the tablename. */ public String getTablename() { return tablename; } /** * @param tablename The tablename to set. */ public void setTablename(String tablename) { this.tablename = tablename; } /** * @return Returns the failOnMultipleResults. */ public boolean isFailingOnMultipleResults() { return failingOnMultipleResults; } /** * @param failOnMultipleResults The failOnMultipleResults to set. */ public void setFailingOnMultipleResults(boolean failOnMultipleResults) { this.failingOnMultipleResults = failOnMultipleResults; } public void loadXML(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException { streamKeyField1=null; returnValueField=null; readData(stepnode, databases); } public void allocate(int nrkeys, int nrvalues) { streamKeyField1 = new String[nrkeys]; tableKeyField = new String[nrkeys]; keyCondition = new String[nrkeys]; streamKeyField2 = new String[nrkeys]; returnValueField = new String[nrvalues]; returnValueNewName = new String[nrvalues]; returnValueDefault = new String[nrvalues]; returnValueDefaultType = new int[nrvalues]; } public Object clone() { DatabaseLookupMeta retval = (DatabaseLookupMeta)super.clone(); int nrkeys = streamKeyField1.length; int nrvalues = returnValueField.length; retval.allocate(nrkeys, nrvalues); for (int i=0;i<nrkeys;i++) { retval.streamKeyField1[i] = streamKeyField1[i]; retval.tableKeyField[i] = tableKeyField[i]; retval.keyCondition[i] = keyCondition[i]; retval.streamKeyField2[i] = streamKeyField2[i]; } for (int i=0;i<nrvalues;i++) { retval.returnValueField[i] = returnValueField[i]; retval.returnValueNewName[i] = returnValueNewName[i]; retval.returnValueDefault[i] = returnValueDefault[i]; retval.returnValueDefaultType[i] = returnValueDefaultType[i]; } return retval; } private void readData(Node stepnode, ArrayList databases) throws KettleXMLException { try { String dtype; String csize; String con = XMLHandler.getTagValue(stepnode, "connection"); //$NON-NLS-1$ databaseMeta = DatabaseMeta.findDatabase(databases, con); cached = "Y".equalsIgnoreCase(XMLHandler.getTagValue(stepnode, "cache")); //$NON-NLS-1$ //$NON-NLS-2$ csize = XMLHandler.getTagValue(stepnode, "cache_size"); //$NON-NLS-1$ cacheSize=Const.toInt(csize, 0); schemaName = XMLHandler.getTagValue(stepnode, "lookup", "schema"); //$NON-NLS-1$ //$NON-NLS-2$ tablename = XMLHandler.getTagValue(stepnode, "lookup", "table"); //$NON-NLS-1$ //$NON-NLS-2$ Node lookup = XMLHandler.getSubNode(stepnode, "lookup"); //$NON-NLS-1$ int nrkeys = XMLHandler.countNodes(lookup, "key"); //$NON-NLS-1$ int nrvalues = XMLHandler.countNodes(lookup, "value"); //$NON-NLS-1$ allocate(nrkeys, nrvalues); for (int i=0;i<nrkeys;i++) { Node knode = XMLHandler.getSubNodeByNr(lookup, "key", i); //$NON-NLS-1$ streamKeyField1 [i] = XMLHandler.getTagValue(knode, "name"); //$NON-NLS-1$ tableKeyField [i] = XMLHandler.getTagValue(knode, "field"); //$NON-NLS-1$ keyCondition[i] = XMLHandler.getTagValue(knode, "condition"); //$NON-NLS-1$ if (keyCondition[i]==null) keyCondition[i]="="; //$NON-NLS-1$ streamKeyField2 [i] = XMLHandler.getTagValue(knode, "name2"); //$NON-NLS-1$ } for (int i=0;i<nrvalues;i++) { Node vnode = XMLHandler.getSubNodeByNr(lookup, "value", i); //$NON-NLS-1$ returnValueField[i] = XMLHandler.getTagValue(vnode, "name"); //$NON-NLS-1$ returnValueNewName[i] = XMLHandler.getTagValue(vnode, "rename"); //$NON-NLS-1$ if (returnValueNewName[i]==null) returnValueNewName[i]=returnValueField[i]; // default: the same name! returnValueDefault[i] = XMLHandler.getTagValue(vnode, "default"); //$NON-NLS-1$ dtype = XMLHandler.getTagValue(vnode, "type"); //$NON-NLS-1$ returnValueDefaultType[i] = Value.getType(dtype); if (returnValueDefaultType[i]<0) { //logError("unknown default value type: "+dtype+" for value "+value[i]+", default to type: String!"); returnValueDefaultType[i]=Value.VALUE_TYPE_STRING; } } orderByClause = XMLHandler.getTagValue(lookup, "orderby"); //Optional, can by null //$NON-NLS-1$ failingOnMultipleResults = "Y".equalsIgnoreCase(XMLHandler.getTagValue(lookup, "fail_on_multiple")); //$NON-NLS-1$ //$NON-NLS-2$ eatingRowOnLookupFailure = "Y".equalsIgnoreCase(XMLHandler.getTagValue(lookup, "eat_row_on_failure")); //$NON-NLS-1$ //$NON-NLS-2$ } catch(Exception e) { throw new KettleXMLException(Messages.getString("DatabaseLookupMeta.ERROR0001.UnableToLoadStepFromXML"), e); //$NON-NLS-1$ } } public void setDefault() { streamKeyField1 = null; returnValueField = null; databaseMeta = null; cached = false; cacheSize = 0; schemaName = ""; //$NON-NLS-1$ tablename = Messages.getString("DatabaseLookupMeta.Default.TableName"); //$NON-NLS-1$ int nrkeys = 0; int nrvalues = 0; allocate(nrkeys, nrvalues); for (int i=0;i<nrkeys;i++) { tableKeyField[i] = Messages.getString("DatabaseLookupMeta.Default.KeyFieldPrefix"); //$NON-NLS-1$ keyCondition[i] = Messages.getString("DatabaseLookupMeta.Default.KeyCondition"); //$NON-NLS-1$ streamKeyField1[i] = Messages.getString("DatabaseLookupMeta.Default.KeyStreamField1"); //$NON-NLS-1$ streamKeyField2[i] = Messages.getString("DatabaseLookupMeta.Default.KeyStreamField2"); //$NON-NLS-1$ } for (int i=0;i<nrvalues;i++) { returnValueField[i]=Messages.getString("DatabaseLookupMeta.Default.ReturnFieldPrefix")+i; //$NON-NLS-1$ returnValueNewName[i]=Messages.getString("DatabaseLookupMeta.Default.ReturnNewNamePrefix")+i; //$NON-NLS-1$ returnValueDefault[i]=Messages.getString("DatabaseLookupMeta.Default.ReturnDefaultValuePrefix")+i; //$NON-NLS-1$ returnValueDefaultType[i]=Value.VALUE_TYPE_STRING; } orderByClause = ""; //$NON-NLS-1$ failingOnMultipleResults = false; eatingRowOnLookupFailure = false; } public Row getFields(Row r, String name, Row info) { Row row; if (r==null) row=new Row(); // give back values else row=r; // add to the existing row of values... if (info==null) { for (int i=0;i<returnValueNewName.length;i++) { Value v=new Value(returnValueNewName[i], returnValueDefaultType[i]); v.setOrigin(name); row.addValue(v); } } else { for (int i=0;i<returnValueNewName.length;i++) { Value v=info.searchValue(returnValueField[i]); if (v!=null) { v.setName(returnValueNewName[i]); v.setOrigin(name); row.addValue(v); } } } return row; } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" "+XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" "+XMLHandler.addTagValue("cache", cached)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("cache_size", cacheSize)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" <lookup>"+Const.CR); //$NON-NLS-1$ retval.append(" "+XMLHandler.addTagValue("schema", schemaName)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("table", tablename)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("orderby", orderByClause)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("fail_on_multiple", failingOnMultipleResults)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("eat_row_on_failure", eatingRowOnLookupFailure)); //$NON-NLS-1$ //$NON-NLS-2$ for (int i=0;i<streamKeyField1.length;i++) { retval.append(" <key>"+Const.CR); //$NON-NLS-1$ retval.append(" "+XMLHandler.addTagValue("name", streamKeyField1[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("field", tableKeyField[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("condition", keyCondition[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("name2", streamKeyField2[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </key>"+Const.CR); //$NON-NLS-1$ } for (int i=0;i<returnValueField.length;i++) { retval.append(" <value>"+Const.CR); //$NON-NLS-1$ retval.append(" "+XMLHandler.addTagValue("name", returnValueField[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("rename", returnValueNewName[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("default", returnValueDefault[i])); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" "+XMLHandler.addTagValue("type", Value.getTypeDesc(returnValueDefaultType[i]))); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </value>"+Const.CR); //$NON-NLS-1$ } retval.append(" </lookup>"+Const.CR); //$NON-NLS-1$ return retval.toString(); } public void readRep(Repository rep, long id_step, ArrayList databases, Hashtable counters) throws KettleException { try { long id_connection = rep.getStepAttributeInteger(id_step, "id_connection"); //$NON-NLS-1$ databaseMeta = DatabaseMeta.findDatabase( databases, id_connection); cached = rep.getStepAttributeBoolean(id_step, "cache"); //$NON-NLS-1$ cacheSize = (int)rep.getStepAttributeInteger(id_step, "cache_size"); //$NON-NLS-1$ schemaName = rep.getStepAttributeString (id_step, "lookup_schema"); //$NON-NLS-1$ tablename = rep.getStepAttributeString (id_step, "lookup_table"); //$NON-NLS-1$ orderByClause = rep.getStepAttributeString (id_step, "lookup_orderby"); //$NON-NLS-1$ failingOnMultipleResults = rep.getStepAttributeBoolean(id_step, "fail_on_multiple"); //$NON-NLS-1$ eatingRowOnLookupFailure = rep.getStepAttributeBoolean(id_step, "eat_row_on_failure"); //$NON-NLS-1$ int nrkeys = rep.countNrStepAttributes(id_step, "lookup_key_name"); //$NON-NLS-1$ int nrvalues = rep.countNrStepAttributes(id_step, "return_value_name"); //$NON-NLS-1$ allocate(nrkeys, nrvalues); for (int i=0;i<nrkeys;i++) { streamKeyField1[i] = rep.getStepAttributeString(id_step, i, "lookup_key_name"); //$NON-NLS-1$ tableKeyField[i] = rep.getStepAttributeString(id_step, i, "lookup_key_field"); //$NON-NLS-1$ keyCondition[i] = rep.getStepAttributeString(id_step, i, "lookup_key_condition"); //$NON-NLS-1$ streamKeyField2[i] = rep.getStepAttributeString(id_step, i, "lookup_key_name2"); //$NON-NLS-1$ } for (int i=0;i<nrvalues;i++) { returnValueField[i] = rep.getStepAttributeString (id_step, i, "return_value_name"); //$NON-NLS-1$ returnValueNewName[i] = rep.getStepAttributeString (id_step, i, "return_value_rename"); //$NON-NLS-1$ returnValueDefault[i] = rep.getStepAttributeString (id_step, i, "return_value_default"); //$NON-NLS-1$ returnValueDefaultType[i] = Value.getType( rep.getStepAttributeString (id_step, i, "return_value_type") ); //$NON-NLS-1$ } } catch(Exception e) { throw new KettleException(Messages.getString("DatabaseLookupMeta.ERROR0002.UnexpectedErrorReadingFromTheRepository"), e); //$NON-NLS-1$ } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "id_connection", databaseMeta==null?-1:databaseMeta.getID()); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "cache", cached); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "cache_size", cacheSize); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "lookup_schema", schemaName); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "lookup_table", tablename); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "lookup_orderby", orderByClause); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "fail_on_multiple", failingOnMultipleResults); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, "eat_row_on_failure", eatingRowOnLookupFailure); //$NON-NLS-1$ for (int i=0;i<streamKeyField1.length;i++) { rep.saveStepAttribute(id_transformation, id_step, i, "lookup_key_name", streamKeyField1[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "lookup_key_field", tableKeyField[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "lookup_key_condition", keyCondition[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "lookup_key_name2", streamKeyField2[i]); //$NON-NLS-1$ } for (int i=0;i<returnValueField.length;i++) { rep.saveStepAttribute(id_transformation, id_step, i, "return_value_name", returnValueField[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "return_value_rename", returnValueNewName[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "return_value_default", returnValueDefault[i]); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "return_value_type", Value.getTypeDesc(returnValueDefaultType[i])); //$NON-NLS-1$ } // Also, save the step-database relationship! if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getID()); } catch(Exception e) { throw new KettleException(Messages.getString("DatabaseLookupMeta.ERROR0003.UnableToSaveStepToRepository")+id_step, e); //$NON-NLS-1$ } } public void check(ArrayList remarks, StepMeta stepinfo, Row prev, String input[], String output[], Row info) { CheckResult cr; String error_message = ""; //$NON-NLS-1$ if (databaseMeta!=null) { Database db = new Database(databaseMeta); databases = new Database[] { db }; // Keep track of this one for cancelQuery try { db.connect(); if (!Const.isEmpty(tablename)) { boolean first=true; boolean error_found=false; error_message = ""; //$NON-NLS-1$ String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tablename); Row r = db.getTableFields( schemaTable ); if (r!=null) { // Check the keys used to do the lookup... for (int i=0;i<tableKeyField.length;i++) { String lufield = tableKeyField[i]; Value v = r.searchValue(lufield); if (v==null) { if (first) { first=false; error_message+=Messages.getString("DatabaseLookupMeta.Check.MissingCompareFieldsInLookupTable")+Const.CR; //$NON-NLS-1$ } error_found=true; error_message+="\t\t"+lufield+Const.CR; //$NON-NLS-1$ } } if (error_found) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DatabaseLookupMeta.Check.AllLookupFieldsFoundInTable"), stepinfo); //$NON-NLS-1$ } remarks.add(cr); // Also check the returned values! for (int i=0;i<returnValueField.length;i++) { String lufield = returnValueField[i]; Value v = r.searchValue(lufield); if (v==null) { if (first) { first=false; error_message+=Messages.getString("DatabaseLookupMeta.Check.MissingReturnFieldsInLookupTable")+Const.CR; //$NON-NLS-1$ } error_found=true; error_message+="\t\t"+lufield+Const.CR; //$NON-NLS-1$ } } if (error_found) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DatabaseLookupMeta.Check.AllReturnFieldsFoundInTable"), stepinfo); //$NON-NLS-1$ } remarks.add(cr); } else { error_message=Messages.getString("DatabaseLookupMeta.Check.CouldNotReadTableInfo"); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } } // Look up fields in the input stream <prev> if (prev!=null && prev.size()>0) { boolean first=true; error_message = ""; //$NON-NLS-1$ boolean error_found = false; for (int i=0;i<streamKeyField1.length;i++) { Value v = prev.searchValue(streamKeyField1[i]); if (v==null) { if (first) { first=false; error_message+=Messages.getString("DatabaseLookupMeta.Check.MissingFieldsNotFoundInInput")+Const.CR; //$NON-NLS-1$ } error_found=true; error_message+="\t\t"+streamKeyField1[i]+Const.CR; //$NON-NLS-1$ } } if (error_found) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DatabaseLookupMeta.Check.AllFieldsFoundInInput"), stepinfo); //$NON-NLS-1$ } remarks.add(cr); } else { error_message=Messages.getString("DatabaseLookupMeta.Check.CouldNotReadFromPreviousSteps")+Const.CR; //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } } catch(KettleDatabaseException dbe) { error_message = Messages.getString("DatabaseLookupMeta.Check.DatabaseErrorWhileChecking")+dbe.getMessage(); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } finally { db.disconnect(); } } else { error_message = Messages.getString("DatabaseLookupMeta.Check.MissingConnectionError"); //$NON-NLS-1$ cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, error_message, stepinfo); remarks.add(cr); } // See if we have input streams leading to this step! if (input.length>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, Messages.getString("DatabaseLookupMeta.Check.StepIsReceivingInfoFromOtherSteps"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, Messages.getString("DatabaseLookupMeta.Check.NoInputReceivedFromOtherSteps"), stepinfo); //$NON-NLS-1$ remarks.add(cr); } } public Row getTableFields() { LogWriter log = LogWriter.getInstance(); Row fields = null; if (databaseMeta!=null) { Database db = new Database(databaseMeta); databases = new Database[] { db }; // Keep track of this one for cancelQuery try { db.connect(); String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tablename); fields = db.getTableFields(schemaTable); } catch(KettleDatabaseException dbe) { log.logError(toString(), Messages.getString("DatabaseLookupMeta.ERROR0004.ErrorGettingTableFields")+dbe.getMessage()); //$NON-NLS-1$ } finally { db.disconnect(); } } return fields; } public StepDialogInterface getDialog(Shell shell, StepMetaInterface info, TransMeta transMeta, String name) { return new DatabaseLookupDialog(shell, info, transMeta, name); } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new DatabaseLookup(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new DatabaseLookupData(); } public void analyseImpact(ArrayList impact, TransMeta transMeta, StepMeta stepinfo, Row prev, String input[], String output[], Row info) { // The keys are read-only... for (int i=0;i<streamKeyField1.length;i++) { Value v = prev.searchValue(streamKeyField1[i]); DatabaseImpact ii = new DatabaseImpact ( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepinfo.getName(), databaseMeta.getDatabaseName(), tablename, tableKeyField[i], streamKeyField1[i], v!=null?v.getOrigin():"?", //$NON-NLS-1$ "", //$NON-NLS-1$ Messages.getString("DatabaseLookupMeta.Impact.Key") //$NON-NLS-1$ ); impact.add(ii); } // The Return fields are read-only too... for (int i=0;i<returnValueField.length;i++) { DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepinfo.getName(), databaseMeta.getDatabaseName(), tablename, returnValueField[i], "", //$NON-NLS-1$ "", //$NON-NLS-1$ "", //$NON-NLS-1$ Messages.getString("DatabaseLookupMeta.Impact.ReturnValue") //$NON-NLS-1$ ); impact.add(ii); } } public DatabaseMeta[] getUsedDatabaseConnections() { if (databaseMeta!=null) { return new DatabaseMeta[] { databaseMeta }; } else { return super.getUsedDatabaseConnections(); } } /** * @return Returns the eatingRowOnLookupFailure. */ public boolean isEatingRowOnLookupFailure() { return eatingRowOnLookupFailure; } /** * @param eatingRowOnLookupFailure The eatingRowOnLookupFailure to set. */ public void setEatingRowOnLookupFailure(boolean eatingRowOnLookupFailure) { this.eatingRowOnLookupFailure = eatingRowOnLookupFailure; } /** * @return the schemaName */ public String getSchemaName() { return schemaName; } /** * @param schemaName the schemaName to set */ public void setSchemaName(String schemaName) { this.schemaName = schemaName; } + + public boolean supportsErrorHandling() + { + return true; + } }
true
false
null
null
diff --git a/src/java/org/wings/SDefaultListModel.java b/src/java/org/wings/SDefaultListModel.java index 3622c0ca..eeb9a1cc 100644 --- a/src/java/org/wings/SDefaultListModel.java +++ b/src/java/org/wings/SDefaultListModel.java @@ -1,64 +1,82 @@ /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS 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. * * Please see COPYING for the complete licence. */ package org.wings; import javax.swing.*; import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; import java.util.List; /** * Default implementation of a {@link ListModel}. * * @author <a href="mailto:haaf@mercatis.de">Armin Haaf</a> * @version $Revision$ */ public class SDefaultListModel extends AbstractListModel { protected final ArrayList data = new ArrayList(2); public SDefaultListModel(List d) { data.clear(); if (d != null) { for (int i = 0; i < d.size(); i++) data.add(d.get(i)); } } public SDefaultListModel(Object[] d) { data.clear(); if (d != null) { for (int i = 0; i < d.length; i++) data.add(d[i]); } } public SDefaultListModel() { + // default constructor } public int getSize() { return data.size(); } public Object getElementAt(int i) { return data.get(i); } + public int indexOf(Object element) { + return data.indexOf(element); + } + + public Enumeration elements() { + return Collections.enumeration(data); + } + + public void clear() { + data.clear(); + } + + public void addElement(Object element) { + data.add(element); + } } diff --git a/src/java/org/wings/plaf/css/DialogCG.java b/src/java/org/wings/plaf/css/DialogCG.java index 9b1b109e..a4184f0d 100644 --- a/src/java/org/wings/plaf/css/DialogCG.java +++ b/src/java/org/wings/plaf/css/DialogCG.java @@ -1,110 +1,110 @@ /* * $Id$ * Copyright 2000,2005 wingS development team. * * This file is part of wingS (http://www.j-wings.org). * * wingS 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. * * Please see COPYING for the complete licence. */ package org.wings.plaf.css; import org.wings.SComponent; import org.wings.SDialog; import org.wings.SIcon; import org.wings.event.SInternalFrameEvent; import org.wings.io.Device; import org.wings.resource.ResourceManager; import java.io.IOException; public class DialogCG extends FormCG implements org.wings.plaf.DialogCG { /** * */ private static final long serialVersionUID = 1L; protected static final String WINDOWICON_CLASSNAME = "WindowIcon"; protected static final String BUTTONICON_CLASSNAME = "WindowButton"; private SIcon closeIcon; /** * Initialize properties from config */ public DialogCG() { setCloseIcon((SIcon) ResourceManager.getObject("DialogCG.closeIcon", SIcon.class)); } protected void writeIcon(Device device, SIcon icon, String cssClass) throws IOException { device.print("<img"); if (cssClass != null) { device.print(" class=\""); device.print(cssClass); device.print("\""); } Utils.optAttribute(device, "src", icon.getURL()); Utils.optAttribute(device, "width", icon.getIconWidth()); Utils.optAttribute(device, "height", icon.getIconHeight()); device.print(" alt=\""); device.print(icon.getIconTitle()); device.print("\"/>"); } protected void writeWindowIcon(Device device, SDialog frame, int event, SIcon icon, String cssClass) throws IOException { Utils.printButtonStart(device, frame, Integer.toString(event), true, frame.getShowAsFormComponent()); device.print(">"); writeIcon(device, icon, null); Utils.printButtonEnd(device, frame, Integer.toString(event), true); } public void writeInternal(final Device device, final SComponent _c) throws IOException { SDialog frame = (SDialog)_c; - writeDivPrefix(device, frame); + writeTablePrefix(device, frame); writeWindowBar(device, frame); device.print("<div class=\"WindowContent\">"); super.writeInternal(device, _c); device.print("</div>"); - writeDivSuffix(device, frame); + writeTableSuffix(device, frame); } protected void writeWindowBar(final Device device, SDialog frame) throws IOException { String text = frame.getTitle(); if (text == null) text = "wingS"; device.print("<div class=\"WindowBar\">"); // frame is rendered in desktopPane // these following icons will be floated to the right by the style sheet... if (frame.isClosable() && closeIcon != null) { writeWindowIcon(device, frame, SInternalFrameEvent.INTERNAL_FRAME_CLOSED, closeIcon, BUTTONICON_CLASSNAME); } device.print("<div class=\"WindowBar_title\">"); // float right end if (frame.getIcon() != null) { writeIcon(device, frame.getIcon(), WINDOWICON_CLASSNAME); } device.print(text); device.print("</div>"); device.print("</div>"); } public SIcon getCloseIcon() { return closeIcon; } public void setCloseIcon(SIcon closeIcon) { this.closeIcon = closeIcon; } }
false
false
null
null
diff --git a/xwords4/android/XWords4/src/org/eehouse/android/xw4/BoardActivity.java b/xwords4/android/XWords4/src/org/eehouse/android/xw4/BoardActivity.java index a4eaf4f2b..76d80e689 100644 --- a/xwords4/android/XWords4/src/org/eehouse/android/xw4/BoardActivity.java +++ b/xwords4/android/XWords4/src/org/eehouse/android/xw4/BoardActivity.java @@ -1,1796 +1,1808 @@ /* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */ /* * Copyright 2009 - 2012 by Eric House (xwords@eehouse.org). All * rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.eehouse.android.xw4; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.view.MenuInflater; import android.view.KeyEvent; import android.view.Window; import android.os.Handler; import android.os.Message; import android.content.Intent; import java.util.concurrent.Semaphore; import java.util.ArrayList; import java.util.Iterator; import android.app.Dialog; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import junit.framework.Assert; import android.content.res.Configuration; import android.content.pm.ActivityInfo; import org.eehouse.android.xw4.jni.*; import org.eehouse.android.xw4.jni.JNIThread.*; import org.eehouse.android.xw4.jni.CurGameInfo.DeviceRole; public class BoardActivity extends XWActivity implements TransportProcs.TPMsgHandler, View.OnClickListener { public static final String INTENT_KEY_CHAT = "chat"; private static final int DLG_OKONLY = DlgDelegate.DIALOG_LAST + 1; private static final int DLG_BADWORDS = DLG_OKONLY + 1; private static final int QUERY_REQUEST_BLK = DLG_OKONLY + 2; private static final int QUERY_INFORM_BLK = DLG_OKONLY + 3; private static final int PICK_TILE_REQUESTBLANK_BLK = DLG_OKONLY + 4; private static final int ASK_PASSWORD_BLK = DLG_OKONLY + 5; private static final int DLG_RETRY = DLG_OKONLY + 6; private static final int QUERY_ENDGAME = DLG_OKONLY + 7; private static final int DLG_DELETED = DLG_OKONLY + 8; private static final int DLG_INVITE = DLG_OKONLY + 9; private static final int DLG_SCORES_BLK = DLG_OKONLY + 10; private static final int DLG_LOOKUP = DLG_OKONLY + 11; private static final int PICK_TILE_REQUESTTRAY_BLK = DLG_OKONLY + 12; private static final int CHAT_REQUEST = 1; private static final int BT_INVITE_RESULT = 2; private static final int SCREEN_ON_TIME = 10 * 60 * 1000; // 10 mins private static final int UNDO_LAST_ACTION = 1; private static final int LAUNCH_INVITE_ACTION = 2; private static final int SYNC_ACTION = 3; private static final int COMMIT_ACTION = 4; private static final int SHOW_EXPL_ACTION = 5; private static final int PREV_HINT_ACTION = 6; private static final int NEXT_HINT_ACTION = 7; private static final int JUGGLE_ACTION = 8; private static final int FLIP_ACTION = 9; private static final int ZOOM_ACTION = 10; private static final int UNDO_ACTION = 11; private static final int CHAT_ACTION = 12; private static final int START_TRADE_ACTION = 13; private static final int LOOKUP_ACTION = 14; private static final int BUTTON_BROWSE_ACTION = 15; private static final int VALUES_ACTION = 16; private static final int BT_PICK_ACTION = 17; private static final String DLG_TITLE = "DLG_TITLE"; private static final String DLG_TITLESTR = "DLG_TITLESTR"; private static final String DLG_BYTES = "DLG_BYTES"; private static final String ROOM = "ROOM"; private static final String PWDNAME = "PWDNAME"; private static final String TOASTSTR = "TOASTSTR"; private static final String WORDS = "WORDS"; private BoardView m_view; private int m_jniGamePtr; private GameUtils.GameLock m_gameLock; private CurGameInfo m_gi; private CommsTransport m_xport; private Handler m_handler = null; private TimerRunnable[] m_timers; private Runnable m_screenTimer; private long m_rowid; private Toolbar m_toolbar; private View m_tradeButtons; private Button m_exchCommmitButton; private Button m_exchCancelButton; private ArrayList<String> m_pendingChats = new ArrayList<String>(); private String m_dlgBytes = null; private EditText m_passwdEdit = null; private LinearLayout m_passwdLyt = null; private int m_dlgTitle; private String m_dlgTitleStr; private String[] m_texts; + private String[] m_btDevs; private String m_curTiles; private boolean m_canUndoTiles; private boolean m_firingPrefs; private JNIUtils m_jniu; private boolean m_volKeysZoom; private boolean m_inTrade; // save this in bundle? private BoardUtilCtxt m_utils; private int m_nMissingPlayers = -1; private int m_invitesPending; + private boolean m_haveAskedMissing = false; // call startActivityForResult synchronously private Semaphore m_forResultWait = new Semaphore(0); private int m_resultCode; private Thread m_blockingThread; private JNIThread m_jniThread; private JNIThread.GameStateInfo m_gsi; private boolean m_blockingDlgPosted = false; private String m_room; private String m_toastStr; private String[] m_words; private String m_pwdName; private int m_missing; private boolean m_haveInvited = false; private static BoardActivity s_this = null; private static Object s_thisLocker = new Object(); public static boolean feedMessage( int gameID, byte[] msg, CommsAddrRec retAddr ) { boolean delivered = false; synchronized( s_thisLocker ) { if ( null != s_this ) { Assert.assertNotNull( s_this.m_gi ); Assert.assertNotNull( s_this.m_gameLock ); Assert.assertNotNull( s_this.m_jniThread ); if ( gameID == s_this.m_gi.gameID ) { s_this.m_jniThread.handle( JNICmd.CMD_RECEIVE, msg, retAddr ); delivered = true; } } } return delivered; } private static void setThis( BoardActivity self ) { synchronized( s_thisLocker ) { Assert.assertNull( s_this ); s_this = self; } } private static void clearThis() { synchronized( s_thisLocker ) { Assert.assertNotNull( s_this ); s_this = null; } } public class TimerRunnable implements Runnable { private int m_why; private int m_when; private int m_handle; private TimerRunnable( int why, int when, int handle ) { m_why = why; m_when = when; m_handle = handle; } public void run() { m_timers[m_why] = null; if ( null != m_jniThread ) { m_jniThread.handleBkgrnd( JNICmd.CMD_TIMER_FIRED, m_why, m_when, m_handle ); } } } @Override protected Dialog onCreateDialog( final int id ) { Dialog dialog = super.onCreateDialog( id ); if ( null == dialog ) { DialogInterface.OnClickListener lstnr; AlertDialog.Builder ab; switch ( id ) { case DLG_OKONLY: case DLG_BADWORDS: case DLG_RETRY: ab = new AlertDialog.Builder( this ) .setTitle( m_dlgTitle ) .setMessage( m_dlgBytes ) .setPositiveButton( R.string.button_ok, null ); if ( DLG_RETRY == id ) { lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dlg, int whichButton ) { m_jniThread.handle( JNIThread.JNICmd.CMD_RESET ); } }; ab.setNegativeButton( R.string.button_retry, lstnr ); } dialog = ab.create(); Utils.setRemoveOnDismiss( this, dialog, id ); break; case DLG_DELETED: ab = new AlertDialog.Builder( BoardActivity.this ) .setTitle( R.string.query_title ) .setMessage( R.string.msg_dev_deleted ) .setPositiveButton( R.string.button_ok, null ); lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dlg, int whichButton ) { waitCloseGame( false ); GameUtils.deleteGame( BoardActivity.this, m_rowid, false ); finish(); } }; ab.setNegativeButton( R.string.button_discard, lstnr ); dialog = ab.create(); break; case QUERY_REQUEST_BLK: case QUERY_INFORM_BLK: case DLG_SCORES_BLK: ab = new AlertDialog.Builder( this ) .setMessage( m_dlgBytes ); if ( 0 != m_dlgTitle ) { ab.setTitle( m_dlgTitle ); } lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { m_resultCode = 1; } }; ab.setPositiveButton( QUERY_REQUEST_BLK == id ? R.string.button_yes : R.string.button_ok, lstnr ); if ( QUERY_REQUEST_BLK == id ) { lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { m_resultCode = 0; } }; ab.setNegativeButton( R.string.button_no, lstnr ); } else if ( DLG_SCORES_BLK == id ) { if ( null != m_words && m_words.length > 0 ) { String buttonTxt; if ( m_words.length == 1 ) { buttonTxt = Utils.format( this, R.string.button_lookupf, m_words[0] ); } else { buttonTxt = getString( R.string.button_lookup ); } lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { showNotAgainDlgThen( R.string. not_again_lookup, R.string. key_na_lookup, LOOKUP_ACTION ); } }; ab.setNegativeButton( buttonTxt, lstnr ); } } dialog = ab.create(); dialog.setOnDismissListener( makeODLforBlocking( id ) ); break; case PICK_TILE_REQUESTBLANK_BLK: case PICK_TILE_REQUESTTRAY_BLK: ab = new AlertDialog.Builder( this ); lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int item ) { m_resultCode = item; } }; ab.setItems( m_texts, lstnr ); if ( PICK_TILE_REQUESTBLANK_BLK == id ) { ab.setTitle( R.string.title_tile_picker ); } else { ab.setTitle( Utils.format( this, R.string.cur_tilesf, m_curTiles ) ); if ( m_canUndoTiles ) { DialogInterface.OnClickListener undoClicked = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { m_resultCode = UtilCtxt.PICKER_BACKUP; removeDialog( id ); } }; ab.setPositiveButton( R.string.tilepick_undo, undoClicked ); } DialogInterface.OnClickListener doAllClicked = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int whichButton ) { m_resultCode = UtilCtxt.PICKER_PICKALL; removeDialog( id ); } }; ab.setNegativeButton( R.string.tilepick_all, doAllClicked ); } dialog = ab.create(); dialog.setOnDismissListener( makeODLforBlocking( id ) ); break; case ASK_PASSWORD_BLK: if ( null == m_passwdLyt ) { setupPasswdVars(); } m_passwdEdit.setText( "", TextView.BufferType.EDITABLE ); ab = new AlertDialog.Builder( this ) .setTitle( m_dlgTitleStr ) .setView( m_passwdLyt ) .setPositiveButton( R.string.button_ok, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dlg, int whichButton ) { m_resultCode = 1; } }); dialog = ab.create(); dialog.setOnDismissListener( makeODLforBlocking( id ) ); break; case QUERY_ENDGAME: dialog = new AlertDialog.Builder( this ) .setTitle( R.string.query_title ) .setMessage( R.string.ids_endnow ) .setPositiveButton( R.string.button_yes, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dlg, int item ) { m_jniThread. handle(JNICmd.CMD_ENDGAME); } }) .setNegativeButton( R.string.button_no, null ) .create(); break; case DLG_INVITE: if ( null != m_room ) { lstnr = new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int item ) { showEmailOrSMSThen( LAUNCH_INVITE_ACTION ); } }; dialog = new AlertDialog.Builder( this ) .setTitle( R.string.query_title ) .setMessage( "" ) .setPositiveButton( R.string.button_yes, lstnr ) .setNegativeButton( R.string.button_no, null ) .create(); } break; default: // just drop it; super.onCreateDialog likely failed break; } } return dialog; } // onCreateDialog @Override public void onPrepareDialog( int id, Dialog dialog ) { switch( id ) { case DLG_INVITE: AlertDialog ad = (AlertDialog)dialog; String format = getString( R.string.invite_msgf ); String message = String.format( format, m_missing ); if ( m_missing > 1 ) { message += getString( R.string.invite_multiple ); } ad.setMessage( message ); break; default: super.onPrepareDialog( id, dialog ); break; } } @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); getBundledData( savedInstanceState ); if ( CommonPrefs.getHideTitleBar( this ) ) { requestWindowFeature( Window.FEATURE_NO_TITLE ); } m_utils = new BoardUtilCtxt(); m_jniu = JNIUtilsImpl.get(); setContentView( R.layout.board ); m_timers = new TimerRunnable[4]; // needs to be in sync with // XWTimerReason m_view = (BoardView)findViewById( R.id.board_view ); m_tradeButtons = findViewById( R.id.exchange_buttons ); m_exchCommmitButton = (Button)findViewById( R.id.exchange_commit ); m_exchCommmitButton.setOnClickListener( this ); m_exchCancelButton = (Button)findViewById( R.id.exchange_cancel ); m_exchCancelButton.setOnClickListener( this ); m_volKeysZoom = CommonPrefs.getVolKeysZoom( this ); Intent intent = getIntent(); m_rowid = intent.getLongExtra( GameUtils.INTENT_KEY_ROWID, -1 ); m_haveInvited = intent.getBooleanExtra( GameUtils.INVITED, false ); setBackgroundColor(); setKeepScreenOn(); } // onCreate @Override protected void onPause() { m_handler = null; waitCloseGame( true ); super.onPause(); } @Override protected void onResume() { super.onResume(); m_handler = new Handler(); m_blockingDlgPosted = false; setKeepScreenOn(); loadGame(); } @Override protected void onSaveInstanceState( Bundle outState ) { super.onSaveInstanceState( outState ); outState.putInt( DLG_TITLESTR, m_dlgTitle ); outState.putString( DLG_TITLESTR, m_dlgTitleStr ); outState.putString( DLG_BYTES, m_dlgBytes ); outState.putString( ROOM, m_room ); outState.putString( TOASTSTR, m_toastStr ); outState.putStringArray( WORDS, m_words ); outState.putString( PWDNAME, m_pwdName ); } private void getBundledData( Bundle bundle ) { if ( null != bundle ) { m_dlgTitleStr = bundle.getString( DLG_TITLESTR ); m_dlgTitle = bundle.getInt( DLG_TITLE ); m_dlgBytes = bundle.getString( DLG_BYTES ); m_room = bundle.getString( ROOM ); m_toastStr = bundle.getString( TOASTSTR ); m_words = bundle.getStringArray( WORDS ); m_pwdName = bundle.getString( PWDNAME ); } } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data ) { if ( Activity.RESULT_CANCELED != resultCode ) { switch ( requestCode ) { case CHAT_REQUEST: String msg = data.getStringExtra( INTENT_KEY_CHAT ); if ( null != msg && msg.length() > 0 ) { m_pendingChats.add( msg ); trySendChats(); } break; case BT_INVITE_RESULT: - m_invitesPending = 0; - String[] devs = data.getStringArrayExtra( BTInviteActivity.DEVS ); - for ( String dev : devs ) { - BTService.inviteRemote( this, dev, m_gi.gameID, m_gi.dictLang, - m_gi.nPlayers, 1 ); - ++m_invitesPending; - } - startProgress( R.string.invite_progress ); + // onActivityResult is called immediately *before* + // onResume -- meaning m_gi etc are still null. + m_btDevs = data.getStringArrayExtra( BTInviteActivity.DEVS ); break; } } } @Override public void onWindowFocusChanged( boolean hasFocus ) { super.onWindowFocusChanged( hasFocus ); if ( hasFocus ) { if ( m_firingPrefs ) { m_firingPrefs = false; m_volKeysZoom = CommonPrefs.getVolKeysZoom( this ); if ( null != m_jniThread ) { m_jniThread.handle( JNIThread.JNICmd.CMD_PREFS_CHANGE ); } // in case of change... setBackgroundColor(); setKeepScreenOn(); } } } @Override public boolean onKeyDown( int keyCode, KeyEvent event ) { boolean handled = false; if ( null != m_jniThread ) { XwJNI.XP_Key xpKey = keyCodeToXPKey( keyCode ); if ( XwJNI.XP_Key.XP_KEY_NONE != xpKey ) { m_jniThread.handle( JNIThread.JNICmd.CMD_KEYDOWN, xpKey ); } else { switch( keyCode ) { case KeyEvent.KEYCODE_VOLUME_DOWN: case KeyEvent.KEYCODE_VOLUME_UP: if ( m_volKeysZoom ) { int zoomBy = KeyEvent.KEYCODE_VOLUME_DOWN == keyCode ? -2 : 2; handled = doZoom( zoomBy ); } break; } } } return handled || super.onKeyDown( keyCode, event ); } @Override public boolean onKeyUp( int keyCode, KeyEvent event ) { if ( null != m_jniThread ) { XwJNI.XP_Key xpKey = keyCodeToXPKey( keyCode ); if ( XwJNI.XP_Key.XP_KEY_NONE != xpKey ) { m_jniThread.handle( JNIThread.JNICmd.CMD_KEYUP, xpKey ); } } return super.onKeyUp( keyCode, event ); } @Override public boolean onCreateOptionsMenu( Menu menu ) { MenuInflater inflater = getMenuInflater(); inflater.inflate( R.menu.board_menu, menu ); // For now undo-last can crash the app or break a game in // networked case. Disable until this is fixed. if ( null != m_gi && m_gi.serverRole != DeviceRole.SERVER_STANDALONE ) { menu.removeItem( R.id.board_menu_undo_last ); } return true; } @Override public boolean onPrepareOptionsMenu( Menu menu ) { super.onPrepareOptionsMenu( menu ); boolean inTrade = false; if ( null != m_gsi ) { inTrade = m_gsi.inTrade; menu.setGroupVisible( R.id.group_done, !inTrade ); } if ( !inTrade ) { MenuItem item = menu.findItem( R.id.board_menu_done ); int strId; if ( 0 >= m_view.curPending() ) { strId = R.string.board_menu_pass; } else { strId = R.string.board_menu_done; } item.setTitle( strId ); item.setEnabled( null == m_gsi || m_gsi.curTurnSelected ); } return true; } public boolean onOptionsItemSelected( MenuItem item ) { boolean handled = true; JNIThread.JNICmd cmd = JNIThread.JNICmd.CMD_NONE; Runnable proc = null; int id = item.getItemId(); switch ( id ) { case R.id.board_menu_done: showNotAgainDlgThen( R.string.not_again_done, R.string.key_notagain_done, COMMIT_ACTION ); break; // case R.id.board_menu_juggle: // cmd = JNIThread.JNICmd.CMD_JUGGLE; // break; // case R.id.board_menu_flip: // cmd = JNIThread.JNICmd.CMD_FLIP; // break; case R.id.board_menu_trade: showNotAgainDlgThen( R.string.not_again_trading, R.string.key_notagain_trading, START_TRADE_ACTION ); break; case R.id.board_menu_tray: cmd = JNIThread.JNICmd.CMD_TOGGLE_TRAY; break; // case R.id.board_menu_undo_current: // cmd = JNIThread.JNICmd.CMD_UNDO_CUR; // break; case R.id.board_menu_undo_last: showConfirmThen( R.string.confirm_undo_last, UNDO_LAST_ACTION ); break; case R.id.board_menu_game_counts: m_jniThread.handle( JNIThread.JNICmd.CMD_COUNTS_VALUES, R.string.counts_values_title ); break; case R.id.board_menu_game_left: m_jniThread.handle( JNIThread.JNICmd.CMD_REMAINING, R.string.tiles_left_title ); break; case R.id.board_menu_game_history: m_jniThread.handle( JNIThread.JNICmd.CMD_HISTORY, R.string.history_title ); break; case R.id.board_menu_game_final: m_jniThread.handle( JNIThread.JNICmd.CMD_FINAL, R.string.history_title ); break; case R.id.board_menu_game_resend: m_jniThread.handle( JNIThread.JNICmd.CMD_RESEND ); break; case R.id.gamel_menu_checkmoves: showNotAgainDlgThen( R.string.not_again_sync, R.string.key_notagain_sync, SYNC_ACTION ); break; case R.id.board_menu_file_prefs: m_firingPrefs = true; startActivity( new Intent( this, PrefsActivity.class ) ); break; case R.id.board_menu_file_about: showAboutDialog(); break; default: DbgUtils.logf( "menuitem %d not handled", id ); handled = false; } if ( handled && cmd != JNIThread.JNICmd.CMD_NONE ) { m_jniThread.handle( cmd ); } return handled; } ////////////////////////////////////////////////// // DlgDelegate.DlgClickNotify interface ////////////////////////////////////////////////// @Override public void dlgButtonClicked( int id, int which ) { if ( LAUNCH_INVITE_ACTION == id ) { if ( DlgDelegate.DISMISS_BUTTON != which ) { GameUtils.launchInviteActivity( BoardActivity.this, DlgDelegate.EMAIL_BTN == which, m_room, null, m_gi.dictLang, m_gi.nPlayers ); } } else if ( AlertDialog.BUTTON_POSITIVE == which ) { JNIThread.JNICmd cmd = JNIThread.JNICmd.CMD_NONE; switch ( id ) { case UNDO_LAST_ACTION: cmd = JNIThread.JNICmd.CMD_UNDO_LAST; break; case SYNC_ACTION: doSyncMenuitem(); break; case BT_PICK_ACTION: GameUtils.launchBTInviter( this, m_nMissingPlayers, BT_INVITE_RESULT ); break; case COMMIT_ACTION: cmd = JNIThread.JNICmd.CMD_COMMIT; break; case SHOW_EXPL_ACTION: Toast.makeText( BoardActivity.this, m_toastStr, Toast.LENGTH_SHORT).show(); m_toastStr = null; break; case BUTTON_BROWSE_ACTION: String dictName = m_gi.dictName( m_view.getCurPlayer() ); DictBrowseActivity.launch( this, dictName ); break; case PREV_HINT_ACTION: cmd = JNIThread.JNICmd.CMD_PREV_HINT; break; case NEXT_HINT_ACTION: cmd = JNIThread.JNICmd.CMD_NEXT_HINT; break; case JUGGLE_ACTION: cmd = JNIThread.JNICmd.CMD_JUGGLE; break; case FLIP_ACTION: cmd = JNIThread.JNICmd.CMD_FLIP; break; case ZOOM_ACTION: cmd = JNIThread.JNICmd.CMD_TOGGLEZOOM; break; case UNDO_ACTION: cmd = JNIThread.JNICmd.CMD_UNDO_CUR; break; case VALUES_ACTION: cmd = JNIThread.JNICmd.CMD_VALUES; break; case CHAT_ACTION: startChatActivity(); break; case START_TRADE_ACTION: Toast.makeText( this, R.string.entering_trade, Toast.LENGTH_SHORT).show(); cmd = JNIThread.JNICmd.CMD_TRADE; break; case LOOKUP_ACTION: launchLookup( m_words, m_gi.dictLang ); break; default: Assert.fail(); } if ( JNIThread.JNICmd.CMD_NONE != cmd ) { checkAndHandle( cmd ); } } } ////////////////////////////////////////////////// // View.OnClickListener interface ////////////////////////////////////////////////// @Override public void onClick( View view ) { if ( view == m_exchCommmitButton ) { m_jniThread.handle( JNIThread.JNICmd.CMD_COMMIT ); } else if ( view == m_exchCancelButton ) { m_jniThread.handle( JNIThread.JNICmd.CMD_CANCELTRADE ); } } ////////////////////////////////////////////////// // BTService.BTEventListener interface ////////////////////////////////////////////////// @Override public void eventOccurred( BTService.BTEvent event, final Object ... args ) { switch( event ) { case MESSAGE_ACCEPTED: m_jniThread.handle( JNICmd.CMD_DRAW_BT_STATUS, true ); break; case MESSAGE_REFUSED: m_jniThread.handle( JNICmd.CMD_DRAW_BT_STATUS, false ); break; case MESSAGE_NOGAME: post( new Runnable() { public void run() { showDialog( DLG_DELETED ); } } ); break; case NEWGAME_FAILURE: DbgUtils.logf( "failed to create game" ); case NEWGAME_SUCCESS: if ( 0 == --m_invitesPending ) { m_handler.post( new Runnable() { public void run() { stopProgress(); } } ); } break; default: super.eventOccurred( event, args ); break; } } ////////////////////////////////////////////////// // TransportProcs.TPMsgHandler interface ////////////////////////////////////////////////// public void tpmRelayConnd( final String room, final int devOrder, final boolean allHere, final int nMissing ) { post( new Runnable() { public void run() { handleConndMessage( room, devOrder, allHere, nMissing ); } } ); } public void tpmRelayErrorProc( TransportProcs.XWRELAY_ERROR relayErr ) { int strID = -1; int dlgID = -1; boolean doToast = false; switch ( relayErr ) { case TOO_MANY: strID = R.string.msg_too_many; dlgID = DLG_OKONLY; break; case NO_ROOM: strID = R.string.msg_no_room; dlgID = DLG_RETRY; break; case DUP_ROOM: strID = R.string.msg_dup_room; dlgID = DLG_OKONLY; break; case LOST_OTHER: case OTHER_DISCON: strID = R.string.msg_lost_other; doToast = true; break; case DEADGAME: case DELETED: strID = R.string.msg_dev_deleted; dlgID = DLG_DELETED; break; case OLDFLAGS: case BADPROTO: case RELAYBUSY: case SHUTDOWN: case TIMEOUT: case HEART_YOU: case HEART_OTHER: break; } if ( doToast ) { Toast.makeText( this, getString( strID ), Toast.LENGTH_SHORT).show(); } else if ( dlgID >= 0 ) { final int strIDf = strID; final int dlgIDf = dlgID; post( new Runnable() { public void run() { m_dlgBytes = getString( strIDf ); m_dlgTitle = R.string.relay_alert; showDialog( dlgIDf ); } }); } } private XwJNI.XP_Key keyCodeToXPKey( int keyCode ) { XwJNI.XP_Key xpKey = XwJNI.XP_Key.XP_KEY_NONE; switch( keyCode ) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: xpKey = XwJNI.XP_Key.XP_RETURN_KEY; break; case KeyEvent.KEYCODE_DPAD_DOWN: xpKey = XwJNI.XP_Key.XP_CURSOR_KEY_DOWN; break; case KeyEvent.KEYCODE_DPAD_LEFT: xpKey = XwJNI.XP_Key.XP_CURSOR_KEY_LEFT; break; case KeyEvent.KEYCODE_DPAD_RIGHT: xpKey = XwJNI.XP_Key.XP_CURSOR_KEY_RIGHT; break; case KeyEvent.KEYCODE_DPAD_UP: xpKey = XwJNI.XP_Key.XP_CURSOR_KEY_UP; break; case KeyEvent.KEYCODE_SPACE: xpKey = XwJNI.XP_Key.XP_RAISEFOCUS_KEY; break; } return xpKey; } // Blocking thread stuff: The problem this is solving occurs when // you have a blocking dialog up, meaning the jni thread is // blocked, and you hit the home button. onPause() gets called // which wants to use jni calls to e.g. summarize. For those to // succeed (the jni being non-reentrant and set up to assert if it // is reentered) the jni thread must first be unblocked and // allowed to return back through the jni. We unblock using // Thread.interrupt method, the exception from which winds up // caught in waitBlockingDialog. The catch dismisses the dialog // with the default/cancel value, but that takes us into the // onDismissListener which normally releases the semaphore. But // if we've interrupted then we can't release it or blocking won't // work for as long as this activity lives. Hence // releaseIfBlocking(). This feels really fragile but it does // work. private void setBlockingThread() { synchronized( this ) { Assert.assertTrue( null == m_blockingThread ); m_blockingThread = Thread.currentThread(); } } private void clearBlockingThread() { synchronized( this ) { Assert.assertTrue( null != m_blockingThread ); m_blockingThread = null; } } private void interruptBlockingThread() { synchronized( this ) { if ( null != m_blockingThread ) { m_blockingThread.interrupt(); } } } private void releaseIfBlocking() { synchronized( this ) { if ( null != m_blockingThread ) { m_forResultWait.release(); } } } private void handleConndMessage( String room, int devOrder, // <- hostID boolean allHere, int nMissing ) { int naMsg = 0; int naKey = 0; String str = null; if ( allHere ) { // All players have now joined the game. The device that // created the room will assign tiles. Then it will be // the first player's turn String fmt = getString( R.string.msg_relay_all_heref ); str = String.format( fmt, room ); if ( devOrder > 1 ) { naMsg = R.string.not_again_conndall; naKey = R.string.key_notagain_conndall; } } else if ( nMissing > 0 ) { // Let's only invite for two-person games for now. Simple // case first.... if ( !m_haveInvited ) { m_haveInvited = true; m_room = room; m_missing = nMissing; showDialog( DLG_INVITE ); } else { String fmt = getString( R.string.msg_relay_waiting ); str = String.format( fmt, devOrder, room, nMissing ); if ( devOrder == 1 ) { naMsg = R.string.not_again_conndfirst; naKey = R.string.key_notagain_conndfirst; } else { naMsg = R.string.not_again_conndmid; naKey = R.string.key_notagain_conndmid; } } } if ( null != str ) { m_toastStr = str; if ( naMsg == 0 ) { dlgButtonClicked( SHOW_EXPL_ACTION, AlertDialog.BUTTON_POSITIVE ); } else { showNotAgainDlgThen( naMsg, naKey, SHOW_EXPL_ACTION ); } } } // handleConndMessage private class BoardUtilCtxt extends UtilCtxtImpl { public BoardUtilCtxt() { super( BoardActivity.this ); } @Override public void requestTime() { post( new Runnable() { public void run() { if ( null != m_jniThread ) { m_jniThread.handleBkgrnd( JNIThread.JNICmd.CMD_DO ); } } } ); } @Override public void remSelected() { m_jniThread.handle( JNIThread.JNICmd.CMD_REMAINING, R.string.tiles_left_title ); } @Override public void setIsServer( boolean isServer ) { DeviceRole newRole = isServer? DeviceRole.SERVER_ISSERVER : DeviceRole.SERVER_ISCLIENT; if ( newRole != m_gi.serverRole ) { DbgUtils.logf( "new role: %s; old role: %s", newRole.toString(), m_gi.serverRole.toString() ); m_gi.serverRole = newRole; if ( !isServer ) { m_jniThread.handle( JNIThread.JNICmd.CMD_SWITCHCLIENT ); } } } @Override public void bonusSquareHeld( int bonus ) { int id = 0; switch( bonus ) { case BONUS_DOUBLE_LETTER: id = R.string.bonus_l2x; break; case BONUS_DOUBLE_WORD: id = R.string.bonus_w2x; break; case BONUS_TRIPLE_LETTER: id = R.string.bonus_l3x; break; case BONUS_TRIPLE_WORD: id = R.string.bonus_w3x; break; default: Assert.fail(); } if ( 0 != id ) { final String bonusStr = getString( id ); post( new Runnable() { public void run() { Toast.makeText( BoardActivity.this, bonusStr, Toast.LENGTH_SHORT).show(); } } ); } } @Override public void playerScoreHeld( int player ) { String expl = XwJNI.model_getPlayersLastScore( m_jniGamePtr, player ); if ( expl.length() == 0 ) { expl = getString( R.string.no_moves_made ); } String name = m_gi.players[player].name; final String text = String.format( "%s\n%s", name, expl ); post( new Runnable() { public void run() { Toast.makeText( BoardActivity.this, text, Toast.LENGTH_SHORT).show(); } } ); } @Override public void cellSquareHeld( final String words ) { post( new Runnable() { public void run() { launchLookup( wordsToArray( words ), m_gi.dictLang ); } } ); } @Override public void setTimer( int why, int when, int handle ) { if ( null != m_timers[why] ) { removeCallbacks( m_timers[why] ); } m_timers[why] = new TimerRunnable( why, when, handle ); int inHowLong; switch ( why ) { case UtilCtxt.TIMER_COMMS: inHowLong = when * 1000; break; case UtilCtxt.TIMER_TIMERTICK: inHowLong = 1000; // when is 0 for TIMER_TIMERTICK break; default: inHowLong = 500; } postDelayed( m_timers[why], inHowLong ); } @Override public void clearTimer( int why ) { if ( null != m_timers[why] ) { removeCallbacks( m_timers[why] ); m_timers[why] = null; } } // This is supposed to be called from the jni thread @Override public int userPickTileBlank( int playerNum, String[] texts) { m_texts = texts; waitBlockingDialog( PICK_TILE_REQUESTBLANK_BLK, 0 ); return m_resultCode; } @Override public int userPickTileTray( int playerNum, String[] texts, String[] curTiles, int nPicked ) { m_texts = texts; m_curTiles = TextUtils.join( ", ", curTiles ); m_canUndoTiles = 0 < nPicked; waitBlockingDialog( PICK_TILE_REQUESTTRAY_BLK, UtilCtxt.PICKER_PICKALL ); return m_resultCode; } @Override public String askPassword( String name ) { // call this each time dlg created or will get exception // for reusing m_passwdLyt m_pwdName = name; setupPasswdVars(); waitBlockingDialog( ASK_PASSWORD_BLK, 0 ); String result = null; // means cancelled if ( 0 != m_resultCode ) { result = m_passwdEdit.getText().toString(); } return result; } @Override public void turnChanged() { post( new Runnable() { public void run() { showNotAgainDlgThen( R.string.not_again_turnchanged, R.string.key_notagain_turnchanged ); } } ); m_jniThread.handle( JNIThread.JNICmd. CMD_ZOOM, -8 ); } @Override public boolean engineProgressCallback() { return ! m_jniThread.busy(); } @Override public boolean userQuery( int id, String query ) { boolean result; switch( id ) { // Though robot-move dialogs don't normally need to block, // if the player after this one is also a robot and we // don't block then a second dialog will replace this one. // So block. Yuck. case UtilCtxt.QUERY_ROBOT_TRADE: m_dlgBytes = query; m_dlgTitle = R.string.info_title; waitBlockingDialog( QUERY_INFORM_BLK, 0 ); result = true; break; // These *are* blocking dialogs case UtilCtxt.QUERY_COMMIT_TURN: m_dlgBytes = query; m_dlgTitle = R.string.query_title; result = 0 != waitBlockingDialog( QUERY_REQUEST_BLK, 0 ); break; default: Assert.fail(); result = false; } return result; } @Override public boolean confirmTrade( String[] tiles ) { m_dlgTitle = R.string.info_title; m_dlgBytes = Utils.format( BoardActivity.this, R.string.query_tradef, TextUtils.join( ", ", tiles ) ); return 0 != waitBlockingDialog( QUERY_REQUEST_BLK, 0 ); } @Override public void userError( int code ) { int resid = 0; switch( code ) { case UtilCtxt.ERR_TILES_NOT_IN_LINE: resid = R.string.str_tiles_not_in_line; break; case UtilCtxt.ERR_NO_EMPTIES_IN_TURN: resid = R.string.str_no_empties_in_turn; break; case UtilCtxt.ERR_TWO_TILES_FIRST_MOVE: resid = R.string.str_two_tiles_first_move; break; case UtilCtxt.ERR_TILES_MUST_CONTACT: resid = R.string.str_tiles_must_contact; break; case UtilCtxt.ERR_NOT_YOUR_TURN: resid = R.string.str_not_your_turn; break; case UtilCtxt.ERR_NO_PEEK_ROBOT_TILES: resid = R.string.str_no_peek_robot_tiles; break; case UtilCtxt.ERR_NO_EMPTY_TRADE: // This should not be possible as the button's // disabled when no tiles selected. Assert.fail(); break; case UtilCtxt.ERR_TOO_FEW_TILES_LEFT_TO_TRADE: resid = R.string.str_too_few_tiles_left_to_trade; break; case UtilCtxt.ERR_CANT_UNDO_TILEASSIGN: resid = R.string.str_cant_undo_tileassign; break; case UtilCtxt.ERR_CANT_HINT_WHILE_DISABLED: resid = R.string.str_cant_hint_while_disabled; break; case UtilCtxt.ERR_NO_PEEK_REMOTE_TILES: resid = R.string.str_no_peek_remote_tiles; break; case UtilCtxt.ERR_REG_UNEXPECTED_USER: resid = R.string.str_reg_unexpected_user; break; case UtilCtxt.ERR_SERVER_DICT_WINS: resid = R.string.str_server_dict_wins; break; case ERR_REG_SERVER_SANS_REMOTE: resid = R.string.str_reg_server_sans_remote; break; } if ( resid != 0 ) { nonBlockingDialog( DLG_OKONLY, getString( resid ) ); } } // userError @Override public void informMissing( boolean isServer, CommsAddrRec.CommsConnType connType, final int nMissingPlayers ) { - if ( isServer && - CommsAddrRec.CommsConnType.COMMS_CONN_BT == connType ) { + if ( isServer && !m_haveAskedMissing + && CommsAddrRec.CommsConnType.COMMS_CONN_BT == connType ) { + m_haveAskedMissing = true; post( new Runnable() { public void run() { DbgUtils.showf( BoardActivity.this, "%d players missing", nMissingPlayers ); m_nMissingPlayers = nMissingPlayers; showConfirmThen( R.string.bt_devs_missing, BT_PICK_ACTION ); } } ); } } @Override public void informMove( String expl, String words ) { m_dlgBytes = expl; m_dlgTitle = R.string.info_title; m_words = wordsToArray( words ); waitBlockingDialog( DLG_SCORES_BLK, 0 ); } @Override public void notifyGameOver() { m_jniThread.handle( JNIThread.JNICmd.CMD_POST_OVER ); } // public void yOffsetChange( int maxOffset, int oldOffset, int newOffset ) // { // DbgUtils.logf( "yOffsetChange(maxOffset=%d)", maxOffset ); // m_view.setVerticalScrollBarEnabled( maxOffset > 0 ); // } @Override public boolean warnIllegalWord( String[] words, int turn, boolean turnLost ) { DbgUtils.logf( "warnIllegalWord" ); boolean accept = turnLost; StringBuffer sb = new StringBuffer(); for ( int ii = 0; ; ) { sb.append( words[ii] ); if ( ++ii == words.length ) { break; } sb.append( "; " ); } String format = getString( R.string.ids_badwords ); String message = String.format( format, sb.toString() ); if ( turnLost ) { nonBlockingDialog( DLG_BADWORDS, message + getString(R.string.badwords_lost) ); } else { m_dlgBytes = message + getString( R.string.badwords_accept ); m_dlgTitle = R.string.query_title; accept = 0 != waitBlockingDialog( QUERY_REQUEST_BLK, 0 ); } DbgUtils.logf( "warnIllegalWord=>%b", accept ); return accept; } // Let's have this block in case there are multiple messages. If // we don't block the jni thread will continue processing messages // and may stack dialogs on top of this one. Including later // chat-messages. @Override public void showChat( final String msg ) { post( new Runnable() { public void run() { DBUtils.appendChatHistory( BoardActivity.this, m_rowid, msg, false ); startChatActivity(); } } ); } } // class BoardUtilCtxt private void loadGame() { if ( 0 == m_jniGamePtr ) { String[] dictNames = GameUtils.dictNames( this, m_rowid ); DictUtils.DictPairs pairs = DictUtils.openDicts( this, dictNames ); if ( pairs.anyMissing( dictNames ) ) { showDictGoneFinish(); } else { Assert.assertNull( m_gameLock ); m_gameLock = new GameUtils.GameLock( m_rowid, true ).lock(); byte[] stream = GameUtils.savedGame( this, m_gameLock ); m_gi = new CurGameInfo( this ); XwJNI.gi_from_stream( m_gi, stream ); String langName = m_gi.langName(); setThis( this ); m_jniGamePtr = XwJNI.initJNI(); if ( m_gi.serverRole != DeviceRole.SERVER_STANDALONE ) { m_xport = new CommsTransport( m_jniGamePtr, this, this, m_gi.serverRole ); } CommonPrefs cp = CommonPrefs.get( this ); if ( null == stream || ! XwJNI.game_makeFromStream( m_jniGamePtr, stream, m_gi, dictNames, pairs.m_bytes, pairs.m_paths, langName, m_utils, m_jniu, m_view, cp, m_xport ) ) { XwJNI.game_makeNewGame( m_jniGamePtr, m_gi, m_utils, m_jniu, m_view, cp, m_xport, dictNames, pairs.m_bytes, pairs.m_paths, langName ); } Handler handler = new Handler() { public void handleMessage( Message msg ) { switch( msg.what ) { case JNIThread.DRAW: m_view.invalidate(); break; case JNIThread.DIALOG: m_dlgBytes = (String)msg.obj; m_dlgTitle = msg.arg1; showDialog( DLG_OKONLY ); break; case JNIThread.QUERY_ENDGAME: showDialog( QUERY_ENDGAME ); break; case JNIThread.TOOLBAR_STATES: if ( null != m_jniThread ) { m_gsi = m_jniThread.getGameStateInfo(); updateToolbar(); if ( m_inTrade != m_gsi.inTrade ) { m_inTrade = m_gsi.inTrade; m_view.setInTrade( m_inTrade ); } adjustTradeVisibility(); } break; case JNIThread.GOT_WORDS: launchLookup( wordsToArray((String)msg.obj), m_gi.dictLang ); break; } } }; m_jniThread = new JNIThread( m_jniGamePtr, m_gi, m_view, m_gameLock, this, handler ); // see http://stackoverflow.com/questions/680180/where-to-stop-\ // destroy-threads-in-android-service-class m_jniThread.setDaemon( true ); m_jniThread.start(); m_view.startHandling( this, m_jniThread, m_jniGamePtr, m_gi ); if ( null != m_xport ) { m_xport.setReceiver( m_jniThread ); } m_jniThread.handle( JNICmd.CMD_START ); if ( !CommonPrefs.getHideTitleBar( this ) ) { setTitle( GameUtils.getName( this, m_rowid ) ); } m_toolbar = new Toolbar( this, R.id.toolbar_horizontal ); populateToolbar(); adjustTradeVisibility(); int flags = DBUtils.getMsgFlags( this, m_rowid ); if ( 0 != (GameSummary.MSG_FLAGS_CHAT & flags) ) { startChatActivity(); } if ( 0 != (GameSummary.MSG_FLAGS_GAMEOVER & flags) ) { m_jniThread.handle( JNIThread.JNICmd.CMD_POST_OVER ); } if ( 0 != flags ) { DBUtils.setMsgFlags( m_rowid, GameSummary.MSG_FLAGS_NONE ); } if ( null != m_xport ) { trySendChats(); m_xport.tickle(); + tryBTInvites(); } } } } // loadGame private void checkAndHandle( JNIThread.JNICmd cmd ) { if ( null != m_jniThread ) { m_jniThread.handle( cmd ); } } private void populateToolbar() { m_toolbar.setListener( Toolbar.BUTTON_BROWSE_DICT, R.string.not_again_browse, R.string.key_na_browse, BUTTON_BROWSE_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_HINT_PREV, R.string.not_again_hintprev, R.string.key_notagain_hintprev, PREV_HINT_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_HINT_NEXT, R.string.not_again_hintnext, R.string.key_notagain_hintnext, NEXT_HINT_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_JUGGLE, R.string.not_again_juggle, R.string.key_notagain_juggle, JUGGLE_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_FLIP, R.string.not_again_flip, R.string.key_notagain_flip, FLIP_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_ZOOM, R.string.not_again_zoom, R.string.key_notagain_zoom, ZOOM_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_VALUES, R.string.not_again_values, R.string.key_na_values, VALUES_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_UNDO, R.string.not_again_undo, R.string.key_notagain_undo, UNDO_ACTION ); m_toolbar.setListener( Toolbar.BUTTON_CHAT, R.string.not_again_chat, R.string.key_notagain_chat, CHAT_ACTION ); } // populateToolbar private OnDismissListener makeODLforBlocking( final int id ) { return new OnDismissListener() { public void onDismiss( DialogInterface di ) { releaseIfBlocking(); removeDialog( id ); } }; } private int waitBlockingDialog( final int dlgID, int cancelResult ) { int result = cancelResult; if ( m_blockingDlgPosted ) { // this has been true; dunno why DbgUtils.logf( "waitBlockingDialog: dropping dlgID %d", dlgID ); } else { setBlockingThread(); m_resultCode = cancelResult; if ( post( new Runnable() { public void run() { showDialog( dlgID ); m_blockingDlgPosted = true; } } ) ) { try { m_forResultWait.acquire(); m_blockingDlgPosted = false; } catch ( java.lang.InterruptedException ie ) { DbgUtils.logf( "waitBlockingDialog: got %s", ie.toString() ); if ( m_blockingDlgPosted ) { dismissDialog( dlgID ); m_blockingDlgPosted = false; } } } clearBlockingThread(); result = m_resultCode; } return result; } private void nonBlockingDialog( final int dlgID, String txt ) { switch ( dlgID ) { case DLG_OKONLY: m_dlgTitle = R.string.info_title; break; case DLG_BADWORDS: m_dlgTitle = R.string.badwords_title; break; default: Assert.fail(); } m_dlgBytes = txt; post( new Runnable() { public void run() { showDialog( dlgID ); } } ); } private boolean doZoom( int zoomBy ) { boolean handled = null != m_jniThread; if ( handled ) { m_jniThread.handle( JNIThread.JNICmd.CMD_ZOOM, zoomBy ); } return handled; } private void startChatActivity() { Intent intent = new Intent( this, ChatActivity.class ); intent.putExtra( GameUtils.INTENT_KEY_ROWID, m_rowid ); startActivityForResult( intent, CHAT_REQUEST ); } private void waitCloseGame( boolean save ) { if ( 0 != m_jniGamePtr ) { if ( null != m_xport ) { m_xport.waitToStop(); m_xport = null; } interruptBlockingThread(); if ( null != m_jniThread ) { m_jniThread.waitToStop( save ); m_jniThread = null; } clearThis(); XwJNI.game_dispose( m_jniGamePtr ); m_jniGamePtr = 0; m_gi = null; m_gameLock.unlock(); m_gameLock = null; } } private void trySendChats() { if ( null != m_jniThread ) { Iterator<String> iter = m_pendingChats.iterator(); while ( iter.hasNext() ) { m_jniThread.handle( JNICmd.CMD_SENDCHAT, iter.next() ); } m_pendingChats.clear(); } } + private void tryBTInvites() + { + if ( null != m_btDevs ) { + m_invitesPending = m_btDevs.length; + for ( String dev : m_btDevs ) { + BTService.inviteRemote( this, dev, m_gi.gameID, m_gi.dictLang, + m_gi.nPlayers, 1 ); + } + startProgress( R.string.invite_progress ); + m_btDevs = null; + } + } + private void updateToolbar() { m_toolbar.update( Toolbar.BUTTON_FLIP, m_gsi.visTileCount >= 1 ); m_toolbar.update( Toolbar.BUTTON_VALUES, m_gsi.visTileCount >= 1 ); m_toolbar.update( Toolbar.BUTTON_JUGGLE, m_gsi.canShuffle ); m_toolbar.update( Toolbar.BUTTON_UNDO, m_gsi.canRedo ); m_toolbar.update( Toolbar.BUTTON_HINT_PREV, m_gsi.canHint ); m_toolbar.update( Toolbar.BUTTON_HINT_NEXT, m_gsi.canHint ); m_toolbar.update( Toolbar.BUTTON_CHAT, m_gsi.gameIsConnected ); m_toolbar.update( Toolbar.BUTTON_BROWSE_DICT, null != m_gi.dictName( m_view.getCurPlayer() ) ); } private void adjustTradeVisibility() { m_toolbar.setVisibility( m_inTrade? View.GONE : View.VISIBLE ); m_tradeButtons.setVisibility( m_inTrade? View.VISIBLE : View.GONE ); if ( m_inTrade ) { m_exchCommmitButton.setEnabled( m_gsi.tradeTilesSelected ); } } private void setBackgroundColor() { int back = CommonPrefs.get(this) .otherColors[CommonPrefs.COLOR_BACKGRND]; m_view.getRootView().setBackgroundColor( back ); } private void setKeepScreenOn() { boolean keepOn = CommonPrefs.getKeepScreenOn( this ); m_view.setKeepScreenOn( keepOn ); if ( keepOn ) { if ( null == m_screenTimer ) { m_screenTimer = new Runnable() { public void run() { DbgUtils.logf( "run() called for setKeepScreenOn()" ); if ( null != m_view ) { m_view.setKeepScreenOn( false ); } } }; } removeCallbacks( m_screenTimer ); // needed? postDelayed( m_screenTimer, SCREEN_ON_TIME ); } } private boolean post( Runnable runnable ) { boolean canPost = null != m_handler; if ( canPost ) { m_handler.post( runnable ); } else { DbgUtils.logf( "post: dropping because handler null" ); } return canPost; } private void postDelayed( Runnable runnable, int when ) { if ( null != m_handler ) { m_handler.postDelayed( runnable, when ); } else { DbgUtils.logf( "postDelayed: dropping %d because handler null", when ); } } private void removeCallbacks( Runnable which ) { if ( null != m_handler ) { m_handler.removeCallbacks( which ); } else { DbgUtils.logf( "removeCallbacks: dropping %h because handler null", which ); } } private String[] wordsToArray( String words ) { String[] tmp = TextUtils.split( words, "\n" ); String[] wordsArray = new String[tmp.length]; for ( int ii = 0, jj = tmp.length; ii < tmp.length; ++ii, --jj ) { wordsArray[ii] = tmp[jj-1]; } return wordsArray; } private void setupPasswdVars() { String fmt = getString( R.string.msg_ask_password ); m_dlgTitleStr = String.format( fmt, m_pwdName ); m_passwdLyt = (LinearLayout)Utils.inflate( BoardActivity.this, R.layout.passwd_view ); m_passwdEdit = (EditText)m_passwdLyt.findViewById( R.id.edit ); } } // class BoardActivity
false
false
null
null