diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/classpath/java/lang/Runtime.java b/classpath/java/lang/Runtime.java index 341d0ed1..a59339bf 100644 --- a/classpath/java/lang/Runtime.java +++ b/classpath/java/lang/Runtime.java @@ -1,170 +1,170 @@ /* Copyright (c) 2008-2009, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package java.lang; import java.io.IOException; import java.io.InputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileDescriptor; import java.util.StringTokenizer; public class Runtime { private static final Runtime instance = new Runtime(); private Runtime() { } public static Runtime getRuntime() { return instance; } public void load(String path) { if (path != null) { load(path, false); } else { throw new NullPointerException(); } } public void loadLibrary(String path) { if (path != null) { load(path, true); } else { throw new NullPointerException(); } } public Process exec(String command) { StringTokenizer t = new StringTokenizer(command); String[] cmd = new String[t.countTokens()]; for (int i = 0; i < cmd.length; i++) cmd[i] = t.nextToken(); return exec(cmd); } - public MyProcess exec(final String[] command) { + public Process exec(final String[] command) { final MyProcess[] process = new MyProcess[1]; final Throwable[] exception = new Throwable[1]; synchronized (process) { Thread t = new Thread() { public void run() { synchronized (process) { try { long[] info = new long[4]; exec(command, info); process[0] = new MyProcess (info[0], (int) info[1], (int) info[2], (int) info[3]); MyProcess p = process[0]; synchronized (p) { try { if (p.pid != 0) { p.exitCode = Runtime.waitFor(p.pid); p.pid = 0; } } finally { p.notifyAll(); } } } catch (Throwable e) { exception[0] = e; } finally { process.notifyAll(); } } } }; t.setDaemon(true); t.start(); while (process[0] == null && exception[0] == null) { try { process.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } if (exception[0] != null) { throw new RuntimeException(exception[0]); } return process[0]; } public native void addShutdownHook(Thread t); private static native void exec(String[] command, long[] process) throws IOException; private static native int waitFor(long pid); private static native void load(String name, boolean mapName); public native void gc(); public native void exit(int code); public native long freeMemory(); public native long totalMemory(); private static class MyProcess extends Process { private long pid; private final int in; private final int out; private final int err; private int exitCode; public MyProcess(long pid, int in, int out, int err) { this.pid = pid; this.in = in; this.out = out; this.err = err; } public void destroy() { throw new RuntimeException("not implemented"); } public InputStream getInputStream() { return new FileInputStream(new FileDescriptor(in)); } public OutputStream getOutputStream() { return new FileOutputStream(new FileDescriptor(out)); } public InputStream getErrorStream() { return new FileInputStream(new FileDescriptor(err)); } public synchronized int exitValue() { if (pid != 0) { throw new IllegalThreadStateException(); } return exitCode; } public synchronized int waitFor() throws InterruptedException { while (pid != 0) { wait(); } return exitCode; } } }
true
true
public MyProcess exec(final String[] command) { final MyProcess[] process = new MyProcess[1]; final Throwable[] exception = new Throwable[1]; synchronized (process) { Thread t = new Thread() { public void run() { synchronized (process) { try { long[] info = new long[4]; exec(command, info); process[0] = new MyProcess (info[0], (int) info[1], (int) info[2], (int) info[3]); MyProcess p = process[0]; synchronized (p) { try { if (p.pid != 0) { p.exitCode = Runtime.waitFor(p.pid); p.pid = 0; } } finally { p.notifyAll(); } } } catch (Throwable e) { exception[0] = e; } finally { process.notifyAll(); } } } }; t.setDaemon(true); t.start(); while (process[0] == null && exception[0] == null) { try { process.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } if (exception[0] != null) { throw new RuntimeException(exception[0]); } return process[0]; }
public Process exec(final String[] command) { final MyProcess[] process = new MyProcess[1]; final Throwable[] exception = new Throwable[1]; synchronized (process) { Thread t = new Thread() { public void run() { synchronized (process) { try { long[] info = new long[4]; exec(command, info); process[0] = new MyProcess (info[0], (int) info[1], (int) info[2], (int) info[3]); MyProcess p = process[0]; synchronized (p) { try { if (p.pid != 0) { p.exitCode = Runtime.waitFor(p.pid); p.pid = 0; } } finally { p.notifyAll(); } } } catch (Throwable e) { exception[0] = e; } finally { process.notifyAll(); } } } }; t.setDaemon(true); t.start(); while (process[0] == null && exception[0] == null) { try { process.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } if (exception[0] != null) { throw new RuntimeException(exception[0]); } return process[0]; }
diff --git a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/util/OSEnvironment.java b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/util/OSEnvironment.java index f0ce96af..25d24f56 100644 --- a/cruisecontrol/main/src/net/sourceforge/cruisecontrol/util/OSEnvironment.java +++ b/cruisecontrol/main/src/net/sourceforge/cruisecontrol/util/OSEnvironment.java @@ -1,297 +1,297 @@ /******************************************************************************** * CruiseControl, a Continuous Integration Toolkit * Copyright (c) 2001-2003, ThoughtWorks, Inc. * 651 W Washington Ave. Suite 600 * Chicago, IL 60661 USA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * + Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * + Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * + Neither the name of ThoughtWorks, Inc., CruiseControl, 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. ********************************************************************************/ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-2002 The Apache Software Foundation. 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 acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Ant", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * 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 THE APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package net.sourceforge.cruisecontrol.util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; /** * A simple utility class for obtaining and parsing system environment * variables. It has been tested on Windows 2000, Windows XP, Solaris, and * HP-UX, though it should work with any Win32 (95+) or Unix based palatform. * * @author <a href="mailto:[email protected]">Robert J. Smith </a> */ public class OSEnvironment { private static final Logger LOG = Logger.getLogger(OSEnvironment.class); /** * Internal representation of the system environment */ private Properties variables = new Properties(); /** * Constructor * * Creates an instance of OSEnvironment, queries the * OS to discover it's environment variables and makes * them available through the getter methods */ public OSEnvironment() { parse(); } /** * Parses the OS environment and makes the environment * variables available through the getter methods */ private final void parse() { String command; // Detemine the correct command to run based on OS name String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("windows 9") > -1) { command = "command.com /c set"; } else if ( (os.indexOf("nt") > -1) - || (os.indexOf("windows 2000") > -1) + || (os.indexOf("windows 200") > -1) || (os.indexOf("windows xp") > -1) || (os.indexOf("os/2") > -1)) { command = "cmd.exe /c set"; } else { // should work for just about any Unix variant command = "env"; } //Get our environment try { Process p = Runtime.getRuntime().exec(command); // Capture the output of the command BufferedReader stdoutStream = new BufferedReader(new InputStreamReader( p.getInputStream())); BufferedReader stderrStream = new BufferedReader(new InputStreamReader( p.getErrorStream())); // Parse the output String line; while ((line = stdoutStream.readLine()) != null) { int idx = line.indexOf('='); String key = line.substring(0, idx); String value = line.substring(idx + 1); variables.setProperty(key, value); } // Close down our streams stdoutStream.close(); stderrStream.close(); } catch (Exception e) { LOG.error("Failed to parse the OS environment.", e); } } /** * Gets the value of an environment variable. The variable * name is case sensitive. * * @param variable The variable for which you wish the value * * @return The value of the variable, or <code>null</code> * if not found * * @see #getVariable(String variable, String defaultValue) */ public String getVariable(String variable) { return variables.getProperty(variable); } /** * Gets the value of an environment variable. The variable * name is case sensitive. * * @param variable the variable for which you wish the value * * @param defaultValue The value to return if the variable is not set in the environment. * * @return The value of the variable. If the variable is not * found, the defaultValue is returned. */ public String getVariable(String variable, String defaultValue) { return variables.getProperty(variable, defaultValue); } /** * Gets the value of an environment variable. The variable * name is NOT case sensitive. If more than one variable * matches the pattern provided, the result is unpredictable. * You are greatly encouraged to use <code>getVariable()</code> * instead. * * @param variable the variable for which you wish the value * * @see #getVariable(String variable) * @see #getVariable(String variable, String defaultValue) */ public String getVariableIgnoreCase(String variable) { Enumeration keys = variables.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); if (key.equalsIgnoreCase(variable)) { return variables.getProperty(key); } } return null; } /** * Adds a variable to this representation of the * environment. If the variable already existed, the * value will be replaced. * * @param variable the variable to set * @param value the value of the variable */ public void add(String variable, String value) { variables.setProperty(variable, value); } /** * Returns all environment variables which were set at * the time the class was instantiated, as well as any * which have been added programatically. * * @return a <code>List</code> of all environment variables. * The <code>List</code> is made up of <code>String</code>s * of the form "variable=value". * * @see #toArray() */ public List getEnvironment() { List env = new ArrayList(); Enumeration keys = variables.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); env.add(key + "=" + variables.getProperty(key)); } return env; } /** * Returns all environment variables which were set at * the time the class was instantiated, as well as any * which have been added programatically. * * @return a <code>String[]</code> containing all * environment variables. The <code>String</code>s * are of the form "variable=value". This is the * format expected by <code>java.lang.Runtime.exec()</code>. * * @see java.lang.Runtime */ public String[] toArray() { List list = getEnvironment(); return (String[]) list.toArray(new String[list.size()]); } /** * Returns a <code>String<code> representation of the * environment. * * @return A <code>String<code> representation of the environment */ public String toString() { return variables.toString(); } }
true
true
private final void parse() { String command; // Detemine the correct command to run based on OS name String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("windows 9") > -1) { command = "command.com /c set"; } else if ( (os.indexOf("nt") > -1) || (os.indexOf("windows 2000") > -1) || (os.indexOf("windows xp") > -1) || (os.indexOf("os/2") > -1)) { command = "cmd.exe /c set"; } else { // should work for just about any Unix variant command = "env"; } //Get our environment try { Process p = Runtime.getRuntime().exec(command); // Capture the output of the command BufferedReader stdoutStream = new BufferedReader(new InputStreamReader( p.getInputStream())); BufferedReader stderrStream = new BufferedReader(new InputStreamReader( p.getErrorStream())); // Parse the output String line; while ((line = stdoutStream.readLine()) != null) { int idx = line.indexOf('='); String key = line.substring(0, idx); String value = line.substring(idx + 1); variables.setProperty(key, value); } // Close down our streams stdoutStream.close(); stderrStream.close(); } catch (Exception e) { LOG.error("Failed to parse the OS environment.", e); } }
private final void parse() { String command; // Detemine the correct command to run based on OS name String os = System.getProperty("os.name").toLowerCase(); if (os.indexOf("windows 9") > -1) { command = "command.com /c set"; } else if ( (os.indexOf("nt") > -1) || (os.indexOf("windows 200") > -1) || (os.indexOf("windows xp") > -1) || (os.indexOf("os/2") > -1)) { command = "cmd.exe /c set"; } else { // should work for just about any Unix variant command = "env"; } //Get our environment try { Process p = Runtime.getRuntime().exec(command); // Capture the output of the command BufferedReader stdoutStream = new BufferedReader(new InputStreamReader( p.getInputStream())); BufferedReader stderrStream = new BufferedReader(new InputStreamReader( p.getErrorStream())); // Parse the output String line; while ((line = stdoutStream.readLine()) != null) { int idx = line.indexOf('='); String key = line.substring(0, idx); String value = line.substring(idx + 1); variables.setProperty(key, value); } // Close down our streams stdoutStream.close(); stderrStream.close(); } catch (Exception e) { LOG.error("Failed to parse the OS environment.", e); } }
diff --git a/src/itschess/Evaluation.java b/src/itschess/Evaluation.java index 92c79fb..7dc7cb2 100644 --- a/src/itschess/Evaluation.java +++ b/src/itschess/Evaluation.java @@ -1,205 +1,205 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package itschess; /** * * @author Ian */ public class Evaluation { public static double eval(Board chessboard){ byte[][] board = chessboard.board; double k = 0; double kb = 0; double q =0; double qb = 0; double r =0; double rb = 0; double b =0; double bb = 0; double n =0; double nb = 0; double p =0; double pb = 0; double d = 0; double db = 0; double kingBonus = 0; double knightBonus = 0; double pawnBonus = 0; double kingEndBonus = 0; double bishopBonus = 0; double kingPenalty = 0; double knightPenalty = 0; double pawnPenalty = 0; double kingEndPenalty = 0; double bishopPenalty = 0; - for(int i = 0; i < 7; i ++) + for(int i = 0; i < 8; i ++) { - for(int j = 0; j < 7; j++) + for(int j = 0; j < 8; j++) { if(board[i][j] == 0) continue; else if(board[i][j] == 1) { k ++; k += KingTable[(i)*8 + (j)]; } else if(board[i][j] == -1) { kb ++; kb += KingTable[Math.abs(i-7)* 8 + Math.abs(j-7)];//have to flip positions for black pieces // kingPenalty = KingTable[(i+1)*(j+1)]; } else if(board[i][j] == 2) { q ++; } else if(board[i][j] == -2) { qb ++; } else if(board[i][j] == 3) { r ++; } else if(board[i][j] == -3) { rb ++; } else if(board[i][j] == 4) { b ++; b += BishopTable[(i)*8 + (j)]; } else if(board[i][j] == -4) { bb ++; bb += BishopTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // bishopBonus -= BishopTable[(i+1)*(j+1)]; } else if(board[i][j] == 5) { n ++; n += KnightTable[(i)*8 + (j)]; } else if(board[i][j] == -5) { nb ++; nb += KnightTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // knightBonus -= KnightTable[(i+1)*(j+1)]; } else if(board[i][j] == 6) { p ++; p += PawnTable[(i)*8 + (j)]; if (i > 0 && board[i-1][j] == 6) d ++; } else if(board[i][j] == -6) { pb ++; pb += PawnTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // pawnBonus -= PawnTable[(i+1)*(j+1)]; if (i < 6 && board[i+1][j] == -6) db ++; } } } double evalNum = 200*(k-kb) + 9*(q-qb) + 5*(r-rb) + 3*((b-bb) + (n-nb)) + (p-pb) - .5*(d-db) + chessboard.boardScore; return evalNum; } private static double[] PawnTable = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, .5, .5, .5, .5, .5, .5, .5, .5, .1, .1, .2, .3, .3, .2, .1, .1, .05, .05, .1, .27, .27, .1, .05, .05, 0, 0, 0, .25, .25, 0, 0, 0, .05, -.05,-.1, 0, 0,-.1, -.05, .05, .05, .1, .1,-.25,-.25, .1, .1, .05, 0, 0, 0, 0, 0, 0, 0, 0 }; private static double[] KnightTable = new double[] { -.5,-.4,-.3,-.3,-.3,-.3,-.4,-.5, -.4,-.2, 0, 0, 0, 0,-.2,-.4, -.3, 0, .1, .15, .15, .1, 0,-.3, -.3, .05, .15, .2, .2, .15, .05,-.3, -.3, 0, .15, .2, .2, 15, 0,-.3, -.3, .05, .1, .15, .15, .1, .05,-.3, -.4,-.2, 0, .05, .05, 0,-.2,-.4, -.5,-.4,-.2,-.3,-.3,-.2,-.4,-.5 }; private static double[] KingTable = new double[] { -.3, -.4, -.4, -.5, -.5, -.4, -.4, -.3, -.3, -.4, -.4, -.5, -.5, -.4, -.4, -.3, -.3, -.4, -.4, -.5, -.5, -.4, -.4, -.3, -.3, -.4, -.4, -.5, -.5, -.4, -.4, -.3, -.2, -.3, -.3, -.4, -.4, -.3, -.3, -.2, -.1, -.2, -.2, -.2, -.2, -.2, -.2, -.1, .2, .2, 0, 0, 0, 0, .2, .2, .2, .3, .1, 0, 0, .1, .3, .2 }; private static double[] KingTableEndGame = new double[] { -.5,-.4,-.3,-.2,-.2,-.3,-.4,-.5, -.3,-.2,-.1, 0, 0,-.1,-.2,-.3, -.3,-.1, .2, .3, .3, .2,-.1,-.3, -.3,-.1, .3, .4, .4, .3,-.1,-.3, -.3,-.1, .3, .4, .4, .3,-.1,-.3, -.3,-.1, .20, .3, .3, .20,-.1,-.3, -.3,-.3, 0, 0, 0, 0,-.3,-.3, -.5,-.3,-.3,-.3,-.3,-.3,-.3,-.5 }; private static double[] BishopTable = new double[] { -.20,-.10,-.10,-.10,-.10,-.10,-.10,-.20, -.10, 0, 0, 0, 0, 0, 0,-.10, -.10, 0, .05, .10, .10, .05, 0,-.10, -.10, .05, .05, .10, .10, .05, .05,-.10, -.10, 0, .10,.10, .10, .10, 0,-.10, -.10, .10, .10, .10, .10, .10, .10,-.10, -.10, .05, 0, 0, 0, 0, .05,-.10, -.20,-.10,-.40,-.10,-.10,-.40,-.10,-.20 }; public static byte pieceValue(byte piece) { if(Math.abs(piece) == 3) { return 5; } else if(Math.abs(piece) == 2) { return 9; } else if(Math.abs(piece) == 1) { return 125; } else if(Math.abs(piece) == 4 || Math.abs(piece) == 5) { return 3; } else if(Math.abs(piece) == 6) { return 1; } return 0; } }
false
true
public static double eval(Board chessboard){ byte[][] board = chessboard.board; double k = 0; double kb = 0; double q =0; double qb = 0; double r =0; double rb = 0; double b =0; double bb = 0; double n =0; double nb = 0; double p =0; double pb = 0; double d = 0; double db = 0; double kingBonus = 0; double knightBonus = 0; double pawnBonus = 0; double kingEndBonus = 0; double bishopBonus = 0; double kingPenalty = 0; double knightPenalty = 0; double pawnPenalty = 0; double kingEndPenalty = 0; double bishopPenalty = 0; for(int i = 0; i < 7; i ++) { for(int j = 0; j < 7; j++) { if(board[i][j] == 0) continue; else if(board[i][j] == 1) { k ++; k += KingTable[(i)*8 + (j)]; } else if(board[i][j] == -1) { kb ++; kb += KingTable[Math.abs(i-7)* 8 + Math.abs(j-7)];//have to flip positions for black pieces // kingPenalty = KingTable[(i+1)*(j+1)]; } else if(board[i][j] == 2) { q ++; } else if(board[i][j] == -2) { qb ++; } else if(board[i][j] == 3) { r ++; } else if(board[i][j] == -3) { rb ++; } else if(board[i][j] == 4) { b ++; b += BishopTable[(i)*8 + (j)]; } else if(board[i][j] == -4) { bb ++; bb += BishopTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // bishopBonus -= BishopTable[(i+1)*(j+1)]; } else if(board[i][j] == 5) { n ++; n += KnightTable[(i)*8 + (j)]; } else if(board[i][j] == -5) { nb ++; nb += KnightTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // knightBonus -= KnightTable[(i+1)*(j+1)]; } else if(board[i][j] == 6) { p ++; p += PawnTable[(i)*8 + (j)]; if (i > 0 && board[i-1][j] == 6) d ++; } else if(board[i][j] == -6) { pb ++; pb += PawnTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // pawnBonus -= PawnTable[(i+1)*(j+1)]; if (i < 6 && board[i+1][j] == -6) db ++; } } } double evalNum = 200*(k-kb) + 9*(q-qb) + 5*(r-rb) + 3*((b-bb) + (n-nb)) + (p-pb) - .5*(d-db) + chessboard.boardScore; return evalNum; }
public static double eval(Board chessboard){ byte[][] board = chessboard.board; double k = 0; double kb = 0; double q =0; double qb = 0; double r =0; double rb = 0; double b =0; double bb = 0; double n =0; double nb = 0; double p =0; double pb = 0; double d = 0; double db = 0; double kingBonus = 0; double knightBonus = 0; double pawnBonus = 0; double kingEndBonus = 0; double bishopBonus = 0; double kingPenalty = 0; double knightPenalty = 0; double pawnPenalty = 0; double kingEndPenalty = 0; double bishopPenalty = 0; for(int i = 0; i < 8; i ++) { for(int j = 0; j < 8; j++) { if(board[i][j] == 0) continue; else if(board[i][j] == 1) { k ++; k += KingTable[(i)*8 + (j)]; } else if(board[i][j] == -1) { kb ++; kb += KingTable[Math.abs(i-7)* 8 + Math.abs(j-7)];//have to flip positions for black pieces // kingPenalty = KingTable[(i+1)*(j+1)]; } else if(board[i][j] == 2) { q ++; } else if(board[i][j] == -2) { qb ++; } else if(board[i][j] == 3) { r ++; } else if(board[i][j] == -3) { rb ++; } else if(board[i][j] == 4) { b ++; b += BishopTable[(i)*8 + (j)]; } else if(board[i][j] == -4) { bb ++; bb += BishopTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // bishopBonus -= BishopTable[(i+1)*(j+1)]; } else if(board[i][j] == 5) { n ++; n += KnightTable[(i)*8 + (j)]; } else if(board[i][j] == -5) { nb ++; nb += KnightTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // knightBonus -= KnightTable[(i+1)*(j+1)]; } else if(board[i][j] == 6) { p ++; p += PawnTable[(i)*8 + (j)]; if (i > 0 && board[i-1][j] == 6) d ++; } else if(board[i][j] == -6) { pb ++; pb += PawnTable[Math.abs(i-7)* 8 + Math.abs(j-7)]; // pawnBonus -= PawnTable[(i+1)*(j+1)]; if (i < 6 && board[i+1][j] == -6) db ++; } } } double evalNum = 200*(k-kb) + 9*(q-qb) + 5*(r-rb) + 3*((b-bb) + (n-nb)) + (p-pb) - .5*(d-db) + chessboard.boardScore; return evalNum; }
diff --git a/src/main/java/com/freeroom/projectci/beans/ReportService.java b/src/main/java/com/freeroom/projectci/beans/ReportService.java index fc23765..5f52f83 100644 --- a/src/main/java/com/freeroom/projectci/beans/ReportService.java +++ b/src/main/java/com/freeroom/projectci/beans/ReportService.java @@ -1,76 +1,76 @@ package com.freeroom.projectci.beans; import com.freeroom.di.annotations.Bean; import com.freeroom.di.annotations.Inject; import com.freeroom.persistence.Athena; import com.freeroom.util.Pair; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.List; import static com.freeroom.projectci.beans.ReportType.*; import static java.lang.String.format; @Bean public class ReportService { @Inject private Athena athena; public Collection getCollection(ReportType type) { return new Collection(type, type.getEstimatedEffort(), calculateUsedEffort(athena.from(TimeReport.class).find(format("type='%s'", type)))); } public Pair<Integer, Integer> getTickBar() { final DateTime now = new DateTime(); final DateTime begin = new DateTime(2014, 4, 15, 0, 0, 0); final DateTime end = new DateTime(2014, 10, 13, 0, 0, 0); return Pair.of(Days.daysBetween(begin, end).getDays(), Days.daysBetween(begin, now).getDays()); } public void addReport(TimeReport report) { athena.persist(report); } private long calculateUsedEffort(List<Object> reports) { long usedEffort = 0; for (Object report : reports) { usedEffort += ((TimeReport) report).getHours(); } return usedEffort; } public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); DateTime date = new DateTime(2014, 4, 15, 0, 0, 0); System.out.println(">>>>>>>>>>>>>> 1111111111111111"); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } - System.out.println(">>>>>>>>>>>>>> 22222222222222222"); + System.out.println(">>>>>>>>>>>>>> 22222222222222222: " + sb.toString()); return sb.toString(); } }
true
true
public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); DateTime date = new DateTime(2014, 4, 15, 0, 0, 0); System.out.println(">>>>>>>>>>>>>> 1111111111111111"); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } System.out.println(">>>>>>>>>>>>>> 22222222222222222"); return sb.toString(); }
public String utilityData() { final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd"); final DateTime yesterday = new DateTime().minusDays(1); DateTime date = new DateTime(2014, 4, 15, 0, 0, 0); System.out.println(">>>>>>>>>>>>>> 1111111111111111"); final StringBuilder sb = new StringBuilder(); sb.append("date\tMust\tOthers\r\n"); while(date.isBefore(yesterday)) { final List<Object> mustReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), UserStory, FunctionalTesting, PerformanceTesting, IntegrationTesting, Document)); final List<Object> othersReports = athena.from(TimeReport.class).find( format("date='%s' and (type='%s' or type='%s' or type='%s' or type='%s')", date.toDate().getTime(), OverTime, BugFixing, Leave, Others)); sb.append(format("%s\t%d\t%d\r\n", formatter.print(date), calculateUsedEffort(mustReports), calculateUsedEffort(othersReports))); date = date.plusDays(1); } System.out.println(">>>>>>>>>>>>>> 22222222222222222: " + sb.toString()); return sb.toString(); }
diff --git a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java index 2ee0c3ec8..bf4eff940 100644 --- a/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java +++ b/fritzing/Fritzing.diagram/src/org/fritzing/fritzing/diagram/part/FritzingPCBExportAction.java @@ -1,122 +1,121 @@ /* * (c) Fachhochschule Potsdam */ package org.fritzing.fritzing.diagram.part; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.emf.common.util.URI; import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer; import org.eclipse.jface.action.IAction; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkbenchWindowActionDelegate; import org.fritzing.fritzing.diagram.export.Fritzing2Eagle; import org.fritzing.fritzing.diagram.preferences.EaglePreferencePage; /** * @generated NOT */ public class FritzingPCBExportAction implements IWorkbenchWindowActionDelegate { /** * @generated NOT */ private IWorkbenchWindow window; /** * @generated NOT */ public void init(IWorkbenchWindow window) { this.window = window; } /** * @generated NOT */ public void dispose() { window = null; } /** * @generated NOT */ public void selectionChanged(IAction action, ISelection selection) { } /** * @generated NOT */ private Shell getShell() { return window.getShell(); } /** * @generated NOT */ public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files // use currently active diagram IDiagramGraphicalViewer viewer = FritzingDiagramEditorUtil.getActiveDiagramEditor() .getDiagramGraphicalViewer(); String script = Fritzing2Eagle.createEagleScript(viewer); // TODO: write script to file URI fritzingDiagramURI = FritzingDiagramEditorUtil.getActiveDiagramURI(); String fritzing2eagleSCR = fritzingDiagramURI.trimFileExtension() .appendFileExtension("scr").toFileString(); try { Writer w = new FileWriter(fritzing2eagleSCR); w.write(script); w.close(); } catch (IOException e1) { e1.printStackTrace(); } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance().getPluginPreferences(); String eagleLocation = preferences.getString( EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if(Platform.getOS().equals(Platform.OS_WIN32)) { - eagleExec = "bin/eagle.exe"; + eagleExec = "\"" + eagleLocation + "bin/eagle.exe" + "\""; } else if(Platform.getOS().equals(Platform.OS_MACOSX)) { - eagleExec = "EAGLE.app/Contents/MacOS/eagle"; + eagleExec = eagleLocation + "EAGLE.app/Contents/MacOS/eagle"; } else if(Platform.getOS().equals(Platform.OS_LINUX)) { - eagleExec = "bin/eagle"; + eagleExec = eagleLocation + "bin/eagle"; } // EAGLE PCB ULP -// String eagleULP = Platform.getLocation().toString() + "/eagle/ulp/fritzing_master.ulp"; String eagleULP = eagleLocation + "ulp/fritzing_master.ulp"; // EAGLE Schematc String eagleSCH = fritzingDiagramURI.trimFileExtension() .appendFileExtension("sch").toFileString(); // EAGLE parameters String eagleParams = "-C\"RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "'\" " + - "\"" + eagleSCH + "\"" ; + "\"" + eagleSCH + "\""; // Run! String command = - "\"" + eagleLocation + eagleExec + "\" " + eagleParams; + eagleExec + " " + eagleParams; try { Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); } } }
false
true
public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files // use currently active diagram IDiagramGraphicalViewer viewer = FritzingDiagramEditorUtil.getActiveDiagramEditor() .getDiagramGraphicalViewer(); String script = Fritzing2Eagle.createEagleScript(viewer); // TODO: write script to file URI fritzingDiagramURI = FritzingDiagramEditorUtil.getActiveDiagramURI(); String fritzing2eagleSCR = fritzingDiagramURI.trimFileExtension() .appendFileExtension("scr").toFileString(); try { Writer w = new FileWriter(fritzing2eagleSCR); w.write(script); w.close(); } catch (IOException e1) { e1.printStackTrace(); } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance().getPluginPreferences(); String eagleLocation = preferences.getString( EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if(Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = "bin/eagle.exe"; } else if(Platform.getOS().equals(Platform.OS_MACOSX)) { eagleExec = "EAGLE.app/Contents/MacOS/eagle"; } else if(Platform.getOS().equals(Platform.OS_LINUX)) { eagleExec = "bin/eagle"; } // EAGLE PCB ULP // String eagleULP = Platform.getLocation().toString() + "/eagle/ulp/fritzing_master.ulp"; String eagleULP = eagleLocation + "ulp/fritzing_master.ulp"; // EAGLE Schematc String eagleSCH = fritzingDiagramURI.trimFileExtension() .appendFileExtension("sch").toFileString(); // EAGLE parameters String eagleParams = "-C\"RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "'\" " + "\"" + eagleSCH + "\"" ; // Run! String command = "\"" + eagleLocation + eagleExec + "\" " + eagleParams; try { Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); } }
public void run(IAction action) { // STEP 1: create Eagle script file from Fritzing files // use currently active diagram IDiagramGraphicalViewer viewer = FritzingDiagramEditorUtil.getActiveDiagramEditor() .getDiagramGraphicalViewer(); String script = Fritzing2Eagle.createEagleScript(viewer); // TODO: write script to file URI fritzingDiagramURI = FritzingDiagramEditorUtil.getActiveDiagramURI(); String fritzing2eagleSCR = fritzingDiagramURI.trimFileExtension() .appendFileExtension("scr").toFileString(); try { Writer w = new FileWriter(fritzing2eagleSCR); w.write(script); w.close(); } catch (IOException e1) { e1.printStackTrace(); } // STEP 2: start Eagle ULP on the created script file // EAGLE folder Preferences preferences = FritzingDiagramEditorPlugin.getInstance().getPluginPreferences(); String eagleLocation = preferences.getString( EaglePreferencePage.EAGLE_LOCATION) + File.separator; // EAGLE executable String eagleExec = ""; if(Platform.getOS().equals(Platform.OS_WIN32)) { eagleExec = "\"" + eagleLocation + "bin/eagle.exe" + "\""; } else if(Platform.getOS().equals(Platform.OS_MACOSX)) { eagleExec = eagleLocation + "EAGLE.app/Contents/MacOS/eagle"; } else if(Platform.getOS().equals(Platform.OS_LINUX)) { eagleExec = eagleLocation + "bin/eagle"; } // EAGLE PCB ULP String eagleULP = eagleLocation + "ulp/fritzing_master.ulp"; // EAGLE Schematc String eagleSCH = fritzingDiagramURI.trimFileExtension() .appendFileExtension("sch").toFileString(); // EAGLE parameters String eagleParams = "-C\"RUN " + "'" + eagleULP + "' " + "'" + fritzing2eagleSCR + "'\" " + "\"" + eagleSCH + "\""; // Run! String command = eagleExec + " " + eagleParams; try { Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java b/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java index 16b1877..7c35dd0 100644 --- a/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java +++ b/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java @@ -1,62 +1,67 @@ package me.sacnoth.bottledexp; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class BottledExpCommandExecutor implements CommandExecutor { public BottledExpCommandExecutor(BottledExp plugin) { } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if ((sender instanceof Player)) { if (cmd.getName().equalsIgnoreCase("bottle")) { Player player = (Player) sender; int currentxp = player.getTotalExperience(); if (args.length == 0) { sender.sendMessage(BottledExp.langCurrentXP + ": " + currentxp + " XP!"); } else if (args.length == 1) { int amount; if (args[0].equals("max")) { amount = (int) Math.floor(currentxp / 10); } else { try { amount = Integer.valueOf(args[0]).intValue(); } catch (NumberFormatException nfe) { sender.sendMessage(ChatColor.RED + BottledExp.errAmount); return false; } } if (currentxp < amount * BottledExp.xpCost) { sender.sendMessage(ChatColor.RED + BottledExp.errXP); - } else { + } + else if (amount == 0) { + sender.sendMessage(BottledExp.langOrder1 + " " + amount + + " " + BottledExp.langOrder2); + } + else { PlayerInventory inventory = player.getInventory(); ItemStack items = new ItemStack(384, amount); inventory.addItem(items); player.setTotalExperience(0); player.setLevel(0); player.setExp(0); player.giveExp(currentxp - (amount * BottledExp.xpCost)); sender.sendMessage(BottledExp.langOrder1 + " " + amount + " " + BottledExp.langOrder2); } } return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player!"); return false; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if ((sender instanceof Player)) { if (cmd.getName().equalsIgnoreCase("bottle")) { Player player = (Player) sender; int currentxp = player.getTotalExperience(); if (args.length == 0) { sender.sendMessage(BottledExp.langCurrentXP + ": " + currentxp + " XP!"); } else if (args.length == 1) { int amount; if (args[0].equals("max")) { amount = (int) Math.floor(currentxp / 10); } else { try { amount = Integer.valueOf(args[0]).intValue(); } catch (NumberFormatException nfe) { sender.sendMessage(ChatColor.RED + BottledExp.errAmount); return false; } } if (currentxp < amount * BottledExp.xpCost) { sender.sendMessage(ChatColor.RED + BottledExp.errXP); } else { PlayerInventory inventory = player.getInventory(); ItemStack items = new ItemStack(384, amount); inventory.addItem(items); player.setTotalExperience(0); player.setLevel(0); player.setExp(0); player.giveExp(currentxp - (amount * BottledExp.xpCost)); sender.sendMessage(BottledExp.langOrder1 + " " + amount + " " + BottledExp.langOrder2); } } return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player!"); return false; } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if ((sender instanceof Player)) { if (cmd.getName().equalsIgnoreCase("bottle")) { Player player = (Player) sender; int currentxp = player.getTotalExperience(); if (args.length == 0) { sender.sendMessage(BottledExp.langCurrentXP + ": " + currentxp + " XP!"); } else if (args.length == 1) { int amount; if (args[0].equals("max")) { amount = (int) Math.floor(currentxp / 10); } else { try { amount = Integer.valueOf(args[0]).intValue(); } catch (NumberFormatException nfe) { sender.sendMessage(ChatColor.RED + BottledExp.errAmount); return false; } } if (currentxp < amount * BottledExp.xpCost) { sender.sendMessage(ChatColor.RED + BottledExp.errXP); } else if (amount == 0) { sender.sendMessage(BottledExp.langOrder1 + " " + amount + " " + BottledExp.langOrder2); } else { PlayerInventory inventory = player.getInventory(); ItemStack items = new ItemStack(384, amount); inventory.addItem(items); player.setTotalExperience(0); player.setLevel(0); player.setExp(0); player.giveExp(currentxp - (amount * BottledExp.xpCost)); sender.sendMessage(BottledExp.langOrder1 + " " + amount + " " + BottledExp.langOrder2); } } return true; } } else { sender.sendMessage(ChatColor.RED + "You must be a player!"); return false; } return false; }
diff --git a/src/PackageInfo/QueryProperties.java b/src/PackageInfo/QueryProperties.java index 38eb473..6bdc342 100644 --- a/src/PackageInfo/QueryProperties.java +++ b/src/PackageInfo/QueryProperties.java @@ -1,132 +1,138 @@ /* * $RCSfile$ * * Copyright (c) 2004 Sun Microsystems, 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: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution 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 Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. * * $Revision$ * $Date$ * $State$ */ import java.util.Map; import javax.media.j3d.*; import java.awt.GraphicsEnvironment; import java.awt.GraphicsConfiguration; import com.sun.j3d.utils.universe.*; public class QueryProperties { public static void main(String[] args) { VirtualUniverse vu = new VirtualUniverse(); Map vuMap = vu.getProperties(); System.out.println("version = " + vuMap.get("j3d.version")); System.out.println("vendor = " + vuMap.get("j3d.vendor")); System.out.println("specification.version = " + vuMap.get("j3d.specification.version")); System.out.println("specification.vendor = " + vuMap.get("j3d.specification.vendor")); System.out.println("renderer = " + vuMap.get("j3d.renderer") + "\n"); GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D(); /* We need to set this to force choosing a pixel format that support the canvas. */ template.setStereo(template.PREFERRED); template.setSceneAntialiasing(template.PREFERRED); GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getBestConfiguration(template); Map c3dMap = new Canvas3D(config).queryProperties(); System.out.println("Renderer version = " + c3dMap.get("native.version")); System.out.println("doubleBufferAvailable = " + c3dMap.get("doubleBufferAvailable")); System.out.println("stereoAvailable = " + c3dMap.get("stereoAvailable")); System.out.println("sceneAntialiasingAvailable = " + c3dMap.get("sceneAntialiasingAvailable")); System.out.println("sceneAntialiasingNumPasses = " + c3dMap.get("sceneAntialiasingNumPasses")); System.out.println("textureColorTableSize = " + c3dMap.get("textureColorTableSize")); System.out.println("textureEnvCombineAvailable = " + c3dMap.get("textureEnvCombineAvailable")); System.out.println("textureCombineDot3Available = " + c3dMap.get("textureCombineDot3Available")); System.out.println("textureCombineSubtractAvailable = " + c3dMap.get("textureCombineSubtractAvailable")); System.out.println("texture3DAvailable = " + c3dMap.get("texture3DAvailable")); System.out.println("textureCubeMapAvailable = " + c3dMap.get("textureCubeMapAvailable")); System.out.println("textureSharpenAvailable = " + c3dMap.get("textureSharpenAvailable")); System.out.println("textureDetailAvailable = " + c3dMap.get("textureDetailAvailable")); System.out.println("textureFilter4Available = " + c3dMap.get("textureFilter4Available")); System.out.println("textureAnisotropicFilterDegreeMax = " + c3dMap.get("textureAnisotropicFilterDegreeMax")); System.out.println("textureBoundaryWidthMax = " + c3dMap.get("textureBoundaryWidthMax")); System.out.println("textureWidthMax = " + c3dMap.get("textureWidthMax")); System.out.println("textureHeightMax = " + c3dMap.get("textureHeightMax")); + System.out.println("texture3DWidthMax = " + + c3dMap.get("texture3DWidthMax")); + System.out.println("texture3DHeightMax = " + + c3dMap.get("texture3DHeightMax")); + System.out.println("texture3DDepthMax = " + + c3dMap.get("texture3DDepthMax")); System.out.println("textureLodOffsetAvailable = " + c3dMap.get("textureLodOffsetAvailable")); System.out.println("textureLodRangeAvailable = " + c3dMap.get("textureLodRangeAvailable")); System.out.println("textureUnitStateMax = " + c3dMap.get("textureUnitStateMax")); System.out.println("compressedGeometry.majorVersionNumber = " + c3dMap.get("compressedGeometry.majorVersionNumber")); System.out.println("compressedGeometry.minorVersionNumber = " + c3dMap.get("compressedGeometry.minorVersionNumber")); System.out.println("compressedGeometry.minorMinorVersionNumber = " + c3dMap.get("compressedGeometry.minorMinorVersionNumber")); System.exit(0); } }
true
true
public static void main(String[] args) { VirtualUniverse vu = new VirtualUniverse(); Map vuMap = vu.getProperties(); System.out.println("version = " + vuMap.get("j3d.version")); System.out.println("vendor = " + vuMap.get("j3d.vendor")); System.out.println("specification.version = " + vuMap.get("j3d.specification.version")); System.out.println("specification.vendor = " + vuMap.get("j3d.specification.vendor")); System.out.println("renderer = " + vuMap.get("j3d.renderer") + "\n"); GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D(); /* We need to set this to force choosing a pixel format that support the canvas. */ template.setStereo(template.PREFERRED); template.setSceneAntialiasing(template.PREFERRED); GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getBestConfiguration(template); Map c3dMap = new Canvas3D(config).queryProperties(); System.out.println("Renderer version = " + c3dMap.get("native.version")); System.out.println("doubleBufferAvailable = " + c3dMap.get("doubleBufferAvailable")); System.out.println("stereoAvailable = " + c3dMap.get("stereoAvailable")); System.out.println("sceneAntialiasingAvailable = " + c3dMap.get("sceneAntialiasingAvailable")); System.out.println("sceneAntialiasingNumPasses = " + c3dMap.get("sceneAntialiasingNumPasses")); System.out.println("textureColorTableSize = " + c3dMap.get("textureColorTableSize")); System.out.println("textureEnvCombineAvailable = " + c3dMap.get("textureEnvCombineAvailable")); System.out.println("textureCombineDot3Available = " + c3dMap.get("textureCombineDot3Available")); System.out.println("textureCombineSubtractAvailable = " + c3dMap.get("textureCombineSubtractAvailable")); System.out.println("texture3DAvailable = " + c3dMap.get("texture3DAvailable")); System.out.println("textureCubeMapAvailable = " + c3dMap.get("textureCubeMapAvailable")); System.out.println("textureSharpenAvailable = " + c3dMap.get("textureSharpenAvailable")); System.out.println("textureDetailAvailable = " + c3dMap.get("textureDetailAvailable")); System.out.println("textureFilter4Available = " + c3dMap.get("textureFilter4Available")); System.out.println("textureAnisotropicFilterDegreeMax = " + c3dMap.get("textureAnisotropicFilterDegreeMax")); System.out.println("textureBoundaryWidthMax = " + c3dMap.get("textureBoundaryWidthMax")); System.out.println("textureWidthMax = " + c3dMap.get("textureWidthMax")); System.out.println("textureHeightMax = " + c3dMap.get("textureHeightMax")); System.out.println("textureLodOffsetAvailable = " + c3dMap.get("textureLodOffsetAvailable")); System.out.println("textureLodRangeAvailable = " + c3dMap.get("textureLodRangeAvailable")); System.out.println("textureUnitStateMax = " + c3dMap.get("textureUnitStateMax")); System.out.println("compressedGeometry.majorVersionNumber = " + c3dMap.get("compressedGeometry.majorVersionNumber")); System.out.println("compressedGeometry.minorVersionNumber = " + c3dMap.get("compressedGeometry.minorVersionNumber")); System.out.println("compressedGeometry.minorMinorVersionNumber = " + c3dMap.get("compressedGeometry.minorMinorVersionNumber")); System.exit(0); }
public static void main(String[] args) { VirtualUniverse vu = new VirtualUniverse(); Map vuMap = vu.getProperties(); System.out.println("version = " + vuMap.get("j3d.version")); System.out.println("vendor = " + vuMap.get("j3d.vendor")); System.out.println("specification.version = " + vuMap.get("j3d.specification.version")); System.out.println("specification.vendor = " + vuMap.get("j3d.specification.vendor")); System.out.println("renderer = " + vuMap.get("j3d.renderer") + "\n"); GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D(); /* We need to set this to force choosing a pixel format that support the canvas. */ template.setStereo(template.PREFERRED); template.setSceneAntialiasing(template.PREFERRED); GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getBestConfiguration(template); Map c3dMap = new Canvas3D(config).queryProperties(); System.out.println("Renderer version = " + c3dMap.get("native.version")); System.out.println("doubleBufferAvailable = " + c3dMap.get("doubleBufferAvailable")); System.out.println("stereoAvailable = " + c3dMap.get("stereoAvailable")); System.out.println("sceneAntialiasingAvailable = " + c3dMap.get("sceneAntialiasingAvailable")); System.out.println("sceneAntialiasingNumPasses = " + c3dMap.get("sceneAntialiasingNumPasses")); System.out.println("textureColorTableSize = " + c3dMap.get("textureColorTableSize")); System.out.println("textureEnvCombineAvailable = " + c3dMap.get("textureEnvCombineAvailable")); System.out.println("textureCombineDot3Available = " + c3dMap.get("textureCombineDot3Available")); System.out.println("textureCombineSubtractAvailable = " + c3dMap.get("textureCombineSubtractAvailable")); System.out.println("texture3DAvailable = " + c3dMap.get("texture3DAvailable")); System.out.println("textureCubeMapAvailable = " + c3dMap.get("textureCubeMapAvailable")); System.out.println("textureSharpenAvailable = " + c3dMap.get("textureSharpenAvailable")); System.out.println("textureDetailAvailable = " + c3dMap.get("textureDetailAvailable")); System.out.println("textureFilter4Available = " + c3dMap.get("textureFilter4Available")); System.out.println("textureAnisotropicFilterDegreeMax = " + c3dMap.get("textureAnisotropicFilterDegreeMax")); System.out.println("textureBoundaryWidthMax = " + c3dMap.get("textureBoundaryWidthMax")); System.out.println("textureWidthMax = " + c3dMap.get("textureWidthMax")); System.out.println("textureHeightMax = " + c3dMap.get("textureHeightMax")); System.out.println("texture3DWidthMax = " + c3dMap.get("texture3DWidthMax")); System.out.println("texture3DHeightMax = " + c3dMap.get("texture3DHeightMax")); System.out.println("texture3DDepthMax = " + c3dMap.get("texture3DDepthMax")); System.out.println("textureLodOffsetAvailable = " + c3dMap.get("textureLodOffsetAvailable")); System.out.println("textureLodRangeAvailable = " + c3dMap.get("textureLodRangeAvailable")); System.out.println("textureUnitStateMax = " + c3dMap.get("textureUnitStateMax")); System.out.println("compressedGeometry.majorVersionNumber = " + c3dMap.get("compressedGeometry.majorVersionNumber")); System.out.println("compressedGeometry.minorVersionNumber = " + c3dMap.get("compressedGeometry.minorVersionNumber")); System.out.println("compressedGeometry.minorMinorVersionNumber = " + c3dMap.get("compressedGeometry.minorMinorVersionNumber")); System.exit(0); }
diff --git a/src/main/java/si/mazi/rescu/HttpTemplate.java b/src/main/java/si/mazi/rescu/HttpTemplate.java index a2336c2..3fcb44b 100644 --- a/src/main/java/si/mazi/rescu/HttpTemplate.java +++ b/src/main/java/si/mazi/rescu/HttpTemplate.java @@ -1,267 +1,268 @@ /** * Copyright (C) 2012 - 2013 Xeiam LLC http://xeiam.com * Copyright (C) 2012 - 2013 Matija Mazi [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package si.mazi.rescu; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import si.mazi.rescu.utils.Assert; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; /** * Various HTTP utility methods */ class HttpTemplate { public final static String CHARSET_UTF_8 = "UTF-8"; private final Logger log = LoggerFactory.getLogger(HttpTemplate.class); private ObjectMapper objectMapper; /** * Default request header fields */ private Map<String, String> defaultHttpHeaders = new HashMap<String, String>(); private final int readTimeout = Config.getHttpReadTimeout(); /** * Constructor */ public HttpTemplate() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Always use UTF8 defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8); // Assume form encoding by default (typically becomes application/json or application/xml) defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded"); // Accept text/plain by default (typically becomes application/json or application/xml) defaultHttpHeaders.put("Accept", "text/plain"); // User agent provides statistics for servers, but some use it for content negotiation so fake good agents defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent } /** * Requests JSON via an HTTP POST * * * @param urlString A string representation of a URL * @param returnType The required return type * @param requestBody The contents of the request body * @param httpHeaders Any custom header values (application/json is provided automatically) * @param method Http method (usually GET or POST) * @param contentType the mime type to be set as the value of the Content-Type header * @param exceptionType * @return String - the fetched JSON String */ public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType, Class<? extends RuntimeException> exceptionType) { log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders should not be null"); httpHeaders.put("Accept", "application/json"); if (contentType != null) { httpHeaders.put("Content-Type", contentType); } try { int contentLength = requestBody == null ? 0 : requestBody.length(); HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } String responseEncoding = getResponseEncoding(connection); int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (httpStatus != 200) { - InputStream errorStream = connection.getErrorStream(); + String httpBody = readInputStreamAsEncodedString(connection.getErrorStream(), responseEncoding); + log.trace("Http call returned {}; response body:\n{}", httpStatus, httpBody); if (exceptionType != null) { - throw JSONUtils.getJsonObject(readInputStreamAsEncodedString(errorStream, responseEncoding), exceptionType, objectMapper); + throw JSONUtils.getJsonObject(httpBody, exceptionType, objectMapper); } else { - throw new HttpStatusException("HTTP status code not 200", httpStatus, readInputStreamAsEncodedString(errorStream, responseEncoding)); + throw new HttpStatusException("HTTP status code not 200", httpStatus, httpBody); } } InputStream inputStream = connection.getInputStream(); // Get the data String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); log.trace("Response body: {}", responseString); return JSONUtils.getJsonObject(responseString, returnType, objectMapper); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } } /** * Provides an internal convenience method to allow easy overriding by test classes * * @param method The HTTP method (e.g. GET, POST etc) * @param urlString A string representation of a URL * @param httpHeaders The HTTP headers (will override the defaults) * @param contentLength * @return An HttpURLConnection based on the given parameters * @throws IOException If something goes wrong */ private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException { Assert.notNull(method, "method cannot be null"); Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); HttpURLConnection connection = getHttpURLConnection(urlString); connection.setRequestMethod(method.name()); // Copy default HTTP headers Map<String, String> headerKeyValues = new HashMap<String, String>(defaultHttpHeaders); // Merge defaultHttpHeaders with httpHeaders headerKeyValues.putAll(httpHeaders); // Add HTTP headers to the request for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue()); } // Perform additional configuration for POST if (contentLength > 0) { connection.setDoOutput(true); connection.setDoInput(true); // Add content length to header connection.setRequestProperty("Content-Length", Integer.toString(contentLength)); } return connection; } /** * @param urlString * @return a HttpURLConnection instance * @throws IOException */ protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(); if (readTimeout > 0) { connection.setReadTimeout(readTimeout); } return connection; } /** * <p> * Reads an InputStream as a String allowing for different encoding types * </p> * * @param inputStream The input stream * @param responseEncoding The encoding to use when converting to a String * @return A String representation of the input stream * @throws IOException If something goes wrong */ String readInputStreamAsEncodedString(InputStream inputStream, String responseEncoding) throws IOException { if (inputStream == null) { return null; } String responseString; if (responseEncoding != null) { // Have an encoding so use it StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, responseEncoding)); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } responseString = sb.toString(); } else { // No encoding specified so use a BufferedInputStream StringBuilder sb = new StringBuilder(); BufferedInputStream bis = new BufferedInputStream(inputStream); byte[] byteContents = new byte[4096]; int bytesRead; String strContents; while ((bytesRead = bis.read(byteContents)) != -1) { strContents = new String(byteContents, 0, bytesRead); sb.append(strContents); } responseString = sb.toString(); } // System.out.println("responseString: " + responseString); return responseString; } /** * Determine the response encoding if specified * * @param connection The HTTP connection * @return The response encoding as a string (taken from "Content-Type") */ private String getResponseEncoding(URLConnection connection) { String charset = null; String contentType = connection.getHeaderField("Content-Type"); if (contentType != null) { for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } } return charset; } }
false
true
public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType, Class<? extends RuntimeException> exceptionType) { log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders should not be null"); httpHeaders.put("Accept", "application/json"); if (contentType != null) { httpHeaders.put("Content-Type", contentType); } try { int contentLength = requestBody == null ? 0 : requestBody.length(); HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } String responseEncoding = getResponseEncoding(connection); int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (httpStatus != 200) { InputStream errorStream = connection.getErrorStream(); if (exceptionType != null) { throw JSONUtils.getJsonObject(readInputStreamAsEncodedString(errorStream, responseEncoding), exceptionType, objectMapper); } else { throw new HttpStatusException("HTTP status code not 200", httpStatus, readInputStreamAsEncodedString(errorStream, responseEncoding)); } } InputStream inputStream = connection.getInputStream(); // Get the data String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); log.trace("Response body: {}", responseString); return JSONUtils.getJsonObject(responseString, returnType, objectMapper); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } }
public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType, Class<? extends RuntimeException> exceptionType) { log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders should not be null"); httpHeaders.put("Accept", "application/json"); if (contentType != null) { httpHeaders.put("Content-Type", contentType); } try { int contentLength = requestBody == null ? 0 : requestBody.length(); HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } String responseEncoding = getResponseEncoding(connection); int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (httpStatus != 200) { String httpBody = readInputStreamAsEncodedString(connection.getErrorStream(), responseEncoding); log.trace("Http call returned {}; response body:\n{}", httpStatus, httpBody); if (exceptionType != null) { throw JSONUtils.getJsonObject(httpBody, exceptionType, objectMapper); } else { throw new HttpStatusException("HTTP status code not 200", httpStatus, httpBody); } } InputStream inputStream = connection.getInputStream(); // Get the data String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); log.trace("Response body: {}", responseString); return JSONUtils.getJsonObject(responseString, returnType, objectMapper); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } }
diff --git a/src/org/encog/neural/networks/training/strategy/RequiredImprovementStrategy.java b/src/org/encog/neural/networks/training/strategy/RequiredImprovementStrategy.java index 167f08b52..ca78492db 100644 --- a/src/org/encog/neural/networks/training/strategy/RequiredImprovementStrategy.java +++ b/src/org/encog/neural/networks/training/strategy/RequiredImprovementStrategy.java @@ -1,171 +1,171 @@ /* * Encog(tm) Core v2.5 * http://www.heatonresearch.com/encog/ * http://code.google.com/p/encog-java/ * * Copyright 2008-2010 by Heaton Research Inc. * * Released under the LGPL. * * 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. * * Encog and Heaton Research are Trademarks of Heaton Research, Inc. * For information on Heaton Research trademarks, visit: * * http://www.heatonresearch.com/copyright.html */ package org.encog.neural.networks.training.strategy; import org.encog.neural.networks.training.Strategy; import org.encog.neural.networks.training.Train; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The reset strategy will reset the weights if the neural network fails to improve by the specified amount over a number of cycles. * * @author jheaton * */ public class RequiredImprovementStrategy implements Strategy { /** * The logging object. */ private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * The required minimum error. */ private final double required; /** * The number of cycles to reach the required minimum error. */ private final int cycles; /** * The training algorithm that is using this strategy. */ private Train train; /** * How many bad cycles have there been so far. */ private int badCycleCount; /** * The last error. */ private double lastError = Double.NaN; /** * If the error is below this, then never reset. */ private double acceptableThreshold; /** * Construct a reset strategy. The error rate must fall below the required * rate in the specified number of cycles, or the neural network will be * reset to random weights and bias values. * * @param required * The required error rate. * @param cycles * The number of cycles to reach that rate. */ public RequiredImprovementStrategy(final double required, final int cycles) { this(required, 0.10, cycles); } /** * Construct a reset strategy. The error rate must fall below the required * rate in the specified number of cycles, or the neural network will be * reset to random weights and bias values. * * @param required * The required error rate. * @param threshold * The accepted threshold, don't reset if error is below this. * @param cycles * The number of cycles to reach that rate. */ public RequiredImprovementStrategy(final double required, final double threshold, final int cycles) { this.required = required; this.cycles = cycles; this.badCycleCount = 0; this.acceptableThreshold = threshold; } /** * Reset if there is not at least a 1% improvement for 5 cycles. Don't reset * if below 10%. * * @param cycles */ public RequiredImprovementStrategy(final int cycles) { this(0.01, 0.10, 5); } /** * Initialize this strategy. * * @param train * The training algorithm. */ public void init(final Train train) { this.train = train; } /** * Called just after a training iteration. */ public void postIteration() { } /** * Called just before a training iteration. */ public void preIteration() { if (train.getError() > this.acceptableThreshold) { if (!Double.isNaN(lastError)) { double improve = (lastError - train.getError()); if (improve < this.required) { this.badCycleCount++; if (this.badCycleCount > this.cycles) { if (this.logger.isDebugEnabled()) { this.logger .debug("Failed to improve network, resetting."); } - //this.train.getNetwork().reset(); + this.train.getNetwork().reset(); this.badCycleCount = 0; this.lastError = Double.NaN; } } else { this.badCycleCount = 0; } } else lastError = train.getError(); } lastError = Math.min(this.train.getError(),lastError); } }
true
true
public void preIteration() { if (train.getError() > this.acceptableThreshold) { if (!Double.isNaN(lastError)) { double improve = (lastError - train.getError()); if (improve < this.required) { this.badCycleCount++; if (this.badCycleCount > this.cycles) { if (this.logger.isDebugEnabled()) { this.logger .debug("Failed to improve network, resetting."); } //this.train.getNetwork().reset(); this.badCycleCount = 0; this.lastError = Double.NaN; } } else { this.badCycleCount = 0; } } else lastError = train.getError(); } lastError = Math.min(this.train.getError(),lastError); }
public void preIteration() { if (train.getError() > this.acceptableThreshold) { if (!Double.isNaN(lastError)) { double improve = (lastError - train.getError()); if (improve < this.required) { this.badCycleCount++; if (this.badCycleCount > this.cycles) { if (this.logger.isDebugEnabled()) { this.logger .debug("Failed to improve network, resetting."); } this.train.getNetwork().reset(); this.badCycleCount = 0; this.lastError = Double.NaN; } } else { this.badCycleCount = 0; } } else lastError = train.getError(); } lastError = Math.min(this.train.getError(),lastError); }
diff --git a/src/main/java/com/radiadesign/catalina/session/RedisSession.java b/src/main/java/com/radiadesign/catalina/session/RedisSession.java index 8781134..9189bc8 100644 --- a/src/main/java/com/radiadesign/catalina/session/RedisSession.java +++ b/src/main/java/com/radiadesign/catalina/session/RedisSession.java @@ -1,82 +1,83 @@ package com.radiadesign.catalina.session; import java.security.Principal; import org.apache.catalina.Manager; import org.apache.catalina.session.StandardSession; import java.util.HashMap; public class RedisSession extends StandardSession { protected static Boolean manualDirtyTrackingSupportEnabled = false; public static void setManualDirtyTrackingSupportEnabled(Boolean enabled) { manualDirtyTrackingSupportEnabled = enabled; } protected static String manualDirtyTrackingAttributeKey = "__changed__"; public static void setManualDirtyTrackingAttributeKey(String key) { manualDirtyTrackingAttributeKey = key; } protected HashMap<String, Object> changedAttributes; protected Boolean dirty; public RedisSession(Manager manager) { super(manager); resetDirtyTracking(); } public Boolean isDirty() { return dirty || !changedAttributes.isEmpty(); } public HashMap<String, Object> getChangedAttributes() { return changedAttributes; } public void resetDirtyTracking() { changedAttributes = new HashMap<String, Object>(); dirty = false; } @Override public void setAttribute(String key, Object value) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { dirty = true; return; } Object oldValue = getAttribute(key); - if ( value == null && oldValue != null - || oldValue == null && value != null - || !value.getClass().isInstance(oldValue) - || !value.equals(oldValue) ) { + if ( (value != null || oldValue != null) + && ( value == null && oldValue != null + || oldValue == null && value != null + || !value.getClass().isInstance(oldValue) + || !value.equals(oldValue) ) ) { changedAttributes.put(key, value); } super.setAttribute(key, value); } @Override public void removeAttribute(String name) { dirty = true; super.removeAttribute(name); } @Override public void setId(String id) { // Specifically do not call super(): it's implementation does unexpected things // like calling manager.remove(session.id) and manager.add(session). this.id = id; } @Override public void setPrincipal(Principal principal) { dirty = true; super.setPrincipal(principal); } }
true
true
public void setAttribute(String key, Object value) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { dirty = true; return; } Object oldValue = getAttribute(key); if ( value == null && oldValue != null || oldValue == null && value != null || !value.getClass().isInstance(oldValue) || !value.equals(oldValue) ) { changedAttributes.put(key, value); } super.setAttribute(key, value); }
public void setAttribute(String key, Object value) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { dirty = true; return; } Object oldValue = getAttribute(key); if ( (value != null || oldValue != null) && ( value == null && oldValue != null || oldValue == null && value != null || !value.getClass().isInstance(oldValue) || !value.equals(oldValue) ) ) { changedAttributes.put(key, value); } super.setAttribute(key, value); }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java index 2e3e024a..456a77c3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -1,64 +1,64 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n._; import com.earth2me.essentials.OfflinePlayer; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; public class Commandtpaccept extends EssentialsCommand { public Commandtpaccept() { super("tpaccept"); } @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || target.getBase() instanceof OfflinePlayer - || (user.isTeleportRequestHere() && !target.isAuthorized("essentials.tpahere"))) + || (user.isTeleportRequestHere() ? !target.isAuthorized("essentials.tpahere") : !target.isAuthorized("essentials.tpa"))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTeleportRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTeleportRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); } }
true
true
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || target.getBase() instanceof OfflinePlayer || (user.isTeleportRequestHere() && !target.isAuthorized("essentials.tpahere"))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTeleportRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTeleportRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); }
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { final User target = user.getTeleportRequest(); if (target == null || target.getBase() instanceof OfflinePlayer || (user.isTeleportRequestHere() ? !target.isAuthorized("essentials.tpahere") : !target.isAuthorized("essentials.tpa"))) { throw new Exception(_("noPendingRequest")); } if (args.length > 0 && !target.getName().contains(args[0])) { throw new Exception(_("noPendingRequest")); } long timeout = ess.getSettings().getTpaAcceptCancellation(); if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { user.requestTeleport(null, false); throw new Exception(_("requestTimedOut")); } final Trade charge = new Trade(this.getName(), ess); if (user.isTeleportRequestHere()) { charge.isAffordableFor(user); } else { charge.isAffordableFor(target); } user.sendMessage(_("requestAccepted")); target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); if (user.isTeleportRequestHere()) { user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); } else { target.getTeleport().teleport(user, charge, TeleportCause.COMMAND); } user.requestTeleport(null, false); }
diff --git a/api/src/test/java/org/openmrs/module/mirebalais/integration/MirthIT.java b/api/src/test/java/org/openmrs/module/mirebalais/integration/MirthIT.java index 8697715a..012796e8 100644 --- a/api/src/test/java/org/openmrs/module/mirebalais/integration/MirthIT.java +++ b/api/src/test/java/org/openmrs/module/mirebalais/integration/MirthIT.java @@ -1,229 +1,229 @@ /* * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.module.mirebalais.integration; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; import org.openmrs.*; import org.openmrs.api.EncounterService; import org.openmrs.api.OrderService; import org.openmrs.api.PatientService; import org.openmrs.api.context.Context; import org.openmrs.module.emr.TestUtils; import org.openmrs.module.mirebalais.MirebalaisGlobalProperties; import org.openmrs.module.mirebalais.MirebalaisHospitalActivator; import org.openmrs.module.pacsintegration.PacsIntegrationGlobalProperties; import org.openmrs.module.patientregistration.PatientRegistrationGlobalProperties; import org.openmrs.test.BaseModuleContextSensitiveTest; import org.openmrs.test.SkipBaseSetup; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.NotTransactional; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Calendar; import java.util.Date; @SkipBaseSetup public class MirthIT extends BaseModuleContextSensitiveTest { protected final Log log = LogFactory.getLog(getClass()); @Override public Boolean useInMemoryDatabase() { return false; } @Override public String getWebappName() { return "mirebalais"; } @Test @DirtiesContext @NotTransactional public void testMirthChannelIntegration() throws Exception { PatientService patientService = Context.getPatientService(); EncounterService encounterService = Context.getEncounterService(); OrderService orderService = Context.getOrderService(); authenticate(); // run the module activator so that the Mirth channels are configured MirebalaisHospitalActivator activator = new MirebalaisHospitalActivator(); activator.started(); // give Mirth channels a few seconds to start Thread.sleep(5000); // confirm that appropriate Mirth channels have been deployed String[] commands = new String[] { "java", "-classpath", MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/*:" + MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/cli-lib/*", "com.mirth.connect.cli.launcher.CommandLineLauncher", "-a", "https://" + MirebalaisGlobalProperties.MIRTH_IP_ADDRESS() + ":" + MirebalaisGlobalProperties.MIRTH_ADMIN_PORT(), "-u", MirebalaisGlobalProperties.MIRTH_USERNAME(), "-p", MirebalaisGlobalProperties.MIRTH_PASSWORD(), "-v", "0.0.0" }; Process mirthShell = Runtime.getRuntime().exec(commands); OutputStream out = mirthShell.getOutputStream(); InputStream in = mirthShell.getInputStream(); // load the status out.write("status\n".getBytes()); out.close(); // confirm that the status shows that the Mirth channel has started String mirthStatus = IOUtils.toString(in); TestUtils.assertFuzzyContains("STARTED Read HL7 From OpenMRS Database", mirthStatus); TestUtils.assertFuzzyContains("STARTED Send HL7 To Pacs", mirthStatus); // stop all channels, clear messages and statistics, and restart in preparation for tests mirthShell = Runtime.getRuntime().exec(commands); out = mirthShell.getOutputStream(); in = mirthShell.getInputStream(); out.write("channel stop *\n".getBytes()); // stop all channels out.write("clearallmessages\n".getBytes()); out.write("resetstats\n".getBytes()); out.write("channel start *\n".getBytes()); // restart all channels out.close(); // now test that when we create a new patient, a new patient message is created // if the test patient already exists, delete it and any existing orders if (patientService.getPatients("2ADMMN").size() > 0) { Patient patient = patientService.getPatients("2ADMMN").get(0); for (Order order : orderService.getOrdersByPatient(patient)) { orderService.purgeOrder(order); } Context.getPatientService().purgePatient(patient); } // TODO: eventually we should make sure all the necessary fields are included here // first create and save a patient Patient patient = new Patient(); patient.setGender("M"); Calendar birthdate = Calendar.getInstance(); birthdate.set(2000, 2, 23); patient.setBirthdate(birthdate.getTime()); PersonName name = new PersonName(); name.setFamilyName("Test Patient"); name.setGivenName("Mirth Integration"); patient.addName(name); PatientIdentifier identifier = new PatientIdentifier(); identifier.setIdentifierType(PatientRegistrationGlobalProperties.GLOBAL_PROPERTY_PRIMARY_IDENTIFIER_TYPE()); identifier.setIdentifier("2ADMMN"); identifier.setPreferred(true); identifier.setLocation(Context.getLocationService().getLocation("Unknown Location")); patient.addIdentifier(identifier); // save the patient patientService.savePatient(patient); /** * Commenting this out because we are not currently sending ADT information to APCS String result = listenForResults(); System.out.println(result); // make sure the appropriate message has been delivered TestUtils.assertContains("MSH|^~\\&|||||||ADT^A01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); // now resave the patient and verify that a patient updated message is sent // save the patient to trigger an update event patientService.savePatient(patient); result = listenForResults(); System.out.println(result); TestUtils.assertContains("MSH|^~\\&|||||||ADT^A08||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); */ // TODO: eventually we should make sure all the necessary fields are concluded here // TODO: specifically: sending facility, device location, universal service id, universal service id text, and modality // now create and save the order for this patient TestOrder order = new TestOrder(); order .setOrderType(Context.getOrderService().getOrderTypeByUuid( Context.getAdministrationService().getGlobalProperty( PacsIntegrationGlobalProperties.RADIOLOGY_ORDER_TYPE_UUID))); // TODO: change this based on how we actually end up doing orders order.setPatient(patient); order.setConcept(Context.getConceptService().getConceptByUuid("fc6de1c0-1a36-11e2-a310-aa00f871a3e1")); // chest x-ray, one view order.setAccessionNumber("ACCESSION NUMBER"); Date radiologyDate = new Date(); order.setStartDate(radiologyDate); order.setUrgency(Order.Urgency.STAT); order.setClinicalHistory("Patient fell off horse"); Encounter encounter = new Encounter(); - encounter.setPatient(Context.getPatientService().getPatient(7)); + encounter.setPatient(patient); encounter.setEncounterDatetime(new Date()); encounter.setLocation(Context.getLocationService().getLocation("Unknown Location")); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.addOrder(order); encounterService.saveEncounter(encounter); String result = listenForResults(); TestUtils.assertContains("MSH|^~\\&||Mirebalais|||||ORM^O01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); TestUtils.assertContains("ORC|NW", result); TestUtils.assertContains( "OBR|||ACCESSION NUMBER|36554-4^Chest 1 view (XRay)|||||||||||||||||||||||^^^^^STAT||||^Patient fell off horse", result); } private String listenForResults() throws IOException { ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global poroperty? listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection Socket mirthConnection = listener.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } // TODO: need an acknowledgement? mirthConnection.close(); listener.close(); return sb.toString(); } }
true
true
public void testMirthChannelIntegration() throws Exception { PatientService patientService = Context.getPatientService(); EncounterService encounterService = Context.getEncounterService(); OrderService orderService = Context.getOrderService(); authenticate(); // run the module activator so that the Mirth channels are configured MirebalaisHospitalActivator activator = new MirebalaisHospitalActivator(); activator.started(); // give Mirth channels a few seconds to start Thread.sleep(5000); // confirm that appropriate Mirth channels have been deployed String[] commands = new String[] { "java", "-classpath", MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/*:" + MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/cli-lib/*", "com.mirth.connect.cli.launcher.CommandLineLauncher", "-a", "https://" + MirebalaisGlobalProperties.MIRTH_IP_ADDRESS() + ":" + MirebalaisGlobalProperties.MIRTH_ADMIN_PORT(), "-u", MirebalaisGlobalProperties.MIRTH_USERNAME(), "-p", MirebalaisGlobalProperties.MIRTH_PASSWORD(), "-v", "0.0.0" }; Process mirthShell = Runtime.getRuntime().exec(commands); OutputStream out = mirthShell.getOutputStream(); InputStream in = mirthShell.getInputStream(); // load the status out.write("status\n".getBytes()); out.close(); // confirm that the status shows that the Mirth channel has started String mirthStatus = IOUtils.toString(in); TestUtils.assertFuzzyContains("STARTED Read HL7 From OpenMRS Database", mirthStatus); TestUtils.assertFuzzyContains("STARTED Send HL7 To Pacs", mirthStatus); // stop all channels, clear messages and statistics, and restart in preparation for tests mirthShell = Runtime.getRuntime().exec(commands); out = mirthShell.getOutputStream(); in = mirthShell.getInputStream(); out.write("channel stop *\n".getBytes()); // stop all channels out.write("clearallmessages\n".getBytes()); out.write("resetstats\n".getBytes()); out.write("channel start *\n".getBytes()); // restart all channels out.close(); // now test that when we create a new patient, a new patient message is created // if the test patient already exists, delete it and any existing orders if (patientService.getPatients("2ADMMN").size() > 0) { Patient patient = patientService.getPatients("2ADMMN").get(0); for (Order order : orderService.getOrdersByPatient(patient)) { orderService.purgeOrder(order); } Context.getPatientService().purgePatient(patient); } // TODO: eventually we should make sure all the necessary fields are included here // first create and save a patient Patient patient = new Patient(); patient.setGender("M"); Calendar birthdate = Calendar.getInstance(); birthdate.set(2000, 2, 23); patient.setBirthdate(birthdate.getTime()); PersonName name = new PersonName(); name.setFamilyName("Test Patient"); name.setGivenName("Mirth Integration"); patient.addName(name); PatientIdentifier identifier = new PatientIdentifier(); identifier.setIdentifierType(PatientRegistrationGlobalProperties.GLOBAL_PROPERTY_PRIMARY_IDENTIFIER_TYPE()); identifier.setIdentifier("2ADMMN"); identifier.setPreferred(true); identifier.setLocation(Context.getLocationService().getLocation("Unknown Location")); patient.addIdentifier(identifier); // save the patient patientService.savePatient(patient); /** * Commenting this out because we are not currently sending ADT information to APCS String result = listenForResults(); System.out.println(result); // make sure the appropriate message has been delivered TestUtils.assertContains("MSH|^~\\&|||||||ADT^A01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); // now resave the patient and verify that a patient updated message is sent // save the patient to trigger an update event patientService.savePatient(patient); result = listenForResults(); System.out.println(result); TestUtils.assertContains("MSH|^~\\&|||||||ADT^A08||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); */ // TODO: eventually we should make sure all the necessary fields are concluded here // TODO: specifically: sending facility, device location, universal service id, universal service id text, and modality // now create and save the order for this patient TestOrder order = new TestOrder(); order .setOrderType(Context.getOrderService().getOrderTypeByUuid( Context.getAdministrationService().getGlobalProperty( PacsIntegrationGlobalProperties.RADIOLOGY_ORDER_TYPE_UUID))); // TODO: change this based on how we actually end up doing orders order.setPatient(patient); order.setConcept(Context.getConceptService().getConceptByUuid("fc6de1c0-1a36-11e2-a310-aa00f871a3e1")); // chest x-ray, one view order.setAccessionNumber("ACCESSION NUMBER"); Date radiologyDate = new Date(); order.setStartDate(radiologyDate); order.setUrgency(Order.Urgency.STAT); order.setClinicalHistory("Patient fell off horse"); Encounter encounter = new Encounter(); encounter.setPatient(Context.getPatientService().getPatient(7)); encounter.setEncounterDatetime(new Date()); encounter.setLocation(Context.getLocationService().getLocation("Unknown Location")); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.addOrder(order); encounterService.saveEncounter(encounter); String result = listenForResults(); TestUtils.assertContains("MSH|^~\\&||Mirebalais|||||ORM^O01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); TestUtils.assertContains("ORC|NW", result); TestUtils.assertContains( "OBR|||ACCESSION NUMBER|36554-4^Chest 1 view (XRay)|||||||||||||||||||||||^^^^^STAT||||^Patient fell off horse", result); }
public void testMirthChannelIntegration() throws Exception { PatientService patientService = Context.getPatientService(); EncounterService encounterService = Context.getEncounterService(); OrderService orderService = Context.getOrderService(); authenticate(); // run the module activator so that the Mirth channels are configured MirebalaisHospitalActivator activator = new MirebalaisHospitalActivator(); activator.started(); // give Mirth channels a few seconds to start Thread.sleep(5000); // confirm that appropriate Mirth channels have been deployed String[] commands = new String[] { "java", "-classpath", MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/*:" + MirebalaisGlobalProperties.MIRTH_DIRECTORY() + "/cli-lib/*", "com.mirth.connect.cli.launcher.CommandLineLauncher", "-a", "https://" + MirebalaisGlobalProperties.MIRTH_IP_ADDRESS() + ":" + MirebalaisGlobalProperties.MIRTH_ADMIN_PORT(), "-u", MirebalaisGlobalProperties.MIRTH_USERNAME(), "-p", MirebalaisGlobalProperties.MIRTH_PASSWORD(), "-v", "0.0.0" }; Process mirthShell = Runtime.getRuntime().exec(commands); OutputStream out = mirthShell.getOutputStream(); InputStream in = mirthShell.getInputStream(); // load the status out.write("status\n".getBytes()); out.close(); // confirm that the status shows that the Mirth channel has started String mirthStatus = IOUtils.toString(in); TestUtils.assertFuzzyContains("STARTED Read HL7 From OpenMRS Database", mirthStatus); TestUtils.assertFuzzyContains("STARTED Send HL7 To Pacs", mirthStatus); // stop all channels, clear messages and statistics, and restart in preparation for tests mirthShell = Runtime.getRuntime().exec(commands); out = mirthShell.getOutputStream(); in = mirthShell.getInputStream(); out.write("channel stop *\n".getBytes()); // stop all channels out.write("clearallmessages\n".getBytes()); out.write("resetstats\n".getBytes()); out.write("channel start *\n".getBytes()); // restart all channels out.close(); // now test that when we create a new patient, a new patient message is created // if the test patient already exists, delete it and any existing orders if (patientService.getPatients("2ADMMN").size() > 0) { Patient patient = patientService.getPatients("2ADMMN").get(0); for (Order order : orderService.getOrdersByPatient(patient)) { orderService.purgeOrder(order); } Context.getPatientService().purgePatient(patient); } // TODO: eventually we should make sure all the necessary fields are included here // first create and save a patient Patient patient = new Patient(); patient.setGender("M"); Calendar birthdate = Calendar.getInstance(); birthdate.set(2000, 2, 23); patient.setBirthdate(birthdate.getTime()); PersonName name = new PersonName(); name.setFamilyName("Test Patient"); name.setGivenName("Mirth Integration"); patient.addName(name); PatientIdentifier identifier = new PatientIdentifier(); identifier.setIdentifierType(PatientRegistrationGlobalProperties.GLOBAL_PROPERTY_PRIMARY_IDENTIFIER_TYPE()); identifier.setIdentifier("2ADMMN"); identifier.setPreferred(true); identifier.setLocation(Context.getLocationService().getLocation("Unknown Location")); patient.addIdentifier(identifier); // save the patient patientService.savePatient(patient); /** * Commenting this out because we are not currently sending ADT information to APCS String result = listenForResults(); System.out.println(result); // make sure the appropriate message has been delivered TestUtils.assertContains("MSH|^~\\&|||||||ADT^A01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); // now resave the patient and verify that a patient updated message is sent // save the patient to trigger an update event patientService.savePatient(patient); result = listenForResults(); System.out.println(result); TestUtils.assertContains("MSH|^~\\&|||||||ADT^A08||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); */ // TODO: eventually we should make sure all the necessary fields are concluded here // TODO: specifically: sending facility, device location, universal service id, universal service id text, and modality // now create and save the order for this patient TestOrder order = new TestOrder(); order .setOrderType(Context.getOrderService().getOrderTypeByUuid( Context.getAdministrationService().getGlobalProperty( PacsIntegrationGlobalProperties.RADIOLOGY_ORDER_TYPE_UUID))); // TODO: change this based on how we actually end up doing orders order.setPatient(patient); order.setConcept(Context.getConceptService().getConceptByUuid("fc6de1c0-1a36-11e2-a310-aa00f871a3e1")); // chest x-ray, one view order.setAccessionNumber("ACCESSION NUMBER"); Date radiologyDate = new Date(); order.setStartDate(radiologyDate); order.setUrgency(Order.Urgency.STAT); order.setClinicalHistory("Patient fell off horse"); Encounter encounter = new Encounter(); encounter.setPatient(patient); encounter.setEncounterDatetime(new Date()); encounter.setLocation(Context.getLocationService().getLocation("Unknown Location")); encounter.setEncounterType(Context.getEncounterService().getEncounterType(1)); encounter.addOrder(order); encounterService.saveEncounter(encounter); String result = listenForResults(); TestUtils.assertContains("MSH|^~\\&||Mirebalais|||||ORM^O01||P|2.3", result); TestUtils.assertContains("PID|||2ADMMN||Test Patient^Mirth Integration||200003230000|M", result); TestUtils.assertContains("ORC|NW", result); TestUtils.assertContains( "OBR|||ACCESSION NUMBER|36554-4^Chest 1 view (XRay)|||||||||||||||||||||||^^^^^STAT||||^Patient fell off horse", result); }
diff --git a/frost-wot/source/frost/Core.java b/frost-wot/source/frost/Core.java index e1b26d23..007d50bf 100644 --- a/frost-wot/source/frost/Core.java +++ b/frost-wot/source/frost/Core.java @@ -1,613 +1,615 @@ /* Core.java / Frost Copyright (C) 2003 Frost Project <jtcfrost.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ package frost; import java.io.*; import java.sql.*; import java.util.*; import java.util.Timer; import java.util.logging.*; import javax.swing.*; import com.l2fprod.gui.plaf.skin.*; import frost.boards.*; import frost.crypt.*; import frost.events.*; import frost.ext.*; import frost.fcp.*; import frost.fileTransfer.*; import frost.gui.*; import frost.gui.help.*; import frost.identities.*; import frost.messaging.*; import frost.storage.*; import frost.storage.database.*; import frost.storage.database.applayer.*; import frost.storage.database.transferlayer.*; import frost.threads.maintenance.*; import frost.util.gui.*; import frost.util.gui.translation.*; /** * Class hold the more non-gui parts of Frost. * * @pattern Singleton * */ public class Core implements FrostEventDispatcher { private static Logger logger = Logger.getLogger(Core.class.getName()); // Core instanciates itself, frostSettings must be created before instance=Core() ! public static SettingsClass frostSettings = new SettingsClass(); private static Core instance = null; private static FrostCrypt crypto = new FrostCrypt(); private static boolean isHelpHtmlSecure = false; private EventDispatcher dispatcher = new EventDispatcher(); private Language language = null; private boolean freenetIsOnline = false; private Timer timer = new Timer(true); private MainFrame mainFrame; private BoardsManager boardsManager; private FileTransferManager fileTransferManager; private static MessageHashes messageHashes; private static FrostIdentities identities; private String keypool; private Core() { initializeLanguage(); } /** * This methods parses the list of available nodes (and converts it if it is in * the old format). If there are no available nodes, it shows a Dialog warning the * user of the situation and returns false. * @return boolean false if no nodes are available. True otherwise. */ private boolean initializeConnectivity() { // determine configured freenet version int freenetVersion = frostSettings.getIntValue("freenetVersion"); // 5 or 7 if( freenetVersion <= 0 ) { FreenetVersionDialog dlg = new FreenetVersionDialog(); dlg.setVisible(true); if( dlg.isChoosedExit() ) { return false; } if( dlg.isChoosedFreenet05() ) { frostSettings.setValue("freenetVersion", "5"); } else if( dlg.isChoosedFreenet07() ) { frostSettings.setValue("freenetVersion", "7"); } else { return false; } freenetVersion = frostSettings.getIntValue("freenetVersion"); // 5 or 7 } if( freenetVersion != FcpHandler.FREENET_05 && freenetVersion != FcpHandler.FREENET_07 ) { MiscToolkit.getInstance().showMessage( language.getString("Core.init.UnsupportedFreenetVersionBody")+": "+freenetVersion, JOptionPane.ERROR_MESSAGE, language.getString("Core.init.UnsupportedFreenetVersionTitle")); return false; } // get the list of available nodes String nodesUnparsed = frostSettings.getValue("availableNodes"); List nodes = new ArrayList(); if (nodesUnparsed == null) { //old format String converted = new String(frostSettings.getValue("nodeAddress")+":"+frostSettings.getValue("nodePort")); nodes.add(converted.trim()); frostSettings.setValue("availableNodes", converted.trim()); } else { // new format String[] _nodes = nodesUnparsed.split(","); for (int i = 0; i < _nodes.length; i++) { nodes.add(_nodes[i]); } } if (nodes.size() == 0) { MiscToolkit.getInstance().showMessage( "Not a single Freenet node configured. You need at least one.", JOptionPane.ERROR_MESSAGE, "ERROR: No Freenet nodes are configured."); return false; } // init the factory with configured nodes try { FcpHandler.initializeFcp(nodes, freenetVersion); } catch(UnsupportedOperationException ex) { MiscToolkit.getInstance().showMessage( ex.getMessage(), JOptionPane.ERROR_MESSAGE, language.getString("Core.init.UnsupportedFreenetVersionTitle")); return false; } // install our security manager that only allows connections to the configured FCP hosts System.setSecurityManager(new FrostSecurityManager()); // check if node is online and if we run on 0.7 testnet freenetIsOnline = false; boolean runningOnTestnet = false; try { List nodeInfo = FcpHandler.inst().getNodeInfo(); if( nodeInfo != null ) { // freenet is online freenetIsOnline = true; // on 0.7 check for "Testnet=true" and warn user if( FcpHandler.getInitializedVersion() == FcpHandler.FREENET_07 ) { for(Iterator i=nodeInfo.iterator(); i.hasNext(); ) { String val = (String)i.next(); if( val.startsWith("Testnet") && val.indexOf("true") > 0 ) { runningOnTestnet = true; } } } } } catch (Exception e) { logger.log(Level.SEVERE, "Exception thrown in initializeConnectivity", e); } if( runningOnTestnet ) { MiscToolkit.getInstance().showMessage( language.getString("Core.init.TestnetWarningBody"), JOptionPane.WARNING_MESSAGE, language.getString("Core.init.TestnetWarningTitle")); } // We warn the user if there aren't any running nodes if (!freenetIsOnline) { MiscToolkit.getInstance().showMessage( language.getString("Core.init.NodeNotRunningBody"), JOptionPane.WARNING_MESSAGE, language.getString("Core.init.NodeNotRunningTitle")); } return true; } public boolean isFreenetOnline() { return freenetIsOnline; } public static FrostCrypt getCrypto() { return crypto; } /** * Tries to send old messages that have not been sent yet */ protected void resendFailedMessages() { // start a thread that waits some seconds for gui to appear, then searches for unsent messages ResendFailedMessagesThread t = new ResendFailedMessagesThread(getBoardsManager().getTofTree(), getBoardsManager().getTofTreeModel()); t.start(); } /** * @param which */ public void deleteDir(String which) { (new DeleteWholeDirThread(this, which)).start(); } /** * @param task * @param delay */ public static void schedule(TimerTask task, long delay) { getInstance().timer.schedule(task, delay); } /** * @param task * @param delay * @param period */ public static void schedule(TimerTask task, long delay, long period) { getInstance().timer.schedule(task, delay, period); } /** * @return pointer to the live core */ public static Core getInstance() { if( instance == null ) { instance = new Core(); } return instance; } /** * @throws Exception */ public void initialize() throws Exception { Splashscreen splashscreen = new Splashscreen(); splashscreen.setVisible(true); keypool = frostSettings.getValue("keypool.dir"); splashscreen.setText(language.getString("Splashscreen.message.1")); splashscreen.setProgress(20); //Initializes the logging and skins new Logging(frostSettings); initializeSkins(); //Initializes storage DAOFactory.initialize(frostSettings); // open databases try { TransferLayerDatabase.initialize(); AppLayerDatabase.initialize(); } catch(SQLException ex) { logger.log(Level.SEVERE, "Error opening the databases", ex); ex.printStackTrace(); throw ex; } // initialize messageHashes messageHashes = new MessageHashes(); messageHashes.initialize(); // CLEANS TEMP DIR! START NO INSERTS BEFORE THIS RUNNED Startup.startupCheck(frostSettings, keypool); // nothing was started until now, its the perfect time to delete all empty date dirs in keypool... CleanUp.deleteEmptyBoardDateDirs( new File(keypool) ); splashscreen.setText(language.getString("Splashscreen.message.2")); splashscreen.setProgress(40); // check if help.zip contains only secure files (no http or ftp links at all) CheckHtmlIntegrity chi = new CheckHtmlIntegrity(); isHelpHtmlSecure = chi.scanZipFile("help/help.zip"); chi = null; boolean doImport = false; // check if this is a first startup if( frostSettings.getIntValue("freenetVersion") == 0 ) { frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); frostSettings.setValue("oneTimeUpdate.convertSigs.didRun", true); frostSettings.setValue("oneTimeUpdate.repairIdentities.didRun", true); // ask user which freenet version to use, set correct default availableNodes, // allow to import an existing identities file FirstStartupDialog startdlg = new FirstStartupDialog(); boolean exitChoosed = startdlg.startDialog(); if( exitChoosed ) { System.exit(1); } // set used version frostSettings.setValue("freenetVersion", startdlg.getFreenetVersion()); // 5 or 7 // init availableNodes with correct port if( startdlg.getOwnHostAndPort() != null ) { // user set own host:port frostSettings.setValue("availableNodes", startdlg.getOwnHostAndPort()); } else if( startdlg.getFreenetVersion() == FcpHandler.FREENET_05 ) { frostSettings.setValue("availableNodes", "127.0.0.1:8481"); } else { // 0.7 if( startdlg.isTestnet() == false ) { frostSettings.setValue("availableNodes", "127.0.0.1:9481"); } else { frostSettings.setValue("availableNodes", "127.0.0.1:9482"); } } if( startdlg.getOldIdentitiesFile() != null && startdlg.getOldIdentitiesFile().length() > 0 ) { boolean wasOk = FileAccess.copyFile(startdlg.getOldIdentitiesFile(), "identities.xml"); if( wasOk == false ) { MiscToolkit.getInstance().showMessage( - "Import of old identities.xml file failed.", + "Copy of old identities.xml file failed.", JOptionPane.ERROR_MESSAGE, - "Import failed"); + "Copy failed"); } + // import old identities file into database + new ImportIdentities().importIdentities(); } } else { // import xml messages into database if( frostSettings.getBoolValue("oneTimeUpdate.importMessages.didRun") == false ) { splashscreen.setText("Import messages into database"); String txt = "<html>Frost must now import the messages, and this could take some time.<br>"+ "Afterwards the files in keypool are not longer needed and will be deleted.<br><br>"+ "<b>BACKUP YOUR FROST DIRECTORY BEFORE STARTING!</b><br>"+ "<br><br>Do you want to start the import NOW press yes.</html>"; int answer = JOptionPane.showConfirmDialog(splashscreen, txt, "About to start import process", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_OPTION); if( answer != JOptionPane.YES_OPTION ) { System.exit(1); } new ImportKnownBoards().importKnownBoards(); new ImportIdentities().importIdentities(); doImport = true; } } splashscreen.setText(language.getString("Splashscreen.message.3")); splashscreen.setProgress(60); if (!initializeConnectivity()) { System.exit(1); } getIdentities().initialize(freenetIsOnline); // TODO: maybe make this configureable in options dialog for the paranoic people? String title; // if( frostSettings.getBoolValue("mainframe.showSimpleTitle") == false ) { // title = "Frost - " + getIdentities().getMyId().getUniqueName(); // } else { title = "Frost"; // } // Display the tray icon (do this before mainframe initializes) if (frostSettings.getBoolValue("showSystrayIcon") == true) { if (JSysTrayIcon.createInstance(0, title, title) == false) { logger.severe("Could not create systray icon."); } } // Main frame mainFrame = new MainFrame(frostSettings, title); getBoardsManager().initialize(); getFileTransferManager().initialize(); if( doImport ) { new ImportXmlMessages().importXmlMessages(getBoardsManager().getTofTreeModel()); new ImportFiles().importFiles(); new ImportDownloadFiles().importDownloadFiles(getBoardsManager().getTofTreeModel(), getFileTransferManager()); frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); } splashscreen.setText(language.getString("Splashscreen.message.4")); splashscreen.setProgress(70); mainFrame.initialize(); if (isFreenetOnline()) { resendFailedMessages(); } splashscreen.setText(language.getString("Splashscreen.message.5")); splashscreen.setProgress(80); // toftree must be loaded before expiration can run! // (cleanup gets the expiration mode from settings itself) CleanUp.processExpiredFiles(MainFrame.getInstance().getTofTreeModel().getAllBoards()); initializeTasks(mainFrame); SwingUtilities.invokeLater(new Runnable() { public void run() { mainFrame.setVisible(true); } }); splashscreen.closeMe(); } public FileTransferManager getFileTransferManager() { if (fileTransferManager == null) { fileTransferManager = new FileTransferManager(frostSettings); fileTransferManager.setMainFrame(mainFrame); fileTransferManager.setTofTreeModel(getBoardsManager().getTofTreeModel()); fileTransferManager.setFreenetIsOnline(isFreenetOnline()); fileTransferManager.setIdentities(getIdentities()); fileTransferManager.setKeypool(keypool); } return fileTransferManager; } public static MessageHashes getMessageHashes() { return messageHashes; } public MainFrame getMainFrame(){ return mainFrame; } private BoardsManager getBoardsManager() { if (boardsManager == null) { boardsManager = new BoardsManager(frostSettings); boardsManager.setMainFrame(mainFrame); boardsManager.setCore(this); } return boardsManager; } /** * @param parentFrame the frame that will be the parent of any * dialog that has to be shown in case an error happens * in one of those tasks */ private void initializeTasks(JFrame parentFrame) { //We initialize the task that checks for spam timer.schedule( new CheckForSpam(frostSettings, getBoardsManager().getTofTree(), getBoardsManager().getTofTreeModel()), 1*60*60*1000, // wait 1 min frostSettings.getIntValue("sampleInterval") * 60 * 60 * 1000); // initialize the task that discards old files TimerTask cleaner = new TimerTask() { public void run() { // each 6 hours cleanup files logger.info("Timer cleaner: Starting to process expired files."); CleanUp.processExpiredFiles(MainFrame.getInstance().getTofTreeModel().getAllBoards()); } }; timer.schedule(cleaner, 6*60*60*1000, 6*60*60*1000); // 6 hrs interval, always run during startup cleaner = null; // initialize the task that frees memory cleaner = new TimerTask() { public void run() { // free memory each 30 min logger.info("freeing memory"); System.gc(); } }; timer.schedule(cleaner, 30 * 60 * 1000, 30 * 60 * 1000); //30 minutes cleaner = null; // initialize the task that saves data StorageManager saver = new StorageManager(frostSettings, this); saver.addAutoSavable(getMessageHashes()); saver.addAutoSavable(getBoardsManager().getTofTree()); saver.addAutoSavable(getFileTransferManager()); saver.addExitSavable(getMessageHashes()); saver.addExitSavable(getIdentities()); saver.addExitSavable(getBoardsManager().getTofTree()); saver.addExitSavable(getFileTransferManager()); saver.addExitSavable(frostSettings); // close databases saver.addExitSavable(AppLayerDatabase.getInstance()); saver.addExitSavable(TransferLayerDatabase.getInstance()); } /** * Initializes the skins system * @param frostSettings the SettingsClass that has the preferences to initialize the skins */ private void initializeSkins() { String skinsEnabled = frostSettings.getValue("skinsEnabled"); if ((skinsEnabled != null) && (skinsEnabled.equals("true"))) { String selectedSkinPath = frostSettings.getValue("selectedSkin"); if ((selectedSkinPath != null) && (!selectedSkinPath.equals("none"))) { try { Skin selectedSkin = SkinLookAndFeel.loadThemePack(selectedSkinPath); SkinLookAndFeel.setSkin(selectedSkin); UIManager.setLookAndFeel(new SkinLookAndFeel()); } catch (UnsupportedLookAndFeelException exception) { logger.severe("The selected skin is not supported by your system\n" + "Skins will be disabled until you choose another one"); frostSettings.setValue("skinsEnabled", false); } catch (Exception exception) { logger.severe("There was an error while loading the selected skin\n" + "Skins will be disabled until you choose another one"); frostSettings.setValue("skinsEnabled", false); } } } } public static FrostIdentities getIdentities() { if (identities == null) { identities = new FrostIdentities(); } return identities; } /** * This method returns the language resource to get internationalized messages * from. That language resource is initialized the first time this method is called. * In that case, if the locale field has a value, it is used to select the * LanguageResource. If not, the locale value in frostSettings is used for that. */ private void initializeLanguage() { if( Frost.getCmdLineLocaleFileName() != null ) { // external bundle specified on command line (overrides config setting) File f = new File(Frost.getCmdLineLocaleFileName()); Language.initializeWithFile(f); } else if (Frost.getCmdLineLocaleName() != null) { // use locale specified on command line (overrides config setting) Language.initializeWithName(Frost.getCmdLineLocaleName()); } else { // use config file parameter (format: de or de;ext String lang = frostSettings.getValue("locale"); String langIsExternal = frostSettings.getValue("localeExternal"); if( lang == null || lang.length() == 0 || lang.equals("default") ) { // for default or if not set at all frostSettings.setValue("locale", "default"); Language.initializeWithName(null); } else { boolean isExternal; if( langIsExternal == null || langIsExternal.length() == 0 || !langIsExternal.equals("true")) { isExternal = false; } else { isExternal = true; } Language.initializeWithName(lang, isExternal); } } language = Language.getInstance(); } /* (non-Javadoc) * @see frost.events.FrostEventDispatcher#dispatchEvent(frost.events.FrostEvent) */ public void dispatchEvent(FrostEvent frostEvent) { dispatcher.dispatchEvent(frostEvent); } public static boolean isHelpHtmlSecure() { return isHelpHtmlSecure; } private class EventDispatcher { /** * @param frostEvent */ public void dispatchEvent(FrostEvent frostEvent) { switch(frostEvent.getId()) { case FrostEvent.STORAGE_ERROR_EVENT_ID: dispatchStorageErrorEvent((StorageErrorEvent) frostEvent); break; default: logger.severe("Unknown FrostEvent received. Id: '" + frostEvent.getId() + "'"); } } /** * @param errorEvent */ public void dispatchStorageErrorEvent(StorageErrorEvent errorEvent) { StringWriter stringWriter = new StringWriter(); errorEvent.getException().printStackTrace(new PrintWriter(stringWriter)); if (mainFrame != null) { JDialogWithDetails.showErrorDialog(mainFrame, language.getString("Saver.AutoTask.title"), errorEvent.getMessage(), stringWriter.toString()); } System.exit(3); } } }
false
true
public void initialize() throws Exception { Splashscreen splashscreen = new Splashscreen(); splashscreen.setVisible(true); keypool = frostSettings.getValue("keypool.dir"); splashscreen.setText(language.getString("Splashscreen.message.1")); splashscreen.setProgress(20); //Initializes the logging and skins new Logging(frostSettings); initializeSkins(); //Initializes storage DAOFactory.initialize(frostSettings); // open databases try { TransferLayerDatabase.initialize(); AppLayerDatabase.initialize(); } catch(SQLException ex) { logger.log(Level.SEVERE, "Error opening the databases", ex); ex.printStackTrace(); throw ex; } // initialize messageHashes messageHashes = new MessageHashes(); messageHashes.initialize(); // CLEANS TEMP DIR! START NO INSERTS BEFORE THIS RUNNED Startup.startupCheck(frostSettings, keypool); // nothing was started until now, its the perfect time to delete all empty date dirs in keypool... CleanUp.deleteEmptyBoardDateDirs( new File(keypool) ); splashscreen.setText(language.getString("Splashscreen.message.2")); splashscreen.setProgress(40); // check if help.zip contains only secure files (no http or ftp links at all) CheckHtmlIntegrity chi = new CheckHtmlIntegrity(); isHelpHtmlSecure = chi.scanZipFile("help/help.zip"); chi = null; boolean doImport = false; // check if this is a first startup if( frostSettings.getIntValue("freenetVersion") == 0 ) { frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); frostSettings.setValue("oneTimeUpdate.convertSigs.didRun", true); frostSettings.setValue("oneTimeUpdate.repairIdentities.didRun", true); // ask user which freenet version to use, set correct default availableNodes, // allow to import an existing identities file FirstStartupDialog startdlg = new FirstStartupDialog(); boolean exitChoosed = startdlg.startDialog(); if( exitChoosed ) { System.exit(1); } // set used version frostSettings.setValue("freenetVersion", startdlg.getFreenetVersion()); // 5 or 7 // init availableNodes with correct port if( startdlg.getOwnHostAndPort() != null ) { // user set own host:port frostSettings.setValue("availableNodes", startdlg.getOwnHostAndPort()); } else if( startdlg.getFreenetVersion() == FcpHandler.FREENET_05 ) { frostSettings.setValue("availableNodes", "127.0.0.1:8481"); } else { // 0.7 if( startdlg.isTestnet() == false ) { frostSettings.setValue("availableNodes", "127.0.0.1:9481"); } else { frostSettings.setValue("availableNodes", "127.0.0.1:9482"); } } if( startdlg.getOldIdentitiesFile() != null && startdlg.getOldIdentitiesFile().length() > 0 ) { boolean wasOk = FileAccess.copyFile(startdlg.getOldIdentitiesFile(), "identities.xml"); if( wasOk == false ) { MiscToolkit.getInstance().showMessage( "Import of old identities.xml file failed.", JOptionPane.ERROR_MESSAGE, "Import failed"); } } } else { // import xml messages into database if( frostSettings.getBoolValue("oneTimeUpdate.importMessages.didRun") == false ) { splashscreen.setText("Import messages into database"); String txt = "<html>Frost must now import the messages, and this could take some time.<br>"+ "Afterwards the files in keypool are not longer needed and will be deleted.<br><br>"+ "<b>BACKUP YOUR FROST DIRECTORY BEFORE STARTING!</b><br>"+ "<br><br>Do you want to start the import NOW press yes.</html>"; int answer = JOptionPane.showConfirmDialog(splashscreen, txt, "About to start import process", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_OPTION); if( answer != JOptionPane.YES_OPTION ) { System.exit(1); } new ImportKnownBoards().importKnownBoards(); new ImportIdentities().importIdentities(); doImport = true; } } splashscreen.setText(language.getString("Splashscreen.message.3")); splashscreen.setProgress(60); if (!initializeConnectivity()) { System.exit(1); } getIdentities().initialize(freenetIsOnline); // TODO: maybe make this configureable in options dialog for the paranoic people? String title; // if( frostSettings.getBoolValue("mainframe.showSimpleTitle") == false ) { // title = "Frost - " + getIdentities().getMyId().getUniqueName(); // } else { title = "Frost"; // } // Display the tray icon (do this before mainframe initializes) if (frostSettings.getBoolValue("showSystrayIcon") == true) { if (JSysTrayIcon.createInstance(0, title, title) == false) { logger.severe("Could not create systray icon."); } } // Main frame mainFrame = new MainFrame(frostSettings, title); getBoardsManager().initialize(); getFileTransferManager().initialize(); if( doImport ) { new ImportXmlMessages().importXmlMessages(getBoardsManager().getTofTreeModel()); new ImportFiles().importFiles(); new ImportDownloadFiles().importDownloadFiles(getBoardsManager().getTofTreeModel(), getFileTransferManager()); frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); } splashscreen.setText(language.getString("Splashscreen.message.4")); splashscreen.setProgress(70); mainFrame.initialize(); if (isFreenetOnline()) { resendFailedMessages(); } splashscreen.setText(language.getString("Splashscreen.message.5")); splashscreen.setProgress(80); // toftree must be loaded before expiration can run! // (cleanup gets the expiration mode from settings itself) CleanUp.processExpiredFiles(MainFrame.getInstance().getTofTreeModel().getAllBoards()); initializeTasks(mainFrame); SwingUtilities.invokeLater(new Runnable() { public void run() { mainFrame.setVisible(true); } }); splashscreen.closeMe(); }
public void initialize() throws Exception { Splashscreen splashscreen = new Splashscreen(); splashscreen.setVisible(true); keypool = frostSettings.getValue("keypool.dir"); splashscreen.setText(language.getString("Splashscreen.message.1")); splashscreen.setProgress(20); //Initializes the logging and skins new Logging(frostSettings); initializeSkins(); //Initializes storage DAOFactory.initialize(frostSettings); // open databases try { TransferLayerDatabase.initialize(); AppLayerDatabase.initialize(); } catch(SQLException ex) { logger.log(Level.SEVERE, "Error opening the databases", ex); ex.printStackTrace(); throw ex; } // initialize messageHashes messageHashes = new MessageHashes(); messageHashes.initialize(); // CLEANS TEMP DIR! START NO INSERTS BEFORE THIS RUNNED Startup.startupCheck(frostSettings, keypool); // nothing was started until now, its the perfect time to delete all empty date dirs in keypool... CleanUp.deleteEmptyBoardDateDirs( new File(keypool) ); splashscreen.setText(language.getString("Splashscreen.message.2")); splashscreen.setProgress(40); // check if help.zip contains only secure files (no http or ftp links at all) CheckHtmlIntegrity chi = new CheckHtmlIntegrity(); isHelpHtmlSecure = chi.scanZipFile("help/help.zip"); chi = null; boolean doImport = false; // check if this is a first startup if( frostSettings.getIntValue("freenetVersion") == 0 ) { frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); frostSettings.setValue("oneTimeUpdate.convertSigs.didRun", true); frostSettings.setValue("oneTimeUpdate.repairIdentities.didRun", true); // ask user which freenet version to use, set correct default availableNodes, // allow to import an existing identities file FirstStartupDialog startdlg = new FirstStartupDialog(); boolean exitChoosed = startdlg.startDialog(); if( exitChoosed ) { System.exit(1); } // set used version frostSettings.setValue("freenetVersion", startdlg.getFreenetVersion()); // 5 or 7 // init availableNodes with correct port if( startdlg.getOwnHostAndPort() != null ) { // user set own host:port frostSettings.setValue("availableNodes", startdlg.getOwnHostAndPort()); } else if( startdlg.getFreenetVersion() == FcpHandler.FREENET_05 ) { frostSettings.setValue("availableNodes", "127.0.0.1:8481"); } else { // 0.7 if( startdlg.isTestnet() == false ) { frostSettings.setValue("availableNodes", "127.0.0.1:9481"); } else { frostSettings.setValue("availableNodes", "127.0.0.1:9482"); } } if( startdlg.getOldIdentitiesFile() != null && startdlg.getOldIdentitiesFile().length() > 0 ) { boolean wasOk = FileAccess.copyFile(startdlg.getOldIdentitiesFile(), "identities.xml"); if( wasOk == false ) { MiscToolkit.getInstance().showMessage( "Copy of old identities.xml file failed.", JOptionPane.ERROR_MESSAGE, "Copy failed"); } // import old identities file into database new ImportIdentities().importIdentities(); } } else { // import xml messages into database if( frostSettings.getBoolValue("oneTimeUpdate.importMessages.didRun") == false ) { splashscreen.setText("Import messages into database"); String txt = "<html>Frost must now import the messages, and this could take some time.<br>"+ "Afterwards the files in keypool are not longer needed and will be deleted.<br><br>"+ "<b>BACKUP YOUR FROST DIRECTORY BEFORE STARTING!</b><br>"+ "<br><br>Do you want to start the import NOW press yes.</html>"; int answer = JOptionPane.showConfirmDialog(splashscreen, txt, "About to start import process", JOptionPane.INFORMATION_MESSAGE, JOptionPane.YES_NO_OPTION); if( answer != JOptionPane.YES_OPTION ) { System.exit(1); } new ImportKnownBoards().importKnownBoards(); new ImportIdentities().importIdentities(); doImport = true; } } splashscreen.setText(language.getString("Splashscreen.message.3")); splashscreen.setProgress(60); if (!initializeConnectivity()) { System.exit(1); } getIdentities().initialize(freenetIsOnline); // TODO: maybe make this configureable in options dialog for the paranoic people? String title; // if( frostSettings.getBoolValue("mainframe.showSimpleTitle") == false ) { // title = "Frost - " + getIdentities().getMyId().getUniqueName(); // } else { title = "Frost"; // } // Display the tray icon (do this before mainframe initializes) if (frostSettings.getBoolValue("showSystrayIcon") == true) { if (JSysTrayIcon.createInstance(0, title, title) == false) { logger.severe("Could not create systray icon."); } } // Main frame mainFrame = new MainFrame(frostSettings, title); getBoardsManager().initialize(); getFileTransferManager().initialize(); if( doImport ) { new ImportXmlMessages().importXmlMessages(getBoardsManager().getTofTreeModel()); new ImportFiles().importFiles(); new ImportDownloadFiles().importDownloadFiles(getBoardsManager().getTofTreeModel(), getFileTransferManager()); frostSettings.setValue("oneTimeUpdate.importMessages.didRun", true); } splashscreen.setText(language.getString("Splashscreen.message.4")); splashscreen.setProgress(70); mainFrame.initialize(); if (isFreenetOnline()) { resendFailedMessages(); } splashscreen.setText(language.getString("Splashscreen.message.5")); splashscreen.setProgress(80); // toftree must be loaded before expiration can run! // (cleanup gets the expiration mode from settings itself) CleanUp.processExpiredFiles(MainFrame.getInstance().getTofTreeModel().getAllBoards()); initializeTasks(mainFrame); SwingUtilities.invokeLater(new Runnable() { public void run() { mainFrame.setVisible(true); } }); splashscreen.closeMe(); }
diff --git a/src/hot/com/infinitiessoft/btrs/action/ReportList.java b/src/hot/com/infinitiessoft/btrs/action/ReportList.java index 0fb40f3..8c858ba 100644 --- a/src/hot/com/infinitiessoft/btrs/action/ReportList.java +++ b/src/hot/com/infinitiessoft/btrs/action/ReportList.java @@ -1,160 +1,160 @@ package com.infinitiessoft.btrs.action; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Out; import org.jboss.seam.framework.EntityQuery; import org.jboss.seam.log.Log; import com.infinitiessoft.btrs.enums.ReportTypeEnum; import com.infinitiessoft.btrs.enums.RoleEnum; import com.infinitiessoft.btrs.enums.StatusEnum; import com.infinitiessoft.btrs.exceptions.BtrsRuntimeException; import com.infinitiessoft.btrs.model.Report; import com.infinitiessoft.btrs.model.Role; import com.infinitiessoft.btrs.model.User; @Name("reportList") public class ReportList extends EntityQuery<Report> { private static final long serialVersionUID = 3852316905644428617L; @Logger Log log; @In User currentUser; private static final String LOGIC_OPERATOR_OR = "or"; @Out(required = false) private List<Report> preparedReports; @Out(required = false) private Map<String, Integer> reportsCounts = new HashMap<String, Integer>(); private static final String EJBQL = "select report from Report report"; private static final String[] RESTRICTIONS = { "report.owner = #{reportList.report.owner}", "report.reviewer = #{reportList.report.reviewer}", "report.currentStatus = #{reportList.report.currentStatus}"}; private Report report = new Report(); public ReportList() { setEjbql(EJBQL); setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS)); setMaxResults(25); } public Report getReport() { return report; } public void prepareCounts() { int outgoingCount = 0; int submittedCount = 0; int rejectedCount = 0; int incomingCount = 0; int allCount = 0; // backup String savedOperator = getRestrictionLogicOperator(); Integer savedMaxResults = getMaxResults(); Integer savedFirstResult = getFirstResult(); // get all reports belonging to current user setRestrictionLogicOperator(LOGIC_OPERATOR_OR); setMaxResults(null); setFirstResult(0); report.setOwner(currentUser); report.setReviewer(currentUser); List<Report> usersReports = getResultList(); for (Report report : usersReports) { if (currentUser.equals(report.getReviewer())) { if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { incomingCount++; - } else if (currentUser.equals(report.getOwner())) { - if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { - submittedCount++; - outgoingCount++; - } else if (StatusEnum.REJECTED.equals(report.getCurrentStatus())) { - rejectedCount++; - outgoingCount++; - } + } + } else if (currentUser.equals(report.getOwner())) { + if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { + submittedCount++; + outgoingCount++; + } else if (StatusEnum.REJECTED.equals(report.getCurrentStatus())) { + rejectedCount++; + outgoingCount++; } } else { String message = "Report (id=" + report.getId() + ") doesn't belong to user " + currentUser; log.error(message); throw new BtrsRuntimeException(message); } } allCount = usersReports.size(); reportsCounts.put(ReportTypeEnum.OUTGOING.getLabel(), outgoingCount); reportsCounts.put(ReportTypeEnum.SUBMITTED.getLabel(), submittedCount); reportsCounts.put(ReportTypeEnum.REJECTED.getLabel(), rejectedCount); reportsCounts.put(ReportTypeEnum.INCOMING.getLabel(), incomingCount); reportsCounts.put(ReportTypeEnum.ALL.getLabel(), allCount); log.debug("Reports Counts are: {0}", reportsCounts); // reset setRestrictionLogicOperator(savedOperator); setMaxResults(savedMaxResults); setFirstResult(savedFirstResult); report = new Report(); } public void prepareList(String type) { if (type == null || type.trim().isEmpty()) { type = determineType(); } if (ReportTypeEnum.OUTGOING.name().equalsIgnoreCase(type)) { report.setOwner(currentUser); report.setCurrentStatus(StatusEnum.APPROVED); List<String> restrictions = new ArrayList<String>(Arrays.asList(RESTRICTIONS)); restrictions.set(2, "report.currentStatus <> #{reportList.report.currentStatus}"); setRestrictionExpressionStrings(restrictions); } else if (ReportTypeEnum.INCOMING.name().equalsIgnoreCase(type)) { report.setReviewer(currentUser); report.setCurrentStatus(StatusEnum.SUBMITTED); } else if (ReportTypeEnum.SUBMITTED.name().equalsIgnoreCase(type)) { report.setOwner(currentUser); report.setCurrentStatus(StatusEnum.SUBMITTED); } else if (ReportTypeEnum.REJECTED.name().equalsIgnoreCase(type)) { report.setOwner(currentUser); report.setCurrentStatus(StatusEnum.REJECTED); } else { // ALL setRestrictionLogicOperator(LOGIC_OPERATOR_OR); report.setOwner(currentUser); report.setReviewer(currentUser); } preparedReports = getResultList(); log.debug("List of prepared Reports is: {0}.", preparedReports); } private String determineType() { for (Role role : currentUser.getRoles()) { if (RoleEnum.ACCOUNTANT.equals(role.getValue())) { return ReportTypeEnum.INCOMING.name().toLowerCase(); } } return ReportTypeEnum.OUTGOING.name().toLowerCase(); } }
true
true
public void prepareCounts() { int outgoingCount = 0; int submittedCount = 0; int rejectedCount = 0; int incomingCount = 0; int allCount = 0; // backup String savedOperator = getRestrictionLogicOperator(); Integer savedMaxResults = getMaxResults(); Integer savedFirstResult = getFirstResult(); // get all reports belonging to current user setRestrictionLogicOperator(LOGIC_OPERATOR_OR); setMaxResults(null); setFirstResult(0); report.setOwner(currentUser); report.setReviewer(currentUser); List<Report> usersReports = getResultList(); for (Report report : usersReports) { if (currentUser.equals(report.getReviewer())) { if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { incomingCount++; } else if (currentUser.equals(report.getOwner())) { if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { submittedCount++; outgoingCount++; } else if (StatusEnum.REJECTED.equals(report.getCurrentStatus())) { rejectedCount++; outgoingCount++; } } } else { String message = "Report (id=" + report.getId() + ") doesn't belong to user " + currentUser; log.error(message); throw new BtrsRuntimeException(message); } } allCount = usersReports.size(); reportsCounts.put(ReportTypeEnum.OUTGOING.getLabel(), outgoingCount); reportsCounts.put(ReportTypeEnum.SUBMITTED.getLabel(), submittedCount); reportsCounts.put(ReportTypeEnum.REJECTED.getLabel(), rejectedCount); reportsCounts.put(ReportTypeEnum.INCOMING.getLabel(), incomingCount); reportsCounts.put(ReportTypeEnum.ALL.getLabel(), allCount); log.debug("Reports Counts are: {0}", reportsCounts); // reset setRestrictionLogicOperator(savedOperator); setMaxResults(savedMaxResults); setFirstResult(savedFirstResult); report = new Report(); }
public void prepareCounts() { int outgoingCount = 0; int submittedCount = 0; int rejectedCount = 0; int incomingCount = 0; int allCount = 0; // backup String savedOperator = getRestrictionLogicOperator(); Integer savedMaxResults = getMaxResults(); Integer savedFirstResult = getFirstResult(); // get all reports belonging to current user setRestrictionLogicOperator(LOGIC_OPERATOR_OR); setMaxResults(null); setFirstResult(0); report.setOwner(currentUser); report.setReviewer(currentUser); List<Report> usersReports = getResultList(); for (Report report : usersReports) { if (currentUser.equals(report.getReviewer())) { if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { incomingCount++; } } else if (currentUser.equals(report.getOwner())) { if (StatusEnum.SUBMITTED.equals(report.getCurrentStatus())) { submittedCount++; outgoingCount++; } else if (StatusEnum.REJECTED.equals(report.getCurrentStatus())) { rejectedCount++; outgoingCount++; } } else { String message = "Report (id=" + report.getId() + ") doesn't belong to user " + currentUser; log.error(message); throw new BtrsRuntimeException(message); } } allCount = usersReports.size(); reportsCounts.put(ReportTypeEnum.OUTGOING.getLabel(), outgoingCount); reportsCounts.put(ReportTypeEnum.SUBMITTED.getLabel(), submittedCount); reportsCounts.put(ReportTypeEnum.REJECTED.getLabel(), rejectedCount); reportsCounts.put(ReportTypeEnum.INCOMING.getLabel(), incomingCount); reportsCounts.put(ReportTypeEnum.ALL.getLabel(), allCount); log.debug("Reports Counts are: {0}", reportsCounts); // reset setRestrictionLogicOperator(savedOperator); setMaxResults(savedMaxResults); setFirstResult(savedFirstResult); report = new Report(); }
diff --git a/AdvanceWars/src/org/game/advwars/GameBoard.java b/AdvanceWars/src/org/game/advwars/GameBoard.java index 6a908ac..92a2e46 100644 --- a/AdvanceWars/src/org/game/advwars/GameBoard.java +++ b/AdvanceWars/src/org/game/advwars/GameBoard.java @@ -1,305 +1,305 @@ package org.game.advwars; import android.view.*; import player.Player; import controller.Controller; import dataconnectors.SaveGUIData; import dataconnectors.SaveGameData; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.PointF; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.util.FloatMath; import android.util.Log; import android.view.View.OnTouchListener; import java.util.ArrayList; public class GameBoard extends Activity implements OnTouchListener { private MediaPlayer mp; private Controller c; private static final String TAG = "GameBoard"; // We can be in one of these 3 states static final int NONE = 0; static final int DRAG = 1; static final int ZOOM = 2; static final int PRESS = 3; int mode = NONE; // Remember some things for zooming PointF start = new PointF(); PointF mid = new PointF(); float oldDist = 1f; private GameBoardView gameBoardView; private GUIGameValues ggvGlobal = new GUIGameValues(); private SaveGUIData sd = new SaveGUIData(); private SaveGameData saveGame = new SaveGameData(); private char p1Char; private char p2Char; private ArrayList<String> commands; private boolean endTurn = false; private boolean move = false; private boolean aiTurn = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gameboard_layout); // Tells Android to adjust the volume of music instead of the ringer //setVolumeControlStream(AudioManager.STREAM_MUSIC); // Load player values ggvGlobal = sd.loadGGVData(); if (ggvGlobal.getFaction().equals("Blue")) { p1Char = 'b'; p2Char = 'r'; } else { p1Char = 'r'; p2Char = 'b'; } gameBoardView = (GameBoardView) findViewById(R.id.gameboard); gameBoardView.setOnTouchListener(this); Player p1 = new Player("Player1", 0, p1Char); Player p2 = new Player("Player2", 1, p2Char); c = new Controller(p1, p2, true, ggvGlobal.getMap()); gameBoardView.setController(c); gameBoardView.initGame(); sd.saveGGVData(ggvGlobal); // Background music if (mp != null){ mp.release(); } // Begin gameplay music mp = MediaPlayer.create(this, R.raw.background_music); mp.setLooping(true); mp.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { Intent i = new Intent(this, InGameMainMenu.class); i.putExtra("ggv", ggvGlobal); startActivityForResult(i, 0); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { ggvGlobal = sd.loadGGVData(); /*----------------- Actions based on in-game main menu selection -----------------*/ if (ggvGlobal.getInGameMenuEndTurn()) { // End turn endTurn = true; if (aiTurn = false) aiTurn = true; } else if (ggvGlobal.getInGameMenuSaveGame()) { // Save game saveGame.saveGameData(c); } else if (ggvGlobal.getInGameMenuQuitGame()) { Intent i = new Intent(this, MainMenu.class); i.putExtra("ggv", ggvGlobal); startActivityForResult(i, 0); } else { // Do nothing // Only hit if a user decides to close the main menu by using phone's Back button } /*------------------- Actions based on in-game menu selection -------------------*/ if (ggvGlobal.getSelectedUnit() != null && ggvGlobal.getSelectedUnit() != "") { c.produceUnit(ggvGlobal.getSelectedUnit()); gameBoardView.setController(c); gameBoardView.initGame(); } else if (ggvGlobal.getSelectedCommand() > -1 && ggvGlobal.getSelectedCommand() < 4) { // Move if (ggvGlobal.getSelectedCommand() == 0) { move = true; ggvGlobal.setMovement(c.unitTakeAction(ggvGlobal.getSelectedCommand())); sd.saveGGVData(ggvGlobal); gameBoardView.setController(c); gameBoardView.initGame(); } // Attack else if (ggvGlobal.getSelectedCommand() == 1) { } // Capture else if (ggvGlobal.getSelectedCommand() == 2) { } // Unit info else { c.unitTakeAction(ggvGlobal.getSelectedCommand()); gameBoardView.setController(c); gameBoardView.initGame(); } } else { // Do nothing // This is not good because it means something is failing :-( } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onTouch(View v, MotionEvent event) { // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = PRESS; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM"); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if(mode == PRESS) { ggvGlobal = sd.loadGGVData(); // Get selected points from game board view int[] selectedPoints = gameBoardView.getPoints(event.getX(), event.getY()); if (move == true && selectedPoints != null && c.isValidMove(selectedPoints[0], selectedPoints[1])) { c.unitMove(selectedPoints[0], selectedPoints[1]); gameBoardView.setController(c); gameBoardView.initGame(); move = false; } else { move = false; // If selected points are valid pass them to the controller and get a list of commands from it if (selectedPoints != null) commands = c.selectCoordinates(selectedPoints[0], selectedPoints[1]); // Check if commands are valid if (commands != null && !commands.isEmpty()) { // What to do if commands are for a unit - if (commands.get(0).toUpperCase().equals("MOVE")) + if (commands.contains("UnitInfo")) { ggvGlobal.setAvailableCommands(commands); ggvGlobal.setUnitInfo(c.getUnitInfo()); Intent i = new Intent(this, InGameMenu.class); i.putExtra("ggv", ggvGlobal); startActivityForResult(i, 0); commands.clear(); } // What to do if commands are for production building else { ggvGlobal.setAvailableCommands(commands); Intent i2 = new Intent(this, UnitSelectionMenu.class); i2.putExtra("ggv", ggvGlobal); startActivityForResult(i2, 0); } } } } mode = NONE; Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_MOVE: if(mode == PRESS && (Math.abs(event.getX() - start.x) > 20 || Math.abs(event.getY() - start.y) > 20)){ mode = DRAG; } if (mode == DRAG) { // ... gameBoardView.translateBoard(-(event.getX() - start.x), -(event.getY() - start.y)); } else if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist; gameBoardView.scaleBoard(scale, mid.x, mid.y); } } break; } v.invalidate(); return true; } /** Determine the space between the first two fingers */ private float spacing(MotionEvent event) { // ... float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } /** Calculate the mid point of the first two fingers */ private void midPoint(PointF point, MotionEvent event) { // ... float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } }
true
true
public boolean onTouch(View v, MotionEvent event) { // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = PRESS; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM"); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if(mode == PRESS) { ggvGlobal = sd.loadGGVData(); // Get selected points from game board view int[] selectedPoints = gameBoardView.getPoints(event.getX(), event.getY()); if (move == true && selectedPoints != null && c.isValidMove(selectedPoints[0], selectedPoints[1])) { c.unitMove(selectedPoints[0], selectedPoints[1]); gameBoardView.setController(c); gameBoardView.initGame(); move = false; } else { move = false; // If selected points are valid pass them to the controller and get a list of commands from it if (selectedPoints != null) commands = c.selectCoordinates(selectedPoints[0], selectedPoints[1]); // Check if commands are valid if (commands != null && !commands.isEmpty()) { // What to do if commands are for a unit if (commands.get(0).toUpperCase().equals("MOVE")) { ggvGlobal.setAvailableCommands(commands); ggvGlobal.setUnitInfo(c.getUnitInfo()); Intent i = new Intent(this, InGameMenu.class); i.putExtra("ggv", ggvGlobal); startActivityForResult(i, 0); commands.clear(); } // What to do if commands are for production building else { ggvGlobal.setAvailableCommands(commands); Intent i2 = new Intent(this, UnitSelectionMenu.class); i2.putExtra("ggv", ggvGlobal); startActivityForResult(i2, 0); } } } } mode = NONE; Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_MOVE: if(mode == PRESS && (Math.abs(event.getX() - start.x) > 20 || Math.abs(event.getY() - start.y) > 20)){ mode = DRAG; } if (mode == DRAG) { // ... gameBoardView.translateBoard(-(event.getX() - start.x), -(event.getY() - start.y)); } else if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist; gameBoardView.scaleBoard(scale, mid.x, mid.y); } } break; } v.invalidate(); return true; }
public boolean onTouch(View v, MotionEvent event) { // Handle touch events here... switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: start.set(event.getX(), event.getY()); Log.d(TAG, "mode=DRAG"); mode = PRESS; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); Log.d(TAG, "oldDist=" + oldDist); if (oldDist > 10f) { midPoint(mid, event); mode = ZOOM; Log.d(TAG, "mode=ZOOM"); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if(mode == PRESS) { ggvGlobal = sd.loadGGVData(); // Get selected points from game board view int[] selectedPoints = gameBoardView.getPoints(event.getX(), event.getY()); if (move == true && selectedPoints != null && c.isValidMove(selectedPoints[0], selectedPoints[1])) { c.unitMove(selectedPoints[0], selectedPoints[1]); gameBoardView.setController(c); gameBoardView.initGame(); move = false; } else { move = false; // If selected points are valid pass them to the controller and get a list of commands from it if (selectedPoints != null) commands = c.selectCoordinates(selectedPoints[0], selectedPoints[1]); // Check if commands are valid if (commands != null && !commands.isEmpty()) { // What to do if commands are for a unit if (commands.contains("UnitInfo")) { ggvGlobal.setAvailableCommands(commands); ggvGlobal.setUnitInfo(c.getUnitInfo()); Intent i = new Intent(this, InGameMenu.class); i.putExtra("ggv", ggvGlobal); startActivityForResult(i, 0); commands.clear(); } // What to do if commands are for production building else { ggvGlobal.setAvailableCommands(commands); Intent i2 = new Intent(this, UnitSelectionMenu.class); i2.putExtra("ggv", ggvGlobal); startActivityForResult(i2, 0); } } } } mode = NONE; Log.d(TAG, "mode=NONE"); break; case MotionEvent.ACTION_MOVE: if(mode == PRESS && (Math.abs(event.getX() - start.x) > 20 || Math.abs(event.getY() - start.y) > 20)){ mode = DRAG; } if (mode == DRAG) { // ... gameBoardView.translateBoard(-(event.getX() - start.x), -(event.getY() - start.y)); } else if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist; gameBoardView.scaleBoard(scale, mid.x, mid.y); } } break; } v.invalidate(); return true; }
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VCheckBox.java b/src/com/vaadin/terminal/gwt/client/ui/VCheckBox.java index be61aea7b..08111452f 100644 --- a/src/com/vaadin/terminal/gwt/client/ui/VCheckBox.java +++ b/src/com/vaadin/terminal/gwt/client/ui/VCheckBox.java @@ -1,198 +1,200 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.client.ui; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.LabelElement; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.vaadin.terminal.gwt.client.ApplicationConnection; import com.vaadin.terminal.gwt.client.BrowserInfo; import com.vaadin.terminal.gwt.client.EventHelper; import com.vaadin.terminal.gwt.client.EventId; import com.vaadin.terminal.gwt.client.Paintable; import com.vaadin.terminal.gwt.client.UIDL; import com.vaadin.terminal.gwt.client.Util; import com.vaadin.terminal.gwt.client.VTooltip; public class VCheckBox extends com.google.gwt.user.client.ui.CheckBox implements Paintable, Field, FocusHandler, BlurHandler { public static final String CLASSNAME = "v-checkbox"; String id; boolean immediate; ApplicationConnection client; private Element errorIndicatorElement; private Icon icon; private boolean isBlockMode = false; private HandlerRegistration focusHandlerRegistration; private HandlerRegistration blurHandlerRegistration; public VCheckBox() { setStyleName(CLASSNAME); addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { if (id == null || client == null) { return; } client.updateVariable(id, "state", getValue(), immediate); } }); sinkEvents(VTooltip.TOOLTIP_EVENTS); Element el = DOM.getFirstChild(getElement()); while (el != null) { DOM.sinkEvents(el, (DOM.getEventsSunk(el) | VTooltip.TOOLTIP_EVENTS)); el = DOM.getNextSibling(el); } } public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Save details this.client = client; id = uidl.getId(); // Ensure correct implementation if (client.updateComponent(this, uidl, false)) { return; } focusHandlerRegistration = EventHelper.updateFocusHandler(this, client, focusHandlerRegistration); blurHandlerRegistration = EventHelper.updateBlurHandler(this, client, blurHandlerRegistration); if (uidl.hasAttribute("error")) { if (errorIndicatorElement == null) { errorIndicatorElement = DOM.createSpan(); errorIndicatorElement.setInnerHTML("&nbsp;"); DOM.setElementProperty(errorIndicatorElement, "className", "v-errorindicator"); DOM.appendChild(getElement(), errorIndicatorElement); DOM.sinkEvents(errorIndicatorElement, VTooltip.TOOLTIP_EVENTS | Event.ONCLICK); + } else { + DOM.setStyleAttribute(errorIndicatorElement, "display", ""); } } else if (errorIndicatorElement != null) { DOM.setStyleAttribute(errorIndicatorElement, "display", "none"); } if (uidl.hasAttribute("readonly")) { setEnabled(false); } if (uidl.hasAttribute("icon")) { if (icon == null) { icon = new Icon(client); DOM.insertChild(getElement(), icon.getElement(), 1); icon.sinkEvents(VTooltip.TOOLTIP_EVENTS); icon.sinkEvents(Event.ONCLICK); } icon.setUri(uidl.getStringAttribute("icon")); } else if (icon != null) { // detach icon DOM.removeChild(getElement(), icon.getElement()); icon = null; } // Set text setText(uidl.getStringAttribute("caption")); setValue(uidl.getBooleanVariable("state")); immediate = uidl.getBooleanAttribute("immediate"); } @Override public void setText(String text) { super.setText(text); if (BrowserInfo.get().isIE() && BrowserInfo.get().getIEVersion() < 8) { boolean breakLink = text == null || "".equals(text); // break or create link between label element and checkbox, to // enable native focus outline around checkbox element itself, if // caption is not present NodeList<Node> childNodes = getElement().getChildNodes(); String id = null; for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.getItem(i); if (item.getNodeName().toLowerCase().equals("input")) { InputElement input = (InputElement) item; id = input.getId(); } if (item.getNodeName().toLowerCase().equals("label")) { LabelElement label = (LabelElement) item; if (breakLink) { label.setHtmlFor(""); } else { label.setHtmlFor(id); } } } } } @Override public void onBrowserEvent(Event event) { if (icon != null && (event.getTypeInt() == Event.ONCLICK) && (DOM.eventGetTarget(event) == icon.getElement())) { setValue(!getValue()); } super.onBrowserEvent(event); if (event.getTypeInt() == Event.ONLOAD) { Util.notifyParentOfSizeChange(this, true); } if (client != null) { client.handleTooltipEvent(event, this); } } @Override public void setWidth(String width) { setBlockMode(); super.setWidth(width); } @Override public void setHeight(String height) { setBlockMode(); super.setHeight(height); } /** * makes container element (span) to be block element to enable sizing. */ private void setBlockMode() { if (!isBlockMode) { DOM.setStyleAttribute(getElement(), "display", "block"); isBlockMode = true; } } public void onFocus(FocusEvent arg0) { client.updateVariable(id, EventId.FOCUS, "", true); } public void onBlur(BlurEvent arg0) { client.updateVariable(id, EventId.BLUR, "", true); } }
true
true
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Save details this.client = client; id = uidl.getId(); // Ensure correct implementation if (client.updateComponent(this, uidl, false)) { return; } focusHandlerRegistration = EventHelper.updateFocusHandler(this, client, focusHandlerRegistration); blurHandlerRegistration = EventHelper.updateBlurHandler(this, client, blurHandlerRegistration); if (uidl.hasAttribute("error")) { if (errorIndicatorElement == null) { errorIndicatorElement = DOM.createSpan(); errorIndicatorElement.setInnerHTML("&nbsp;"); DOM.setElementProperty(errorIndicatorElement, "className", "v-errorindicator"); DOM.appendChild(getElement(), errorIndicatorElement); DOM.sinkEvents(errorIndicatorElement, VTooltip.TOOLTIP_EVENTS | Event.ONCLICK); } } else if (errorIndicatorElement != null) { DOM.setStyleAttribute(errorIndicatorElement, "display", "none"); } if (uidl.hasAttribute("readonly")) { setEnabled(false); } if (uidl.hasAttribute("icon")) { if (icon == null) { icon = new Icon(client); DOM.insertChild(getElement(), icon.getElement(), 1); icon.sinkEvents(VTooltip.TOOLTIP_EVENTS); icon.sinkEvents(Event.ONCLICK); } icon.setUri(uidl.getStringAttribute("icon")); } else if (icon != null) { // detach icon DOM.removeChild(getElement(), icon.getElement()); icon = null; } // Set text setText(uidl.getStringAttribute("caption")); setValue(uidl.getBooleanVariable("state")); immediate = uidl.getBooleanAttribute("immediate"); }
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) { // Save details this.client = client; id = uidl.getId(); // Ensure correct implementation if (client.updateComponent(this, uidl, false)) { return; } focusHandlerRegistration = EventHelper.updateFocusHandler(this, client, focusHandlerRegistration); blurHandlerRegistration = EventHelper.updateBlurHandler(this, client, blurHandlerRegistration); if (uidl.hasAttribute("error")) { if (errorIndicatorElement == null) { errorIndicatorElement = DOM.createSpan(); errorIndicatorElement.setInnerHTML("&nbsp;"); DOM.setElementProperty(errorIndicatorElement, "className", "v-errorindicator"); DOM.appendChild(getElement(), errorIndicatorElement); DOM.sinkEvents(errorIndicatorElement, VTooltip.TOOLTIP_EVENTS | Event.ONCLICK); } else { DOM.setStyleAttribute(errorIndicatorElement, "display", ""); } } else if (errorIndicatorElement != null) { DOM.setStyleAttribute(errorIndicatorElement, "display", "none"); } if (uidl.hasAttribute("readonly")) { setEnabled(false); } if (uidl.hasAttribute("icon")) { if (icon == null) { icon = new Icon(client); DOM.insertChild(getElement(), icon.getElement(), 1); icon.sinkEvents(VTooltip.TOOLTIP_EVENTS); icon.sinkEvents(Event.ONCLICK); } icon.setUri(uidl.getStringAttribute("icon")); } else if (icon != null) { // detach icon DOM.removeChild(getElement(), icon.getElement()); icon = null; } // Set text setText(uidl.getStringAttribute("caption")); setValue(uidl.getBooleanVariable("state")); immediate = uidl.getBooleanAttribute("immediate"); }
diff --git a/application/test/test/UserDatabaseTest.java b/application/test/test/UserDatabaseTest.java index 53601a6c..5795655a 100644 --- a/application/test/test/UserDatabaseTest.java +++ b/application/test/test/UserDatabaseTest.java @@ -1,205 +1,205 @@ package test; import java.util.Date; import java.util.List; import models.dbentities.UserModel; import models.user.Gender; import models.user.Independent; import models.user.Organizer; import models.user.Teacher; import models.user.UserType; import models.user.User; import org.junit.Test; import com.avaje.ebean.Ebean; import java.security.SecureRandom; import java.math.BigInteger; import javax.persistence.PersistenceException; import junit.framework.Assert; public class UserDatabaseTest extends ContextTest { private SecureRandom random = new SecureRandom(); /* * Test IndependentUser database insertion. */ @Test public void makeIndependentUser() { String id = "id"; String name = "Bertrand Russell"; User userFind = null; UserModel mdl = new UserModel(id,UserType.PUPIL_OR_INDEP, name, new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Male,"nl"); User user = new Independent(mdl); try{ user.data.save(); }catch(PersistenceException e){ Assert.fail("Could not save the user"); } Assert.assertNotNull(Ebean.find(UserModel.class).where().eq("id",user.data.id).where().eq("type", UserType.PUPIL_OR_INDEP.toString()).findUnique()); UserModel userModel = Ebean.find(UserModel.class).where().eq("id", user.data.id).findUnique(); Assert.assertEquals(true, userModel.gender == Gender.Male); Assert.assertEquals(true, userModel.preflanguage == "nl"); Assert.assertEquals(true, userModel.email =="mail@localhost"); Assert.assertEquals(true, userModel.password == "password"); user.data.delete(); } /* * Test teacher database insertion. */ @Test public void makeTeacher(){ int numberOfTeachers = 10; String teacherID = new BigInteger(130,random).toString(); String name = "Maya Angelou"; for(int i = 0; i < numberOfTeachers; i++){ try{ new Teacher(new UserModel(new BigInteger(130,random).toString(),UserType.TEACHER, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")).data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } List<UserModel> teacherList = UserModel.find.where().like("type", "TEACHER").findList(); Assert.assertTrue(teacherList.size() == numberOfTeachers); User teacher = new Teacher(new UserModel(teacherID, UserType.TEACHER, name, new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); teacher.data.save(); Assert.assertNotNull(Ebean.find(UserModel.class).where().eq("id",teacherID).findUnique()); Assert.assertNotNull(Ebean.find(UserModel.class).where().eq("name", name).findUnique()); UserModel userModel = Ebean.find(UserModel.class).where().eq("id", teacher.data.id).findUnique(); Assert.assertEquals(true, userModel.gender == Gender.Female); Assert.assertEquals(true, userModel.preflanguage == "nl"); Assert.assertEquals(true, userModel.email =="mail@localhost"); Assert.assertEquals(true, userModel.password == "password"); teacher.data.delete(); } @Test public void makeOrganizer(){ int numberOfOrganizer = 10; String organizerID = new BigInteger(130,random).toString(); String name = "Maya Angelou"; for(int i = 0; i < numberOfOrganizer; i++){ try{ new Organizer(new UserModel(new BigInteger(130,random).toString(),UserType.ORGANIZER, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"en")).data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } List<UserModel> organizerList = UserModel.find.where().like("type", "ORGANIZER").findList(); Assert.assertTrue(organizerList.size() == numberOfOrganizer); User organizer = new Organizer(new UserModel(organizerID, UserType.ORGANIZER, name, new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"en")); organizer.data.save(); Assert.assertNotNull(Ebean.find(UserModel.class).where().eq("id",organizerID).findUnique()); Assert.assertNotNull(Ebean.find(UserModel.class).where().eq("name", name).findUnique()); UserModel userModel = Ebean.find(UserModel.class).where().eq("id", organizer.data.id).findUnique(); Assert.assertEquals(true, userModel.gender == Gender.Female); Assert.assertEquals(true, userModel.preflanguage == "en"); Assert.assertEquals(true, userModel.email =="mail@localhost"); Assert.assertEquals(true, userModel.password == "password"); organizer.data.delete(); } /** * Test user finder. */ @Test public void findListBasedOnType(){ int numberOfIndependentUser = 10; - int numberOfPupils = 5; + int numberOfTeachers = 5; //First clear the Users for (UserModel um :UserModel.find.all()){ um.delete(); } //generate random IndependentUser and save them. for(int i = 0; i < numberOfIndependentUser; i++){ try{ Independent ip = new Independent(new UserModel(new BigInteger(130,random).toString(),UserType.PUPIL_OR_INDEP, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); ip.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } //generate random Pupils. - for(int i = 0; i < numberOfPupils; i++){ + for(int i = 0; i < numberOfTeachers; i++){ try{ - Independent pu = new Independent(new UserModel(new BigInteger(130,random).toString(),UserType.PUPIL_OR_INDEP, + Teacher t = new Teacher(new UserModel(new BigInteger(130,random).toString(),UserType.TEACHER, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); - pu.data.save(); + t.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } List<UserModel> allUsers = UserModel.find.all(); List<UserModel> allIndepententUser = UserModel.find.where().like("type", UserType.PUPIL_OR_INDEP.toString()).findList(); - List<UserModel> allPupils = UserModel.find.where().like("type",UserType.PUPIL_OR_INDEP.toString()).findList(); + List<UserModel> allTeachers = UserModel.find.where().like("type",UserType.TEACHER.toString()).findList(); System.out.println(allIndepententUser.size()); - System.out.println(allPupils.size()); - Assert.assertTrue(Integer.toString(allUsers.size()),allUsers.size() == numberOfIndependentUser+numberOfPupils); + System.out.println(allTeachers.size()); + Assert.assertTrue(Integer.toString(allUsers.size()),allUsers.size() == numberOfIndependentUser+numberOfTeachers); Assert.assertTrue("indep",allIndepententUser.size() == numberOfIndependentUser); - Assert.assertTrue("pup",allPupils.size() == numberOfPupils); + Assert.assertTrue("teach",allTeachers.size() == numberOfTeachers); } }
false
true
public void findListBasedOnType(){ int numberOfIndependentUser = 10; int numberOfPupils = 5; //First clear the Users for (UserModel um :UserModel.find.all()){ um.delete(); } //generate random IndependentUser and save them. for(int i = 0; i < numberOfIndependentUser; i++){ try{ Independent ip = new Independent(new UserModel(new BigInteger(130,random).toString(),UserType.PUPIL_OR_INDEP, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); ip.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } //generate random Pupils. for(int i = 0; i < numberOfPupils; i++){ try{ Independent pu = new Independent(new UserModel(new BigInteger(130,random).toString(),UserType.PUPIL_OR_INDEP, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); pu.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } List<UserModel> allUsers = UserModel.find.all(); List<UserModel> allIndepententUser = UserModel.find.where().like("type", UserType.PUPIL_OR_INDEP.toString()).findList(); List<UserModel> allPupils = UserModel.find.where().like("type",UserType.PUPIL_OR_INDEP.toString()).findList(); System.out.println(allIndepententUser.size()); System.out.println(allPupils.size()); Assert.assertTrue(Integer.toString(allUsers.size()),allUsers.size() == numberOfIndependentUser+numberOfPupils); Assert.assertTrue("indep",allIndepententUser.size() == numberOfIndependentUser); Assert.assertTrue("pup",allPupils.size() == numberOfPupils); }
public void findListBasedOnType(){ int numberOfIndependentUser = 10; int numberOfTeachers = 5; //First clear the Users for (UserModel um :UserModel.find.all()){ um.delete(); } //generate random IndependentUser and save them. for(int i = 0; i < numberOfIndependentUser; i++){ try{ Independent ip = new Independent(new UserModel(new BigInteger(130,random).toString(),UserType.PUPIL_OR_INDEP, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); ip.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } //generate random Pupils. for(int i = 0; i < numberOfTeachers; i++){ try{ Teacher t = new Teacher(new UserModel(new BigInteger(130,random).toString(),UserType.TEACHER, new BigInteger(130,random).toString(), new Date(), new Date(), "password", "salt", "mail@localhost", Gender.Female,"nl")); t.data.save(); }catch(PersistenceException e){Assert.fail("Could not save the user");} } List<UserModel> allUsers = UserModel.find.all(); List<UserModel> allIndepententUser = UserModel.find.where().like("type", UserType.PUPIL_OR_INDEP.toString()).findList(); List<UserModel> allTeachers = UserModel.find.where().like("type",UserType.TEACHER.toString()).findList(); System.out.println(allIndepententUser.size()); System.out.println(allTeachers.size()); Assert.assertTrue(Integer.toString(allUsers.size()),allUsers.size() == numberOfIndependentUser+numberOfTeachers); Assert.assertTrue("indep",allIndepententUser.size() == numberOfIndependentUser); Assert.assertTrue("teach",allTeachers.size() == numberOfTeachers); }
diff --git a/de.hswt.hrm.main/src/de/hswt/hrm/main/handlers/AboutHandler.java b/de.hswt.hrm.main/src/de/hswt/hrm/main/handlers/AboutHandler.java index f4b68b8f..397ac6b5 100644 --- a/de.hswt.hrm.main/src/de/hswt/hrm/main/handlers/AboutHandler.java +++ b/de.hswt.hrm.main/src/de/hswt/hrm/main/handlers/AboutHandler.java @@ -1,70 +1,70 @@ /******************************************************************************* * Copyright (c) 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 *******************************************************************************/ package de.hswt.hrm.main.handlers; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import javax.inject.Named; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; public class AboutHandler { @Execute public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { String[] developer = new String[] { "Tobias Placht", "Anton Schreck", "Lucas Haering", "Marek Bieber", "Benjamin Pabst", "Michael Sieger","Stefan Kleeberger"}; StringBuilder sb = new StringBuilder(); Arrays.sort(developer); for (String s : developer) { sb.append(s); sb.append("\n"); } // EASTER EGG new Thread(new Runnable() { @Override public void run() { try { - URL url = new URL("platform:/plugin/de.hswt.hrm.main/media/2-10_journey_stand.wav"); + URL url = new URL("platform:/plugin/de.hswt.hrm.main/media/freestyler.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream audioStream = AudioSystem.getAudioInputStream( new BufferedInputStream(url.openConnection().getInputStream())); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException|LineUnavailableException|IOException e) { e.printStackTrace(); } } }).start(); // EASTER EGG END MessageDialog.openInformation(shell, "Developed by", sb.toString()); } }
true
true
public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { String[] developer = new String[] { "Tobias Placht", "Anton Schreck", "Lucas Haering", "Marek Bieber", "Benjamin Pabst", "Michael Sieger","Stefan Kleeberger"}; StringBuilder sb = new StringBuilder(); Arrays.sort(developer); for (String s : developer) { sb.append(s); sb.append("\n"); } // EASTER EGG new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("platform:/plugin/de.hswt.hrm.main/media/2-10_journey_stand.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream audioStream = AudioSystem.getAudioInputStream( new BufferedInputStream(url.openConnection().getInputStream())); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException|LineUnavailableException|IOException e) { e.printStackTrace(); } } }).start(); // EASTER EGG END MessageDialog.openInformation(shell, "Developed by", sb.toString()); }
public void execute(@Named(IServiceConstants.ACTIVE_SHELL) Shell shell) { String[] developer = new String[] { "Tobias Placht", "Anton Schreck", "Lucas Haering", "Marek Bieber", "Benjamin Pabst", "Michael Sieger","Stefan Kleeberger"}; StringBuilder sb = new StringBuilder(); Arrays.sort(developer); for (String s : developer) { sb.append(s); sb.append("\n"); } // EASTER EGG new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("platform:/plugin/de.hswt.hrm.main/media/freestyler.wav"); Clip clip = AudioSystem.getClip(); AudioInputStream audioStream = AudioSystem.getAudioInputStream( new BufferedInputStream(url.openConnection().getInputStream())); clip.open(audioStream); clip.start(); } catch (UnsupportedAudioFileException|LineUnavailableException|IOException e) { e.printStackTrace(); } } }).start(); // EASTER EGG END MessageDialog.openInformation(shell, "Developed by", sb.toString()); }
diff --git a/src/main/java/framework/utils/CloudBootstrapper.java b/src/main/java/framework/utils/CloudBootstrapper.java index 5d9aa752..47ac680f 100644 --- a/src/main/java/framework/utils/CloudBootstrapper.java +++ b/src/main/java/framework/utils/CloudBootstrapper.java @@ -1,65 +1,65 @@ package framework.utils; import java.io.File; import java.io.IOException; import java.util.Map; public class CloudBootstrapper extends Bootstrapper { private static final int DEFAULT_BOOTSTRAP_CLOUD_TIMEOUT = 30; private String provider; private boolean noWebServices = false; private Map<String, Object> cloudOverrides; public CloudBootstrapper() { super(DEFAULT_BOOTSTRAP_CLOUD_TIMEOUT); } public void setProvider(String provider) { this.provider = provider; } public void setNoWebServices(boolean noWebServices) { this.noWebServices = noWebServices; } public boolean isNoWebServices() { return noWebServices; } public void setCloudOverrides(Map<String, Object> overrides) { this.cloudOverrides = overrides; } @Override public String getBootstrapCommand() { if (provider == null) { throw new IllegalStateException("provider cannot be null!, please use setProvider"); } return "bootstrap-cloud " + provider; } @Override public String getOptions() throws IOException { StringBuilder builder = new StringBuilder(); if (noWebServices) { builder.append("-no-web-services"); } if (cloudOverrides != null && !cloudOverrides.isEmpty()) { File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrides); builder - .append("--cloud-overrides").append(" ") + .append("-cloud-overrides").append(" ") .append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" "); } return builder.toString(); } @Override public String getTeardownCommand() { return "teardown-cloud " + provider; } }
true
true
public String getOptions() throws IOException { StringBuilder builder = new StringBuilder(); if (noWebServices) { builder.append("-no-web-services"); } if (cloudOverrides != null && !cloudOverrides.isEmpty()) { File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrides); builder .append("--cloud-overrides").append(" ") .append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" "); } return builder.toString(); }
public String getOptions() throws IOException { StringBuilder builder = new StringBuilder(); if (noWebServices) { builder.append("-no-web-services"); } if (cloudOverrides != null && !cloudOverrides.isEmpty()) { File cloudOverridesFile = IOUtils.createTempOverridesFile(cloudOverrides); builder .append("-cloud-overrides").append(" ") .append(cloudOverridesFile.getAbsolutePath().replace("\\", "/")).append(" "); } return builder.toString(); }
diff --git a/src/gov/nih/nci/caintegrator/analysis/server/HierarchicalClusteringTaskR.java b/src/gov/nih/nci/caintegrator/analysis/server/HierarchicalClusteringTaskR.java index c15fbf3..50d6e1d 100755 --- a/src/gov/nih/nci/caintegrator/analysis/server/HierarchicalClusteringTaskR.java +++ b/src/gov/nih/nci/caintegrator/analysis/server/HierarchicalClusteringTaskR.java @@ -1,295 +1,295 @@ package gov.nih.nci.caintegrator.analysis.server; import gov.nih.nci.caintegrator.analysis.messaging.AnalysisResult; import gov.nih.nci.caintegrator.analysis.messaging.HierarchicalClusteringRequest; import gov.nih.nci.caintegrator.analysis.messaging.HierarchicalClusteringResult; import gov.nih.nci.caintegrator.enumeration.ClusterByType; import gov.nih.nci.caintegrator.exceptions.AnalysisServerException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.apache.log4j.Logger; import org.rosuda.JRclient.REXP; //import gov.nih.nci.caintegrator.exceptions.AnalysisServerException; /** * Performs Hierarchical Clustering using R. * * @author harrismic * */ /** * caIntegrator License * * Copyright 2001-2005 Science Applications International Corporation ("SAIC"). * The software subject to this notice and license includes both human readable source code form and machine readable, * binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with * the National Cancer Institute ("NCI") by NCI employees and employees of SAIC. * To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States * Code, section 105. * This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an * entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control" * for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity, * whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) * beneficial ownership of such entity. * This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive, * worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights * in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly * display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed * to and by third parties the caIntegrator Software and any modifications and derivative works thereof; * and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such * rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting * or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no * charge to You. * 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions * and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce * the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This * product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user * documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments * normally appear. * 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and * "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any * trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with * the terms of this License. * 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and * into any third party proprietary programs. However, if You incorporate the Software into third party proprietary * programs, You agree that You are solely responsible for obtaining any permission from such third parties required to * incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including * without limitation Your end-users, of their obligation to secure any required permissions from such third parties * before incorporating the Software into such third party proprietary software programs. In the event that You fail * to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such permissions. * 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and * to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses * of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction, * and distribution of the Work otherwise complies with the conditions stated in this License. * 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES 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. * */ public class HierarchicalClusteringTaskR extends AnalysisTaskR { private HierarchicalClusteringResult result; public static final int MAX_REPORTERS_FOR_GENE_CLUSTERING = 3000; private static Logger logger = Logger.getLogger(HierarchicalClusteringTaskR.class); public HierarchicalClusteringTaskR(HierarchicalClusteringRequest request) { this(request, false); } public HierarchicalClusteringTaskR(HierarchicalClusteringRequest request, boolean debugRcommands) { super(request, debugRcommands); } public HierarchicalClusteringRequest getRequest() { return (HierarchicalClusteringRequest) super.getRequest(); } /** * This method is used to keep an enumerated type value change from breaking the call to * the R function. The R function is expecting an exact match on the string passed * as a parameter. * @return the quoted string representing the distance matrix type. */ public String getDistanceMatrixRparamStr() { switch(getRequest().getDistanceMatrix()) { case Correlation : return getQuotedString("Correlation"); case Euclidean : return getQuotedString("Euclidean"); } return null; } /** * This method is used to keep an enumerated type value change from breaking the call to * the R function. The R function is expecting an exact match on the string passed * as a parameter. * @return the quoted string representing the linkage method */ public String getLinkageMethodRparamStr() { switch(getRequest().getLinkageMethod()) { case Average: return getQuotedString("average"); case Complete: return getQuotedString("complete"); case Single: return getQuotedString("single"); } return null; } /** * Implement Hierarchical */ public void run() { HierarchicalClusteringRequest hcRequest = (HierarchicalClusteringRequest) getRequest(); result = new HierarchicalClusteringResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing hierarchical clustering analysis request=" + hcRequest); try { setDataFile(hcRequest.getDataFileName()); } catch (AnalysisServerException e) { logger.error("Internal Error. Error setting data file to fileName=" + hcRequest.getDataFileName()); setException(e); return; } try { // get the submatrix to operate on doRvoidEval("hcInputMatrix <- dataMatrix"); doRvoidEval("hcInputMatrix <- GeneFilterWithVariance(hcInputMatrix," + hcRequest.getVarianceFilterValue() + ")"); String rCmd = null; if ((hcRequest.getSampleGroup()==null)||(hcRequest.getSampleGroup().size() < 2)) { //sample group should never be null when passed from middle tier AnalysisServerException ex = new AnalysisServerException( "Not enough samples to cluster."); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Sample group is null or not enough samples for Hierarchical clustering."); return; } rCmd = getRgroupCmd("sampleIds", hcRequest.getSampleGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.onegrp(hcInputMatrix, sampleIds)"; doRvoidEval(rCmd); if (hcRequest.getReporterGroup() != null) { rCmd = getRgroupCmd("reporterIds", hcRequest.getReporterGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.rep(hcInputMatrix, reporterIds)"; doRvoidEval(rCmd); } String plotCmd = null; // get the request parameters if (hcRequest.getClusterBy() == ClusterByType.Samples) { // cluster by samples rCmd = "mycluster <- mysamplecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[2]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else if (hcRequest.getClusterBy() == ClusterByType.Genes) { // cluster by genes //check the hcInputMatrix size. If there are more than 1000 reporters then //throw an exception. // check to see if the number of reporters to be used for the clustering is //too large. If it is then return an error int numReportersToUse = doREval("dim(hcInputMatrix)[1]").asInt(); if (numReportersToUse > MAX_REPORTERS_FOR_GENE_CLUSTERING) { AnalysisServerException ex = new AnalysisServerException( "Too many reporters to cluster , try increasing the variance filter value, attempted to use numReporters=" + numReportersToUse); ex.setFailedRequest(hcRequest); setException(ex); logger.info("Attempted to use numReporters=" + numReportersToUse + " in hcClustering. Returning exception."); return; } rCmd = "mycluster <- mygenecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[1]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else { AnalysisServerException ex = new AnalysisServerException("Unrecognized cluster by type"); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Unrecognized cluster by type"); return; } Vector orderedLabels = doREval("clusterLabels <- mycluster$labels[mycluster$order]").asVector(); float numPix = (float)orderedLabels.size() * 15.0f; int imgWidth = Math.round(numPix/72.0f); imgWidth = Math.max(3, imgWidth); int imgHeight = 10; byte[] imgCode = getImageCode(plotCmd, imgHeight, imgWidth); result.setImageCode(imgCode); List<String> orderedLabelList = new ArrayList<String>(orderedLabels.size()); String label = null; for (int i=0; i < orderedLabels.size(); i++ ) { label = ((REXP) orderedLabels.get(i)).asString(); orderedLabelList.add(i,label); } if (hcRequest.getClusterBy() == ClusterByType.Genes) { result.setClusteredReporterIDs(orderedLabelList); } else if (hcRequest.getClusterBy() == ClusterByType.Samples) { result.setClusteredSampleIDs(orderedLabelList); } } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( - "Internal Error. Caught AnalysisServerException in HierarchicalClusteringTaskR." + asex.getMessage()); + "Problem with clustering computation (Try using a less stringent variance filter). Caught AnalysisServerException in HierarchicalClusteringTaskR." + asex.getMessage()); aex.setFailedRequest(hcRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught AnalysisServerException in HierarchicalClusteringTaskR." + ex.getMessage()); asex.setFailedRequest(hcRequest); setException(asex); return; } } @Override public AnalysisResult getResult() { return result; } /** * Clean up some of the memory on the R server */ public void cleanUp() { //doRvoidEval("remove(hcInputMatrix)"); //doRvoidEval("remove(mycluster)"); try { setRComputeConnection(null); } catch (AnalysisServerException e) { logger.error("Error in cleanUp method"); logger.error(e); setException(e); } } }
true
true
public void run() { HierarchicalClusteringRequest hcRequest = (HierarchicalClusteringRequest) getRequest(); result = new HierarchicalClusteringResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing hierarchical clustering analysis request=" + hcRequest); try { setDataFile(hcRequest.getDataFileName()); } catch (AnalysisServerException e) { logger.error("Internal Error. Error setting data file to fileName=" + hcRequest.getDataFileName()); setException(e); return; } try { // get the submatrix to operate on doRvoidEval("hcInputMatrix <- dataMatrix"); doRvoidEval("hcInputMatrix <- GeneFilterWithVariance(hcInputMatrix," + hcRequest.getVarianceFilterValue() + ")"); String rCmd = null; if ((hcRequest.getSampleGroup()==null)||(hcRequest.getSampleGroup().size() < 2)) { //sample group should never be null when passed from middle tier AnalysisServerException ex = new AnalysisServerException( "Not enough samples to cluster."); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Sample group is null or not enough samples for Hierarchical clustering."); return; } rCmd = getRgroupCmd("sampleIds", hcRequest.getSampleGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.onegrp(hcInputMatrix, sampleIds)"; doRvoidEval(rCmd); if (hcRequest.getReporterGroup() != null) { rCmd = getRgroupCmd("reporterIds", hcRequest.getReporterGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.rep(hcInputMatrix, reporterIds)"; doRvoidEval(rCmd); } String plotCmd = null; // get the request parameters if (hcRequest.getClusterBy() == ClusterByType.Samples) { // cluster by samples rCmd = "mycluster <- mysamplecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[2]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else if (hcRequest.getClusterBy() == ClusterByType.Genes) { // cluster by genes //check the hcInputMatrix size. If there are more than 1000 reporters then //throw an exception. // check to see if the number of reporters to be used for the clustering is //too large. If it is then return an error int numReportersToUse = doREval("dim(hcInputMatrix)[1]").asInt(); if (numReportersToUse > MAX_REPORTERS_FOR_GENE_CLUSTERING) { AnalysisServerException ex = new AnalysisServerException( "Too many reporters to cluster , try increasing the variance filter value, attempted to use numReporters=" + numReportersToUse); ex.setFailedRequest(hcRequest); setException(ex); logger.info("Attempted to use numReporters=" + numReportersToUse + " in hcClustering. Returning exception."); return; } rCmd = "mycluster <- mygenecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[1]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else { AnalysisServerException ex = new AnalysisServerException("Unrecognized cluster by type"); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Unrecognized cluster by type"); return; } Vector orderedLabels = doREval("clusterLabels <- mycluster$labels[mycluster$order]").asVector(); float numPix = (float)orderedLabels.size() * 15.0f; int imgWidth = Math.round(numPix/72.0f); imgWidth = Math.max(3, imgWidth); int imgHeight = 10; byte[] imgCode = getImageCode(plotCmd, imgHeight, imgWidth); result.setImageCode(imgCode); List<String> orderedLabelList = new ArrayList<String>(orderedLabels.size()); String label = null; for (int i=0; i < orderedLabels.size(); i++ ) { label = ((REXP) orderedLabels.get(i)).asString(); orderedLabelList.add(i,label); } if (hcRequest.getClusterBy() == ClusterByType.Genes) { result.setClusteredReporterIDs(orderedLabelList); } else if (hcRequest.getClusterBy() == ClusterByType.Samples) { result.setClusteredSampleIDs(orderedLabelList); } } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( "Internal Error. Caught AnalysisServerException in HierarchicalClusteringTaskR." + asex.getMessage()); aex.setFailedRequest(hcRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught AnalysisServerException in HierarchicalClusteringTaskR." + ex.getMessage()); asex.setFailedRequest(hcRequest); setException(asex); return; } }
public void run() { HierarchicalClusteringRequest hcRequest = (HierarchicalClusteringRequest) getRequest(); result = new HierarchicalClusteringResult(getRequest().getSessionId(), getRequest().getTaskId()); logger.info(getExecutingThreadName() + " processing hierarchical clustering analysis request=" + hcRequest); try { setDataFile(hcRequest.getDataFileName()); } catch (AnalysisServerException e) { logger.error("Internal Error. Error setting data file to fileName=" + hcRequest.getDataFileName()); setException(e); return; } try { // get the submatrix to operate on doRvoidEval("hcInputMatrix <- dataMatrix"); doRvoidEval("hcInputMatrix <- GeneFilterWithVariance(hcInputMatrix," + hcRequest.getVarianceFilterValue() + ")"); String rCmd = null; if ((hcRequest.getSampleGroup()==null)||(hcRequest.getSampleGroup().size() < 2)) { //sample group should never be null when passed from middle tier AnalysisServerException ex = new AnalysisServerException( "Not enough samples to cluster."); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Sample group is null or not enough samples for Hierarchical clustering."); return; } rCmd = getRgroupCmd("sampleIds", hcRequest.getSampleGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.onegrp(hcInputMatrix, sampleIds)"; doRvoidEval(rCmd); if (hcRequest.getReporterGroup() != null) { rCmd = getRgroupCmd("reporterIds", hcRequest.getReporterGroup()); doRvoidEval(rCmd); rCmd = "hcInputMatrix <- getSubmatrix.rep(hcInputMatrix, reporterIds)"; doRvoidEval(rCmd); } String plotCmd = null; // get the request parameters if (hcRequest.getClusterBy() == ClusterByType.Samples) { // cluster by samples rCmd = "mycluster <- mysamplecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[2]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else if (hcRequest.getClusterBy() == ClusterByType.Genes) { // cluster by genes //check the hcInputMatrix size. If there are more than 1000 reporters then //throw an exception. // check to see if the number of reporters to be used for the clustering is //too large. If it is then return an error int numReportersToUse = doREval("dim(hcInputMatrix)[1]").asInt(); if (numReportersToUse > MAX_REPORTERS_FOR_GENE_CLUSTERING) { AnalysisServerException ex = new AnalysisServerException( "Too many reporters to cluster , try increasing the variance filter value, attempted to use numReporters=" + numReportersToUse); ex.setFailedRequest(hcRequest); setException(ex); logger.info("Attempted to use numReporters=" + numReportersToUse + " in hcClustering. Returning exception."); return; } rCmd = "mycluster <- mygenecluster(hcInputMatrix," + getDistanceMatrixRparamStr() + "," + getLinkageMethodRparamStr() + ")"; doRvoidEval(rCmd); plotCmd = "plot(mycluster, labels=dimnames(hcInputMatrix)[[1]], xlab=\"\", ylab=\"\",ps=8,sub=\"\", hang=-1)"; } else { AnalysisServerException ex = new AnalysisServerException("Unrecognized cluster by type"); ex.setFailedRequest(hcRequest); setException(ex); logger.error("Unrecognized cluster by type"); return; } Vector orderedLabels = doREval("clusterLabels <- mycluster$labels[mycluster$order]").asVector(); float numPix = (float)orderedLabels.size() * 15.0f; int imgWidth = Math.round(numPix/72.0f); imgWidth = Math.max(3, imgWidth); int imgHeight = 10; byte[] imgCode = getImageCode(plotCmd, imgHeight, imgWidth); result.setImageCode(imgCode); List<String> orderedLabelList = new ArrayList<String>(orderedLabels.size()); String label = null; for (int i=0; i < orderedLabels.size(); i++ ) { label = ((REXP) orderedLabels.get(i)).asString(); orderedLabelList.add(i,label); } if (hcRequest.getClusterBy() == ClusterByType.Genes) { result.setClusteredReporterIDs(orderedLabelList); } else if (hcRequest.getClusterBy() == ClusterByType.Samples) { result.setClusteredSampleIDs(orderedLabelList); } } catch (AnalysisServerException asex) { AnalysisServerException aex = new AnalysisServerException( "Problem with clustering computation (Try using a less stringent variance filter). Caught AnalysisServerException in HierarchicalClusteringTaskR." + asex.getMessage()); aex.setFailedRequest(hcRequest); setException(aex); return; } catch (Exception ex) { AnalysisServerException asex = new AnalysisServerException( "Internal Error. Caught AnalysisServerException in HierarchicalClusteringTaskR." + ex.getMessage()); asex.setFailedRequest(hcRequest); setException(asex); return; } }
diff --git a/src/bots/Map.java b/src/bots/Map.java index 7210389..d0acffa 100644 --- a/src/bots/Map.java +++ b/src/bots/Map.java @@ -1,117 +1,117 @@ package bots; import java.awt.Component; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class Map { private static final int TILE_SIZE = 10; private final int width; private final int height; private final List<List<Ground>> tiles; private final BufferedImage offscreen; private final BufferedImage map_img; public Map(String name) throws IOException { URL url = this.getClass().getResource("/resources/maps/"+name); assert (url != null); map_img = (BufferedImage) new ImageIcon(ImageIO.read(url)).getImage(); width = map_img.getWidth() * TILE_SIZE; height = map_img.getHeight() * TILE_SIZE; tiles = new ArrayList<List<Ground>>(height); offscreen = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } public Ground get(final int x, final int y) { if (x < 0 || y < 0 || x > width || y > height) { return Ground.Void; } final int tileX = x / TILE_SIZE; final int tileY = y / TILE_SIZE; return tiles.get(tileX).get(tileY); } public void paint(Graphics g, Component observer) { g.drawImage(offscreen, 0, 0, observer); } public Image cloneImage() { BufferedImage img = new BufferedImage(offscreen.getWidth(), offscreen.getHeight(), offscreen.getType()); Graphics g = img.getGraphics(); g.drawImage(offscreen, 0, 0, null); return img; } public int getWidth() { return width; } public int getHeight() { return height; } public void init(Base red, Base blue) { // TODO paint a nicer map! for (int img_x = 0; img_x < map_img.getWidth(); img_x++) { List<Ground> row = new ArrayList<Ground>(width); for (int img_y = 0; img_y < map_img.getWidth(); img_y++) { int pixel = map_img.getRGB(img_y, img_x); Ground ground = Ground.Void; switch (pixel) { case 0xff3a9d3a: ground = Ground.Grass; break; case 0xff375954: ground = Ground.Swamp; break; case 0xffe8d35e: ground = Ground.Sand; break; case 0xff323f05: ground = Ground.Forest; break; case 0xff0000ff: /* BLUE */ ground = Ground.Grass; - blue.setPosition(img_x*TILE_SIZE, img_y*TILE_SIZE); + blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2)); break; case 0xff787878: ground = Ground.Rocks; break; case 0xffffffff: /* WHITE */ ground = Ground.Grass; break; case 0xffff0000: /* RED */ ground = Ground.Grass; - red.setPosition(img_x*TILE_SIZE, img_y*TILE_SIZE); + red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2)); break; case 0xff3674db: ground = Ground.Water; break; default: throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel)); } row.add(img_y, ground); /* paint offscreen image */ for (int i = 0; i < TILE_SIZE; i++) { for (int j = 0; j < TILE_SIZE; j++) { offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel); } } } tiles.add(row); } } }
false
true
public void init(Base red, Base blue) { // TODO paint a nicer map! for (int img_x = 0; img_x < map_img.getWidth(); img_x++) { List<Ground> row = new ArrayList<Ground>(width); for (int img_y = 0; img_y < map_img.getWidth(); img_y++) { int pixel = map_img.getRGB(img_y, img_x); Ground ground = Ground.Void; switch (pixel) { case 0xff3a9d3a: ground = Ground.Grass; break; case 0xff375954: ground = Ground.Swamp; break; case 0xffe8d35e: ground = Ground.Sand; break; case 0xff323f05: ground = Ground.Forest; break; case 0xff0000ff: /* BLUE */ ground = Ground.Grass; blue.setPosition(img_x*TILE_SIZE, img_y*TILE_SIZE); break; case 0xff787878: ground = Ground.Rocks; break; case 0xffffffff: /* WHITE */ ground = Ground.Grass; break; case 0xffff0000: /* RED */ ground = Ground.Grass; red.setPosition(img_x*TILE_SIZE, img_y*TILE_SIZE); break; case 0xff3674db: ground = Ground.Water; break; default: throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel)); } row.add(img_y, ground); /* paint offscreen image */ for (int i = 0; i < TILE_SIZE; i++) { for (int j = 0; j < TILE_SIZE; j++) { offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel); } } } tiles.add(row); } }
public void init(Base red, Base blue) { // TODO paint a nicer map! for (int img_x = 0; img_x < map_img.getWidth(); img_x++) { List<Ground> row = new ArrayList<Ground>(width); for (int img_y = 0; img_y < map_img.getWidth(); img_y++) { int pixel = map_img.getRGB(img_y, img_x); Ground ground = Ground.Void; switch (pixel) { case 0xff3a9d3a: ground = Ground.Grass; break; case 0xff375954: ground = Ground.Swamp; break; case 0xffe8d35e: ground = Ground.Sand; break; case 0xff323f05: ground = Ground.Forest; break; case 0xff0000ff: /* BLUE */ ground = Ground.Grass; blue.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2)); break; case 0xff787878: ground = Ground.Rocks; break; case 0xffffffff: /* WHITE */ ground = Ground.Grass; break; case 0xffff0000: /* RED */ ground = Ground.Grass; red.setPosition(img_x*TILE_SIZE+(TILE_SIZE/2), img_y*TILE_SIZE+(TILE_SIZE/2)); break; case 0xff3674db: ground = Ground.Water; break; default: throw new RuntimeException("Map broken. Unknown color: "+Integer.toHexString(pixel)); } row.add(img_y, ground); /* paint offscreen image */ for (int i = 0; i < TILE_SIZE; i++) { for (int j = 0; j < TILE_SIZE; j++) { offscreen.setRGB(img_x*TILE_SIZE+i, img_y*TILE_SIZE+j, pixel); } } } tiles.add(row); } }
diff --git a/Test.java b/Test.java index 643f5f6..d2a9805 100644 --- a/Test.java +++ b/Test.java @@ -1,38 +1,38 @@ import org.antlr.runtime.*; import org.antlr.runtime.tree.Tree; import org.antlr.runtime.debug.ParseTreeBuilder; public class Test { public static void printTree(Tree t, int indent, int spaces) { for (int i = 0; i < t.getChildCount(); i++) { for (int j = 0; j < indent; j++) System.out.print(' '); Tree ch = t.getChild(i); System.out.println(ch); printTree(ch, spaces+indent, spaces); } } public static void main(String[] args) throws Exception { - if (args.length != 1) { + if (args.length < 1) { System.err.println("Usage: java Test <file> ..."); return; } for (int i = 0; i < args.length; i++) { MiniAdaLexer lex = new MiniAdaLexer(new MiniAdaFileStream(args[i])); CommonTokenStream tokens = new CommonTokenStream(lex); ParseTreeBuilder builder = new ParseTreeBuilder("compilation"); MiniAdaParser parse = new MiniAdaParser(tokens, builder); try { parse.compilation(); System.out.println("Parsing file: " + args[i]); printTree(builder.getTree(), 2, 2); } catch (RecognitionException e) { e.printStackTrace(); return; } } } }
true
true
public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Test <file> ..."); return; } for (int i = 0; i < args.length; i++) { MiniAdaLexer lex = new MiniAdaLexer(new MiniAdaFileStream(args[i])); CommonTokenStream tokens = new CommonTokenStream(lex); ParseTreeBuilder builder = new ParseTreeBuilder("compilation"); MiniAdaParser parse = new MiniAdaParser(tokens, builder); try { parse.compilation(); System.out.println("Parsing file: " + args[i]); printTree(builder.getTree(), 2, 2); } catch (RecognitionException e) { e.printStackTrace(); return; } } }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Usage: java Test <file> ..."); return; } for (int i = 0; i < args.length; i++) { MiniAdaLexer lex = new MiniAdaLexer(new MiniAdaFileStream(args[i])); CommonTokenStream tokens = new CommonTokenStream(lex); ParseTreeBuilder builder = new ParseTreeBuilder("compilation"); MiniAdaParser parse = new MiniAdaParser(tokens, builder); try { parse.compilation(); System.out.println("Parsing file: " + args[i]); printTree(builder.getTree(), 2, 2); } catch (RecognitionException e) { e.printStackTrace(); return; } } }
diff --git a/Game.java b/Game.java index 4bfadcb..ef6f222 100644 --- a/Game.java +++ b/Game.java @@ -1,719 +1,716 @@ // Copyright 2010 owners of the AI Challenge 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. // // Author: Jeff Cameron ([email protected]) // // Stores the game state. import java.awt.*; import java.awt.image.*; import java.awt.geom.AffineTransform; import java.util.*; import java.lang.Math; import java.io.*; public class Game implements Cloneable { // There are two modes: // * If mode == 0, then s is interpreted as a filename, and the game is // initialized by reading map data out of the named file. // * If mode == 1, then s is interpreted as a string that contains map // data directly. The string is parsed in the same way that the // contents of a map file would be. // This constructor does not actually initialize the game object. You must // always call Init() before the game object will be in any kind of // coherent state. public Game(String s, int maxGameLength, int mode, String logFilename) { this.logFilename = logFilename; planets = new ArrayList<Planet>(); fleets = new ArrayList<Fleet>(); gamePlayback = ""; initMode = mode; switch (initMode) { case 0: mapFilename = s; break; case 1: mapData = s; break; default: break; } this.maxGameLength = maxGameLength; numTurns = 0; } // Initializes a game of Planet Wars. Loads the map data from the file // specified in the constructor. Returns 1 on success, 0 on failure. public int Init() { // Delete the contents of the log file. if (logFilename != null) { try { FileOutputStream fos = new FileOutputStream(logFilename); fos.close(); WriteLogMessage("initializing"); } catch (Exception e) { // do nothing. } } switch (initMode) { case 0: return LoadMapFromFile(mapFilename); case 1: return ParseGameState(mapData); default: return 0; } } public void WriteLogMessage(String message) { if (logFilename == null) { return; } BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(logFilename, true)); bw.write(message); bw.newLine(); bw.flush(); } catch (Exception e) { // do nothing. } finally { try { bw.close(); } catch (Exception e) { } } } // Returns the number of planets. Planets are numbered starting with 0. public int NumPlanets() { return planets.size(); } // Returns the planet with the given planet_id. There are NumPlanets() // planets. They are numbered starting at 0. public Planet GetPlanet(int planetID) { return planets.get(planetID); } // Returns the number of fleets. public int NumFleets() { return fleets.size(); } // Returns the fleet with the given fleet_id. Fleets are numbered starting // with 0. There are NumFleets() fleets. fleet_id's are not consistent from // one turn to the next. public Fleet GetFleet(int fleetID) { return fleets.get(fleetID); } // Writes a string which represents the current game state. No point-of- // view switching is performed. public String toString() { return PovRepresentation(-1); } // Writes a string which represents the current game state. This string // conforms to the Point-in-Time format from the project Wiki. // // Optionally, you may specify the pov (Point of View) parameter. The pov // parameter is a player number. If specified, the player numbers 1 and pov // will be swapped in the game state output. This is used when sending the // game state to individual players, so that they can always assume that // they are player number 1. public String PovRepresentation(int pov) { String s = ""; for (Planet p : planets) { s += "P " + p.X() + " " + p.Y() + " " + PovSwitch(pov, p.Owner()) + " " + p.NumShips() + " " + p.GrowthRate() + "\n"; } for (Fleet f : fleets) { s += "F " + PovSwitch(pov, f.Owner()) + " " + f.NumShips() + " " + f.SourcePlanet() + " " + f.DestinationPlanet() + " " + f.TotalTripLength() + " " + f.TurnsRemaining() + "\n"; } return s; } // Carries out the point-of-view switch operation, so that each player can // always assume that he is player number 1. There are three cases. // 1. If pov < 0 then no pov switching is being used. Return player_id. // 2. If player_id == pov then return 1 so that each player thinks he is // player number 1. // 3. If player_id == 1 then return pov so that the real player 1 looks // like he is player number "pov". // 4. Otherwise return player_id, since players other than 1 and pov are // unaffected by the pov switch. public static int PovSwitch(int pov, int playerID) { if (pov < 0) return playerID; if (playerID == pov) return 1; if (playerID == 1) return pov; return playerID; } // Returns the distance between two planets, rounded up to the next highest // integer. This is the number of discrete time steps it takes to get // between the two planets. public int Distance(int sourcePlanet, int destinationPlanet) { Planet source = planets.get(sourcePlanet); Planet destination = planets.get(destinationPlanet); double dx = source.X() - destination.X(); double dy = source.Y() - destination.Y(); return (int)Math.ceil(Math.sqrt(dx * dx + dy * dy)); } // Executes one time step. // * Planet bonuses are added to non-neutral planets. // * Fleets are advanced towards their destinations. // * Fleets that arrive at their destination are dealt with. public void DoTimeStep() { // Add ships to each non-neutral planet according to its growth rate. for (Planet p : planets) { if (p.Owner() > 0) { p.AddShips(p.GrowthRate()); } } // Advance all fleets by one time step. Collect the ones that are // arriving at their destination planets this turn. Group them by // destination and attacking player using the attackers map. For // example, attackers[3][4] will store how many of player 4's ships // are landing on planet 3 this turn. ArrayList<Fleet> newFleets = new ArrayList<Fleet>(); Map<Integer, Map<Integer, Integer>> attackers = new TreeMap<Integer, Map<Integer, Integer>>(); for (Fleet f : fleets) { f.TimeStep(); if (f.TurnsRemaining() == 0) { int dest = f.DestinationPlanet(); int attacker = f.Owner(); if (!attackers.containsKey(dest)) { attackers.put(dest, new TreeMap<Integer, Integer>()); } if (!attackers.get(dest).containsKey(attacker)) { attackers.get(dest).put(attacker, 0); } int existingAttackers = attackers.get(dest).get(attacker); attackers.get(dest).put(attacker, existingAttackers + f.NumShips()); } else { newFleets.add(f); } } fleets = newFleets; // Resolve the status of each planet which is being attacked. This is // non-trivial, since a planet can be attacked by many different // players at once. for (int i = 0; i < planets.size(); ++i) { if (!attackers.containsKey(i)) { continue; } Planet p = planets.get(i); int defender = p.Owner(); // Add the current owner's "attacking" ships to the defending // forces. if (attackers.get(i).containsKey(defender)) { p.AddShips(attackers.get(i).get(defender)); attackers.get(i).remove(defender); } // Empty the attackers into a vector of fleets and sort them from // weakest to strongest. ArrayList<Fleet> enemyFleets = new ArrayList<Fleet>(); int numEnemyShips = 0; for (Integer j : attackers.get(i).keySet()) { int numAttackers = attackers.get(i).get(j); enemyFleets.add(new Fleet(j, numAttackers)); numEnemyShips += numAttackers; } Collections.sort(enemyFleets); // Starting with the weakest attacker, the attackers take turns // chipping away the defending forces one by one until there are // either no more defenders or no more attackers. int whoseTurn = 0; while (p.NumShips() > 0 && numEnemyShips > 0) { if (enemyFleets.get(whoseTurn).NumShips() > 0) { p.RemoveShips(1); enemyFleets.get(whoseTurn).RemoveShips(1); --numEnemyShips; if (enemyFleets.get(whoseTurn).NumShips() == 0) { enemyFleets.remove(whoseTurn); --whoseTurn; } } ++whoseTurn; if (whoseTurn >= enemyFleets.size()) { whoseTurn = 0; } } // If there are no enemy fleets left, then the defender keeps // control of the planet. If there are any enemy fleets left, then // they battle it out to determine who gets control of the planet. // This is done by cycling through the attackers and subtracting // one ship at a time from each, until there is only one attacker // left. If the last attackers are all eliminated at the same time, // then the planet becomes neutral with zero ships occupying it. if (numEnemyShips > 0) { p.Owner(0); - while (true) { + while (enemyFleets.size() > 1) { for (int j = 0; j < enemyFleets.size(); ++j) { enemyFleets.get(j).RemoveShips(1); if (enemyFleets.get(j).NumShips() <= 0) { enemyFleets.remove(j); --j; } } - if (enemyFleets.size() == 0) { - break; - } - if (enemyFleets.size() == 1) { - p.Owner(enemyFleets.get(0).Owner()); - p.NumShips(enemyFleets.get(0).NumShips()); - break; - } + } + if (enemyFleets.size() == 1) { + p.Owner(enemyFleets.get(0).Owner()); + p.NumShips(enemyFleets.get(0).NumShips()); + break; } } } for (Planet p : planets) { gamePlayback += "" + p.Owner() + "." + p.NumShips() + ","; } for (Fleet f : fleets) { gamePlayback += "" + f.Owner() + "." + f.NumShips() + "." + f.SourcePlanet() + "." + f.DestinationPlanet() + "." + f.TotalTripLength() + "." + f.TurnsRemaining() + ","; } if (gamePlayback.charAt(gamePlayback.length() - 1) == ',') { gamePlayback = gamePlayback.substring(0, gamePlayback.length() - 1); } gamePlayback += ":"; // Check to see if the maximum number of turns has been reached. ++numTurns; } // Issue an order. This function takes num_ships off the source_planet, // puts them into a newly-created fleet, calculates the distance to the // destination_planet, and sets the fleet's total trip time to that // distance. Checks that the given player_id is allowed to give the given // order. If not, the offending player is kicked from the game. If the // order was carried out without any issue, and everything is peachy, then // 0 is returned. Otherwise, -1 is returned. public int IssueOrder(int playerID, int sourcePlanet, int destinationPlanet, int numShips) { Planet source = planets.get(sourcePlanet); if (source.Owner() != playerID || numShips > source.NumShips() || numShips < 0) { WriteLogMessage("Dropping player " + playerID + ". source.Owner() = " + source.Owner() + ", playerID = " + playerID + ", numShips = " + numShips + ", source.NumShips() = " + source.NumShips()); DropPlayer(playerID); return -1; } source.RemoveShips(numShips); int distance = Distance(sourcePlanet, destinationPlanet); Fleet f = new Fleet(source.Owner(), numShips, sourcePlanet, destinationPlanet, distance, distance); fleets.add(f); return 0; } public void AddFleet(Fleet f) { fleets.add(f); } // Behaves just like the longer form of IssueOrder, but takes a string // of the form "source_planet destination_planet num_ships". That is, three // integers separated by space characters. public int IssueOrder(int playerID, String order) { String[] tokens = order.split(" "); if (tokens.length != 3) { return -1; } int sourcePlanet = Integer.parseInt(tokens[0]); int destinationPlanet = Integer.parseInt(tokens[1]); int numShips = Integer.parseInt(tokens[2]); return IssueOrder(playerID, sourcePlanet, destinationPlanet, numShips); } // Kicks a player out of the game. This is used in cases where a player // tries to give an illegal order or runs over the time limit. public void DropPlayer(int playerID) { for (Planet p : planets) { if (p.Owner() == playerID) { p.Owner(0); } } for (Fleet f : fleets) { if (f.Owner() == playerID) { f.Kill(); } } } // Returns true if the named player owns at least one planet or fleet. // Otherwise, the player is deemed to be dead and false is returned. public boolean IsAlive(int playerID) { for (Planet p : planets) { if (p.Owner() == playerID) { return true; } } for (Fleet f : fleets) { if (f.Owner() == playerID) { return true; } } return false; } // If the game is not yet over (ie: at least two players have planets or // fleets remaining), returns -1. If the game is over (ie: only one player // is left) then that player's number is returned. If there are no // remaining players, then the game is a draw and 0 is returned. public int Winner() { Set<Integer> remainingPlayers = new TreeSet<Integer>(); for (Planet p : planets) { remainingPlayers.add(p.Owner()); } for (Fleet f : fleets) { remainingPlayers.add(f.Owner()); } remainingPlayers.remove(0); if (numTurns > maxGameLength) { int leadingPlayer = -1; int mostShips = -1; for (int playerID : remainingPlayers) { int numShips = NumShips(playerID); if (numShips == mostShips) { leadingPlayer = 0; } else if (numShips > mostShips) { leadingPlayer = playerID; mostShips = numShips; } } return leadingPlayer; } switch (remainingPlayers.size()) { case 0: return 0; case 1: return ((Integer)remainingPlayers.toArray()[0]).intValue(); default: return -1; } } // Returns the game playback string. This is a complete record of the game, // and can be passed to a visualization program to playback the game. public String GamePlaybackString() { return gamePlayback; } // Returns the number of ships that the current player has, either located // on planets or in flight. public int NumShips(int playerID) { int numShips = 0; for (Planet p : planets) { if (p.Owner() == playerID) { numShips += p.NumShips(); } } for (Fleet f : fleets) { if (f.Owner() == playerID) { numShips += f.NumShips(); } } return numShips; } // Gets a color for a player (clamped) private Color GetColor(int player, ArrayList<Color> colors) { if (player > colors.size()) { return Color.PINK; } else { return colors.get(player); } } private Point getPlanetPos(Planet p, double top, double left, double right, double bottom, int width, int height) { int x = (int)((p.X() - left) / (right - left) * width); int y = height - (int)((p.Y() - top) / (bottom - top) * height); return new Point(x, y); } // A planet's inherent radius is its radius before being transformed for // rendering. The final rendered radii of all the planets are proportional // to their inherent radii. The radii are scaled for maximum aesthetic // appeal. private double inherentRadius(Planet p) { return Math.sqrt(p.GrowthRate()); //return Math.log(p.GrowthRate() + 3.0); //return p.GrowthRate(); } // Renders the current state of the game to a graphics object // // The offset is a number between 0 and 1 that specifies how far we are // past this game state, in units of time. As this parameter varies from // 0 to 1, the fleets all move in the forward direction. This is used to // fake smooth animation. // // On success, return an image. If something goes wrong, returns null. void Render(int width, // Desired image width int height, // Desired image height double offset, // Real number between 0 and 1 BufferedImage bgImage, // Background image ArrayList<Color> colors, // Player colors Graphics2D g) { // Rendering context Font planetFont = new Font("Sans Serif", Font.BOLD, 12); Font fleetFont = new Font("Sans serif", Font.BOLD, 18); Color bgColor = new Color(188, 189, 172); Color textColor = Color.BLACK; if (bgImage != null) { g.drawImage(bgImage, 0, 0, null); } // Determine the dimensions of the viewport in game coordinates. double top = Double.MAX_VALUE; double left = Double.MAX_VALUE; double right = Double.MIN_VALUE; double bottom = Double.MIN_VALUE; for (Planet p : planets) { if (p.X() < left) left = p.X(); if (p.X() > right) right = p.X(); if (p.Y() > bottom) bottom = p.Y(); if (p.Y() < top) top = p.Y(); } double xRange = right - left; double yRange = bottom - top; double paddingFactor = 0.1; left -= xRange * paddingFactor; right += xRange * paddingFactor; top -= yRange * paddingFactor; bottom += yRange * paddingFactor; Point[] planetPos = new Point[planets.size()]; g.setFont(planetFont); FontMetrics fm = g.getFontMetrics(planetFont); // Determine the best scaling factor for the sizes of the planets. double minSizeFactor = Double.MAX_VALUE; for (int i = 0; i < planets.size(); ++i) { for (int j = i + 1; j < planets.size(); ++j) { Planet a = planets.get(i); Planet b = planets.get(j); double dx = b.X() - a.X(); double dy = b.Y() - a.Y(); double dist = Math.sqrt(dx * dx + dy * dy); double aSize = inherentRadius(a); double bSize = inherentRadius(b); double sizeFactor = dist / (Math.sqrt(a.GrowthRate())); minSizeFactor = Math.min(sizeFactor, minSizeFactor); } } minSizeFactor *= 1.2; // Draw the planets. int i = 0; for (Planet p : planets) { Point pos = getPlanetPos(p, top, left, right, bottom, width, height); planetPos[i++] = pos; int x = pos.x; int y = pos.y; double size = minSizeFactor * inherentRadius(p); int r = (int)Math.min(size / (right - left) * width, size / (bottom - top) * height); g.setColor(GetColor(p.Owner(), colors)); int cx = x - r / 2; int cy = y - r / 2; g.fillOval(cx, cy, r, r); Color c = g.getColor(); for (int step = 1; step >= 0; step--) { g.setColor(g.getColor().brighter()); g.drawOval(x - (r-step)/2, y - (r-step)/2, r-step, r-step); } g.setColor(c); for (int step = 0; step < 3; step++) { g.drawOval(x - (r+step)/2, y - (r+step)/2, r+step, r+step); g.setColor(g.getColor().darker()); } java.awt.geom.Rectangle2D bounds = fm.getStringBounds(Integer.toString(p.NumShips()), g); x -= bounds.getWidth()/2; y += fm.getAscent()/2; g.setColor(textColor); g.drawString(Integer.toString(p.NumShips()), x, y); } // Draw fleets g.setFont(fleetFont); fm = g.getFontMetrics(fleetFont); for (Fleet f : fleets) { Point sPos = planetPos[f.SourcePlanet()]; Point dPos = planetPos[f.DestinationPlanet()]; double tripProgress = 1.0 - (double)f.TurnsRemaining() / f.TotalTripLength(); if (tripProgress > 0.99 || tripProgress < 0.01) { continue; } double dx = dPos.x - sPos.x; double dy = dPos.y - sPos.y; double x = sPos.x + dx * tripProgress; double y = sPos.y + dy * tripProgress; java.awt.geom.Rectangle2D textBounds = fm.getStringBounds(Integer.toString(f.NumShips()), g); g.setColor(GetColor(f.Owner(), colors).darker()); g.drawString(Integer.toString(f.NumShips()), (int)(x-textBounds.getWidth()/2), (int)(y+textBounds.getHeight()/2)); } } // Parses a game state from a string. On success, returns 1. On failure, // returns 0. private int ParseGameState(String s) { planets.clear(); fleets.clear(); String[] lines = s.split("\n"); for (int i = 0; i < lines.length; ++i) { String line = lines[i]; int commentBegin = line.indexOf('#'); if (commentBegin >= 0) { line = line.substring(0, commentBegin); } if (line.trim().length() == 0) { continue; } String[] tokens = line.split(" "); if (tokens.length == 0) { continue; } if (tokens[0].equals("P")) { if (tokens.length != 6) { return 0; } double x = Double.parseDouble(tokens[1]); double y = Double.parseDouble(tokens[2]); int owner = Integer.parseInt(tokens[3]); int numShips = Integer.parseInt(tokens[4]); int growthRate = Integer.parseInt(tokens[5]); Planet p = new Planet(owner, numShips, growthRate, x, y); planets.add(p); if (gamePlayback.length() > 0) { gamePlayback += ":"; } gamePlayback += "" + x + "," + y + "," + owner + "," + numShips + "," + growthRate; } else if (tokens[0].equals("F")) { if (tokens.length != 7) { return 0; } int owner = Integer.parseInt(tokens[1]); int numShips = Integer.parseInt(tokens[2]); int source = Integer.parseInt(tokens[3]); int destination = Integer.parseInt(tokens[4]); int totalTripLength = Integer.parseInt(tokens[5]); int turnsRemaining = Integer.parseInt(tokens[6]); Fleet f = new Fleet(owner, numShips, source, destination, totalTripLength, turnsRemaining); fleets.add(f); } else { return 0; } } gamePlayback += "|"; return 1; } // Loads a map from a test file. The text file contains a description of // the starting state of a game. See the project wiki for a description of // the file format. It should be called the Planet Wars Point-in-Time // format. On success, return 1. On failure, returns 0. private int LoadMapFromFile(String mapFilename) { String s = ""; BufferedReader in = null; try { in = new BufferedReader(new FileReader(mapFilename)); int c; while ((c = in.read()) >= 0) { s += (char)c; } } catch (Exception e) { return 0; } finally { try { in.close(); } catch (Exception e) { // Fucked. } } return ParseGameState(s); } // Store all the planets and fleets. OMG we wouldn't wanna lose all the // planets and fleets, would we!? private ArrayList<Planet> planets; private ArrayList<Fleet> fleets; // The filename of the map that this game is being played on. private String mapFilename; // The string of map data to parse. private String mapData; // Stores a mode identifier which determines how to initialize this object. // See the constructor for details. private int initMode; // This is the game playback string. It's a complete description of the // game. It can be read by a visualization program to visualize the game. private String gamePlayback; // The maximum length of the game in turns. After this many turns, the game // will end, with whoever has the most ships as the winner. If there is no // player with the most ships, then the game is a draw. private int maxGameLength; private int numTurns; // This is the name of the file in which to write log messages. private String logFilename; private Game (Game _g) { planets = new ArrayList<Planet>(); for (Planet p : _g.planets) { planets.add((Planet)(p.clone())); } fleets = new ArrayList<Fleet>(); for (Fleet f : _g.fleets) { fleets.add((Fleet)(f.clone())); } if (_g.mapFilename != null) mapFilename = new String(_g.mapFilename); if (_g.mapData != null) mapData = new String(_g.mapData); initMode = _g.initMode; if (_g.gamePlayback != null) gamePlayback = new String(_g.gamePlayback); maxGameLength = _g.maxGameLength; numTurns = _g.numTurns; // Dont need to init the drawing stuff (it does it itself) } public Object clone() { return new Game(this); } }
false
true
public void DoTimeStep() { // Add ships to each non-neutral planet according to its growth rate. for (Planet p : planets) { if (p.Owner() > 0) { p.AddShips(p.GrowthRate()); } } // Advance all fleets by one time step. Collect the ones that are // arriving at their destination planets this turn. Group them by // destination and attacking player using the attackers map. For // example, attackers[3][4] will store how many of player 4's ships // are landing on planet 3 this turn. ArrayList<Fleet> newFleets = new ArrayList<Fleet>(); Map<Integer, Map<Integer, Integer>> attackers = new TreeMap<Integer, Map<Integer, Integer>>(); for (Fleet f : fleets) { f.TimeStep(); if (f.TurnsRemaining() == 0) { int dest = f.DestinationPlanet(); int attacker = f.Owner(); if (!attackers.containsKey(dest)) { attackers.put(dest, new TreeMap<Integer, Integer>()); } if (!attackers.get(dest).containsKey(attacker)) { attackers.get(dest).put(attacker, 0); } int existingAttackers = attackers.get(dest).get(attacker); attackers.get(dest).put(attacker, existingAttackers + f.NumShips()); } else { newFleets.add(f); } } fleets = newFleets; // Resolve the status of each planet which is being attacked. This is // non-trivial, since a planet can be attacked by many different // players at once. for (int i = 0; i < planets.size(); ++i) { if (!attackers.containsKey(i)) { continue; } Planet p = planets.get(i); int defender = p.Owner(); // Add the current owner's "attacking" ships to the defending // forces. if (attackers.get(i).containsKey(defender)) { p.AddShips(attackers.get(i).get(defender)); attackers.get(i).remove(defender); } // Empty the attackers into a vector of fleets and sort them from // weakest to strongest. ArrayList<Fleet> enemyFleets = new ArrayList<Fleet>(); int numEnemyShips = 0; for (Integer j : attackers.get(i).keySet()) { int numAttackers = attackers.get(i).get(j); enemyFleets.add(new Fleet(j, numAttackers)); numEnemyShips += numAttackers; } Collections.sort(enemyFleets); // Starting with the weakest attacker, the attackers take turns // chipping away the defending forces one by one until there are // either no more defenders or no more attackers. int whoseTurn = 0; while (p.NumShips() > 0 && numEnemyShips > 0) { if (enemyFleets.get(whoseTurn).NumShips() > 0) { p.RemoveShips(1); enemyFleets.get(whoseTurn).RemoveShips(1); --numEnemyShips; if (enemyFleets.get(whoseTurn).NumShips() == 0) { enemyFleets.remove(whoseTurn); --whoseTurn; } } ++whoseTurn; if (whoseTurn >= enemyFleets.size()) { whoseTurn = 0; } } // If there are no enemy fleets left, then the defender keeps // control of the planet. If there are any enemy fleets left, then // they battle it out to determine who gets control of the planet. // This is done by cycling through the attackers and subtracting // one ship at a time from each, until there is only one attacker // left. If the last attackers are all eliminated at the same time, // then the planet becomes neutral with zero ships occupying it. if (numEnemyShips > 0) { p.Owner(0); while (true) { for (int j = 0; j < enemyFleets.size(); ++j) { enemyFleets.get(j).RemoveShips(1); if (enemyFleets.get(j).NumShips() <= 0) { enemyFleets.remove(j); --j; } } if (enemyFleets.size() == 0) { break; } if (enemyFleets.size() == 1) { p.Owner(enemyFleets.get(0).Owner()); p.NumShips(enemyFleets.get(0).NumShips()); break; } } } } for (Planet p : planets) { gamePlayback += "" + p.Owner() + "." + p.NumShips() + ","; } for (Fleet f : fleets) { gamePlayback += "" + f.Owner() + "." + f.NumShips() + "." + f.SourcePlanet() + "." + f.DestinationPlanet() + "." + f.TotalTripLength() + "." + f.TurnsRemaining() + ","; } if (gamePlayback.charAt(gamePlayback.length() - 1) == ',') { gamePlayback = gamePlayback.substring(0, gamePlayback.length() - 1); } gamePlayback += ":"; // Check to see if the maximum number of turns has been reached. ++numTurns; }
public void DoTimeStep() { // Add ships to each non-neutral planet according to its growth rate. for (Planet p : planets) { if (p.Owner() > 0) { p.AddShips(p.GrowthRate()); } } // Advance all fleets by one time step. Collect the ones that are // arriving at their destination planets this turn. Group them by // destination and attacking player using the attackers map. For // example, attackers[3][4] will store how many of player 4's ships // are landing on planet 3 this turn. ArrayList<Fleet> newFleets = new ArrayList<Fleet>(); Map<Integer, Map<Integer, Integer>> attackers = new TreeMap<Integer, Map<Integer, Integer>>(); for (Fleet f : fleets) { f.TimeStep(); if (f.TurnsRemaining() == 0) { int dest = f.DestinationPlanet(); int attacker = f.Owner(); if (!attackers.containsKey(dest)) { attackers.put(dest, new TreeMap<Integer, Integer>()); } if (!attackers.get(dest).containsKey(attacker)) { attackers.get(dest).put(attacker, 0); } int existingAttackers = attackers.get(dest).get(attacker); attackers.get(dest).put(attacker, existingAttackers + f.NumShips()); } else { newFleets.add(f); } } fleets = newFleets; // Resolve the status of each planet which is being attacked. This is // non-trivial, since a planet can be attacked by many different // players at once. for (int i = 0; i < planets.size(); ++i) { if (!attackers.containsKey(i)) { continue; } Planet p = planets.get(i); int defender = p.Owner(); // Add the current owner's "attacking" ships to the defending // forces. if (attackers.get(i).containsKey(defender)) { p.AddShips(attackers.get(i).get(defender)); attackers.get(i).remove(defender); } // Empty the attackers into a vector of fleets and sort them from // weakest to strongest. ArrayList<Fleet> enemyFleets = new ArrayList<Fleet>(); int numEnemyShips = 0; for (Integer j : attackers.get(i).keySet()) { int numAttackers = attackers.get(i).get(j); enemyFleets.add(new Fleet(j, numAttackers)); numEnemyShips += numAttackers; } Collections.sort(enemyFleets); // Starting with the weakest attacker, the attackers take turns // chipping away the defending forces one by one until there are // either no more defenders or no more attackers. int whoseTurn = 0; while (p.NumShips() > 0 && numEnemyShips > 0) { if (enemyFleets.get(whoseTurn).NumShips() > 0) { p.RemoveShips(1); enemyFleets.get(whoseTurn).RemoveShips(1); --numEnemyShips; if (enemyFleets.get(whoseTurn).NumShips() == 0) { enemyFleets.remove(whoseTurn); --whoseTurn; } } ++whoseTurn; if (whoseTurn >= enemyFleets.size()) { whoseTurn = 0; } } // If there are no enemy fleets left, then the defender keeps // control of the planet. If there are any enemy fleets left, then // they battle it out to determine who gets control of the planet. // This is done by cycling through the attackers and subtracting // one ship at a time from each, until there is only one attacker // left. If the last attackers are all eliminated at the same time, // then the planet becomes neutral with zero ships occupying it. if (numEnemyShips > 0) { p.Owner(0); while (enemyFleets.size() > 1) { for (int j = 0; j < enemyFleets.size(); ++j) { enemyFleets.get(j).RemoveShips(1); if (enemyFleets.get(j).NumShips() <= 0) { enemyFleets.remove(j); --j; } } } if (enemyFleets.size() == 1) { p.Owner(enemyFleets.get(0).Owner()); p.NumShips(enemyFleets.get(0).NumShips()); break; } } } for (Planet p : planets) { gamePlayback += "" + p.Owner() + "." + p.NumShips() + ","; } for (Fleet f : fleets) { gamePlayback += "" + f.Owner() + "." + f.NumShips() + "." + f.SourcePlanet() + "." + f.DestinationPlanet() + "." + f.TotalTripLength() + "." + f.TurnsRemaining() + ","; } if (gamePlayback.charAt(gamePlayback.length() - 1) == ',') { gamePlayback = gamePlayback.substring(0, gamePlayback.length() - 1); } gamePlayback += ":"; // Check to see if the maximum number of turns has been reached. ++numTurns; }
diff --git a/src/com/gitblit/utils/ActivityUtils.java b/src/com/gitblit/utils/ActivityUtils.java index 204fe3c..d6afd93 100644 --- a/src/com/gitblit/utils/ActivityUtils.java +++ b/src/com/gitblit/utils/ActivityUtils.java @@ -1,196 +1,196 @@ /* * Copyright 2011 gitblit.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gitblit.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import com.gitblit.GitBlit; import com.gitblit.models.Activity; import com.gitblit.models.Activity.RepositoryCommit; import com.gitblit.models.GravatarProfile; import com.gitblit.models.RefModel; import com.gitblit.models.RepositoryModel; import com.google.gson.reflect.TypeToken; /** * Utility class for building activity information from repositories. * * @author James Moger * */ public class ActivityUtils { /** * Gets the recent activity from the repositories for the last daysBack days * on the specified branch. * * @param models * the list of repositories to query * @param daysBack * the number of days back from Now to collect * @param objectId * the branch to retrieve. If this value is null the default * branch of the repository is used. * @return */ public static List<Activity> getRecentActivity(List<RepositoryModel> models, int daysBack, String objectId) { // Activity panel shows last daysBack of activity across all // repositories. Date thresholdDate = new Date(System.currentTimeMillis() - daysBack * TimeUtils.ONEDAY); // Build a map of DailyActivity from the available repositories for the // specified threshold date. DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); Map<String, Activity> activity = new HashMap<String, Activity>(); for (RepositoryModel model : models) { if (model.hasCommits && model.lastChange.after(thresholdDate)) { Repository repository = GitBlit.self().getRepository(model.name); List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, thresholdDate); Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository); repository.close(); // determine commit branch String branch = objectId; - if (StringUtils.isEmpty(branch)) { + if (StringUtils.isEmpty(branch) && !commits.isEmpty()) { List<RefModel> headRefs = allRefs.get(commits.get(0).getId()); List<String> localBranches = new ArrayList<String>(); for (RefModel ref : headRefs) { if (ref.getName().startsWith(Constants.R_HEADS)) { localBranches.add(ref.getName().substring(Constants.R_HEADS.length())); } } // determine branch if (localBranches.size() == 1) { // only one branch, choose it branch = localBranches.get(0); } else if (localBranches.size() > 1) { if (localBranches.contains("master")) { // choose master branch = "master"; } else { // choose first branch branch = localBranches.get(0); } } } for (RevCommit commit : commits) { Date date = JGitUtils.getCommitDate(commit); String dateStr = df.format(date); if (!activity.containsKey(dateStr)) { // Normalize the date to midnight cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); activity.put(dateStr, new Activity(cal.getTime())); } RepositoryCommit commitModel = activity.get(dateStr).addCommit(model.name, branch, commit); commitModel.setRefs(allRefs.get(commit.getId())); } } } List<Activity> recentActivity = new ArrayList<Activity>(activity.values()); for (Activity daily : recentActivity) { Collections.sort(daily.commits); } return recentActivity; } /** * Returns the Gravatar profile, if available, for the specified email * address. * * @param emailaddress * @return a Gravatar Profile * @throws IOException */ public static GravatarProfile getGravatarProfileFromAddress(String emailaddress) throws IOException { return getGravatarProfile(StringUtils.getMD5(emailaddress.toLowerCase())); } /** * Creates a Gravatar thumbnail url from the specified email address. * * @param email * address to query Gravatar * @param width * size of thumbnail. if width <= 0, the defalt of 60 is used. * @return */ public static String getGravatarThumbnailUrl(String email, int width) { if (width <= 0) { width = 60; } String emailHash = StringUtils.getMD5(email); String url = MessageFormat.format( "http://www.gravatar.com/avatar/{0}?s={1,number,0}&d=identicon", emailHash, width); return url; } /** * Returns the Gravatar profile, if available, for the specified hashcode. * address. * * @param hash * the hash of the email address * @return a Gravatar Profile * @throws IOException */ public static GravatarProfile getGravatarProfile(String hash) throws IOException { String url = MessageFormat.format("http://www.gravatar.com/{0}.json", hash); // Gravatar has a complex json structure Type profileType = new TypeToken<Map<String, List<GravatarProfile>>>() { }.getType(); Map<String, List<GravatarProfile>> profiles = null; try { profiles = JsonUtils.retrieveJson(url, profileType); } catch (FileNotFoundException e) { } if (profiles == null || profiles.size() == 0) { return null; } // due to the complex json structure we need to pull out the profile // from a list 2 levels deep GravatarProfile profile = profiles.values().iterator().next().get(0); return profile; } }
true
true
public static List<Activity> getRecentActivity(List<RepositoryModel> models, int daysBack, String objectId) { // Activity panel shows last daysBack of activity across all // repositories. Date thresholdDate = new Date(System.currentTimeMillis() - daysBack * TimeUtils.ONEDAY); // Build a map of DailyActivity from the available repositories for the // specified threshold date. DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); Map<String, Activity> activity = new HashMap<String, Activity>(); for (RepositoryModel model : models) { if (model.hasCommits && model.lastChange.after(thresholdDate)) { Repository repository = GitBlit.self().getRepository(model.name); List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, thresholdDate); Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository); repository.close(); // determine commit branch String branch = objectId; if (StringUtils.isEmpty(branch)) { List<RefModel> headRefs = allRefs.get(commits.get(0).getId()); List<String> localBranches = new ArrayList<String>(); for (RefModel ref : headRefs) { if (ref.getName().startsWith(Constants.R_HEADS)) { localBranches.add(ref.getName().substring(Constants.R_HEADS.length())); } } // determine branch if (localBranches.size() == 1) { // only one branch, choose it branch = localBranches.get(0); } else if (localBranches.size() > 1) { if (localBranches.contains("master")) { // choose master branch = "master"; } else { // choose first branch branch = localBranches.get(0); } } } for (RevCommit commit : commits) { Date date = JGitUtils.getCommitDate(commit); String dateStr = df.format(date); if (!activity.containsKey(dateStr)) { // Normalize the date to midnight cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); activity.put(dateStr, new Activity(cal.getTime())); } RepositoryCommit commitModel = activity.get(dateStr).addCommit(model.name, branch, commit); commitModel.setRefs(allRefs.get(commit.getId())); } } } List<Activity> recentActivity = new ArrayList<Activity>(activity.values()); for (Activity daily : recentActivity) { Collections.sort(daily.commits); } return recentActivity; }
public static List<Activity> getRecentActivity(List<RepositoryModel> models, int daysBack, String objectId) { // Activity panel shows last daysBack of activity across all // repositories. Date thresholdDate = new Date(System.currentTimeMillis() - daysBack * TimeUtils.ONEDAY); // Build a map of DailyActivity from the available repositories for the // specified threshold date. DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); Map<String, Activity> activity = new HashMap<String, Activity>(); for (RepositoryModel model : models) { if (model.hasCommits && model.lastChange.after(thresholdDate)) { Repository repository = GitBlit.self().getRepository(model.name); List<RevCommit> commits = JGitUtils.getRevLog(repository, objectId, thresholdDate); Map<ObjectId, List<RefModel>> allRefs = JGitUtils.getAllRefs(repository); repository.close(); // determine commit branch String branch = objectId; if (StringUtils.isEmpty(branch) && !commits.isEmpty()) { List<RefModel> headRefs = allRefs.get(commits.get(0).getId()); List<String> localBranches = new ArrayList<String>(); for (RefModel ref : headRefs) { if (ref.getName().startsWith(Constants.R_HEADS)) { localBranches.add(ref.getName().substring(Constants.R_HEADS.length())); } } // determine branch if (localBranches.size() == 1) { // only one branch, choose it branch = localBranches.get(0); } else if (localBranches.size() > 1) { if (localBranches.contains("master")) { // choose master branch = "master"; } else { // choose first branch branch = localBranches.get(0); } } } for (RevCommit commit : commits) { Date date = JGitUtils.getCommitDate(commit); String dateStr = df.format(date); if (!activity.containsKey(dateStr)) { // Normalize the date to midnight cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); activity.put(dateStr, new Activity(cal.getTime())); } RepositoryCommit commitModel = activity.get(dateStr).addCommit(model.name, branch, commit); commitModel.setRefs(allRefs.get(commit.getId())); } } } List<Activity> recentActivity = new ArrayList<Activity>(activity.values()); for (Activity daily : recentActivity) { Collections.sort(daily.commits); } return recentActivity; }
diff --git a/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java b/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java index e4c7b3ade..6170193bc 100644 --- a/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java +++ b/lttng/org.eclipse.linuxtools.lttng.core/src/org/eclipse/linuxtools/internal/lttng/core/trace/LTTngTrace.java @@ -1,1005 +1,1005 @@ /******************************************************************************* * Copyright (c) 2009, 2011 Ericsson, MontaVista Software * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * William Bourque ([email protected]) - Initial API and implementation * Yufen Kuo ([email protected]) - add support to allow user specify trace library path *******************************************************************************/ package org.eclipse.linuxtools.internal.lttng.core.trace; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.linuxtools.internal.lttng.core.TraceHelper; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEventContent; import org.eclipse.linuxtools.internal.lttng.core.event.LttngEventType; import org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation; import org.eclipse.linuxtools.internal.lttng.core.event.LttngTimestamp; import org.eclipse.linuxtools.internal.lttng.core.exceptions.LttngException; import org.eclipse.linuxtools.internal.lttng.core.tracecontrol.utility.LiveTraceManager; import org.eclipse.linuxtools.internal.lttng.jni.common.JniTime; import org.eclipse.linuxtools.lttng.jni.JniEvent; import org.eclipse.linuxtools.lttng.jni.JniMarker; import org.eclipse.linuxtools.lttng.jni.JniTrace; import org.eclipse.linuxtools.lttng.jni.JniTracefile; import org.eclipse.linuxtools.lttng.jni.factory.JniTraceFactory; import org.eclipse.linuxtools.tmf.core.event.ITmfEvent; import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp; import org.eclipse.linuxtools.tmf.core.event.TmfEvent; import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange; import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp; import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException; import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest.ExecutionType; import org.eclipse.linuxtools.tmf.core.request.TmfEventRequest; import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal; import org.eclipse.linuxtools.tmf.core.trace.ITmfContext; import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser; import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation; import org.eclipse.linuxtools.tmf.core.trace.TmfCheckpointIndexer; import org.eclipse.linuxtools.tmf.core.trace.TmfContext; import org.eclipse.linuxtools.tmf.core.trace.TmfExperiment; import org.eclipse.linuxtools.tmf.core.trace.TmfTrace; class LTTngTraceException extends LttngException { static final long serialVersionUID = -1636648737081868146L; public LTTngTraceException(final String errMsg) { super(errMsg); } } /** * <b><u>LTTngTrace</u></b> * <p> * * LTTng trace implementation. It accesses the C trace handling library * (seeking, reading and parsing) through the JNI component. */ public class LTTngTrace extends TmfTrace implements ITmfEventParser { public final static boolean PRINT_DEBUG = false; public final static boolean UNIQUE_EVENT = true; private final static boolean SHOW_LTT_DEBUG_DEFAULT = false; private final static boolean IS_PARSING_NEEDED_DEFAULT = !UNIQUE_EVENT; private final static int CHECKPOINT_PAGE_SIZE = 50000; private final static long LTTNG_STREAMING_INTERVAL = 2000; // in ms // Reference to our JNI trace private JniTrace currentJniTrace; LttngTimestamp eventTimestamp; String eventSource; LttngEventContent eventContent; String eventReference; // The actual event LttngEvent currentLttngEvent; // The current location LttngLocation previousLocation; LttngEventType eventType; // Hashmap of the possible types of events (Tracefile/CPU/Marker in the JNI) HashMap<Integer, LttngEventType> traceTypes; // This vector will be used to quickly find a marker name from a position Vector<Integer> traceTypeNames; private String traceLibPath; public LTTngTrace() { } @Override public boolean validate(final IProject project, final String path) { if (fileExists(path)) { final String traceLibPath = TraceHelper.getTraceLibDirFromProject(project); try { final LTTngTraceVersion version = new LTTngTraceVersion(path, traceLibPath); return version.isValidLttngTrace(); } catch (final LttngException e) { } } return false; } @Override public synchronized void initTrace(final IResource resource, final String path, final Class<? extends ITmfEvent> eventType) throws TmfTraceException { super.initialize(resource, path, eventType); setIndexer(new TmfCheckpointIndexer(this, getCacheSize())); initialize(resource, path, eventType); } @Override protected synchronized void initialize(final IResource resource, final String path, final Class<? extends ITmfEvent> eventType) throws TmfTraceException { try { if (resource != null) { IProject project = resource.getProject(); traceLibPath = (project != null) ? TraceHelper.getTraceLibDirFromProject(project) : null; } currentJniTrace = JniTraceFactory.getJniTrace(path, traceLibPath, SHOW_LTT_DEBUG_DEFAULT); } catch (final Exception e) { throw new TmfTraceException(e.getMessage()); } // Export all the event types from the JNI side traceTypes = new HashMap<Integer, LttngEventType>(); traceTypeNames = new Vector<Integer>(); initialiseEventTypes(currentJniTrace); // Build the re-used event structure eventTimestamp = new LttngTimestamp(); eventSource = ""; //$NON-NLS-1$ this.eventType = new LttngEventType(); eventContent = new LttngEventContent(currentLttngEvent); eventReference = getName(); // Create the skeleton event currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, this.eventType, eventContent, eventReference, null); // Create a new current location previousLocation = new LttngLocation(); // Set the currentEvent to the eventContent eventContent.setEvent(currentLttngEvent); setParser(this); setCacheSize(CHECKPOINT_PAGE_SIZE); initializeStreamingMonitor(); } private void initializeStreamingMonitor() { final JniTrace jniTrace = getCurrentJniTrace(); if (jniTrace == null || (!jniTrace.isLiveTraceSupported() || !LiveTraceManager.isLiveTrace(jniTrace.getTracepath()))) { // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); final LttngTimestamp startTime = new LttngTimestamp(event.getTimestamp()); final LttngTimestamp endTime = new LttngTimestamp(currentJniTrace.getEndTime().getTime()); setTimeRange(new TmfTimeRange(startTime, endTime)); final TmfTraceUpdatedSignal signal = new TmfTraceUpdatedSignal(this, this, getTimeRange()); broadcast(signal); return; } // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); setEndTime(TmfTimestamp.BIG_BANG); final long startTime = event != null ? event.getTimestamp().getValue() : TmfTimestamp.BIG_BANG.getValue(); setStreamingInterval(LTTNG_STREAMING_INTERVAL); final Thread thread = new Thread("Streaming Monitor for trace " + getName()) { //$NON-NLS-1$ LttngTimestamp safeTimestamp = null; TmfTimeRange timeRange = null; @SuppressWarnings({ "unchecked", "restriction" }) @Override public void run() { - while (!fExecutor.isShutdown()) { + while (!executorIsShutdown()) { final TmfExperiment experiment = TmfExperiment.getCurrentExperiment(); if (experiment != null) { @SuppressWarnings("rawtypes") final TmfEventRequest request = new TmfEventRequest(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ExecutionType.FOREGROUND) { @Override public void handleCompleted() { updateJniTrace(); } }; experiment.sendRequest(request); try { request.waitForCompletion(); } catch (final InterruptedException e) { } } else updateJniTrace(); try { Thread.sleep(LTTNG_STREAMING_INTERVAL); } catch (final InterruptedException e) { } } } private void updateJniTrace() { final JniTrace jniTrace = getCurrentJniTrace(); currentJniTrace.updateTrace(); final long endTime = jniTrace.getEndTime().getTime(); final LttngTimestamp startTimestamp = new LttngTimestamp(startTime); final LttngTimestamp endTimestamp = new LttngTimestamp(endTime); if (safeTimestamp != null && safeTimestamp.compareTo(getTimeRange().getEndTime(), false) > 0) timeRange = new TmfTimeRange(startTimestamp, safeTimestamp); else timeRange = null; safeTimestamp = endTimestamp; if (timeRange != null) setTimeRange(timeRange); } }; thread.start(); } /** * Default Constructor. * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) */ public LTTngTrace(final IResource resource, final String path) throws Exception { // Call with "wait for completion" true and "skip indexing" false this(resource, path, null, true, false); } /** * Constructor, with control over the indexing. * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * @param waitForCompletion Should we wait for indexign to complete before * moving on. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) */ public LTTngTrace(final IResource resource, final String path, final boolean waitForCompletion) throws Exception { // Call with "skip indexing" false this(resource, path, null, waitForCompletion, true); } /** * Default constructor, with control over the indexing and possibility to * bypass indexation * <p> * * @param name Name of the trace * @param path Path to a <b>directory</b> that contain an LTTng trace. * @param traceLibPath Path to a <b>directory</b> that contains LTTng trace * libraries. * @param waitForCompletion Should we wait for indexign to complete before * moving on. * @param bypassIndexing Should we bypass indexing completly? This is should * only be useful for unit testing. * * @exception Exception (most likely LTTngTraceException or * FileNotFoundException) * */ public LTTngTrace(final IResource resource, final String path, final String traceLibPath, final boolean waitForCompletion, final boolean bypassIndexing) throws Exception { // super(resource, LttngEvent.class, path, CHECKPOINT_PAGE_SIZE, false); super(resource, LttngEvent.class, path, CHECKPOINT_PAGE_SIZE); initialize(resource, path, LttngEvent.class); // if (!bypassIndexing) // indexTrace(false); this.traceLibPath = traceLibPath; } /* * Copy constructor is forbidden for LttngEvenmStream */ public LTTngTrace(final LTTngTrace other) throws Exception { this(other.getResource(), other.getPath(), other.getTraceLibPath(), false, true); setTimeRange(new TmfTimeRange(new LttngTimestamp(other.getStartTime()), new LttngTimestamp(other.getEndTime()))); } public String getTraceLibPath() { return traceLibPath; } /* * Fill out the HashMap with "Type" (Tracefile/Marker) * * This should be called at construction once the trace is open */ private void initialiseEventTypes(final JniTrace trace) { // Work variables LttngEventType tmpType = null; String[] markerFieldsLabels = null; String newTracefileKey = null; Integer newMarkerKey = null; JniTracefile newTracefile = null; JniMarker newMarker = null; // First, obtain an iterator on TRACEFILES of owned by the TRACE final Iterator<String> tracefileItr = trace.getTracefilesMap().keySet().iterator(); while (tracefileItr.hasNext()) { newTracefileKey = tracefileItr.next(); newTracefile = trace.getTracefilesMap().get(newTracefileKey); // From the TRACEFILE read, obtain its MARKER final Iterator<Integer> markerItr = newTracefile.getTracefileMarkersMap().keySet().iterator(); while (markerItr.hasNext()) { newMarkerKey = markerItr.next(); newMarker = newTracefile.getTracefileMarkersMap().get(newMarkerKey); // From the MARKER we can obtain the MARKERFIELDS keys (i.e. // labels) markerFieldsLabels = newMarker.getMarkerFieldsHashMap().keySet() .toArray(new String[newMarker.getMarkerFieldsHashMap().size()]); tmpType = new LttngEventType(newTracefile.getTracefileName(), newTracefile.getCpuNumber(), newMarker.getName(), newMarkerKey.intValue(), markerFieldsLabels); // Add the type to the map/vector addEventTypeToMap(tmpType); } } } /* * Add a new type to the HashMap * * As the hashmap use a key format that is a bit dangerous to use, we should * always add using this function. */ private void addEventTypeToMap(final LttngEventType newEventType) { final int newTypeKey = EventTypeKey.getEventTypeHash(newEventType); this.traceTypes.put(newTypeKey, newEventType); this.traceTypeNames.add(newTypeKey); } /** * Return the latest saved location. Note : Modifying the returned location * may result in buggy positionning! * * @return The LttngLocation as it was after the last operation. * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation */ @Override public synchronized ITmfLocation<?> getCurrentLocation() { return previousLocation; } /** * Position the trace to the event at the given location. * <p> * NOTE : Seeking by location is very fast compare to seeking by position * but is still slower than "ReadNext", avoid using it for small interval. * * @param location Location of the event in the trace. If no event available * at this exact location, we will position ourself to the next * one. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized ITmfContext seekEvent(final ITmfLocation<?> location) { if (PRINT_DEBUG) System.out.println("seekLocation(location) location -> " + location); //$NON-NLS-1$ // If the location in context is null, create a new one if (location == null) { LttngLocation curLocation = new LttngLocation(); final ITmfContext context = seekEvent(curLocation.getOperationTime()); context.setRank(0); return context; } // The only seek valid in LTTng is with the time, we call // seekEvent(timestamp) LttngLocation curLocation = (LttngLocation) location; final ITmfContext context = seekEvent(curLocation.getOperationTime()); // If the location is marked with the read next flag // then it is pointing to the next event following the operation time if (curLocation.isLastOperationReadNext()) getNext(context); return context; } /** * Position the trace to the event at the given time. * <p> * NOTE : Seeking by time is very fast compare to seeking by position but is * still slower than "ReadNext", avoid using it for small interval. * * @param timestamp Time of the event in the trace. If no event available at * this exact time, we will position ourself to the next one. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized TmfContext seekEvent(final ITmfTimestamp timestamp) { if (PRINT_DEBUG) System.out.println("seekEvent(timestamp) timestamp -> " + timestamp); //$NON-NLS-1$ // Call JNI to seek currentJniTrace.seekToTime(new JniTime(timestamp.getValue())); // Save the time at which we seeked previousLocation.setOperationTime(timestamp.getValue()); // Set the operation marker as seek, to be able to detect we did "seek" // this event previousLocation.setLastOperationSeek(); final LttngLocation curLocation = new LttngLocation(previousLocation); return new TmfContext(curLocation); } /** * Position the trace to the event at the given position (rank). * <p> * NOTE : Seeking by position is very slow in LTTng, consider seeking by * timestamp. * * @param rank Position (or rank) of the event in the trace, starting at 0. * * @return The TmfContext that point to this event * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized TmfContext seekEvent(final long rank) { if (PRINT_DEBUG) System.out.println("seekEvent(rank) rank -> " + rank); //$NON-NLS-1$ // Position the trace at the checkpoint final ITmfContext checkpointContext = getIndexer().seekIndex(rank); LttngLocation location = (LttngLocation) checkpointContext.getLocation(); ITmfTimestamp timestamp = location.getLocation(); long index = rank / getCacheSize(); // Seek to the found time final TmfContext tmpContext = seekEvent(timestamp); tmpContext.setRank((index + 1) * getCacheSize()); previousLocation = (LttngLocation) tmpContext.getLocation(); // Ajust the index of the event we found at this check point position Long currentPosition = index * getCacheSize(); Long lastTimeValueRead = 0L; // Get the event at current position. This won't move to the next one JniEvent tmpJniEvent = currentJniTrace.findNextEvent(); // Now that we are positionned at the checkpoint, // we need to "readNext" (Position - CheckpointPosition) times or until // trace "run out" while ((tmpJniEvent != null) && (currentPosition < rank)) { tmpJniEvent = currentJniTrace.readNextEvent(); currentPosition++; } // If we found our event, save its timestamp if (tmpJniEvent != null) lastTimeValueRead = tmpJniEvent.getEventTime().getTime(); // Set the operation marker as seek, to be able to detect we did "seek" // this event previousLocation.setLastOperationSeek(); // Save read event time previousLocation.setOperationTime(lastTimeValueRead); // *** VERIFY *** // Is that too paranoid? // // We don't trust what upper level could do with our internal location // so we create a new one to return instead final LttngLocation curLocation = new LttngLocation(previousLocation); return new TmfContext(curLocation, rank); } @Override public TmfContext seekEvent(final double ratio) { // TODO Auto-generated method stub return null; } @Override public double getLocationRatio(final ITmfLocation<?> location) { // TODO Auto-generated method stub return 0; } /** * Return the event in the trace according to the given context. Read it if * necessary. * <p> * Similar (same?) as ParseEvent except that calling GetNext twice read the * next one the second time. * * @param context Current TmfContext where to get the event * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ public int nbEventsRead = 0; @Override public synchronized LttngEvent getNext(final ITmfContext context) { if (PRINT_DEBUG) System.out.println("getNextEvent(context) context.getLocation() -> " //$NON-NLS-1$ + context.getLocation()); LttngEvent returnedEvent = null; LttngLocation curLocation = null; curLocation = (LttngLocation) context.getLocation(); // If the location in context is null, create a new one if (curLocation == null) curLocation = getCurrentLocation(context); // *** Positioning trick : // GetNextEvent only read the trace if : // 1- The last operation was NOT a ParseEvent --> A read is required // OR // 2- The time of the previous location is different from the current // one --> A seek + a read is required if ((!(curLocation.isLastOperationParse())) || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) { if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) { if (PRINT_DEBUG) System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$ + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$ + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$ seekEvent(curLocation.getOperationTime()); // If the location is marked with the read next flag // then it is pointing to the next event following the operation time if (curLocation.isLastOperationReadNext()) { readNextEvent(curLocation); } } // Read the next event from the trace. The last one will NO LONGER // BE VALID. returnedEvent = readNextEvent(curLocation); } else { // No event was read, just return the one currently loaded (the last // one we read) returnedEvent = currentLttngEvent; // Set the operation marker as read to both locations, to be able to // detect we need to read the next event previousLocation.setLastOperationReadNext(); curLocation.setLastOperationReadNext(); } // If we read an event, set it's time to the locations (both previous // and current) if (returnedEvent != null) setPreviousAndCurrentTimes(context, returnedEvent, curLocation); return returnedEvent; } // this method was extracted for profiling purposes private synchronized void setPreviousAndCurrentTimes(final ITmfContext context, final LttngEvent returnedEvent, final LttngLocation curLocation) { final ITmfTimestamp eventTimestamp = returnedEvent.getTimestamp(); // long eventTime = eventTimestamp.getValue(); previousLocation.setOperationTime(eventTimestamp.getValue()); curLocation.setOperationTime(eventTimestamp.getValue()); updateAttributes(context, eventTimestamp); context.increaseRank(); } // this method was extracted for profiling purposes private synchronized LttngEvent readNextEvent(final LttngLocation curLocation) { LttngEvent returnedEvent; // Read the next event from the trace. The last one will NO LONGER BE // VALID. returnedEvent = readEvent(curLocation); nbEventsRead++; // Set the operation marker as read to both locations, to be able to // detect we need to read the next event previousLocation.setLastOperationReadNext(); curLocation.setLastOperationReadNext(); return returnedEvent; } // this method was extracted for profiling purposes private LttngLocation getCurrentLocation(final ITmfContext context) { LttngLocation curLocation; curLocation = new LttngLocation(); context.setLocation(curLocation); return curLocation; } /** * Return the event in the trace according to the given context. Read it if * necessary. * <p> * Similar (same?) as GetNextEvent except that calling ParseEvent twice will * return the same event * * @param context Current TmfContext where to get the event * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngLocation * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext */ @Override public synchronized LttngEvent parseEvent(final ITmfContext context) { if (PRINT_DEBUG) System.out.println("parseEvent(context) context.getLocation() -> " //$NON-NLS-1$ + context.getLocation()); LttngEvent returnedEvent = null; LttngLocation curLocation = null; // If the location in context is null, create a new one if (context.getLocation() == null) { curLocation = new LttngLocation(); context.setLocation(curLocation); } else curLocation = (LttngLocation) context.getLocation(); // *** HACK *** // TMF assumes it is possible to read (GetNextEvent) to the next Event // once ParseEvent() is called // In LTTNG, there is not difference between "Parsing" and "Reading" an // event. // So, before "Parsing" an event, we have to make sure we didn't "Read" // it alreafy. // Also, "Reading" invalidate the previous Event in LTTNG and seek back // is very costly, // so calling twice "Parse" will return the same event, giving a way to // get the "Currently loaded" event // *** Positionning trick : // ParseEvent only read the trace if : // 1- The last operation was NOT a ParseEvent --> A read is required // OR // 2- The time of the previous location is different from the current // one --> A seek + a read is required if (!curLocation.isLastOperationParse() || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) { // Previous time != Current time : We need to reposition to the // current time if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) { if (PRINT_DEBUG) System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$ + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$ + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$ seekEvent(curLocation.getOperationTime()); } // Read the next event from the trace. The last one will NO LONGER // BE VALID. returnedEvent = readEvent(curLocation); } else // No event was read, just return the one currently loaded (the last // one we read) returnedEvent = currentLttngEvent; // If we read an event, set it's time to the locations (both previous // and current) if (returnedEvent != null) { previousLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); curLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); } // Set the operation marker as parse to both location, to be able to // detect we already "read" this event previousLocation.setLastOperationParse(); curLocation.setLastOperationParse(); return returnedEvent; } /* * Read the next event from the JNI and convert it as Lttng Event<p> * * @param location Current LttngLocation that to be updated with the event * timestamp * * @return The LttngEvent we read of null if no event are available * * @see org.eclipse.linuxtools.lttng.event.LttngLocation * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace */ private synchronized LttngEvent readEvent(final LttngLocation location) { LttngEvent returnedEvent = null; JniEvent tmpEvent = null; // Read the next event from JNI. THIS WILL INVALIDATE THE CURRENT LTTNG // EVENT. tmpEvent = currentJniTrace.readNextEvent(); if (tmpEvent != null) { // *** NOTE // Convert will update the currentLttngEvent returnedEvent = convertJniEventToTmf(tmpEvent); location.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp()); } else location.setOperationTime(getEndTime().getValue() + 1); return returnedEvent; } /** * Method to convert a JniEvent into a LttngEvent. * <p> * * Note : This method will call LttngEvent convertEventJniToTmf(JniEvent, * boolean) with a default value for isParsingNeeded * * @param newEvent The JniEvent to convert into LttngEvent * * @return The converted LttngEvent * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent convertJniEventToTmf(final JniEvent newEvent) { currentLttngEvent = convertJniEventToTmf(newEvent, IS_PARSING_NEEDED_DEFAULT); return currentLttngEvent; } /** * Method to convert a JniEvent into a LttngEvent * * @param jniEvent The JniEvent to convert into LttngEvent * @param isParsingNeeded A boolean value telling if the event should be * parsed or not. * * @return The converted LttngEvent * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent convertJniEventToTmf(final JniEvent jniEvent, final boolean isParsingNeeded) { if (UNIQUE_EVENT) { // *** // UNHACKED : We can no longer do that because TCF need to maintain // several events at once. // This is very slow to do so in LTTng, this has to be temporary. // *** HACK *** // To save time here, we only set value instead of allocating new // object // This give an HUGE performance improvement // all allocation done in the LttngTrace constructor // *** eventTimestamp.setValue(jniEvent.getEventTime().getTime()); eventSource = jniEvent.requestEventSource(); eventType = traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent)); final String fullTracePath = getName(); final String reference = fullTracePath.substring(fullTracePath.lastIndexOf('/') + 1); currentLttngEvent.setReference(reference); eventContent.emptyContent(); currentLttngEvent.setType(eventType); // Save the jni reference currentLttngEvent.updateJniEventReference(jniEvent); // Parse now if was asked // Warning : THIS IS SLOW if (isParsingNeeded) eventContent.getFields(); return currentLttngEvent; } else return convertJniEventToTmfMultipleEventEvilFix(jniEvent, isParsingNeeded); } /** * This method is a temporary fix to support multiple events at once in TMF * This is expected to be slow and should be fixed in another way. See * comment in convertJniEventToTmf(); * * @param jniEvent The current JNI Event * @return Current Lttng Event fully parsed */ private synchronized LttngEvent convertJniEventToTmfMultipleEventEvilFix(final JniEvent jniEvent, final boolean isParsingNeeded) { // *** HACK *** // Below : the "fix" with all the new and the full-parse // Allocating new memory is slow. // Parsing every events is very slow. eventTimestamp = new LttngTimestamp(jniEvent.getEventTime().getTime()); eventSource = jniEvent.requestEventSource(); eventReference = getName(); eventType = new LttngEventType(traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent))); eventContent = new LttngEventContent(currentLttngEvent); currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, eventType, eventContent, eventReference, null); // The jni reference is no longer reliable but we will keep it anyhow currentLttngEvent.updateJniEventReference(jniEvent); // Ensure that the content is correctly set eventContent.setEvent(currentLttngEvent); // Parse the event if it was needed // *** WARNING *** // ONLY for testing, NOT parsing events with non-unique events WILL // result in segfault in the JVM if (isParsingNeeded) eventContent.getFields(); return currentLttngEvent; } /** * Reference to the current LttngTrace we are reading from. * <p> * * Note : This bypass the framework and should not be use, except for * testing! * * @return Reference to the current LttngTrace * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace */ public JniTrace getCurrentJniTrace() { return currentJniTrace; } /** * Return a reference to the current LttngEvent we have in memory. * * @return The current (last read) LttngEvent * * @see org.eclipse.linuxtools.internal.lttng.core.event.LttngEvent */ public synchronized LttngEvent getCurrentEvent() { return currentLttngEvent; } /** * Get the major version number for the current trace * * @return Version major or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public short getVersionMajor() { if (currentJniTrace != null) return currentJniTrace.getLttMajorVersion(); else return -1; } /** * Get the minor version number for the current trace * * @return Version minor or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public short getVersionMinor() { if (currentJniTrace != null) return currentJniTrace.getLttMinorVersion(); else return -1; } /** * Get the number of CPU for this trace * * @return Number of CPU or -1 if unknown * * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace * */ public int getCpuNumber() { if (currentJniTrace != null) return currentJniTrace.getCpuNumber(); else return -1; } @Override public synchronized void dispose() { if (currentJniTrace != null) currentJniTrace.closeTrace(); super.dispose(); } /** * Return a String identifying this trace. * * @return String that identify this trace */ @Override @SuppressWarnings("nls") public String toString() { String returnedData = ""; returnedData += "Path :" + getPath() + " "; returnedData += "Trace:" + currentJniTrace + " "; returnedData += "Event:" + currentLttngEvent; return returnedData; } } /* * EventTypeKey inner class * * This class is used to make the process of generating the HashMap key more * transparent and so less error prone to use */ final class EventTypeKey { // *** WARNING *** // These two getEventTypeKey() functions should ALWAYS construct the key the // same ways! // Otherwise, every type search will fail! // added final to encourage inlining. // generating a hash code by hand to avoid a string creation final static public int getEventTypeHash(final LttngEventType newEventType) { return generateHash(newEventType.getTracefileName(), newEventType.getCpuId(), newEventType.getMarkerName()); } final private static int generateHash(final String traceFileName, final long cpuNumber, final String markerName) { // 0x1337 is a prime number. The number of CPUs is always under 8192 on // the current kernel, so this will work with the current linux kernel. final int cpuHash = (int) (cpuNumber * (0x1337)); return traceFileName.hashCode() ^ (cpuHash) ^ markerName.hashCode(); } // generating a hash code by hand to avoid a string creation final static public int getEventTypeHash(final JniEvent newEvent) { return generateHash(newEvent.getParentTracefile().getTracefileName(), newEvent.getParentTracefile() .getCpuNumber(), newEvent.requestEventMarker().getName()); } }
true
true
private void initializeStreamingMonitor() { final JniTrace jniTrace = getCurrentJniTrace(); if (jniTrace == null || (!jniTrace.isLiveTraceSupported() || !LiveTraceManager.isLiveTrace(jniTrace.getTracepath()))) { // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); final LttngTimestamp startTime = new LttngTimestamp(event.getTimestamp()); final LttngTimestamp endTime = new LttngTimestamp(currentJniTrace.getEndTime().getTime()); setTimeRange(new TmfTimeRange(startTime, endTime)); final TmfTraceUpdatedSignal signal = new TmfTraceUpdatedSignal(this, this, getTimeRange()); broadcast(signal); return; } // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); setEndTime(TmfTimestamp.BIG_BANG); final long startTime = event != null ? event.getTimestamp().getValue() : TmfTimestamp.BIG_BANG.getValue(); setStreamingInterval(LTTNG_STREAMING_INTERVAL); final Thread thread = new Thread("Streaming Monitor for trace " + getName()) { //$NON-NLS-1$ LttngTimestamp safeTimestamp = null; TmfTimeRange timeRange = null; @SuppressWarnings({ "unchecked", "restriction" }) @Override public void run() { while (!fExecutor.isShutdown()) { final TmfExperiment experiment = TmfExperiment.getCurrentExperiment(); if (experiment != null) { @SuppressWarnings("rawtypes") final TmfEventRequest request = new TmfEventRequest(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ExecutionType.FOREGROUND) { @Override public void handleCompleted() { updateJniTrace(); } }; experiment.sendRequest(request); try { request.waitForCompletion(); } catch (final InterruptedException e) { } } else updateJniTrace(); try { Thread.sleep(LTTNG_STREAMING_INTERVAL); } catch (final InterruptedException e) { } } } private void updateJniTrace() { final JniTrace jniTrace = getCurrentJniTrace(); currentJniTrace.updateTrace(); final long endTime = jniTrace.getEndTime().getTime(); final LttngTimestamp startTimestamp = new LttngTimestamp(startTime); final LttngTimestamp endTimestamp = new LttngTimestamp(endTime); if (safeTimestamp != null && safeTimestamp.compareTo(getTimeRange().getEndTime(), false) > 0) timeRange = new TmfTimeRange(startTimestamp, safeTimestamp); else timeRange = null; safeTimestamp = endTimestamp; if (timeRange != null) setTimeRange(timeRange); } }; thread.start(); }
private void initializeStreamingMonitor() { final JniTrace jniTrace = getCurrentJniTrace(); if (jniTrace == null || (!jniTrace.isLiveTraceSupported() || !LiveTraceManager.isLiveTrace(jniTrace.getTracepath()))) { // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); final LttngTimestamp startTime = new LttngTimestamp(event.getTimestamp()); final LttngTimestamp endTime = new LttngTimestamp(currentJniTrace.getEndTime().getTime()); setTimeRange(new TmfTimeRange(startTime, endTime)); final TmfTraceUpdatedSignal signal = new TmfTraceUpdatedSignal(this, this, getTimeRange()); broadcast(signal); return; } // Set the time range of the trace final ITmfContext context = seekEvent(0); final LttngEvent event = getNext(context); setEndTime(TmfTimestamp.BIG_BANG); final long startTime = event != null ? event.getTimestamp().getValue() : TmfTimestamp.BIG_BANG.getValue(); setStreamingInterval(LTTNG_STREAMING_INTERVAL); final Thread thread = new Thread("Streaming Monitor for trace " + getName()) { //$NON-NLS-1$ LttngTimestamp safeTimestamp = null; TmfTimeRange timeRange = null; @SuppressWarnings({ "unchecked", "restriction" }) @Override public void run() { while (!executorIsShutdown()) { final TmfExperiment experiment = TmfExperiment.getCurrentExperiment(); if (experiment != null) { @SuppressWarnings("rawtypes") final TmfEventRequest request = new TmfEventRequest(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ExecutionType.FOREGROUND) { @Override public void handleCompleted() { updateJniTrace(); } }; experiment.sendRequest(request); try { request.waitForCompletion(); } catch (final InterruptedException e) { } } else updateJniTrace(); try { Thread.sleep(LTTNG_STREAMING_INTERVAL); } catch (final InterruptedException e) { } } } private void updateJniTrace() { final JniTrace jniTrace = getCurrentJniTrace(); currentJniTrace.updateTrace(); final long endTime = jniTrace.getEndTime().getTime(); final LttngTimestamp startTimestamp = new LttngTimestamp(startTime); final LttngTimestamp endTimestamp = new LttngTimestamp(endTime); if (safeTimestamp != null && safeTimestamp.compareTo(getTimeRange().getEndTime(), false) > 0) timeRange = new TmfTimeRange(startTimestamp, safeTimestamp); else timeRange = null; safeTimestamp = endTimestamp; if (timeRange != null) setTimeRange(timeRange); } }; thread.start(); }
diff --git a/src/main/java/de/switajski/priebes/flexibleorders/domain/Amount.java b/src/main/java/de/switajski/priebes/flexibleorders/domain/Amount.java index 2eb9bc79..3ad6a541 100644 --- a/src/main/java/de/switajski/priebes/flexibleorders/domain/Amount.java +++ b/src/main/java/de/switajski/priebes/flexibleorders/domain/Amount.java @@ -1,92 +1,92 @@ package de.switajski.priebes.flexibleorders.domain; import java.math.BigDecimal; import java.text.DecimalFormat; import javax.persistence.Embeddable; import javax.validation.constraints.NotNull; @Embeddable public class Amount { private final static DecimalFormat DECIMAL_FORMAT = new DecimalFormat(",##0.00"); @NotNull private BigDecimal value = BigDecimal.ZERO; @NotNull private Currency currency = Currency.EUR; public Amount() {} public Amount(BigDecimal value, Currency currency) { this.value = value; this.currency = currency; } public Amount(BigDecimal value){ this.value = value; } public BigDecimal getValue() { return value; } public void setValue(BigDecimal value) { this.value = value; } public Currency getCurrency() { return currency; } public void setCurrency(Currency currency) { this.currency = currency; } /** * * @param negotiatedPriceNet not null and has currency * @return */ public Amount add(Amount negotiatedPriceNet) { if (this.currency == null) currency = negotiatedPriceNet.getCurrency(); if (sameCurrency(negotiatedPriceNet)) return new Amount(negotiatedPriceNet.getValue().add(this.getValue()), this.currency); else throw new IllegalArgumentException("tried to add amounts with different currencies"); } public boolean sameCurrency(Amount negotiatedPriceNet) { return negotiatedPriceNet.getCurrency().equals(this.currency); } public String toString(){ String currencyChar = ""; switch (getCurrency()) { - case EUR: currencyChar+= " �"; break; + case EUR: currencyChar+= " \u20ac"; break; case PLN: currencyChar+= " zl"; } String s = DECIMAL_FORMAT.format(value) + currencyChar; return s; } public Amount multiply(Integer quantity) { return new Amount(value.multiply(new BigDecimal(quantity)), currency); } public Amount devide(double divisor) { if (divisor == 0d) throw new IllegalArgumentException("Cannot devide by zero"); return new Amount(this.value.divide(new BigDecimal(divisor)), this.currency); } public boolean isGreaterZero(){ if (this.getValue() == null) return false; if (this.getValue().compareTo(BigDecimal.ZERO) > 0) return true; return false; } }
true
true
public String toString(){ String currencyChar = ""; switch (getCurrency()) { case EUR: currencyChar+= " �"; break; case PLN: currencyChar+= " zl"; } String s = DECIMAL_FORMAT.format(value) + currencyChar; return s; }
public String toString(){ String currencyChar = ""; switch (getCurrency()) { case EUR: currencyChar+= " \u20ac"; break; case PLN: currencyChar+= " zl"; } String s = DECIMAL_FORMAT.format(value) + currencyChar; return s; }
diff --git a/src/main/java/com/mycompany/app/App.java b/src/main/java/com/mycompany/app/App.java index 52ac766..5958b07 100644 --- a/src/main/java/com/mycompany/app/App.java +++ b/src/main/java/com/mycompany/app/App.java @@ -1,18 +1,18 @@ package com.mycompany.app; public class App { public static void main( String[] args ) { - String str1 = null; + String str1 = "str"; String str2 = "str"; System.out.println("Hello World! "+str1.equals(str2)); String test1 = "123"; char[] test2 = null; - test1 = String.copyValueOf(test2); + String.copyValueOf(test2); System.out.println("Hello World! "+test1); System.out.println("Hello World! "+test2); } }
false
true
public static void main( String[] args ) { String str1 = null; String str2 = "str"; System.out.println("Hello World! "+str1.equals(str2)); String test1 = "123"; char[] test2 = null; test1 = String.copyValueOf(test2); System.out.println("Hello World! "+test1); System.out.println("Hello World! "+test2); }
public static void main( String[] args ) { String str1 = "str"; String str2 = "str"; System.out.println("Hello World! "+str1.equals(str2)); String test1 = "123"; char[] test2 = null; String.copyValueOf(test2); System.out.println("Hello World! "+test1); System.out.println("Hello World! "+test2); }
diff --git a/src/main/java/hudson/plugins/jira/listissuesparameter/JiraIssueParameterDefinition.java b/src/main/java/hudson/plugins/jira/listissuesparameter/JiraIssueParameterDefinition.java index f00fdfa..6d3c95f 100644 --- a/src/main/java/hudson/plugins/jira/listissuesparameter/JiraIssueParameterDefinition.java +++ b/src/main/java/hudson/plugins/jira/listissuesparameter/JiraIssueParameterDefinition.java @@ -1,97 +1,98 @@ package hudson.plugins.jira.listissuesparameter; import hudson.plugins.jira.JiraSession; import hudson.plugins.jira.JiraSite; import hudson.plugins.jira.soap.RemoteIssue; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.ParameterDefinition; import hudson.model.ParameterValue; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.rpc.ServiceException; import static hudson.Util.fixNull; import static java.util.Arrays.asList; public class JiraIssueParameterDefinition extends ParameterDefinition { private static final long serialVersionUID = 3927562542249244416L; private String jiraIssueFilter; @DataBoundConstructor public JiraIssueParameterDefinition(String name, String description, String jiraIssueFilter) { super(name, description); this.jiraIssueFilter = jiraIssueFilter; } @Override public ParameterValue createValue(StaplerRequest req) { String[] values = req.getParameterValues(getName()); if (values == null || values.length != 1) { return null; } else { return new JiraIssueParameterValue(getName(), values[0]); } } @Override public ParameterValue createValue(StaplerRequest req, JSONObject formData) { JiraIssueParameterValue value = req.bindJSON( JiraIssueParameterValue.class, formData); return value; } public List<JiraIssueParameterDefinition.Result> getIssues() throws IOException, ServiceException { AbstractProject<?, ?> context = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class); JiraSite site = JiraSite.get(context); + if (site==null) throw new IllegalStateException("JIRA site needs to be configured in the project "+context.getFullDisplayName()); JiraSession session = site.createSession(); if (session==null) throw new IllegalStateException("Remote SOAP access for JIRA isn't configured in Jenkins"); RemoteIssue[] issues = session.getIssuesFromJqlSearch(jiraIssueFilter); List<Result> issueValues = new ArrayList<Result>(); for (RemoteIssue issue : fixNull(asList(issues))) { issueValues.add(new Result(issue)); } return issueValues; } public String getJiraIssueFilter() { return jiraIssueFilter; } public void setJiraIssueFilter(String jiraIssueFilter) { this.jiraIssueFilter = jiraIssueFilter; } @Extension public static class DescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { return "JIRA Issue Parameter"; } } public static class Result { public final String key; public final String summary; public Result(final RemoteIssue issue) { this.key = issue.getKey(); this.summary = issue.getSummary(); } } }
true
true
public List<JiraIssueParameterDefinition.Result> getIssues() throws IOException, ServiceException { AbstractProject<?, ?> context = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class); JiraSite site = JiraSite.get(context); JiraSession session = site.createSession(); if (session==null) throw new IllegalStateException("Remote SOAP access for JIRA isn't configured in Jenkins"); RemoteIssue[] issues = session.getIssuesFromJqlSearch(jiraIssueFilter); List<Result> issueValues = new ArrayList<Result>(); for (RemoteIssue issue : fixNull(asList(issues))) { issueValues.add(new Result(issue)); } return issueValues; }
public List<JiraIssueParameterDefinition.Result> getIssues() throws IOException, ServiceException { AbstractProject<?, ?> context = Stapler.getCurrentRequest().findAncestorObject(AbstractProject.class); JiraSite site = JiraSite.get(context); if (site==null) throw new IllegalStateException("JIRA site needs to be configured in the project "+context.getFullDisplayName()); JiraSession session = site.createSession(); if (session==null) throw new IllegalStateException("Remote SOAP access for JIRA isn't configured in Jenkins"); RemoteIssue[] issues = session.getIssuesFromJqlSearch(jiraIssueFilter); List<Result> issueValues = new ArrayList<Result>(); for (RemoteIssue issue : fixNull(asList(issues))) { issueValues.add(new Result(issue)); } return issueValues; }
diff --git a/src/main/java/org/apache/commons/chain/generic/DispatchLookupCommand.java b/src/main/java/org/apache/commons/chain/generic/DispatchLookupCommand.java index 9cc889f..89ae936 100644 --- a/src/main/java/org/apache/commons/chain/generic/DispatchLookupCommand.java +++ b/src/main/java/org/apache/commons/chain/generic/DispatchLookupCommand.java @@ -1,243 +1,243 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.chain.generic; import org.apache.commons.chain.CatalogFactory; import org.apache.commons.chain.Command; import org.apache.commons.chain.Context; import org.apache.commons.chain.Filter; import java.lang.reflect.Method; import java.util.WeakHashMap; /** * <p>This command combines elements of the {@link LookupCommand} with the * {@link DispatchCommand}. Look up a specified {@link Command} (which could * also be a {@link org.apache.commons.chain.Chain}) in a * {@link org.apache.commons.chain.Catalog}, and delegate execution to * it. Introspection is used to lookup the appropriate method to delegate * execution to. If the delegated-to {@link Command} is also a * {@link Filter}, its <code>postprocess()</code> method will also be invoked * at the appropriate time.</p> * * <p>The name of the {@link Command} can be specified either directly (via * the <code>name</code> property) or indirectly (via the <code>nameKey</code> * property). Exactly one of these must be set.</p> * * <p>The name of the method to be called can be specified either directly * (via the <code>method</code> property) or indirectly (via the <code> * methodKey</code> property). Exactly one of these must be set.</p> * * <p>If the <code>optional</code> property is set to <code>true</code>, * failure to find the specified command in the specified catalog will be * silently ignored. Otherwise, a lookup failure will trigger an * <code>IllegalArgumentException</code>.</p> * * @param <C> Type of the context associated with this command * * @author Sean Schofield * @version $Revision$ * @since Chain 1.1 */ public class DispatchLookupCommand<C extends Context> extends LookupCommand<C> implements Filter<C> { // -------------------------------------------------------------- Constructors /** * Create an instance with an unspecified <code>catalogFactory</code> property. * This property can be set later using <code>setProperty</code>, or if it is not set, * the static singleton instance from <code>CatalogFactory.getInstance()</code> will be used. */ public DispatchLookupCommand() { super(); }; /** * Create an instance and initialize the <code>catalogFactory</code> property * to given <code>factory</code>. * @param factory The Catalog Factory. */ public DispatchLookupCommand(CatalogFactory factory) { super(factory); } // ------------------------------------------------------- Static Variables /** * The base implementation expects dispatch methods to take a <code> * Context</code> as their only argument. */ private static final Class<?>[] DEFAULT_SIGNATURE = new Class<?>[] {Context.class}; // ----------------------------------------------------- Instance Variables private final WeakHashMap<String, Method> methods = new WeakHashMap<String, Method>(); // ------------------------------------------------------------- Properties private String method = null; private String methodKey = null; /** * Return the method name. * @return The method name. */ public String getMethod() { return method; } /** * Return the Context key for the method name. * @return The Context key for the method name. */ public String getMethodKey() { return methodKey; } /** * Set the method name. * @param method The method name. */ public void setMethod(String method) { this.method = method; } /** * Set the Context key for the method name. * @param methodKey The Context key for the method name. */ public void setMethodKey(String methodKey) { this.methodKey = methodKey; } // --------------------------------------------------------- Public Methods /** * <p>Look up the specified command, and (if found) execute it.</p> * * @param context The context for this request * @return the result of executing the looked-up command's method, or * <code>false</code> if no command is found. * * @throws Exception if no such {@link Command} can be found and the * <code>optional</code> property is set to <code>false</code> */ public boolean execute(C context) throws Exception { if (this.getMethod() == null && this.getMethodKey() == null) { throw new IllegalStateException( "Neither 'method' nor 'methodKey' properties are defined " ); } Command<C> command = getCommand(context); if (command != null) { Method methodObject = extractMethod(command, context); Object obj = methodObject.invoke(command, getArguments(context)); Boolean result = (Boolean)obj; return (result != null && result.booleanValue()); } else { return false; } } // ------------------------------------------------------ Protected Methods /** * <p>Return a <code>Class[]</code> describing the expected signature of * the method. The default is a signature that just accepts the command's * {@link Context}. The method can be overidden to provide a different * method signature.<p> * * @return the expected method signature */ protected Class<?>[] getSignature() { return DEFAULT_SIGNATURE; } /** * Get the arguments to be passed into the dispatch method. * Default implementation simply returns the context which was passed in, * but subclasses could use this to wrap the context in some other type, * or extract key values from the context to pass in. The length and types * of values returned by this must coordinate with the return value of * <code>getSignature()</code> * * @param context The context associated with the request * @return the method arguments to be used */ protected Object[] getArguments(C context) { return new Object[] {context}; } // -------------------------------------------------------- Private Methods /** * Extract the dispatch method. The base implementation uses the * command's <code>method</code> property at the name of a method * to look up, or, if that is not defined, uses the <code> * methodKey</code> to lookup the method name in the context. * * @param command The commmand that contains the method to be * executed. * @param context The context associated with this request * @return the dispatch method * * @throws NoSuchMethodException if no method can be found under the * specified name. * @throws NullPointerException if no methodName can be determined */ - private Method extractMethod(Command command, C context) + private Method extractMethod(Command<C> command, C context) throws NoSuchMethodException { String methodName = this.getMethod(); if (methodName == null) { Object methodContextObj = context.get(getMethodKey()); if (methodContextObj == null) { throw new NullPointerException("No value found in context under " + getMethodKey()); } methodName = methodContextObj.toString(); } Method theMethod = null; synchronized (methods) { theMethod = methods.get(methodName); if (theMethod == null) { theMethod = command.getClass().getMethod(methodName, getSignature()); methods.put(methodName, theMethod); } } return theMethod; } }
true
true
private Method extractMethod(Command command, C context) throws NoSuchMethodException { String methodName = this.getMethod(); if (methodName == null) { Object methodContextObj = context.get(getMethodKey()); if (methodContextObj == null) { throw new NullPointerException("No value found in context under " + getMethodKey()); } methodName = methodContextObj.toString(); } Method theMethod = null; synchronized (methods) { theMethod = methods.get(methodName); if (theMethod == null) { theMethod = command.getClass().getMethod(methodName, getSignature()); methods.put(methodName, theMethod); } } return theMethod; }
private Method extractMethod(Command<C> command, C context) throws NoSuchMethodException { String methodName = this.getMethod(); if (methodName == null) { Object methodContextObj = context.get(getMethodKey()); if (methodContextObj == null) { throw new NullPointerException("No value found in context under " + getMethodKey()); } methodName = methodContextObj.toString(); } Method theMethod = null; synchronized (methods) { theMethod = methods.get(methodName); if (theMethod == null) { theMethod = command.getClass().getMethod(methodName, getSignature()); methods.put(methodName, theMethod); } } return theMethod; }
diff --git a/src/minecraft/co/uk/flansmods/client/FlansModClient.java b/src/minecraft/co/uk/flansmods/client/FlansModClient.java index 4525e608..e598b6e2 100644 --- a/src/minecraft/co/uk/flansmods/client/FlansModClient.java +++ b/src/minecraft/co/uk/flansmods/client/FlansModClient.java @@ -1,293 +1,293 @@ package co.uk.flansmods.client; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.entity.RendererLivingEntity; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderLivingEvent; import net.minecraftforge.client.event.RenderPlayerEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.Event; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.world.WorldEvent; import co.uk.flansmods.api.IControllable; import co.uk.flansmods.common.BlockGunBox; import co.uk.flansmods.common.FlansMod; import co.uk.flansmods.common.GunBoxType; import co.uk.flansmods.common.InfoType; import co.uk.flansmods.common.driveables.DriveableType; import co.uk.flansmods.common.driveables.EntityDriveable; import co.uk.flansmods.common.driveables.EntityPlane; import co.uk.flansmods.common.driveables.EntityVehicle; import co.uk.flansmods.common.driveables.PlaneType; import co.uk.flansmods.common.driveables.VehicleType; import co.uk.flansmods.common.guns.GunType; import co.uk.flansmods.common.guns.ItemGun; import co.uk.flansmods.common.network.PacketBuyWeapon; import co.uk.flansmods.common.teams.Gametype; import co.uk.flansmods.common.teams.Team; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ObfuscationReflectionHelper; public class FlansModClient extends FlansMod { public static boolean doneTutorial = false; public static boolean controlModeMouse = false; // 0 = Standard controls, 1 = Mouse public static int controlModeSwitchTimer = 20; public static int shootTime; public static int scopeTime; public static GunType zoomOverlay; public static float playerRecoil; public static float antiRecoil; public static float playerZoom = 1.0F; public static float newZoom = 1.0F; public static float lastPlayerZoom; public static float originalMouseSensitivity = 0.5F; public static boolean originalHideGUI = false; public static int originalThirdPerson = 0; public static boolean inPlane = false; public static ResourceLocation resources; public void load() { if (ABORT) { log("Failed to load dependencies! Not loading Flan's Mod."); return; } log("Loading Flan's mod."); MinecraftForge.EVENT_BUS.register(this); } @ForgeSubscribe public void renderLiving(RenderPlayerEvent.Pre event) { RendererLivingEntity.NAME_TAG_RANGE = 64F; RendererLivingEntity.NAME_TAG_RANGE_SNEAK = 32F; if(event.entity instanceof EntityPlayer) { GuiTeamScores.PlayerData rendering = GuiTeamScores.getPlayerData(event.entity.getEntityName()); GuiTeamScores.PlayerData thePlayer = GuiTeamScores.getPlayerData(minecraft.thePlayer.username); Team renderingTeam = rendering == null ? Team.spectators : rendering.team.team; Team thePlayerTeam = thePlayer == null ? Team.spectators : thePlayer.team.team; //Spectators see all if(thePlayerTeam == Team.spectators) return; //Nobody sees spectators if(renderingTeam == Team.spectators) { event.setCanceled(true); return; } //If we are on the other team, don't render the name tag if(renderingTeam != thePlayerTeam) { RendererLivingEntity.NAME_TAG_RANGE = 0F; RendererLivingEntity.NAME_TAG_RANGE_SNEAK = 0F; return; } //If its DM, don't render the name tag if(!GuiTeamScores.sortedByTeam) { RendererLivingEntity.NAME_TAG_RANGE = 0F; RendererLivingEntity.NAME_TAG_RANGE_SNEAK = 0F; return; } } } public static void tick() { if (minecraft.thePlayer == null) return; if(minecraft.thePlayer.ridingEntity instanceof IControllable && minecraft.currentScreen == null) minecraft.displayGuiScreen(new GuiDriveableController((IControllable)minecraft.thePlayer.ridingEntity)); // Guns if (shootTime > 0) shootTime--; if(scopeTime > 0) scopeTime--; if (playerRecoil > 0) playerRecoil *= 0.8F; minecraft.thePlayer.rotationPitch -= playerRecoil; antiRecoil += playerRecoil; minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F; antiRecoil *= 0.8F; Item itemInHand = null; ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem(); if (itemstackInHand != null) itemInHand = itemstackInHand.getItem(); if (itemInHand != null) { if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope)) { newZoom = 1.0F; } } float dZoom = newZoom - playerZoom; playerZoom += dZoom / 3F; - if (playerZoom < 1.1F && zoomOverlay != null) + if (playerZoom < 1.01F && zoomOverlay != null) { minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity; playerZoom = 1.0F; zoomOverlay = null; minecraft.gameSettings.hideGUI = originalHideGUI; minecraft.gameSettings.thirdPersonView = originalThirdPerson; } if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "Y", "field_78503_V"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } lastPlayerZoom = playerZoom; if (minecraft.thePlayer.ridingEntity instanceof IControllable) { inPlane = true; try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getPlayerRoll(), "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } if(minecraft.thePlayer.ridingEntity instanceof IControllable) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getCameraDistance(), "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } } else if(inPlane) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } inPlane = false; } if (controlModeSwitchTimer > 0) controlModeSwitchTimer--; if (errorStringTimer > 0) errorStringTimer--; } @ForgeSubscribe public void chatMessage(ClientChatReceivedEvent event) { if(event.message.startsWith("{\"translate\":\"flanDeath.")) { String[] split = event.message.split("\\."); split[split.length - 1] = split[split.length - 1].split("\"}")[0]; event.setCanceled(true); TickHandlerClient.addKillMessage(split); //FMLClientHandler.instance().getClient().thePlayer.sendChatToPlayer(split[3] + " killed " + split[2] + " with a " + InfoType.getType(split[1]).name); } } @ForgeSubscribe public void entitySpawn(EntityJoinWorldEvent event) { /* if(event.entity.worldObj.isRemote && event.entity == Minecraft.getMinecraft().thePlayer) System.out.println(event.entity.toString()); if(event.entity.worldObj.isRemote && event.entity instanceof EntityHorse) System.out.println(event.entity.toString()); */ } private boolean checkFileExists(File file) { if(!file.exists()) { try { file.createNewFile(); } catch(Exception e) { FlansMod.log("Failed to create file"); FlansMod.log(file.getAbsolutePath()); } return false; } return true; } public static boolean flipControlMode() { if (controlModeSwitchTimer > 0) return false; controlModeMouse = !controlModeMouse; FMLClientHandler.instance().getClient().displayGuiScreen(controlModeMouse ? new GuiDriveableController((IControllable)FMLClientHandler.instance().getClient().thePlayer.ridingEntity) : null); controlModeSwitchTimer = 40; return true; } public static void shoot() { // TODO : SMP guns } public static Minecraft minecraft = FMLClientHandler.instance().getClient(); }
true
true
public static void tick() { if (minecraft.thePlayer == null) return; if(minecraft.thePlayer.ridingEntity instanceof IControllable && minecraft.currentScreen == null) minecraft.displayGuiScreen(new GuiDriveableController((IControllable)minecraft.thePlayer.ridingEntity)); // Guns if (shootTime > 0) shootTime--; if(scopeTime > 0) scopeTime--; if (playerRecoil > 0) playerRecoil *= 0.8F; minecraft.thePlayer.rotationPitch -= playerRecoil; antiRecoil += playerRecoil; minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F; antiRecoil *= 0.8F; Item itemInHand = null; ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem(); if (itemstackInHand != null) itemInHand = itemstackInHand.getItem(); if (itemInHand != null) { if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope)) { newZoom = 1.0F; } } float dZoom = newZoom - playerZoom; playerZoom += dZoom / 3F; if (playerZoom < 1.1F && zoomOverlay != null) { minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity; playerZoom = 1.0F; zoomOverlay = null; minecraft.gameSettings.hideGUI = originalHideGUI; minecraft.gameSettings.thirdPersonView = originalThirdPerson; } if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "Y", "field_78503_V"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } lastPlayerZoom = playerZoom; if (minecraft.thePlayer.ridingEntity instanceof IControllable) { inPlane = true; try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getPlayerRoll(), "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } if(minecraft.thePlayer.ridingEntity instanceof IControllable) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getCameraDistance(), "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } } else if(inPlane) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } inPlane = false; } if (controlModeSwitchTimer > 0) controlModeSwitchTimer--; if (errorStringTimer > 0) errorStringTimer--; }
public static void tick() { if (minecraft.thePlayer == null) return; if(minecraft.thePlayer.ridingEntity instanceof IControllable && minecraft.currentScreen == null) minecraft.displayGuiScreen(new GuiDriveableController((IControllable)minecraft.thePlayer.ridingEntity)); // Guns if (shootTime > 0) shootTime--; if(scopeTime > 0) scopeTime--; if (playerRecoil > 0) playerRecoil *= 0.8F; minecraft.thePlayer.rotationPitch -= playerRecoil; antiRecoil += playerRecoil; minecraft.thePlayer.rotationPitch += antiRecoil * 0.2F; antiRecoil *= 0.8F; Item itemInHand = null; ItemStack itemstackInHand = minecraft.thePlayer.inventory.getCurrentItem(); if (itemstackInHand != null) itemInHand = itemstackInHand.getItem(); if (itemInHand != null) { if (!(itemInHand instanceof ItemGun && ((ItemGun) itemInHand).type.hasScope)) { newZoom = 1.0F; } } float dZoom = newZoom - playerZoom; playerZoom += dZoom / 3F; if (playerZoom < 1.01F && zoomOverlay != null) { minecraft.gameSettings.mouseSensitivity = originalMouseSensitivity; playerZoom = 1.0F; zoomOverlay = null; minecraft.gameSettings.hideGUI = originalHideGUI; minecraft.gameSettings.thirdPersonView = originalThirdPerson; } if (Math.abs(playerZoom - lastPlayerZoom) > 1F / 64F) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, playerZoom, "cameraZoom", "Y", "field_78503_V"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } lastPlayerZoom = playerZoom; if (minecraft.thePlayer.ridingEntity instanceof IControllable) { inPlane = true; try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getPlayerRoll(), "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } if(minecraft.thePlayer.ridingEntity instanceof IControllable) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, ((IControllable)minecraft.thePlayer.ridingEntity).getCameraDistance(), "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } } } else if(inPlane) { try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 0F, "camRoll", "N", "field_78495_O"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } try { ObfuscationReflectionHelper.setPrivateValue(EntityRenderer.class, minecraft.entityRenderer, 4.0F, "thirdPersonDistance", "A", "field_78490_B"); } catch (Exception e) { log("I forgot to update obfuscated reflection D:"); throw new RuntimeException(e); } inPlane = false; } if (controlModeSwitchTimer > 0) controlModeSwitchTimer--; if (errorStringTimer > 0) errorStringTimer--; }
diff --git a/grails-app/services/org/chai/kevin/value/ExpressionService.java b/grails-app/services/org/chai/kevin/value/ExpressionService.java index 7527f2ed..1e68b1ae 100644 --- a/grails-app/services/org/chai/kevin/value/ExpressionService.java +++ b/grails-app/services/org/chai/kevin/value/ExpressionService.java @@ -1,256 +1,256 @@ package org.chai.kevin.value; /* * Copyright (c) 2011, Clinton Health Access Initiative. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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. */ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.chai.kevin.JaqlService; import org.chai.kevin.LocationService; import org.chai.kevin.data.Calculation; import org.chai.kevin.data.Data; import org.chai.kevin.data.DataElement; import org.chai.kevin.data.DataService; import org.chai.kevin.data.NormalizedDataElement; import org.chai.kevin.data.RawDataElement; import org.chai.kevin.data.Type; import org.chai.kevin.location.CalculationEntity; import org.chai.kevin.location.DataLocationEntity; import org.chai.kevin.location.DataEntityType; import org.hisp.dhis.period.Period; import org.springframework.transaction.annotation.Transactional; import com.ibm.jaql.json.type.JsonValue; public class ExpressionService { private static final Log log = LogFactory.getLog(ExpressionService.class); private static final Log expressionLog = LogFactory.getLog("ExpressionLog"); private DataService dataService; private LocationService locationService; private ValueService valueService; private JaqlService jaqlService; public static class StatusValuePair { public Status status = null; public Value value = null; } @Transactional(readOnly=true) public <T extends CalculationPartialValue> List<T> calculatePartialValues(Calculation<T> calculation, CalculationEntity entity, Period period) { if (log.isDebugEnabled()) log.debug("calculateValue(calculation="+calculation+",period="+period+",entity="+entity+")"); List<T> result = new ArrayList<T>(); for (String expression : calculation.getPartialExpressions()) { result.addAll(calculatePartialValues(calculation, expression, entity, period)); } return result; } private <T extends CalculationPartialValue> Set<T> calculatePartialValues(Calculation<T> calculation, String expression, CalculationEntity entity, Period period) { if (log.isDebugEnabled()) log.debug("calculateValue(expression="+expression+",period="+period+",entity="+entity+")"); Set<T> result = new HashSet<T>(); for (DataEntityType type : locationService.listTypes()) { Set<DataEntityType> collectForType = new HashSet<DataEntityType>(); collectForType.add(type); List<DataLocationEntity> facilities = entity.collectDataLocationEntities(null, collectForType); if (!facilities.isEmpty()) { Map<DataLocationEntity, StatusValuePair> values = new HashMap<DataLocationEntity, StatusValuePair>(); for (DataLocationEntity facility : facilities) { StatusValuePair statusValuePair = getExpressionStatusValuePair(expression, Calculation.TYPE, period, facility, DataElement.class); values.put(facility, statusValuePair); } result.add(calculation.getCalculationPartialValue(expression, values, entity, period, type)); } } return result; } @Transactional(readOnly=true) public NormalizedDataElementValue calculateValue(NormalizedDataElement normalizedDataElement, DataLocationEntity facility, Period period) { if (log.isDebugEnabled()) log.debug("calculateValue(normalizedDataElement="+normalizedDataElement+",period="+period+",facility="+facility+")"); String expression = normalizedDataElement.getExpression(period, facility.getType().getCode()); StatusValuePair statusValuePair = getExpressionStatusValuePair(expression, normalizedDataElement.getType(), period, facility, RawDataElement.class); NormalizedDataElementValue expressionValue = new NormalizedDataElementValue(statusValuePair.value, statusValuePair.status, facility, normalizedDataElement, period); if (log.isDebugEnabled()) log.debug("getValue()="+expressionValue); return expressionValue; } // location has to be a facility private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) { StatusValuePair statusValuePair = new StatusValuePair(); if (expression == null) { statusValuePair.status = Status.DOES_NOT_APPLY; statusValuePair.value = Value.NULL_INSTANCE(); } else { Map<String, T> datas = getDataInExpression(expression, clazz); if (hasNullValues(datas.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_DATA_ELEMENT; } else { Map<String, Value> valueMap = new HashMap<String, Value>(); Map<String, Type> typeMap = new HashMap<String, Type>(); for (Entry<String, T> entry : datas.entrySet()) { DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period); valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue()); typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType()); } if (hasNullValues(valueMap.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_VALUE; } else { try { statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap); statusValuePair.status = Status.VALID; } catch (IllegalArgumentException e) { - expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}"); + expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}", e); log.warn("there was an error evaluating expression: "+expression, e); statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.ERROR; } } } } return statusValuePair; } // TODO do this for validation rules @Transactional(readOnly=true) public <T extends Data<?>> boolean expressionIsValid(String formula, Class<T> allowedClazz) { if (formula.contains("\n")) return false; Map<String, T> variables = getDataInExpression(formula, allowedClazz); if (hasNullValues(variables.values())) return false; Map<String, String> jaqlVariables = new HashMap<String, String>(); for (Entry<String, T> variable : variables.entrySet()) { Type type = variable.getValue().getType(); jaqlVariables.put(variable.getKey(), type.getJaqlValue(type.getPlaceHolderValue())); } try { jaqlService.getJsonValue(formula, jaqlVariables); } catch (IllegalArgumentException e) { return false; } return true; } @Transactional(readOnly=true) public <T extends Data<?>> Map<String, T> getDataInExpression(String expression, Class<T> clazz) { if (log.isDebugEnabled()) log.debug("getDataInExpression(expression="+expression+", clazz="+clazz+")"); Map<String, T> dataInExpression = new HashMap<String, T>(); Set<String> placeholders = getVariables(expression); for (String placeholder : placeholders) { T data = null; try { data = dataService.getData(Long.parseLong(placeholder.replace("$", "")), clazz); } catch (NumberFormatException e) { log.error("wrong format for dataelement: "+placeholder); } dataInExpression.put(placeholder, data); } if (log.isDebugEnabled()) log.debug("getDataInExpression()="+dataInExpression); return dataInExpression; } public static Set<String> getVariables(String expression) { Set<String> placeholders = null; if ( expression != null ) { placeholders = new HashSet<String>(); final Matcher matcher = Pattern.compile("\\$\\d+").matcher( expression ); while (matcher.find()) { String match = matcher.group(); placeholders.add(match); } } return placeholders; } public static String convertStringExpression(String expression, Map<String, String> mapping) { String result = expression; for (Entry<String, String> entry : mapping.entrySet()) { // TODO validate key if (!Pattern.matches("\\$\\d+", entry.getKey())) throw new IllegalArgumentException("key does not match expression pattern: "+entry); result = result.replaceAll("\\"+entry.getKey()+"(\\z|\\D|$)", entry.getValue().replace("$", "\\$")+"$1"); } return result; } private static <T extends Object> boolean hasNullValues(Collection<T> values) { for (Object object : values) { if (object == null) return true; } return false; } public void setDataService(DataService dataService) { this.dataService = dataService; } public void setValueService(ValueService valueService) { this.valueService = valueService; } public void setLocationService(LocationService locationService) { this.locationService = locationService; } public void setJaqlService(JaqlService jaqlService) { this.jaqlService = jaqlService; } }
true
true
private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) { StatusValuePair statusValuePair = new StatusValuePair(); if (expression == null) { statusValuePair.status = Status.DOES_NOT_APPLY; statusValuePair.value = Value.NULL_INSTANCE(); } else { Map<String, T> datas = getDataInExpression(expression, clazz); if (hasNullValues(datas.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_DATA_ELEMENT; } else { Map<String, Value> valueMap = new HashMap<String, Value>(); Map<String, Type> typeMap = new HashMap<String, Type>(); for (Entry<String, T> entry : datas.entrySet()) { DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period); valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue()); typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType()); } if (hasNullValues(valueMap.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_VALUE; } else { try { statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap); statusValuePair.status = Status.VALID; } catch (IllegalArgumentException e) { expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}"); log.warn("there was an error evaluating expression: "+expression, e); statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.ERROR; } } } } return statusValuePair; }
private <T extends DataElement<S>, S extends DataValue> StatusValuePair getExpressionStatusValuePair(String expression, Type type, Period period, DataLocationEntity facility, Class<T> clazz) { StatusValuePair statusValuePair = new StatusValuePair(); if (expression == null) { statusValuePair.status = Status.DOES_NOT_APPLY; statusValuePair.value = Value.NULL_INSTANCE(); } else { Map<String, T> datas = getDataInExpression(expression, clazz); if (hasNullValues(datas.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_DATA_ELEMENT; } else { Map<String, Value> valueMap = new HashMap<String, Value>(); Map<String, Type> typeMap = new HashMap<String, Type>(); for (Entry<String, T> entry : datas.entrySet()) { DataValue dataValue = valueService.getDataElementValue(entry.getValue(), facility, period); valueMap.put(entry.getValue().getId().toString(), dataValue==null?null:dataValue.getValue()); typeMap.put(entry.getValue().getId().toString(), entry.getValue().getType()); } if (hasNullValues(valueMap.values())) { statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.MISSING_VALUE; } else { try { statusValuePair.value = jaqlService.evaluate(expression, type, valueMap, typeMap); statusValuePair.status = Status.VALID; } catch (IllegalArgumentException e) { expressionLog.error("expression={"+expression+"}, type={"+type+"}, period={"+period+"}, facility={"+facility+"}, valueMap={"+valueMap+"}, typeMap={"+typeMap+"}", e); log.warn("there was an error evaluating expression: "+expression, e); statusValuePair.value = Value.NULL_INSTANCE(); statusValuePair.status = Status.ERROR; } } } } return statusValuePair; }
diff --git a/app/src/main/java/com/github/mobile/ui/issue/AssigneeDialog.java b/app/src/main/java/com/github/mobile/ui/issue/AssigneeDialog.java index 09de4e6d..41bde909 100644 --- a/app/src/main/java/com/github/mobile/ui/issue/AssigneeDialog.java +++ b/app/src/main/java/com/github/mobile/ui/issue/AssigneeDialog.java @@ -1,136 +1,136 @@ /* * Copyright 2012 GitHub Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mobile.ui.issue; import static java.lang.String.CASE_INSENSITIVE_ORDER; import com.github.mobile.R.string; import com.github.mobile.ui.DialogFragmentActivity; import com.github.mobile.ui.ProgressDialogTask; import com.github.mobile.ui.SingleChoiceDialogFragment; import com.github.mobile.util.ToastUtils; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.eclipse.egit.github.core.IRepositoryIdProvider; import org.eclipse.egit.github.core.User; import org.eclipse.egit.github.core.service.CollaboratorService; /** * Dialog helper to display a list of assignees to select one from */ public class AssigneeDialog { private CollaboratorService service; private Map<String, User> collaborators; private final int requestCode; private final DialogFragmentActivity activity; private final IRepositoryIdProvider repository; /** * Create dialog helper to display assignees * * @param activity * @param requestCode * @param repository * @param service */ public AssigneeDialog(final DialogFragmentActivity activity, final int requestCode, final IRepositoryIdProvider repository, final CollaboratorService service) { this.activity = activity; this.requestCode = requestCode; this.repository = repository; this.service = service; } private void load(final String selectedAssignee) { new ProgressDialogTask<List<User>>(activity) { @Override public List<User> run() throws Exception { List<User> users = service.getCollaborators(repository); Map<String, User> loadedCollaborators = new TreeMap<String, User>(CASE_INSENSITIVE_ORDER); for (User user : users) loadedCollaborators.put(user.getLogin(), user); collaborators = loadedCollaborators; return users; } @Override protected void onSuccess(List<User> all) throws Exception { super.onSuccess(all); show(selectedAssignee); } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); - ToastUtils.show(activity, e, string.error_assignee_update); + ToastUtils.show(activity, e, string.error_collaborators_load); } @Override public void execute() { dismissProgress(); showIndeterminate(string.loading_collaborators); super.execute(); } }.execute(); } /** * Get collaborator with login * * @param login * @return collaborator or null if none found with login */ public User getCollaborator(String login) { if (collaborators == null) return null; if (login == null || login.length() == 0) return null; return collaborators.get(login); } /** * Show dialog with given assignee selected * * @param selectedAssignee */ public void show(String selectedAssignee) { if (collaborators == null) { load(selectedAssignee); return; } final String[] names = collaborators.keySet().toArray(new String[collaborators.size()]); int checked = -1; if (selectedAssignee != null) for (int i = 0; i < names.length; i++) if (selectedAssignee.equals(names[i])) checked = i; SingleChoiceDialogFragment.show(activity, requestCode, activity.getString(string.select_assignee), null, names, checked); } }
true
true
private void load(final String selectedAssignee) { new ProgressDialogTask<List<User>>(activity) { @Override public List<User> run() throws Exception { List<User> users = service.getCollaborators(repository); Map<String, User> loadedCollaborators = new TreeMap<String, User>(CASE_INSENSITIVE_ORDER); for (User user : users) loadedCollaborators.put(user.getLogin(), user); collaborators = loadedCollaborators; return users; } @Override protected void onSuccess(List<User> all) throws Exception { super.onSuccess(all); show(selectedAssignee); } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); ToastUtils.show(activity, e, string.error_assignee_update); } @Override public void execute() { dismissProgress(); showIndeterminate(string.loading_collaborators); super.execute(); } }.execute(); }
private void load(final String selectedAssignee) { new ProgressDialogTask<List<User>>(activity) { @Override public List<User> run() throws Exception { List<User> users = service.getCollaborators(repository); Map<String, User> loadedCollaborators = new TreeMap<String, User>(CASE_INSENSITIVE_ORDER); for (User user : users) loadedCollaborators.put(user.getLogin(), user); collaborators = loadedCollaborators; return users; } @Override protected void onSuccess(List<User> all) throws Exception { super.onSuccess(all); show(selectedAssignee); } @Override protected void onException(Exception e) throws RuntimeException { super.onException(e); ToastUtils.show(activity, e, string.error_collaborators_load); } @Override public void execute() { dismissProgress(); showIndeterminate(string.loading_collaborators); super.execute(); } }.execute(); }
diff --git a/src/main/java/co/altruix/scheduler/PccSchedulerApp.java b/src/main/java/co/altruix/scheduler/PccSchedulerApp.java index 588cd5c..ac23c4c 100644 --- a/src/main/java/co/altruix/scheduler/PccSchedulerApp.java +++ b/src/main/java/co/altruix/scheduler/PccSchedulerApp.java @@ -1,159 +1,160 @@ package co.altruix.scheduler; import static org.quartz.SimpleScheduleBuilder.simpleSchedule; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import javax.jms.Session; import org.apache.commons.io.IOUtils; import org.quartz.JobBuilder; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.impl.StdSchedulerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.altruix.commons.api.di.PccException; import at.silverstrike.pcc.api.persistence.Persistence; import co.altruix.pcc.api.mq.MqInfrastructureInitializer; import co.altruix.pcc.api.mq.MqInfrastructureInitializerFactory; import co.altruix.pcc.api.outgoingqueuechannel.OutgoingQueueChannel; import co.altruix.pcc.api.outgoingqueuechannel.OutgoingQueueChannelFactory; import co.altruix.scheduler.api.jobdatamapcreator.JobDataMapCreator; import co.altruix.scheduler.api.jobdatamapcreator.JobDataMapCreatorFactory; import co.altruix.scheduler.impl.di.DefaultPccSchedulerInjectorFactory; import co.altruix.scheduler.impl.scheduledrecalculation.DefaultScheduledRecalculationJob; import com.google.inject.Injector; public final class PccSchedulerApp { private static final String PCC_RECALCULATION = "pcc-recalculation-job"; private static final String CONFIG_FILE = "conf.properties"; private static final Logger LOGGER = LoggerFactory .getLogger(PccSchedulerApp.class); public void run() { try { final Properties config = readConfig(); final Injector injector = initDependencyInjector(); final Persistence persistence = injector.getInstance(Persistence.class); persistence.openSession(Persistence.HOST_LOCAL, null, null, Persistence.DB_PRODUCTION); final String brokerUrl = config.getProperty("brokerUrl"); final String username = config.getProperty("username"); final String password = config.getProperty("password"); final MqInfrastructureInitializer mqInitializer = initMq(injector, brokerUrl, username, password); final Session session = mqInitializer.getSession(); final OutgoingQueueChannelFactory factory = injector.getInstance(OutgoingQueueChannelFactory.class); final OutgoingQueueChannel channel = factory.create(); channel.setChannelName("scheduler2workerQueueName"); channel.setChannelName(config.getProperty("scheduler2workerQueueName")); channel.setSession(session); + channel.init(); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); final JobDetail job = JobBuilder.newJob(DefaultScheduledRecalculationJob.class) .withIdentity(PCC_RECALCULATION).build(); final JobDataMap jobDataMap = getJobDataMap(injector, session, channel); final Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("pcc-recalculation-trigger") .usingJobData(jobDataMap) .startNow() .withSchedule( simpleSchedule() .withIntervalInMinutes(5) .repeatForever()).build(); scheduler.scheduleJob(job, trigger); } catch (final SchedulerException exception) { LOGGER.error("", exception); } catch (final PccException exception) { LOGGER.error("", exception); } } private JobDataMap getJobDataMap(final Injector injector, final Session session, final OutgoingQueueChannel channel) throws PccException { final JobDataMapCreatorFactory jobDataMapCreatorFactory = injector.getInstance(JobDataMapCreatorFactory.class); final JobDataMapCreator jobDataMapCreator = jobDataMapCreatorFactory.create(); jobDataMapCreator.setChannel(channel); jobDataMapCreator.setInjector(injector); jobDataMapCreator.setSession(session); jobDataMapCreator.run(); final JobDataMap jobDataMap = jobDataMapCreator.getJobDataMap(); return jobDataMap; } private MqInfrastructureInitializer initMq(final Injector aInjector, final String aBrokerUrl, final String aUsername, final String aPassword) throws PccException { final MqInfrastructureInitializerFactory factory = aInjector.getInstance(MqInfrastructureInitializerFactory.class); final MqInfrastructureInitializer mqInitializer = factory.create(); mqInitializer.setUsername(aUsername); mqInitializer.setPassword(aPassword); mqInitializer.setBrokerUrl(aBrokerUrl); mqInitializer.run(); return mqInitializer; } private Properties readConfig() { final Properties config = new Properties(); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(new File(CONFIG_FILE)); config.load(fileInputStream); } catch (final IOException exception) { LOGGER.error("", exception); } finally { IOUtils.closeQuietly(fileInputStream); } return config; } private Injector initDependencyInjector() { final DefaultPccSchedulerInjectorFactory injectorFactory = new DefaultPccSchedulerInjectorFactory(); final Injector injector = injectorFactory.createInjector(); return injector; } public static void main(String[] args) { final PccSchedulerApp app = new PccSchedulerApp(); app.run(); } }
true
true
public void run() { try { final Properties config = readConfig(); final Injector injector = initDependencyInjector(); final Persistence persistence = injector.getInstance(Persistence.class); persistence.openSession(Persistence.HOST_LOCAL, null, null, Persistence.DB_PRODUCTION); final String brokerUrl = config.getProperty("brokerUrl"); final String username = config.getProperty("username"); final String password = config.getProperty("password"); final MqInfrastructureInitializer mqInitializer = initMq(injector, brokerUrl, username, password); final Session session = mqInitializer.getSession(); final OutgoingQueueChannelFactory factory = injector.getInstance(OutgoingQueueChannelFactory.class); final OutgoingQueueChannel channel = factory.create(); channel.setChannelName("scheduler2workerQueueName"); channel.setChannelName(config.getProperty("scheduler2workerQueueName")); channel.setSession(session); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); final JobDetail job = JobBuilder.newJob(DefaultScheduledRecalculationJob.class) .withIdentity(PCC_RECALCULATION).build(); final JobDataMap jobDataMap = getJobDataMap(injector, session, channel); final Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("pcc-recalculation-trigger") .usingJobData(jobDataMap) .startNow() .withSchedule( simpleSchedule() .withIntervalInMinutes(5) .repeatForever()).build(); scheduler.scheduleJob(job, trigger); } catch (final SchedulerException exception) { LOGGER.error("", exception); } catch (final PccException exception) { LOGGER.error("", exception); } }
public void run() { try { final Properties config = readConfig(); final Injector injector = initDependencyInjector(); final Persistence persistence = injector.getInstance(Persistence.class); persistence.openSession(Persistence.HOST_LOCAL, null, null, Persistence.DB_PRODUCTION); final String brokerUrl = config.getProperty("brokerUrl"); final String username = config.getProperty("username"); final String password = config.getProperty("password"); final MqInfrastructureInitializer mqInitializer = initMq(injector, brokerUrl, username, password); final Session session = mqInitializer.getSession(); final OutgoingQueueChannelFactory factory = injector.getInstance(OutgoingQueueChannelFactory.class); final OutgoingQueueChannel channel = factory.create(); channel.setChannelName("scheduler2workerQueueName"); channel.setChannelName(config.getProperty("scheduler2workerQueueName")); channel.setSession(session); channel.init(); final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); scheduler.start(); final JobDetail job = JobBuilder.newJob(DefaultScheduledRecalculationJob.class) .withIdentity(PCC_RECALCULATION).build(); final JobDataMap jobDataMap = getJobDataMap(injector, session, channel); final Trigger trigger = TriggerBuilder .newTrigger() .withIdentity("pcc-recalculation-trigger") .usingJobData(jobDataMap) .startNow() .withSchedule( simpleSchedule() .withIntervalInMinutes(5) .repeatForever()).build(); scheduler.scheduleJob(job, trigger); } catch (final SchedulerException exception) { LOGGER.error("", exception); } catch (final PccException exception) { LOGGER.error("", exception); } }
diff --git a/src/org/red5/server/stream/FlowControlService.java b/src/org/red5/server/stream/FlowControlService.java index 5c9bf782..e822eda2 100644 --- a/src/org/red5/server/stream/FlowControlService.java +++ b/src/org/red5/server/stream/FlowControlService.java @@ -1,318 +1,319 @@ package org.red5.server.stream; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.red5.server.api.IBandwidthConfigure; import org.red5.server.api.IFlowControllable; import org.red5.server.api.stream.support.SimpleBandwidthConfigure; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * An implementation of IFlowControlService. * TODO fairly distribute tokens across child nodes and elegantly * order the IFlowControllables for scheduling (give priority to buckets * that have threads waiting). * @author The Red5 Project ([email protected]) * @author Steven Gong ([email protected]) */ public class FlowControlService extends TimerTask implements IFlowControlService, ApplicationContextAware { private long interval = 10; private long defaultCapacity = 1024 * 100; private Timer timer; private Map<IFlowControllable, DataObject> fcsMap = new HashMap<IFlowControllable, DataObject>(); private DummyBucket dummyBucket = new DummyBucket(); public void registerFlowControllable(IFlowControllable fc) { synchronized (fcsMap) { if (fcsMap.containsKey(fcsMap)) return; if (fc.getBandwidthConfigure() == null) return; DataObject obj = new DataObject(); obj.bwConfig = new SimpleBandwidthConfigure(fc.getBandwidthConfigure()); long maxBurst = obj.bwConfig.getMaxBurst(); if (maxBurst <= 0) { maxBurst = defaultCapacity; } long burst = obj.bwConfig.getBurst(); if (burst > maxBurst) { burst = maxBurst; } else if (burst < 0) { burst = 0; } if (obj.bwConfig.getOverallBandwidth() >= 0) { obj.overallBucket = new TokenBucket(burst); obj.overallBucket.setCapacity(maxBurst); obj.overallBucket.setSpeed(bps2Bpms(obj.bwConfig.getOverallBandwidth())); obj.audioWrapper = new TokenBucketWrapper(obj.overallBucket); obj.videoWrapper = new TokenBucketWrapper(obj.overallBucket); } else { obj.audioBucket = new TokenBucket(burst); obj.audioBucket.setCapacity(maxBurst); obj.audioBucket.setSpeed(bps2Bpms(obj.bwConfig.getAudioBandwidth())); obj.videoBucket = new TokenBucket(burst); obj.videoBucket.setCapacity(maxBurst); obj.videoBucket.setSpeed(bps2Bpms(obj.bwConfig.getVideoBandwidth())); obj.audioWrapper = new TokenBucketWrapper(obj.audioBucket); obj.videoWrapper = new TokenBucketWrapper(obj.videoBucket); } fcsMap.put(fc, obj); } } public void unregisterFlowControllable(IFlowControllable fc) { synchronized (fcsMap) { // TODO migrate the waiting threads to ancestors fcsMap.remove(fc); } } public void updateBWConfigure(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); if (obj == null) return; if (fc.getBandwidthConfigure() == null) { // simple unregister the flow controllable // TODO migrate the waiting threads to ancestors fcsMap.remove(fc); + return; } IBandwidthConfigure oldConf = obj.bwConfig; IBandwidthConfigure newConf = fc.getBandwidthConfigure(); long maxBurst = newConf.getMaxBurst(); if (maxBurst <= 0) { maxBurst = defaultCapacity; } long burst = newConf.getBurst(); if (burst > maxBurst) { burst = maxBurst; } else { burst = 0; } if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() >= 0) { obj.overallBucket.setCapacity(newConf.getMaxBurst()); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); } else if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() < 0) { // TODO migrate waiting threads on overallBucket // to a/v buckets obj.overallBucket = null; obj.audioBucket = new TokenBucket(burst); obj.audioBucket.setCapacity(maxBurst); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket = new TokenBucket(burst); obj.videoBucket.setCapacity(maxBurst); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); obj.audioWrapper.wrapped = obj.audioBucket; obj.videoWrapper.wrapped = obj.videoBucket; } else if (oldConf.getOverallBandwidth() < 0 && newConf.getOverallBandwidth() >= 0) { // TODO migrate waiting threads on a/v buckets // to overallBucket obj.audioBucket = null; obj.videoBucket = null; obj.overallBucket = new TokenBucket(burst); obj.overallBucket.setCapacity(maxBurst); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); obj.audioWrapper.wrapped = obj.overallBucket; obj.videoWrapper.wrapped = obj.overallBucket; } else { obj.audioBucket.setCapacity(newConf.getMaxBurst()); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket.setCapacity(newConf.getMaxBurst()); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); } obj.bwConfig = new SimpleBandwidthConfigure(newConf); } } public void resetTokenBuckets(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); if (obj != null) { if (obj.overallBucket != null) { obj.overallBucket.reset(); } if (obj.audioBucket != null) { obj.audioBucket.reset(); } if (obj.videoBucket != null) { obj.videoBucket.reset(); } } } } public ITokenBucket getAudioTokenBucket(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); while (obj == null && fc.getParentFlowControllable() != null) { fc = fc.getParentFlowControllable(); obj = fcsMap.get(fc); } if (obj != null) { return obj.audioWrapper; } else { return dummyBucket; } } } public ITokenBucket getVideoTokenBucket(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); while (obj == null && fc.getParentFlowControllable() != null) { fc = fc.getParentFlowControllable(); obj = fcsMap.get(fc); } if (obj != null) { return obj.videoWrapper; } else { return dummyBucket; } } } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { } @Override public void run() { synchronized (fcsMap) { for (IFlowControllable fc : fcsMap.keySet()) { // search through all parents to find the first ancestor that's // registered IFlowControllable ITokenBucket ancestorOverallBucket = null; ITokenBucket ancestorAudioBucket = null; ITokenBucket ancestorVideoBucket = null; IFlowControllable parent = fc.getParentFlowControllable(); while (parent != null) { if (fcsMap.containsKey(parent)) { DataObject theObj = fcsMap.get(parent); if (theObj.overallBucket != null) { ancestorOverallBucket = theObj.overallBucket; } else { ancestorAudioBucket = theObj.audioBucket; ancestorVideoBucket = theObj.videoBucket; } break; } } if (ancestorOverallBucket == null && ancestorAudioBucket == null && ancestorVideoBucket == null) { // no ancestors are registered, use the default one ancestorVideoBucket = dummyBucket; ancestorAudioBucket = dummyBucket; ancestorOverallBucket = dummyBucket; } DataObject obj = fcsMap.get(fc); if (obj.overallBucket != null) { long tokenCount = obj.overallBucket.getSpeed() * interval; long availableTokens = ancestorOverallBucket.acquireTokenBestEffort(tokenCount); obj.overallBucket.addToken(availableTokens); } else { long tokenCount = obj.audioBucket.getSpeed() * interval; long availableTokens = ancestorAudioBucket.acquireTokenBestEffort(tokenCount); obj.audioBucket.addToken(availableTokens); tokenCount = obj.videoBucket.getSpeed() * interval; availableTokens = ancestorVideoBucket.acquireTokenBestEffort(tokenCount); obj.videoBucket.addToken(availableTokens); } } } } public void init() { timer = new Timer("FlowControlService", true); timer.schedule(this, interval, interval); } public void setInterval(long interval) { this.interval = interval; } public void setDefaultCapacity(long defaultCapacity) { this.defaultCapacity = defaultCapacity; } private long bps2Bpms(long bps) { return bps / 1000 / 8; } private class DataObject { private IBandwidthConfigure bwConfig; private TokenBucketWrapper audioWrapper; private TokenBucketWrapper videoWrapper; private TokenBucket videoBucket; private TokenBucket audioBucket; private TokenBucket overallBucket; } private class TokenBucketWrapper implements ITokenBucket { private ITokenBucket wrapped; public TokenBucketWrapper(ITokenBucket wrapped) { this.wrapped = wrapped; } public boolean acquireToken(long tokenCount, long wait) { return wrapped.acquireToken(tokenCount, wait); } public long acquireTokenBestEffort(long upperLimitCount) { return wrapped.acquireTokenBestEffort(upperLimitCount); } public boolean acquireTokenNonblocking(long tokenCount, ITokenBucketCallback callback) { return wrapped.acquireTokenNonblocking(tokenCount, callback); } public long getCapacity() { return wrapped.getCapacity(); } public long getSpeed() { return wrapped.getSpeed(); } public void reset() { wrapped.reset(); } } /** * A bucket that always has token available. */ private class DummyBucket implements ITokenBucket { public boolean acquireToken(long tokenCount, long wait) { return true; } public long acquireTokenBestEffort(long upperLimitCount) { return upperLimitCount; } public boolean acquireTokenNonblocking(long tokenCount, ITokenBucketCallback callback) { return true; } public long getCapacity() { return 0; } public long getSpeed() { return 0; } public void reset() { } } }
true
true
public void updateBWConfigure(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); if (obj == null) return; if (fc.getBandwidthConfigure() == null) { // simple unregister the flow controllable // TODO migrate the waiting threads to ancestors fcsMap.remove(fc); } IBandwidthConfigure oldConf = obj.bwConfig; IBandwidthConfigure newConf = fc.getBandwidthConfigure(); long maxBurst = newConf.getMaxBurst(); if (maxBurst <= 0) { maxBurst = defaultCapacity; } long burst = newConf.getBurst(); if (burst > maxBurst) { burst = maxBurst; } else { burst = 0; } if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() >= 0) { obj.overallBucket.setCapacity(newConf.getMaxBurst()); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); } else if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() < 0) { // TODO migrate waiting threads on overallBucket // to a/v buckets obj.overallBucket = null; obj.audioBucket = new TokenBucket(burst); obj.audioBucket.setCapacity(maxBurst); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket = new TokenBucket(burst); obj.videoBucket.setCapacity(maxBurst); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); obj.audioWrapper.wrapped = obj.audioBucket; obj.videoWrapper.wrapped = obj.videoBucket; } else if (oldConf.getOverallBandwidth() < 0 && newConf.getOverallBandwidth() >= 0) { // TODO migrate waiting threads on a/v buckets // to overallBucket obj.audioBucket = null; obj.videoBucket = null; obj.overallBucket = new TokenBucket(burst); obj.overallBucket.setCapacity(maxBurst); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); obj.audioWrapper.wrapped = obj.overallBucket; obj.videoWrapper.wrapped = obj.overallBucket; } else { obj.audioBucket.setCapacity(newConf.getMaxBurst()); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket.setCapacity(newConf.getMaxBurst()); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); } obj.bwConfig = new SimpleBandwidthConfigure(newConf); } }
public void updateBWConfigure(IFlowControllable fc) { synchronized (fcsMap) { DataObject obj = fcsMap.get(fc); if (obj == null) return; if (fc.getBandwidthConfigure() == null) { // simple unregister the flow controllable // TODO migrate the waiting threads to ancestors fcsMap.remove(fc); return; } IBandwidthConfigure oldConf = obj.bwConfig; IBandwidthConfigure newConf = fc.getBandwidthConfigure(); long maxBurst = newConf.getMaxBurst(); if (maxBurst <= 0) { maxBurst = defaultCapacity; } long burst = newConf.getBurst(); if (burst > maxBurst) { burst = maxBurst; } else { burst = 0; } if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() >= 0) { obj.overallBucket.setCapacity(newConf.getMaxBurst()); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); } else if (oldConf.getOverallBandwidth() >= 0 && newConf.getOverallBandwidth() < 0) { // TODO migrate waiting threads on overallBucket // to a/v buckets obj.overallBucket = null; obj.audioBucket = new TokenBucket(burst); obj.audioBucket.setCapacity(maxBurst); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket = new TokenBucket(burst); obj.videoBucket.setCapacity(maxBurst); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); obj.audioWrapper.wrapped = obj.audioBucket; obj.videoWrapper.wrapped = obj.videoBucket; } else if (oldConf.getOverallBandwidth() < 0 && newConf.getOverallBandwidth() >= 0) { // TODO migrate waiting threads on a/v buckets // to overallBucket obj.audioBucket = null; obj.videoBucket = null; obj.overallBucket = new TokenBucket(burst); obj.overallBucket.setCapacity(maxBurst); obj.overallBucket.setSpeed(bps2Bpms(newConf.getOverallBandwidth())); obj.audioWrapper.wrapped = obj.overallBucket; obj.videoWrapper.wrapped = obj.overallBucket; } else { obj.audioBucket.setCapacity(newConf.getMaxBurst()); obj.audioBucket.setSpeed(bps2Bpms(newConf.getAudioBandwidth())); obj.videoBucket.setCapacity(newConf.getMaxBurst()); obj.videoBucket.setSpeed(bps2Bpms(newConf.getVideoBandwidth())); } obj.bwConfig = new SimpleBandwidthConfigure(newConf); } }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskActivationHistory.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskActivationHistory.java index f909ac67b..7756a58e4 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskActivationHistory.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskActivationHistory.java @@ -1,142 +1,142 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.views; import java.util.ArrayList; import java.util.List; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.monitor.core.InteractionEvent; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; /** * @author Ken Sueda (original prototype) * @author Wesley Coelho (Added persistent tasks) * @author Mik Kersten (hardening) * @author Rob Elves */ public class TaskActivationHistory { private List<AbstractTask> history = new ArrayList<AbstractTask>(); private int currentIndex = -1; /** * The number of tasks from the previous Eclipse session to load into the history at startup. (This is not the * maximum size of the history, which is currently unbounded) */ private static final int NUM_SAVED_HISTORY_ITEMS_TO_LOAD = 12; private boolean persistentHistoryLoaded = false; /** * Load in a number of saved history tasks from previous session. Should be called from constructor but * ContextManager doesn't seem to be able to provide activity history at that point * * @author Wesley Coelho */ public void loadPersistentHistory() { int tasksAdded = 0; history.clear(); for (int i = ContextCorePlugin.getContextManager().getActivityMetaContext().getInteractionHistory().size() - 1; i >= 0; i--) { AbstractTask prevTask = getHistoryTaskAt(i); if (prevTask != null && !history.contains(prevTask)) { // !isDuplicate(prevTask, i + 1)) { history.add(0, prevTask); currentIndex++; tasksAdded++; if (tasksAdded == NUM_SAVED_HISTORY_ITEMS_TO_LOAD) { break; } } } persistentHistoryLoaded = true; } /** * Returns the task corresponding to the interaction event history item at the specified position */ protected AbstractTask getHistoryTaskAt(int pos) { InteractionEvent event = ContextCorePlugin.getContextManager() .getActivityMetaContext() .getInteractionHistory() .get(pos); return TasksUiPlugin.getTaskListManager().getTaskList().getTask(event.getStructureHandle()); } public void addTask(AbstractTask task) { try { if (!persistentHistoryLoaded) { loadPersistentHistory(); persistentHistoryLoaded = true; } history.remove(task); history.add(task); currentIndex = history.size() - 1; } catch (RuntimeException e) { StatusHandler.fail(e, "could not add task to history", false); } } public AbstractTask getPreviousTask() { try { boolean active = false; for (AbstractTask task : history) { if (task.isActive()) { active = true; break; } } if (hasPrevious()) { - if ((currentIndex == 0 && !history.get(currentIndex).isActive()) || !active) { + if (currentIndex < history.size()-1 && ((currentIndex == 0 && !history.get(currentIndex).isActive()) || !active)) { return history.get(currentIndex); } else { return history.get(--currentIndex); } } else { return null; } } catch (RuntimeException e) { StatusHandler.fail(e, "could not get previous task from history", false); return null; } } public List<AbstractTask> getPreviousTasks() { return history; } public boolean hasPrevious() { try { if (!persistentHistoryLoaded) { loadPersistentHistory(); persistentHistoryLoaded = true; } return (currentIndex == 0 && !history.get(currentIndex).isActive()) || currentIndex > 0; } catch (RuntimeException e) { StatusHandler.fail(e, "could determine previous task", false); return false; } } public void clear() { try { history.clear(); currentIndex = -1; } catch (RuntimeException e) { StatusHandler.fail(e, "could not clear history", false); } } }
true
true
public AbstractTask getPreviousTask() { try { boolean active = false; for (AbstractTask task : history) { if (task.isActive()) { active = true; break; } } if (hasPrevious()) { if ((currentIndex == 0 && !history.get(currentIndex).isActive()) || !active) { return history.get(currentIndex); } else { return history.get(--currentIndex); } } else { return null; } } catch (RuntimeException e) { StatusHandler.fail(e, "could not get previous task from history", false); return null; } }
public AbstractTask getPreviousTask() { try { boolean active = false; for (AbstractTask task : history) { if (task.isActive()) { active = true; break; } } if (hasPrevious()) { if (currentIndex < history.size()-1 && ((currentIndex == 0 && !history.get(currentIndex).isActive()) || !active)) { return history.get(currentIndex); } else { return history.get(--currentIndex); } } else { return null; } } catch (RuntimeException e) { StatusHandler.fail(e, "could not get previous task from history", false); return null; } }
diff --git a/src/net/colar/netbeans/fan/FanUtilities.java b/src/net/colar/netbeans/fan/FanUtilities.java index 51fffa7..beff63d 100644 --- a/src/net/colar/netbeans/fan/FanUtilities.java +++ b/src/net/colar/netbeans/fan/FanUtilities.java @@ -1,102 +1,102 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.colar.netbeans.fan; import java.io.File; import java.util.StringTokenizer; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; /** * Generic utilities * @author thibautc */ public class FanUtilities { /** * Opens the given file in the editor. * @param newFile * @throws DataObjectNotFoundException */ public static void openFileInEditor(File newFile) throws DataObjectNotFoundException { FileObject fob = FileUtil.toFileObject(newFile); openFileInEditor(fob); } private static void openFileInEditor(FileObject fob) throws DataObjectNotFoundException { if (fob != null) { DataObject dob = DataObject.find(fob); OpenCookie oc = dob.getCookie(OpenCookie.class); if (oc != null) { oc.open(); } } } /** * Find a file object relative to a current fileobject. * @param fo * @param path * @return */ public static FileObject getRelativeFileObject(final FileObject fo, String relativePath) { - StringTokenizer st = new StringTokenizer(relativePath.replaceAll("\\","/"), "/"); + StringTokenizer st = new StringTokenizer(relativePath.replaceAll("\\\\","/"), "/"); // If fo is a file, we start from the parent folder FileObject curFile= fo.isFolder()?fo:fo.getParent(); // folow the relative path to try and find the requested file while ((curFile != null) && st.hasMoreTokens()) { String nameExt = st.nextToken(); // if "." do nothing. if( ! nameExt.equals(".")) { if(nameExt.equals("..")) curFile = curFile.getParent(); else curFile = curFile.getFileObject(nameExt); } } return curFile; } /** * Debug fileObject * @param fo */ public static void dumpFileObject(FileObject fo) { System.err.println("---- FileObject DUMP -----"); try { dumpFileObject(fo, ""); System.err.println("**---- FileObject root dump -----"); //dumpFileObject(fo.getFileSystem().getRoot(),"**"); } catch (Exception e) { e.printStackTrace(); } } private static void dumpFileObject(FileObject fo, String indent) throws Exception { System.err.println(indent + "toStr: " + fo.toString()); System.err.println(indent + "Name: " + fo.getNameExt()); System.err.println(indent + "Path: " + fo.getPath()); System.err.println(indent + "URL: " + fo.getURL()); FileObject[] children = fo.getChildren(); //indent+=" "; //for(int i=0;i!=children.length;i++) // dumpFileObject(children[i],indent); } }
true
true
public static FileObject getRelativeFileObject(final FileObject fo, String relativePath) { StringTokenizer st = new StringTokenizer(relativePath.replaceAll("\\","/"), "/"); // If fo is a file, we start from the parent folder FileObject curFile= fo.isFolder()?fo:fo.getParent(); // folow the relative path to try and find the requested file while ((curFile != null) && st.hasMoreTokens()) { String nameExt = st.nextToken(); // if "." do nothing. if( ! nameExt.equals(".")) { if(nameExt.equals("..")) curFile = curFile.getParent(); else curFile = curFile.getFileObject(nameExt); } } return curFile; }
public static FileObject getRelativeFileObject(final FileObject fo, String relativePath) { StringTokenizer st = new StringTokenizer(relativePath.replaceAll("\\\\","/"), "/"); // If fo is a file, we start from the parent folder FileObject curFile= fo.isFolder()?fo:fo.getParent(); // folow the relative path to try and find the requested file while ((curFile != null) && st.hasMoreTokens()) { String nameExt = st.nextToken(); // if "." do nothing. if( ! nameExt.equals(".")) { if(nameExt.equals("..")) curFile = curFile.getParent(); else curFile = curFile.getFileObject(nameExt); } } return curFile; }
diff --git a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextClearAction.java b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextClearAction.java index 9902c2595..0ff2f0c99 100644 --- a/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextClearAction.java +++ b/org.eclipse.mylyn.context.ui/src/org/eclipse/mylyn/internal/context/ui/actions/ContextClearAction.java @@ -1,61 +1,57 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.context.ui.actions; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.mylar.context.core.ContextCorePlugin; import org.eclipse.mylar.internal.tasks.ui.views.TaskListView; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import org.eclipse.ui.PlatformUI; /** * @author Mik Kersten */ public class ContextClearAction implements IViewActionDelegate { public static final String ID = "org.eclipse.mylar.ui.clear.context"; public void init(IViewPart view) { } public void run(IAction action) { ITask task = TaskListView.getFromActivePerspective().getSelectedTask(); if (task instanceof ITask) { boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), "Confirm clear context", "Clear context for the selected task?"); if (!deleteConfirmed) return; if (task.isActive()) { TasksUiPlugin.getTaskListManager().deactivateTask(task); ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); TasksUiPlugin.getTaskListManager().activateTask(task); } else { ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); } -// ContextCorePlugin.getContextManager().contextDeleted((task).getHandleIdentifier()); // ((Task)selectedObject).getContextPath()); -// ContextCorePlugin.getContextManager().contextActivated((task).getHandleIdentifier()); - // ((Task)selectedObject).getContextPath()); - TaskListView.getFromActivePerspective().getViewer().refresh(); } } public void selectionChanged(IAction action, ISelection selection) { } }
true
true
public void run(IAction action) { ITask task = TaskListView.getFromActivePerspective().getSelectedTask(); if (task instanceof ITask) { boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), "Confirm clear context", "Clear context for the selected task?"); if (!deleteConfirmed) return; if (task.isActive()) { TasksUiPlugin.getTaskListManager().deactivateTask(task); ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); TasksUiPlugin.getTaskListManager().activateTask(task); } else { ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); } // ContextCorePlugin.getContextManager().contextDeleted((task).getHandleIdentifier()); // ((Task)selectedObject).getContextPath()); // ContextCorePlugin.getContextManager().contextActivated((task).getHandleIdentifier()); // ((Task)selectedObject).getContextPath()); TaskListView.getFromActivePerspective().getViewer().refresh(); } }
public void run(IAction action) { ITask task = TaskListView.getFromActivePerspective().getSelectedTask(); if (task instanceof ITask) { boolean deleteConfirmed = MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(), "Confirm clear context", "Clear context for the selected task?"); if (!deleteConfirmed) return; if (task.isActive()) { TasksUiPlugin.getTaskListManager().deactivateTask(task); ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); TasksUiPlugin.getTaskListManager().activateTask(task); } else { ContextCorePlugin.getContextManager().deleteContext((task).getHandleIdentifier()); } } }
diff --git a/src/dk/itu/big_red/model/import_export/BigraphXMLImport.java b/src/dk/itu/big_red/model/import_export/BigraphXMLImport.java index d239c6af..4551bb99 100644 --- a/src/dk/itu/big_red/model/import_export/BigraphXMLImport.java +++ b/src/dk/itu/big_red/model/import_export/BigraphXMLImport.java @@ -1,184 +1,188 @@ package dk.itu.big_red.model.import_export; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.Path; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.SWT; import org.w3c.dom.Document; import org.w3c.dom.Element; import dk.itu.big_red.application.plugin.RedPlugin; import dk.itu.big_red.import_export.Import; import dk.itu.big_red.import_export.ImportFailedException; import dk.itu.big_red.model.Bigraph; import dk.itu.big_red.model.Container; import dk.itu.big_red.model.Control; import dk.itu.big_red.model.InnerName; import dk.itu.big_red.model.Layoutable; import dk.itu.big_red.model.Link; import dk.itu.big_red.model.Node; import dk.itu.big_red.model.Point; import dk.itu.big_red.model.Port; import dk.itu.big_red.model.assistants.AppearanceGenerator; import dk.itu.big_red.model.assistants.ModelFactory; import dk.itu.big_red.model.changes.Change; import dk.itu.big_red.model.changes.ChangeRejectedException; import dk.itu.big_red.model.changes.bigraph.BigraphChangeAddChild; import dk.itu.big_red.model.changes.bigraph.BigraphChangeConnect; import dk.itu.big_red.model.interfaces.internal.INameable; import dk.itu.big_red.util.DOM; import dk.itu.big_red.util.UI; import dk.itu.big_red.util.resources.Project; /** * XMLImport reads a XML document and produces a corresponding {@link Bigraph}. * @author alec * @see BigraphXMLExport * */ public class BigraphXMLImport extends Import<Bigraph> { private enum AppearanceStatus { NOTHING_YET, MANDATORY, FORBIDDEN } boolean warnedAboutLayouts = false; private AppearanceStatus as = AppearanceStatus.NOTHING_YET; @Override public Bigraph importObject() throws ImportFailedException { try { Document d = DOM.validate(DOM.parse(source), RedPlugin.getResource("schema/bigraph.xsd")); source.close(); return makeBigraph(d.getDocumentElement()); } catch (Exception e) { throw new ImportFailedException(e); } } private void applyChange(Change c) throws ImportFailedException { try { bigraph.tryApplyChange(c); } catch (ChangeRejectedException e) { throw new ImportFailedException(e); } } private Bigraph bigraph = null; private Bigraph makeBigraph(Element e) throws ImportFailedException { bigraph = new Bigraph(); String signaturePath = e.getAttribute("signature"); IFile sigFile = Project.findFileByPath(null, new Path(signaturePath)); SignatureXMLImport si = new SignatureXMLImport(); try { si.setInputStream(sigFile.getContents()); bigraph.setSignature(sigFile, si.importObject()); } catch (Exception ex) { throw new ImportFailedException(ex); } processContainer(e, bigraph); if (as == AppearanceStatus.FORBIDDEN) applyChange(bigraph.relayout()); return bigraph; } private Container processContainer(Element e, Container model) throws ImportFailedException { if (model instanceof INameable) ((INameable)model).setName(DOM.getAttributeNS(e, XMLNS.BIGRAPH, "name")); for (Element i : DOM.getChildElements(e)) addChild(model, i); return model; } private Link processLink(Element e, Link model) throws ImportFailedException { model.setName(DOM.getAttributeNS(e, XMLNS.BIGRAPH, "name")); return model; } private Point processPoint(Element e, Point model) throws ImportFailedException { String name = DOM.getAttributeNS(e, XMLNS.BIGRAPH, "name"), link = DOM.getAttributeNS(e, XMLNS.BIGRAPH, "link"); model.setName(name); applyChange( new BigraphChangeConnect(model, (Link)bigraph.getNamespaceManager().getObject(Link.class, link))); return model; } private void addChild(Container context, Element e) throws ImportFailedException { Object model; if (!e.getNodeName().equals("node")) { model = ModelFactory.getNewObject(e.getNodeName()); } else { String controlName = DOM.getAttributeNS(e, XMLNS.BIGRAPH, "control"); Control c = bigraph.getSignature().getControl(controlName); + if (c == null) + throw new ImportFailedException( + "The control \"" + controlName + "\" isn't defined by " + + "this bigraph's signature."); model = new Node(c); } if (model instanceof Layoutable && context != null && !(model instanceof Port)) applyChange(new BigraphChangeAddChild(context, (Layoutable)model, new Rectangle())); boolean warn = false; Element el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "appearance"); switch (as) { case FORBIDDEN: warn = (el != null); break; case MANDATORY: warn = (el == null && !(model instanceof Port)); break; case NOTHING_YET: as = (el != null ? AppearanceStatus.MANDATORY : AppearanceStatus.FORBIDDEN); break; } if (warn && !warnedAboutLayouts) { UI.showMessageBox(SWT.ICON_WARNING, "All or nothing!", "Some objects in this bigraph have layout data, and some don't. " + "Big Red ignores layout data unless all objects have it."); as = AppearanceStatus.FORBIDDEN; warnedAboutLayouts = true; } if (el != null && as == AppearanceStatus.MANDATORY) { if (as == AppearanceStatus.NOTHING_YET) as = AppearanceStatus.MANDATORY; AppearanceGenerator.setAppearance(el, model); } if (model instanceof Container) { processContainer(e, (Container)model); } else if (model instanceof Port) { if (context instanceof Node) { Node n = (Node)context; for (Port p : n.getPorts()) { if (p.getName().equals(e.getAttribute("name"))) { processPoint(e, p); break; } } } } else if (model instanceof Link) { processLink(e, (Link)model); } else if (model instanceof InnerName) { processPoint(e, (InnerName)model); } else { /* fail in some other way? */; } } }
true
true
private void addChild(Container context, Element e) throws ImportFailedException { Object model; if (!e.getNodeName().equals("node")) { model = ModelFactory.getNewObject(e.getNodeName()); } else { String controlName = DOM.getAttributeNS(e, XMLNS.BIGRAPH, "control"); Control c = bigraph.getSignature().getControl(controlName); model = new Node(c); } if (model instanceof Layoutable && context != null && !(model instanceof Port)) applyChange(new BigraphChangeAddChild(context, (Layoutable)model, new Rectangle())); boolean warn = false; Element el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "appearance"); switch (as) { case FORBIDDEN: warn = (el != null); break; case MANDATORY: warn = (el == null && !(model instanceof Port)); break; case NOTHING_YET: as = (el != null ? AppearanceStatus.MANDATORY : AppearanceStatus.FORBIDDEN); break; } if (warn && !warnedAboutLayouts) { UI.showMessageBox(SWT.ICON_WARNING, "All or nothing!", "Some objects in this bigraph have layout data, and some don't. " + "Big Red ignores layout data unless all objects have it."); as = AppearanceStatus.FORBIDDEN; warnedAboutLayouts = true; } if (el != null && as == AppearanceStatus.MANDATORY) { if (as == AppearanceStatus.NOTHING_YET) as = AppearanceStatus.MANDATORY; AppearanceGenerator.setAppearance(el, model); } if (model instanceof Container) { processContainer(e, (Container)model); } else if (model instanceof Port) { if (context instanceof Node) { Node n = (Node)context; for (Port p : n.getPorts()) { if (p.getName().equals(e.getAttribute("name"))) { processPoint(e, p); break; } } } } else if (model instanceof Link) { processLink(e, (Link)model); } else if (model instanceof InnerName) { processPoint(e, (InnerName)model); } else { /* fail in some other way? */; } }
private void addChild(Container context, Element e) throws ImportFailedException { Object model; if (!e.getNodeName().equals("node")) { model = ModelFactory.getNewObject(e.getNodeName()); } else { String controlName = DOM.getAttributeNS(e, XMLNS.BIGRAPH, "control"); Control c = bigraph.getSignature().getControl(controlName); if (c == null) throw new ImportFailedException( "The control \"" + controlName + "\" isn't defined by " + "this bigraph's signature."); model = new Node(c); } if (model instanceof Layoutable && context != null && !(model instanceof Port)) applyChange(new BigraphChangeAddChild(context, (Layoutable)model, new Rectangle())); boolean warn = false; Element el = DOM.removeNamedChildElement(e, XMLNS.BIG_RED, "appearance"); switch (as) { case FORBIDDEN: warn = (el != null); break; case MANDATORY: warn = (el == null && !(model instanceof Port)); break; case NOTHING_YET: as = (el != null ? AppearanceStatus.MANDATORY : AppearanceStatus.FORBIDDEN); break; } if (warn && !warnedAboutLayouts) { UI.showMessageBox(SWT.ICON_WARNING, "All or nothing!", "Some objects in this bigraph have layout data, and some don't. " + "Big Red ignores layout data unless all objects have it."); as = AppearanceStatus.FORBIDDEN; warnedAboutLayouts = true; } if (el != null && as == AppearanceStatus.MANDATORY) { if (as == AppearanceStatus.NOTHING_YET) as = AppearanceStatus.MANDATORY; AppearanceGenerator.setAppearance(el, model); } if (model instanceof Container) { processContainer(e, (Container)model); } else if (model instanceof Port) { if (context instanceof Node) { Node n = (Node)context; for (Port p : n.getPorts()) { if (p.getName().equals(e.getAttribute("name"))) { processPoint(e, p); break; } } } } else if (model instanceof Link) { processLink(e, (Link)model); } else if (model instanceof InnerName) { processPoint(e, (InnerName)model); } else { /* fail in some other way? */; } }
diff --git a/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonProcess.java b/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonProcess.java index ef0ec58e..71d89e0f 100644 --- a/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonProcess.java +++ b/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonProcess.java @@ -1,746 +1,746 @@ /* * DaemonMainThread.java * * Copyright (C) 2013 IBR, TU Braunschweig * * Written-by: Dominik Schürmann <[email protected]> * Johannes Morgenroth <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package de.tubs.ibr.dtn.service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.wifi.WifiManager; import android.preference.PreferenceManager; import android.provider.Settings.Secure; import android.util.Log; import de.tubs.ibr.dtn.DaemonState; import de.tubs.ibr.dtn.api.Node; import de.tubs.ibr.dtn.api.SingletonEndpoint; import de.tubs.ibr.dtn.swig.DaemonRunLevel; import de.tubs.ibr.dtn.swig.NativeDaemon; import de.tubs.ibr.dtn.swig.NativeDaemonCallback; import de.tubs.ibr.dtn.swig.NativeDaemonException; import de.tubs.ibr.dtn.swig.NativeEventCallback; import de.tubs.ibr.dtn.swig.NativeNode; import de.tubs.ibr.dtn.swig.NativeStats; import de.tubs.ibr.dtn.swig.StringVec; public class DaemonProcess { private final static String TAG = "DaemonProcess"; private NativeDaemon mDaemon = null; private DaemonProcessHandler mHandler = null; private Context mContext = null; private DaemonState _state = DaemonState.OFFLINE; private WifiManager.MulticastLock _mcast_lock = null; private final static String GNUSTL_NAME = "gnustl_shared"; private final static String CRYPTO_NAME = "crypto"; private final static String SSL_NAME = "ssl"; private final static String IBRCOMMON_NAME = "ibrcommon"; private final static String IBRDTN_NAME = "ibrdtn"; private final static String DTND_NAME = "dtnd"; private final static String ANDROID_GLUE_NAME = "android-glue"; // CloudUplink Parameter private static final SingletonEndpoint __CLOUD_EID__ = new SingletonEndpoint( "dtn://cloud.dtnbone.dtn"); private static final String __CLOUD_PROTOCOL__ = "tcp"; private static final String __CLOUD_ADDRESS__ = "134.169.35.130"; // quorra.ibr.cs.tu-bs.de"; private static final String __CLOUD_PORT__ = "4559"; public interface OnRestartListener { public void OnStop(); public void OnReloadConfiguration(); public void OnStart(); }; /** * Loads all shared libraries in the right order with System.loadLibrary() */ private static void loadLibraries() { try { System.loadLibrary(GNUSTL_NAME); System.loadLibrary(CRYPTO_NAME); System.loadLibrary(SSL_NAME); System.loadLibrary(IBRCOMMON_NAME); System.loadLibrary(IBRDTN_NAME); System.loadLibrary(DTND_NAME); System.loadLibrary(ANDROID_GLUE_NAME); } catch (UnsatisfiedLinkError e) { Log.e(TAG, "UnsatisfiedLinkError! Are you running special hardware?", e); } catch (Exception e) { Log.e(TAG, "Loading the libraries failed!", e); } } static { // load libraries on first use of this class loadLibraries(); } public DaemonProcess(Context context, DaemonProcessHandler handler) { this.mDaemon = new NativeDaemon(mDaemonCallback, mEventCallback); this.mContext = context; this.mHandler = handler; } public String[] getVersion() { StringVec version = mDaemon.getVersion(); return new String[] { version.get(0), version.get(1) }; } public synchronized NativeStats getStats() { return mDaemon.getStats(); } public synchronized List<Node> getNeighbors() { List<Node> ret = new LinkedList<Node>(); StringVec neighbors = mDaemon.getNeighbors(); for (int i = 0; i < neighbors.size(); i++) { String eid = neighbors.get(i); try { // get extended info NativeNode nn = mDaemon.getInfo(eid); Node n = new Node(); n.endpoint = new SingletonEndpoint(eid); n.type = nn.getType().toString(); ret.add(n); } catch (NativeDaemonException e) { } } return ret; } public synchronized void clearStorage() { mDaemon.clearStorage(); } public DaemonState getState() { return _state; } private void setState(DaemonState newState) { if (_state.equals(newState)) return; _state = newState; mHandler.onStateChanged(_state); } public synchronized void initiateConnection(String endpoint) { if (getState().equals(DaemonState.ONLINE)) { mDaemon.initiateConnection(endpoint); } } public synchronized void initialize() { // lower the thread priority android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); // get daemon preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.mContext); // listen to preference changes preferences.registerOnSharedPreferenceChangeListener(_pref_listener); // enable debug based on prefs int logLevel = Integer.valueOf(preferences.getString("log_options", "0")); int debugVerbosity = Integer.valueOf(preferences.getString("log_debug_verbosity", "0")); // disable debugging if the log level is lower than 3 if (logLevel < 3) debugVerbosity = 0; // set logging options mDaemon.setLogging("Core", logLevel); // set logfile options String logFilePath = null; if (preferences.getBoolean("log_enable_file", false)) { File logPath = DaemonStorageUtils.getStoragePath("logs"); if (logPath != null) { logPath.mkdirs(); Calendar cal = Calendar.getInstance(); String time = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.HOUR) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND); logFilePath = logPath.getPath() + File.separatorChar + "ibrdtn_" + time + ".log"; } } if (logFilePath != null) { // enable file logging mDaemon.setLogFile(logFilePath, logLevel); } else { // disable file logging mDaemon.setLogFile("", 0); } // set debug verbosity mDaemon.setDebug(debugVerbosity); // initialize daemon configuration onConfigurationChanged(); try { mDaemon.init(DaemonRunLevel.RUNLEVEL_API); } catch (NativeDaemonException e) { Log.e(TAG, "error while initializing the daemon process", e); } } public synchronized void start() { WifiManager wifi_manager = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE); // listen to multicast packets _mcast_lock = wifi_manager.createMulticastLock(TAG); _mcast_lock.acquire(); // reload daemon configuration onConfigurationChanged(); try { mDaemon.init(DaemonRunLevel.RUNLEVEL_ROUTING_EXTENSIONS); } catch (NativeDaemonException e) { Log.e(TAG, "error while starting the daemon process", e); } } public synchronized void stop() { // stop the running daemon try { mDaemon.init(DaemonRunLevel.RUNLEVEL_API); } catch (NativeDaemonException e) { Log.e(TAG, "error while stopping the daemon process", e); } // release multicast lock if (_mcast_lock != null) { _mcast_lock.release(); _mcast_lock = null; } } public synchronized void restart(Integer runlevel, OnRestartListener listener) { // restart the daemon DaemonRunLevel restore = mDaemon.getRunLevel(); DaemonRunLevel rl = DaemonRunLevel.swigToEnum(runlevel); // do not restart if the current runlevel is below or equal if (restore.swigValue() <= rl.swigValue()) { // reload configuration onConfigurationChanged(); if (listener != null) listener.OnReloadConfiguration(); } try { // bring the daemon down mDaemon.init(rl); if (listener != null) listener.OnStop(); // reload configuration onConfigurationChanged(); if (listener != null) listener.OnReloadConfiguration(); // restore the old runlevel mDaemon.init(restore); if (listener != null) listener.OnStart(); } catch (NativeDaemonException e) { Log.e(TAG, "error while restarting the daemon process", e); } } public synchronized void destroy() { // get daemon preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.mContext); // unlisten to preference changes preferences.unregisterOnSharedPreferenceChangeListener(_pref_listener); // stop the running daemon try { mDaemon.init(DaemonRunLevel.RUNLEVEL_ZERO); } catch (NativeDaemonException e) { Log.e(TAG, "error while destroying the daemon process", e); } } final HashMap<String, DaemonRunLevel> mRestartMap = initializeRestartMap(); private HashMap<String, DaemonRunLevel> initializeRestartMap() { HashMap<String, DaemonRunLevel> ret = new HashMap<String, DaemonRunLevel>(); ret.put("endpoint_id", DaemonRunLevel.RUNLEVEL_CORE); ret.put("routing", DaemonRunLevel.RUNLEVEL_ROUTING_EXTENSIONS); ret.put("interface_", DaemonRunLevel.RUNLEVEL_NETWORK); ret.put("discovery_announce", DaemonRunLevel.RUNLEVEL_NETWORK); ret.put("checkIdleTimeout", DaemonRunLevel.RUNLEVEL_NETWORK); ret.put("checkFragmentation", DaemonRunLevel.RUNLEVEL_NETWORK); ret.put("timesync_mode", DaemonRunLevel.RUNLEVEL_API); ret.put("storage_mode", DaemonRunLevel.RUNLEVEL_CORE); ret.put("cloud_uplink_3g", DaemonRunLevel.RUNLEVEL_NETWORK); return ret; } final HashSet<String> mConfigurationSet = initializeConfigurationSet(); private HashSet<String> initializeConfigurationSet() { HashSet<String> ret = new HashSet<String>(); ret.add("constrains_lifetime"); ret.add("constrains_timestamp"); ret.add("security_mode"); ret.add("security_bab_key"); ret.add("log_options"); ret.add("log_debug_verbosity"); ret.add("log_enable_file"); ret.add("storage_mode"); return ret; } private SharedPreferences.OnSharedPreferenceChangeListener _pref_listener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { Log.d(TAG, "Preferences has changed " + key); if (mRestartMap.containsKey(key)) { // check runlevel and restart some runlevels if necessary final Intent intent = new Intent(DaemonProcess.this.mContext, DaemonService.class); intent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_RESTART); intent.putExtra("runlevel", mRestartMap.get(key).swigValue() - 1); DaemonProcess.this.mContext.startService(intent); } else if (key.equals("enabledSwitch")) { if (prefs.getBoolean(key, false)) { // startup the daemon process final Intent intent = new Intent(DaemonProcess.this.mContext, DaemonService.class); intent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_STARTUP); DaemonProcess.this.mContext.startService(intent); } else { // shutdown the daemon final Intent intent = new Intent(DaemonProcess.this.mContext, DaemonService.class); intent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_SHUTDOWN); DaemonProcess.this.mContext.startService(intent); } } else if (key.startsWith("interface_")) { // a interface has been removed or added // check runlevel and restart some runlevels if necessary final Intent intent = new Intent(DaemonProcess.this.mContext, DaemonService.class); intent.setAction(de.tubs.ibr.dtn.service.DaemonService.ACTION_RESTART); intent.putExtra("runlevel", mRestartMap.get("interface_").swigValue() - 1); DaemonProcess.this.mContext.startService(intent); } else if (key.equals("cloud_uplink")) { Log.d(TAG, key + " == " + String.valueOf( prefs.getBoolean(key, false) )); synchronized(DaemonProcess.this) { if (prefs.getBoolean(key, false)) { mDaemon.addConnection(__CLOUD_EID__.toString(), __CLOUD_PROTOCOL__, __CLOUD_ADDRESS__, __CLOUD_PORT__); } else { mDaemon.removeConnection(__CLOUD_EID__.toString(), __CLOUD_PROTOCOL__, __CLOUD_ADDRESS__, __CLOUD_PORT__); } } } else if (key.startsWith("log_options")) { Log.d(TAG, key + " == " + prefs.getString(key, "<not set>")); int logLevel = Integer.valueOf(prefs.getString("log_options", "0")); int debugVerbosity = Integer.valueOf(prefs.getString("log_debug_verbosity", "0")); // disable debugging if the log level is lower than 3 if (logLevel < 3) debugVerbosity = 0; synchronized(DaemonProcess.this) { // set logging options mDaemon.setLogging("Core", logLevel); // set debug verbosity mDaemon.setDebug( debugVerbosity ); } } else if (key.startsWith("log_debug_verbosity")) { Log.d(TAG, key + " == " + prefs.getString(key, "<not set>")); int logLevel = Integer.valueOf(prefs.getString("log_options", "0")); int debugVerbosity = Integer.valueOf(prefs.getString("log_debug_verbosity", "0")); // disable debugging if the log level is lower than 3 if (logLevel < 3) debugVerbosity = 0; synchronized(DaemonProcess.this) { // set debug verbosity mDaemon.setDebug( debugVerbosity ); } } else if (key.startsWith("log_enable_file")) { Log.d(TAG, key + " == " + prefs.getBoolean(key, false)); // set logfile options String logFilePath = null; if (prefs.getBoolean("log_enable_file", false)) { File logPath = DaemonStorageUtils.getStoragePath("logs"); if (logPath != null) { logPath.mkdirs(); Calendar cal = Calendar.getInstance(); String time = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.DAY_OF_MONTH) + cal.get(Calendar.HOUR) + cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND); logFilePath = logPath.getPath() + File.separatorChar + "ibrdtn_" + time + ".log"; } } synchronized(DaemonProcess.this) { if (logFilePath != null) { int logLevel = Integer.valueOf(prefs.getString("log_options", "0")); // enable file logging mDaemon.setLogFile(logFilePath, logLevel); } else { // disable file logging mDaemon.setLogFile("", 0); } } } else if (mConfigurationSet.contains(key)) { // default action onConfigurationChanged(); } } }; private void onConfigurationChanged() { String configPath = mContext.getFilesDir().getPath() + "/" + "config"; // create configuration file createConfig(mContext, configPath); // set configuration file mDaemon.setConfigFile(configPath); } private NativeEventCallback mEventCallback = new NativeEventCallback() { @Override public void eventRaised(String eventName, String action, StringVec data) { Intent event = new Intent(de.tubs.ibr.dtn.Intent.EVENT); Intent neighborIntent = null; event.addCategory(Intent.CATEGORY_DEFAULT); event.putExtra("name", eventName); if (eventName.equals("NodeEvent")) { neighborIntent = new Intent(de.tubs.ibr.dtn.Intent.NEIGHBOR); neighborIntent.addCategory(Intent.CATEGORY_DEFAULT); } // place the action into the intent if (action.length() > 0) { event.putExtra("action", action); if (neighborIntent != null) { neighborIntent.putExtra("action", action); } } // put all attributes into the intent for (int i = 0; i < data.size(); i++) { String entry = data.get(i); String entry_data[] = entry.split(": ", 2); // skip invalid entries if (entry_data.length < 2) continue; event.putExtra("attr:" + entry_data[0], entry_data[1]); if (neighborIntent != null) { neighborIntent.putExtra("attr:" + entry_data[0], entry_data[1]); } } // send event intent mHandler.onEvent(event); if (neighborIntent != null) { mHandler.onEvent(neighborIntent); mHandler.onNeighborhoodChanged(); } if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "EVENT intent broadcasted: " + eventName + "; Action: " + action); } } }; private NativeDaemonCallback mDaemonCallback = new NativeDaemonCallback() { @Override public void levelChanged(DaemonRunLevel level) { if (DaemonRunLevel.RUNLEVEL_ROUTING_EXTENSIONS.equals(level)) { // enable cloud-uplink SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DaemonProcess.this.mContext); if (prefs.getBoolean("cloud_uplink", false)) { mDaemon.addConnection(__CLOUD_EID__.toString(), __CLOUD_PROTOCOL__, __CLOUD_ADDRESS__, __CLOUD_PORT__); } setState(DaemonState.ONLINE); } else if (DaemonRunLevel.RUNLEVEL_API.equals(level)) { setState(DaemonState.OFFLINE); } } }; /** * Create Hex String from byte array * * @param data * @return */ private static String toHex(byte[] data) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < data.length; i++) hexString.append(Integer.toHexString(0xFF & data[i])); return hexString.toString(); } /** * Build unique endpoint id from Secure.ANDROID_ID * * @param context * @return */ public static SingletonEndpoint getUniqueEndpointID(Context context) { final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); byte[] digest = md.digest(androidId.getBytes()); return new SingletonEndpoint("dtn://android-" + toHex(digest).substring(4, 12) + ".dtn"); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "md5 not available"); } return new SingletonEndpoint("dtn://android-" + androidId.substring(4, 12) + ".dtn"); } /** * Creates config for dtnd in specified path * * @param context */ private void createConfig(Context context, String configPath) { // load preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); File config = new File(configPath); // remove old config file if (config.exists()) { config.delete(); } try { FileOutputStream writer = context.openFileOutput("config", Context.MODE_PRIVATE); // initialize default values if configured set already de.tubs.ibr.dtn.daemon.Preferences.initializeDefaultPreferences(context); // set EID PrintStream p = new PrintStream(writer); p.println("local_uri = " + preferences.getString("endpoint_id", getUniqueEndpointID(context).toString())); p.println("routing = " + preferences.getString("routing", "default")); // enable traffic stats p.println("stats_traffic = yes"); if (preferences.getBoolean("constrains_lifetime", false)) { p.println("limit_lifetime = 1209600"); } if (preferences.getBoolean("constrains_timestamp", false)) { p.println("limit_predated_timestamp = 1209600"); } // limit block size to 50 MB p.println("limit_blocksize = 250M"); p.println("limit_foreign_blocksize = 50M"); String secmode = preferences.getString("security_mode", "disabled"); if (!secmode.equals("disabled")) { File sec_folder = new File(context.getFilesDir().getPath() + "/bpsec"); if (!sec_folder.exists() || sec_folder.isDirectory()) { p.println("security_path = " + sec_folder.getPath()); } } if (secmode.equals("bab")) { // write default BAB key to file String bab_key = preferences.getString("security_bab_key", ""); File bab_file = new File(context.getFilesDir().getPath() + "/default-bab-key.mac"); // remove old key file if (bab_file.exists()) bab_file.delete(); FileOutputStream bab_output = context.openFileOutput("default-bab-key.mac", Context.MODE_PRIVATE); PrintStream bab_writer = new PrintStream(bab_output); bab_writer.print(bab_key); bab_writer.flush(); bab_writer.close(); if (bab_key.length() > 0) { // enable security extension: BAB p.println("security_level = 1"); // add BAB key to the configuration p.println("security_bab_default_key = " + bab_file.getPath()); } } String timesyncmode = preferences.getString("timesync_mode", "disabled"); if (timesyncmode.equals("master")) { p.println("time_reference = yes"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = no"); p.println("time_set_clock = no"); } else if (timesyncmode.equals("slave")) { p.println("time_reference = no"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = yes"); p.println("time_set_clock = no"); p.println("#time_sigma = 1.001"); p.println("#time_psi = 0.9"); p.println("#time_sync_level = 0.15"); } if (preferences.getBoolean("checkIdleTimeout", false)) { p.println("tcp_idle_timeout = 30"); } if (preferences.getBoolean("checkFragmentation", true)) { p.println("fragmentation = yes"); } // set multicast address for discovery p.println("discovery_address = ff02::142 224.0.0.142"); if (preferences.getBoolean("discovery_announce", true)) { p.println("discovery_announce = 1"); } else { p.println("discovery_announce = 0"); } String internet_ifaces = ""; String ifaces = ""; Map<String, ?> prefs = preferences.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (key.startsWith("interface_")) { if (entry.getValue() instanceof Boolean) { if ((Boolean) entry.getValue()) { String iface = key.substring(10, key.length()); ifaces = ifaces + " " + iface; p.println("net_" + iface + "_type = tcp"); p.println("net_" + iface + "_interface = " + iface); p.println("net_" + iface + "_port = 4556"); internet_ifaces += iface + " "; } } } } p.println("net_interfaces = " + ifaces); if (!preferences.getBoolean("cloud_uplink_3g", false)) { p.println("net_internet = " + internet_ifaces); } - String storage_mode = preferences.getString( "storage_mode", "disk-persistant" ); - if ("disk".equals( storage_mode ) || "disk-persistant".equals( storage_mode )) { + String storage_mode = preferences.getString( "storage_mode", "disk-persistent" ); + if ("disk".equals( storage_mode ) || "disk-persistent".equals( storage_mode )) { // storage path File blobPath = DaemonStorageUtils.getStoragePath("blob"); if (blobPath != null) { p.println("blob_path = " + blobPath.getPath()); // flush storage path File[] files = blobPath.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } } - if ("disk-persistant".equals( storage_mode )) { + if ("disk-persistent".equals( storage_mode )) { File bundlePath = DaemonStorageUtils.getStoragePath("bundles"); if (bundlePath != null) { p.println("storage_path = " + bundlePath.getPath()); } } // enable interface rebind p.println("net_rebind = yes"); // flush the write buffer p.flush(); // close the filehandle writer.close(); } catch (IOException e) { Log.e(TAG, "Problem writing config", e); } } }
false
true
private void createConfig(Context context, String configPath) { // load preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); File config = new File(configPath); // remove old config file if (config.exists()) { config.delete(); } try { FileOutputStream writer = context.openFileOutput("config", Context.MODE_PRIVATE); // initialize default values if configured set already de.tubs.ibr.dtn.daemon.Preferences.initializeDefaultPreferences(context); // set EID PrintStream p = new PrintStream(writer); p.println("local_uri = " + preferences.getString("endpoint_id", getUniqueEndpointID(context).toString())); p.println("routing = " + preferences.getString("routing", "default")); // enable traffic stats p.println("stats_traffic = yes"); if (preferences.getBoolean("constrains_lifetime", false)) { p.println("limit_lifetime = 1209600"); } if (preferences.getBoolean("constrains_timestamp", false)) { p.println("limit_predated_timestamp = 1209600"); } // limit block size to 50 MB p.println("limit_blocksize = 250M"); p.println("limit_foreign_blocksize = 50M"); String secmode = preferences.getString("security_mode", "disabled"); if (!secmode.equals("disabled")) { File sec_folder = new File(context.getFilesDir().getPath() + "/bpsec"); if (!sec_folder.exists() || sec_folder.isDirectory()) { p.println("security_path = " + sec_folder.getPath()); } } if (secmode.equals("bab")) { // write default BAB key to file String bab_key = preferences.getString("security_bab_key", ""); File bab_file = new File(context.getFilesDir().getPath() + "/default-bab-key.mac"); // remove old key file if (bab_file.exists()) bab_file.delete(); FileOutputStream bab_output = context.openFileOutput("default-bab-key.mac", Context.MODE_PRIVATE); PrintStream bab_writer = new PrintStream(bab_output); bab_writer.print(bab_key); bab_writer.flush(); bab_writer.close(); if (bab_key.length() > 0) { // enable security extension: BAB p.println("security_level = 1"); // add BAB key to the configuration p.println("security_bab_default_key = " + bab_file.getPath()); } } String timesyncmode = preferences.getString("timesync_mode", "disabled"); if (timesyncmode.equals("master")) { p.println("time_reference = yes"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = no"); p.println("time_set_clock = no"); } else if (timesyncmode.equals("slave")) { p.println("time_reference = no"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = yes"); p.println("time_set_clock = no"); p.println("#time_sigma = 1.001"); p.println("#time_psi = 0.9"); p.println("#time_sync_level = 0.15"); } if (preferences.getBoolean("checkIdleTimeout", false)) { p.println("tcp_idle_timeout = 30"); } if (preferences.getBoolean("checkFragmentation", true)) { p.println("fragmentation = yes"); } // set multicast address for discovery p.println("discovery_address = ff02::142 224.0.0.142"); if (preferences.getBoolean("discovery_announce", true)) { p.println("discovery_announce = 1"); } else { p.println("discovery_announce = 0"); } String internet_ifaces = ""; String ifaces = ""; Map<String, ?> prefs = preferences.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (key.startsWith("interface_")) { if (entry.getValue() instanceof Boolean) { if ((Boolean) entry.getValue()) { String iface = key.substring(10, key.length()); ifaces = ifaces + " " + iface; p.println("net_" + iface + "_type = tcp"); p.println("net_" + iface + "_interface = " + iface); p.println("net_" + iface + "_port = 4556"); internet_ifaces += iface + " "; } } } } p.println("net_interfaces = " + ifaces); if (!preferences.getBoolean("cloud_uplink_3g", false)) { p.println("net_internet = " + internet_ifaces); } String storage_mode = preferences.getString( "storage_mode", "disk-persistant" ); if ("disk".equals( storage_mode ) || "disk-persistant".equals( storage_mode )) { // storage path File blobPath = DaemonStorageUtils.getStoragePath("blob"); if (blobPath != null) { p.println("blob_path = " + blobPath.getPath()); // flush storage path File[] files = blobPath.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } } if ("disk-persistant".equals( storage_mode )) { File bundlePath = DaemonStorageUtils.getStoragePath("bundles"); if (bundlePath != null) { p.println("storage_path = " + bundlePath.getPath()); } } // enable interface rebind p.println("net_rebind = yes"); // flush the write buffer p.flush(); // close the filehandle writer.close(); } catch (IOException e) { Log.e(TAG, "Problem writing config", e); } }
private void createConfig(Context context, String configPath) { // load preferences SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); File config = new File(configPath); // remove old config file if (config.exists()) { config.delete(); } try { FileOutputStream writer = context.openFileOutput("config", Context.MODE_PRIVATE); // initialize default values if configured set already de.tubs.ibr.dtn.daemon.Preferences.initializeDefaultPreferences(context); // set EID PrintStream p = new PrintStream(writer); p.println("local_uri = " + preferences.getString("endpoint_id", getUniqueEndpointID(context).toString())); p.println("routing = " + preferences.getString("routing", "default")); // enable traffic stats p.println("stats_traffic = yes"); if (preferences.getBoolean("constrains_lifetime", false)) { p.println("limit_lifetime = 1209600"); } if (preferences.getBoolean("constrains_timestamp", false)) { p.println("limit_predated_timestamp = 1209600"); } // limit block size to 50 MB p.println("limit_blocksize = 250M"); p.println("limit_foreign_blocksize = 50M"); String secmode = preferences.getString("security_mode", "disabled"); if (!secmode.equals("disabled")) { File sec_folder = new File(context.getFilesDir().getPath() + "/bpsec"); if (!sec_folder.exists() || sec_folder.isDirectory()) { p.println("security_path = " + sec_folder.getPath()); } } if (secmode.equals("bab")) { // write default BAB key to file String bab_key = preferences.getString("security_bab_key", ""); File bab_file = new File(context.getFilesDir().getPath() + "/default-bab-key.mac"); // remove old key file if (bab_file.exists()) bab_file.delete(); FileOutputStream bab_output = context.openFileOutput("default-bab-key.mac", Context.MODE_PRIVATE); PrintStream bab_writer = new PrintStream(bab_output); bab_writer.print(bab_key); bab_writer.flush(); bab_writer.close(); if (bab_key.length() > 0) { // enable security extension: BAB p.println("security_level = 1"); // add BAB key to the configuration p.println("security_bab_default_key = " + bab_file.getPath()); } } String timesyncmode = preferences.getString("timesync_mode", "disabled"); if (timesyncmode.equals("master")) { p.println("time_reference = yes"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = no"); p.println("time_set_clock = no"); } else if (timesyncmode.equals("slave")) { p.println("time_reference = no"); p.println("time_discovery_announcements = yes"); p.println("time_synchronize = yes"); p.println("time_set_clock = no"); p.println("#time_sigma = 1.001"); p.println("#time_psi = 0.9"); p.println("#time_sync_level = 0.15"); } if (preferences.getBoolean("checkIdleTimeout", false)) { p.println("tcp_idle_timeout = 30"); } if (preferences.getBoolean("checkFragmentation", true)) { p.println("fragmentation = yes"); } // set multicast address for discovery p.println("discovery_address = ff02::142 224.0.0.142"); if (preferences.getBoolean("discovery_announce", true)) { p.println("discovery_announce = 1"); } else { p.println("discovery_announce = 0"); } String internet_ifaces = ""; String ifaces = ""; Map<String, ?> prefs = preferences.getAll(); for (Map.Entry<String, ?> entry : prefs.entrySet()) { String key = entry.getKey(); if (key.startsWith("interface_")) { if (entry.getValue() instanceof Boolean) { if ((Boolean) entry.getValue()) { String iface = key.substring(10, key.length()); ifaces = ifaces + " " + iface; p.println("net_" + iface + "_type = tcp"); p.println("net_" + iface + "_interface = " + iface); p.println("net_" + iface + "_port = 4556"); internet_ifaces += iface + " "; } } } } p.println("net_interfaces = " + ifaces); if (!preferences.getBoolean("cloud_uplink_3g", false)) { p.println("net_internet = " + internet_ifaces); } String storage_mode = preferences.getString( "storage_mode", "disk-persistent" ); if ("disk".equals( storage_mode ) || "disk-persistent".equals( storage_mode )) { // storage path File blobPath = DaemonStorageUtils.getStoragePath("blob"); if (blobPath != null) { p.println("blob_path = " + blobPath.getPath()); // flush storage path File[] files = blobPath.listFiles(); if (files != null) { for (File f : files) { f.delete(); } } } } if ("disk-persistent".equals( storage_mode )) { File bundlePath = DaemonStorageUtils.getStoragePath("bundles"); if (bundlePath != null) { p.println("storage_path = " + bundlePath.getPath()); } } // enable interface rebind p.println("net_rebind = yes"); // flush the write buffer p.flush(); // close the filehandle writer.close(); } catch (IOException e) { Log.e(TAG, "Problem writing config", e); } }
diff --git a/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java b/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java index bb19b20..c46b8be 100644 --- a/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java +++ b/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java @@ -1,536 +1,537 @@ /* * Copyright 2012 LinkedIn Corp. * * 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 azkaban.viewer.hdfs; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.AccessControlException; import org.apache.log4j.Logger; import azkaban.security.commons.HadoopSecurityManager; import azkaban.security.commons.HadoopSecurityManagerException; import azkaban.user.User; import azkaban.utils.Props; import azkaban.webapp.servlet.LoginAbstractAzkabanServlet; import azkaban.webapp.servlet.Page; import azkaban.webapp.session.Session; public class HdfsBrowserServlet extends LoginAbstractAzkabanServlet { private static final long serialVersionUID = 1L; private static final String PROXY_USER_SESSION_KEY = "hdfs.browser.proxy.user"; private static final String HADOOP_SECURITY_MANAGER_CLASS_PARAM = "hadoop.security.manager.class"; public static final int DEFAULT_START_LINE = 1; public static final int DEFAULT_END_LINE = 100; public static final int FILE_MAX_LINES = 100; private static Logger logger = Logger.getLogger(HdfsBrowserServlet.class); private ArrayList<HdfsFileViewer> viewers = new ArrayList<HdfsFileViewer>(); private HdfsFileViewer defaultViewer; private Props props; private boolean shouldProxy; private boolean allowGroupProxy; private String viewerName; private String viewerPath; private HadoopSecurityManager hadoopSecurityManager; public HdfsBrowserServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); viewerPath = props.getString("viewer.path"); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); shouldProxy = props.getBoolean("azkaban.should.proxy", false); allowGroupProxy = props.getBoolean("allow.group.proxy", false); logger.info("Hdfs browser should proxy: " + shouldProxy); props.put("fs.hdfs.impl.disable.cache", "true"); try { hadoopSecurityManager = loadHadoopSecurityManager(props, logger); } catch (RuntimeException e) { e.printStackTrace(); throw new RuntimeException("Failed to get hadoop security manager!" + e.getCause()); } defaultViewer = new TextFileViewer(); viewers.add(new AvroFileViewer()); viewers.add(new ParquetFileViewer()); viewers.add(new JsonSequenceFileViewer()); viewers.add(new ImageFileViewer()); viewers.add(new BsonFileViewer()); viewers.add(defaultViewer); logger.info("HDFS Browser initiated"); } private HadoopSecurityManager loadHadoopSecurityManager( Props props, Logger logger) throws RuntimeException { Class<?> hadoopSecurityManagerClass = props.getClass( HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, HdfsBrowserServlet.class.getClassLoader()); logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager) getInstanceMethod.invoke( hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause()); throw new RuntimeException(e.getCause()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getCause()); } return hadoopSecurityManager; } private FileSystem getFileSystem(String username) throws HadoopSecurityManagerException { return hadoopSecurityManager.getFSAsUser(username); } @Override protected void handleGet( HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { User user = session.getUser(); String username = user.getUserId(); if (hasParam(req, "action") && getParam(req, "action").equals("goHomeDir")) { username = getParam(req, "proxyname"); } else if (allowGroupProxy) { String proxyName = (String)session.getSessionData(PROXY_USER_SESSION_KEY); if (proxyName != null) { username = proxyName; } } FileSystem fs = null; try { fs = getFileSystem(username); try { if (hasParam(req, "ajax")) { handleAjaxAction(fs, username, req, resp, session); } else { handleFsDisplay(fs, username, req, resp, session); } } catch (IOException e) { throw e; } catch (ServletException se) { throw se; } catch (Exception ge) { throw ge; } finally { if(fs != null) { fs.close(); } } } catch (Exception e) { //e.printStackTrace(); Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("error_message", "Error: " + e.getMessage()); page.add("user", username); page.add("allowproxy", allowGroupProxy); page.add("no_fs", "true"); page.add("viewerName", viewerName); page.render(); } finally { if (fs != null) { fs.close(); } } } @Override protected void handlePost( HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { User user = session.getUser(); if (!hasParam(req, "action")) { return; } HashMap<String,String> results = new HashMap<String,String>(); String action = getParam(req, "action"); if (action.equals("changeProxyUser")) { if (hasParam(req, "proxyname")) { String newProxyname = getParam(req, "proxyname"); if (user.getUserId().equals(newProxyname) || user.isInGroup(newProxyname) || user.getRoles().contains("admin")) { session.setSessionData(PROXY_USER_SESSION_KEY, newProxyname); } else { results.put("error", "User '" + user.getUserId() + "' cannot proxy as '" + newProxyname + "'"); } } } else { results.put("error", "action param is not set"); } this.writeJSON(resp, results); } private void handleFsDisplay( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException, ServletException, IllegalArgumentException, IllegalStateException { String prefix = req.getContextPath() + req.getServletPath(); String fsPath = req.getRequestURI().substring(prefix.length()); Path path; if (fsPath.length() == 0) { fsPath = "/"; } path = new Path(fsPath); if (logger.isDebugEnabled()) logger.debug("path=" + path.toString()); if (!fs.exists(path)) { throw new IllegalArgumentException(path.toUri().getPath() + " does not exist."); } else if (fs.isFile(path)) { displayFilePage(fs, user, req, resp, session, path); } else if (fs.getFileStatus(path).isDir()) { displayDirPage(fs, user, req, resp, session, path); } else { throw new IllegalStateException( "It exists, it is not a file, and it is not a directory, what is it precious?"); } } private void displayDirPage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } try { FileStatus[] subdirs = fs.listStatus(path); page.add("subdirs", subdirs); long size = 0; for (int i = 0; i < subdirs.length; ++i) { if (subdirs[i].isDir()) { continue; } size += subdirs[i].getLen(); } page.add("dirsize", size); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read file or directory"); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); } private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); + page.add("path", path.toString()); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); } private void handleAjaxAction( FileSystem fs, String username, HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException { Map<String, Object> ret = new HashMap<String, Object>(); String ajaxName = getParam(request, "ajax"); Path path = null; if (!hasParam(request, "path")) { ret.put("error", "Missing parameter 'path'."); this.writeJSON(response, ret); return; } path = new Path(getParam(request, "path")); if (!fs.exists(path)) { ret.put("error", path.toUri().getPath() + " does not exist."); this.writeJSON(response, ret); return; } if (ajaxName.equals("fetchschema")) { handleAjaxFetchSchema(fs, request, ret, session, path); } else if (ajaxName.equals("fetchfile")) { handleAjaxFetchFile(fs, request, ret, session, path); } else { ret.put("error", "Unknown AJAX action " + ajaxName); } if (ret != null) { this.writeJSON(response, ret); } } private void handleAjaxFetchSchema( FileSystem fs, HttpServletRequest req, Map<String, Object> ret, Session session, Path path) throws IOException, ServletException { HdfsFileViewer fileViewer = null; if (hasParam(req, "viewerId")) { fileViewer = viewers.get(getIntParam(req, "viewerId")); if (!fileViewer.getCapabilities(fs, path).contains(Capability.SCHEMA)) { fileViewer = null; } } else { for (HdfsFileViewer viewer : viewers) { if (viewer.getCapabilities(fs, path).contains(Capability.SCHEMA)) { fileViewer = viewer; } } } if (fileViewer == null) { ret.put("error", "No viewers can display schema."); return; } ret.put("schema", fileViewer.getSchema(fs, path)); } private void handleAjaxFetchFile( FileSystem fs, HttpServletRequest req, Map<String, Object> ret, Session session, Path path) throws IOException, ServletException { int startLine = getIntParam(req, "startLine", DEFAULT_START_LINE); int endLine = getIntParam(req, "endLine", DEFAULT_END_LINE); if (endLine < startLine) { ret.put("error", "Invalid range: endLine < startLine."); return; } if (endLine - startLine > FILE_MAX_LINES) { ret.put("error", "Invalid range: range exceeds max number of lines."); return; } // use registered viewers to show the file content boolean outputed = false; ByteArrayOutputStream output = new ByteArrayOutputStream(); if (hasParam(req, "viewerId")) { HdfsFileViewer viewer = viewers.get(getIntParam(req, "viewerId")); if (viewer.getCapabilities(fs, path).contains(Capability.READ)) { viewer.displayFile(fs, path, output, startLine, endLine); outputed = true; } } for (HdfsFileViewer viewer : viewers) { if (viewer.getCapabilities(fs, path).contains(Capability.READ)) { viewer.displayFile(fs, path, output, startLine, endLine); outputed = true; break; // don't need to try other viewers } } // use default text viewer if (!outputed) { if (defaultViewer.getCapabilities(fs, path).contains(Capability.READ)) { defaultViewer.displayFile(fs, path, output, startLine, endLine); } else { ret.put("error", "Cannot retrieve file."); return; } } ret.put("chunk", output.toString()); } }
true
true
private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("path", path.toString()); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
diff --git a/ubticket/src/edu/ub/bda/ubticket/windows/ComprarEntradasWindow.java b/ubticket/src/edu/ub/bda/ubticket/windows/ComprarEntradasWindow.java index 06be6cd..c9672b8 100644 --- a/ubticket/src/edu/ub/bda/ubticket/windows/ComprarEntradasWindow.java +++ b/ubticket/src/edu/ub/bda/ubticket/windows/ComprarEntradasWindow.java @@ -1,275 +1,276 @@ package edu.ub.bda.ubticket.windows; import com.googlecode.lanterna.gui.Action; import com.googlecode.lanterna.gui.Border; import com.googlecode.lanterna.gui.Window; import com.googlecode.lanterna.gui.component.Button; import com.googlecode.lanterna.gui.component.Label; import com.googlecode.lanterna.gui.component.Panel; import com.googlecode.lanterna.gui.component.Table; import com.googlecode.lanterna.gui.component.TextBox; import com.googlecode.lanterna.gui.dialog.ListSelectDialog; import com.googlecode.lanterna.gui.dialog.MessageBox; import edu.ub.bda.UBTicket; import edu.ub.bda.ubticket.beans.Entrada; import edu.ub.bda.ubticket.beans.Espacio; import edu.ub.bda.ubticket.beans.Espectaculo; import edu.ub.bda.ubticket.beans.Sesion; import edu.ub.bda.ubticket.utils.AutenticacionServicio; import edu.ub.bda.ubticket.utils.HibernateTransaction; import java.util.Calendar; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Restrictions; /** * * @author olopezsa13 */ public class ComprarEntradasWindow extends Window { private final Button seleccionarEspacioButton; private final Espacio espacio = new Espacio(); private final UBTicket ubticket; private Panel tablaPanel; private Table tabla; private Label paginaEtiqueta; private Panel paginadorPanel; /* private final TextBox dia; private final TextBox mes; private final TextBox anyo; private final TextBox hora; private final TextBox minuto; */ private Integer maxFilas = 10; private Integer pagina = 0; private Integer maxPaginas = 0; public ComprarEntradasWindow(final UBTicket ubticket) { super("Comprar entradas"); this.ubticket = ubticket; Panel espacioPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); espacioPanel.addComponent(new Label(" Espacio seleccionado:")); seleccionarEspacioButton = new Button("Ninguno", new Action() { @Override public void doAction() { List<Espacio> espacios = new HibernateTransaction<List<Espacio>>() { @Override public List<Espacio> run() { /** * @TODO Hay que soportar listas paginadas de espacios */ Query query = session.createQuery("from Espacio"); return (List<Espacio>) query.list(); } }.execute(); Espacio[] vector = new Espacio[espacios.size()]; espacios.toArray(vector); Espacio esp = ListSelectDialog.showDialog(ubticket.getGUIScreen(), "ATENCIÓN", "Seleccione el espacio:", vector); if ( esp != null ) { + pagina = 0; espacio.copyFrom(esp); seleccionarEspacioButton.setText(esp.getNombre()); paginadorPanel.setVisible(true); actualizarTabla(); } } }); espacioPanel.addComponent(seleccionarEspacioButton); addComponent(espacioPanel); Calendar calendar = Calendar.getInstance(); /* Panel diasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label(" DIA: ")); diasPanel.addComponent(dia = new TextBox(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(mes = new TextBox(Integer.toString(calendar.get(Calendar.MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(anyo = new TextBox(Integer.toString(calendar.get(Calendar.YEAR)), 5)); addComponent(diasPanel); Panel horasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label("HORA: ")); diasPanel.addComponent(hora = new TextBox(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2)); diasPanel.addComponent(new Label(":")); diasPanel.addComponent(minuto = new TextBox(Integer.toString(calendar.get(Calendar.MINUTE)), 2)); addComponent(horasPanel); */ tablaPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); addComponent(tablaPanel); paginadorPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); paginadorPanel.setVisible(false); paginadorPanel.addComponent(new Button("<--", new Action() { @Override public void doAction() { if ( pagina > 0 ) { pagina--; actualizarTabla(); } } })); paginaEtiqueta = new Label(); paginaEtiqueta.setText(getTextoPagina()); paginadorPanel.addComponent(paginaEtiqueta); paginadorPanel.addComponent(new Button("-->", new Action() { @Override public void doAction() { if ( ( pagina + 1 ) < maxPaginas ) { pagina++; actualizarTabla(); } } })); addComponent(paginadorPanel); addComponent(new Button("Cancelar", new Action() { @Override public void doAction() { close(); } })); } @Override public void onVisible() { this.setFocus(seleccionarEspacioButton); } private void actualizarTabla() { actualizarPagina(); List<Sesion> list = new HibernateTransaction<List<Sesion>>() { @Override public List<Sesion> run() { Criteria query = session.createCriteria(Sesion.class) .add(Restrictions.eq("espacio", espacio)); query.setFirstResult(pagina * maxFilas); query.setMaxResults(maxFilas); return query.list(); } }.execute(); if ( list != null && list.size() > 0 ) { boolean addComponent = false; if ( tabla == null ) { tabla = new Table(4, "Espectáculos"); addComponent = true; } else { tabla.removeAllRows(); } for ( Sesion sesion : list ) { Espectaculo o = sesion.getEspectaculo(); tabla.addRow(new Label(o.getTitulo()), new Label(o.getCategoria().getNombre()), new Label(sesion.getFecha_inicio().toString()), new Button("Comprar por " + sesion.getPrecio().toString() + "€", new ComprarEntradaAction(ubticket, sesion))); } if ( addComponent ) { tablaPanel.addComponent(tabla); } } } private String getTextoPagina() { Integer pag = pagina + 1; return pag.toString() + " / " + maxPaginas.toString(); } private void actualizarPagina() { Integer numFilas = new HibernateTransaction<Integer>() { @Override public Integer run() { Query query = session.createSQLQuery("SELECT COUNT(*) FROM SESION WHERE ESPACIO_ID = :espacio_id"); query.setInteger("espacio_id", espacio.getId()); return (Integer) query.list().get(0); } }.execute(); Double maxPaginasFP = numFilas.doubleValue() / maxFilas.doubleValue(); maxPaginas = (int) Math.ceil(maxPaginasFP.doubleValue()); paginaEtiqueta.setText(getTextoPagina()); } private class ComprarEntradaAction implements Action { private Sesion sesion; private UBTicket ubticket; public ComprarEntradaAction(UBTicket ubticket, Sesion sesion) { this.sesion = sesion; this.ubticket = ubticket; } @Override public void doAction() { new HibernateTransaction() { @Override public Object run() { Entrada entrada = new Entrada(); entrada.setSesion(sesion); entrada.setUsuario(AutenticacionServicio.GetUsuario()); session.saveOrUpdate(entrada); return null; } }.execute(); MessageBox.showMessageBox(ubticket.getGUIScreen(), "ATENCIÓN", "Ha comprado una entrada de '" + sesion.getEspectaculo().getTitulo() + "'."); } } }
true
true
public ComprarEntradasWindow(final UBTicket ubticket) { super("Comprar entradas"); this.ubticket = ubticket; Panel espacioPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); espacioPanel.addComponent(new Label(" Espacio seleccionado:")); seleccionarEspacioButton = new Button("Ninguno", new Action() { @Override public void doAction() { List<Espacio> espacios = new HibernateTransaction<List<Espacio>>() { @Override public List<Espacio> run() { /** * @TODO Hay que soportar listas paginadas de espacios */ Query query = session.createQuery("from Espacio"); return (List<Espacio>) query.list(); } }.execute(); Espacio[] vector = new Espacio[espacios.size()]; espacios.toArray(vector); Espacio esp = ListSelectDialog.showDialog(ubticket.getGUIScreen(), "ATENCIÓN", "Seleccione el espacio:", vector); if ( esp != null ) { espacio.copyFrom(esp); seleccionarEspacioButton.setText(esp.getNombre()); paginadorPanel.setVisible(true); actualizarTabla(); } } }); espacioPanel.addComponent(seleccionarEspacioButton); addComponent(espacioPanel); Calendar calendar = Calendar.getInstance(); /* Panel diasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label(" DIA: ")); diasPanel.addComponent(dia = new TextBox(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(mes = new TextBox(Integer.toString(calendar.get(Calendar.MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(anyo = new TextBox(Integer.toString(calendar.get(Calendar.YEAR)), 5)); addComponent(diasPanel); Panel horasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label("HORA: ")); diasPanel.addComponent(hora = new TextBox(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2)); diasPanel.addComponent(new Label(":")); diasPanel.addComponent(minuto = new TextBox(Integer.toString(calendar.get(Calendar.MINUTE)), 2)); addComponent(horasPanel); */ tablaPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); addComponent(tablaPanel); paginadorPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); paginadorPanel.setVisible(false); paginadorPanel.addComponent(new Button("<--", new Action() { @Override public void doAction() { if ( pagina > 0 ) { pagina--; actualizarTabla(); } } })); paginaEtiqueta = new Label(); paginaEtiqueta.setText(getTextoPagina()); paginadorPanel.addComponent(paginaEtiqueta); paginadorPanel.addComponent(new Button("-->", new Action() { @Override public void doAction() { if ( ( pagina + 1 ) < maxPaginas ) { pagina++; actualizarTabla(); } } })); addComponent(paginadorPanel); addComponent(new Button("Cancelar", new Action() { @Override public void doAction() { close(); } })); }
public ComprarEntradasWindow(final UBTicket ubticket) { super("Comprar entradas"); this.ubticket = ubticket; Panel espacioPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); espacioPanel.addComponent(new Label(" Espacio seleccionado:")); seleccionarEspacioButton = new Button("Ninguno", new Action() { @Override public void doAction() { List<Espacio> espacios = new HibernateTransaction<List<Espacio>>() { @Override public List<Espacio> run() { /** * @TODO Hay que soportar listas paginadas de espacios */ Query query = session.createQuery("from Espacio"); return (List<Espacio>) query.list(); } }.execute(); Espacio[] vector = new Espacio[espacios.size()]; espacios.toArray(vector); Espacio esp = ListSelectDialog.showDialog(ubticket.getGUIScreen(), "ATENCIÓN", "Seleccione el espacio:", vector); if ( esp != null ) { pagina = 0; espacio.copyFrom(esp); seleccionarEspacioButton.setText(esp.getNombre()); paginadorPanel.setVisible(true); actualizarTabla(); } } }); espacioPanel.addComponent(seleccionarEspacioButton); addComponent(espacioPanel); Calendar calendar = Calendar.getInstance(); /* Panel diasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label(" DIA: ")); diasPanel.addComponent(dia = new TextBox(Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(mes = new TextBox(Integer.toString(calendar.get(Calendar.MONTH)), 3)); diasPanel.addComponent(new Label("/")); diasPanel.addComponent(anyo = new TextBox(Integer.toString(calendar.get(Calendar.YEAR)), 5)); addComponent(diasPanel); Panel horasPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); diasPanel.addComponent(new Label("HORA: ")); diasPanel.addComponent(hora = new TextBox(Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)), 2)); diasPanel.addComponent(new Label(":")); diasPanel.addComponent(minuto = new TextBox(Integer.toString(calendar.get(Calendar.MINUTE)), 2)); addComponent(horasPanel); */ tablaPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); addComponent(tablaPanel); paginadorPanel = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL); paginadorPanel.setVisible(false); paginadorPanel.addComponent(new Button("<--", new Action() { @Override public void doAction() { if ( pagina > 0 ) { pagina--; actualizarTabla(); } } })); paginaEtiqueta = new Label(); paginaEtiqueta.setText(getTextoPagina()); paginadorPanel.addComponent(paginaEtiqueta); paginadorPanel.addComponent(new Button("-->", new Action() { @Override public void doAction() { if ( ( pagina + 1 ) < maxPaginas ) { pagina++; actualizarTabla(); } } })); addComponent(paginadorPanel); addComponent(new Button("Cancelar", new Action() { @Override public void doAction() { close(); } })); }
diff --git a/src/main/java/hudson/plugins/jira/JiraProjectProperty.java b/src/main/java/hudson/plugins/jira/JiraProjectProperty.java index 265e0e5..80d5fb1 100644 --- a/src/main/java/hudson/plugins/jira/JiraProjectProperty.java +++ b/src/main/java/hudson/plugins/jira/JiraProjectProperty.java @@ -1,133 +1,135 @@ package hudson.plugins.jira; import hudson.Extension; import hudson.model.AbstractProject; import hudson.model.Job; import hudson.model.JobProperty; import hudson.model.JobPropertyDescriptor; import hudson.util.CopyOnWriteList; import net.sf.json.JSONObject; import org.apache.commons.beanutils.Converter; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import java.net.MalformedURLException; import java.net.URL; import java.util.logging.Logger; /** * Associates {@link AbstractProject} with {@link JiraSite}. * * @author Kohsuke Kawaguchi */ public class JiraProjectProperty extends JobProperty<AbstractProject<?, ?>> { /** * Used to find {@link JiraSite}. Matches {@link JiraSite#getName()}. Always * non-null (but beware that this value might become stale if the system * config is changed.) */ public final String siteName; @DataBoundConstructor public JiraProjectProperty(String siteName) { if (siteName == null) { // defaults to the first one JiraSite[] sites = DESCRIPTOR.getSites(); if (sites.length > 0) siteName = sites[0].getName(); } this.siteName = siteName; } /** * Gets the {@link JiraSite} that this project belongs to. * * @return null if the configuration becomes out of sync. */ public JiraSite getSite() { JiraSite[] sites = DESCRIPTOR.getSites(); if (siteName == null && sites.length > 0) // default return sites[0]; for (JiraSite site : sites) { if (site.getName().equals(siteName)) return site; } return null; } @Override public DescriptorImpl getDescriptor() { return DESCRIPTOR; } @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public static final class DescriptorImpl extends JobPropertyDescriptor { private final CopyOnWriteList<JiraSite> sites = new CopyOnWriteList<JiraSite>(); public DescriptorImpl() { super(JiraProjectProperty.class); load(); } @Override @SuppressWarnings("unchecked") public boolean isApplicable(Class<? extends Job> jobType) { return AbstractProject.class.isAssignableFrom(jobType); } @Override public String getDisplayName() { return Messages.JiraProjectProperty_DisplayName(); } public void setSites(JiraSite site) { sites.add(site); } public JiraSite[] getSites() { return sites.toArray(new JiraSite[0]); } @Override public JobProperty<?> newInstance(StaplerRequest req, JSONObject formData) throws FormException { JiraProjectProperty jpp = req.bindParameters( JiraProjectProperty.class, "jira."); if (jpp.siteName == null) jpp = null; // not configured return jpp; } @Override public boolean configure(StaplerRequest req, JSONObject formData) { //Fix^H^H^HDirty hack for empty string to URL conversion error + //Should check for existing handler etc, but since this is a dirty hack, + //we won't Stapler.CONVERT_UTILS.deregister(java.net.URL.class); Converter tmpUrlConverter = new Converter() { public Object convert(Class aClass, Object o) { if(o == null || "".equals(o) || "null".equals(o)) return null; try { return new URL((String) o); } catch (MalformedURLException e) { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + LOGGER.warning(String.format("%s is not a valid URL.", o.toString())); return null; } } }; Stapler.CONVERT_UTILS.register(tmpUrlConverter, java.net.URL.class); //End hack sites.replaceBy(req.bindJSONToList(JiraSite.class, formData.get("sites"))); save(); return true; } } private static final Logger LOGGER = Logger .getLogger(JiraProjectProperty.class.getName()); }
false
true
public boolean configure(StaplerRequest req, JSONObject formData) { //Fix^H^H^HDirty hack for empty string to URL conversion error Stapler.CONVERT_UTILS.deregister(java.net.URL.class); Converter tmpUrlConverter = new Converter() { public Object convert(Class aClass, Object o) { if(o == null || "".equals(o) || "null".equals(o)) return null; try { return new URL((String) o); } catch (MalformedURLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } } }; Stapler.CONVERT_UTILS.register(tmpUrlConverter, java.net.URL.class); //End hack sites.replaceBy(req.bindJSONToList(JiraSite.class, formData.get("sites"))); save(); return true; }
public boolean configure(StaplerRequest req, JSONObject formData) { //Fix^H^H^HDirty hack for empty string to URL conversion error //Should check for existing handler etc, but since this is a dirty hack, //we won't Stapler.CONVERT_UTILS.deregister(java.net.URL.class); Converter tmpUrlConverter = new Converter() { public Object convert(Class aClass, Object o) { if(o == null || "".equals(o) || "null".equals(o)) return null; try { return new URL((String) o); } catch (MalformedURLException e) { LOGGER.warning(String.format("%s is not a valid URL.", o.toString())); return null; } } }; Stapler.CONVERT_UTILS.register(tmpUrlConverter, java.net.URL.class); //End hack sites.replaceBy(req.bindJSONToList(JiraSite.class, formData.get("sites"))); save(); return true; }
diff --git a/src/plugins/Library/ui/MainPageToadlet.java b/src/plugins/Library/ui/MainPageToadlet.java index 610a5e5..00c897a 100644 --- a/src/plugins/Library/ui/MainPageToadlet.java +++ b/src/plugins/Library/ui/MainPageToadlet.java @@ -1,135 +1,135 @@ /* 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.Library.ui; import plugins.Library.Library; import freenet.client.HighLevelSimpleClient; import freenet.clients.http.PageNode; import freenet.clients.http.RedirectException; import freenet.clients.http.Toadlet; import freenet.clients.http.ToadletContext; import freenet.clients.http.ToadletContextClosedException; import freenet.node.NodeClientCore; import freenet.pluginmanager.PluginRespirator; import freenet.support.HTMLNode; import freenet.support.Logger; import freenet.support.MultiValueTable; import freenet.support.api.HTTPRequest; import java.io.IOException; import java.net.URI; import java.util.Collection; /** * Encapsulates the MainPage in a Toadlet * @author MikeB */ public class MainPageToadlet extends Toadlet { private NodeClientCore core; private final Library library; private final PluginRespirator pr; public MainPageToadlet(HighLevelSimpleClient client, Library library, NodeClientCore core, PluginRespirator pr) { super(client); this.core = core; this.library = library; this.pr = pr; } public void handleMethodGET(URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Library.class.getClassLoader()); try { // process the request String title = Library.plugName; MainPage page = MainPage.processGetRequest(request); if(page == null) page = new MainPage(library, pr); else { String query = page.getQuery(); - if(query != null && !query.isEmpty()) + if(query != null && query.length() > 0) title = query + " - " + Library.plugName; } PageNode p = ctx.getPageMaker().getPageNode(title, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; MultiValueTable<String, String> headers = new MultiValueTable(); page.writeContent(contentNode, headers); // write reply writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } catch(RuntimeException e) { // this way isnt working particularly well, i think the ctx only gives out one page maker Logger.error(this, "Runtime Exception writing main page", e); PageNode p = ctx.getPageMaker().getPageNode(Library.plugName, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; MainPage errorpage = new MainPage(e, library, pr); MultiValueTable<String, String> headers = new MultiValueTable(); errorpage.writeContent(contentNode, headers); writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } finally { Thread.currentThread().setContextClassLoader(origClassLoader); } } public void handleMethodPOST(URI uri, HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Library.class.getClassLoader()); String formPassword = request.getPartAsString("formPassword", 32); try { // Get the nodes of the page PageNode p = ctx.getPageMaker().getPageNode(Library.plugName, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; MainPage page = MainPage.processPostRequest(request, contentNode, formPassword!=null && formPassword.equals(core.formPassword), library, pr); if(page==null) page = new MainPage(library,pr); // Process the request MultiValueTable<String, String> headers = new MultiValueTable(); // write reply page.writeContent(contentNode, headers); // write reply writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } catch(RuntimeException e) { Logger.error(this, "Runtime Exception writing main page", e); PageNode p = ctx.getPageMaker().getPageNode(Library.plugName, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; // makes a mainpage for showing errors MainPage errorpage = new MainPage(e, library, pr); MultiValueTable<String, String> headers = new MultiValueTable(); errorpage.writeContent(contentNode, headers); writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } finally { Thread.currentThread().setContextClassLoader(origClassLoader); } } @Override public String path() { return MainPage.path(); } public String name() { return "WelcomeToadlet.searchFreenet"; } public String menu() { return "FProxyToadlet.categoryBrowsing"; } }
true
true
public void handleMethodGET(URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Library.class.getClassLoader()); try { // process the request String title = Library.plugName; MainPage page = MainPage.processGetRequest(request); if(page == null) page = new MainPage(library, pr); else { String query = page.getQuery(); if(query != null && !query.isEmpty()) title = query + " - " + Library.plugName; } PageNode p = ctx.getPageMaker().getPageNode(title, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; MultiValueTable<String, String> headers = new MultiValueTable(); page.writeContent(contentNode, headers); // write reply writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } catch(RuntimeException e) { // this way isnt working particularly well, i think the ctx only gives out one page maker
public void handleMethodGET(URI uri, final HTTPRequest request, final ToadletContext ctx) throws ToadletContextClosedException, IOException, RedirectException { ClassLoader origClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(Library.class.getClassLoader()); try { // process the request String title = Library.plugName; MainPage page = MainPage.processGetRequest(request); if(page == null) page = new MainPage(library, pr); else { String query = page.getQuery(); if(query != null && query.length() > 0) title = query + " - " + Library.plugName; } PageNode p = ctx.getPageMaker().getPageNode(title, ctx); // Style p.headNode.addChild("link", new String[]{"rel", "href", "type"} , new String[]{"stylesheet", path() + "static/style.css", "text/css"}); HTMLNode pageNode = p.outer; HTMLNode contentNode = p.content; MultiValueTable<String, String> headers = new MultiValueTable(); page.writeContent(contentNode, headers); // write reply writeHTMLReply(ctx, 200, "OK", headers, pageNode.generate()); } catch(RuntimeException e) { // this way isnt working particularly well, i think the ctx only gives out one page maker
diff --git a/src/com/intellij/plugin/crap4j/CrapChecker.java b/src/com/intellij/plugin/crap4j/CrapChecker.java index ae95cc7..310806a 100644 --- a/src/com/intellij/plugin/crap4j/CrapChecker.java +++ b/src/com/intellij/plugin/crap4j/CrapChecker.java @@ -1,44 +1,44 @@ package com.intellij.plugin.crap4j; import com.intellij.openapi.project.Project; import com.intellij.plugin.crap4j.complexity.CyclomaticComplexity; import com.intellij.plugin.crap4j.complexity.MethodComplexity; import com.intellij.plugin.crap4j.coverage.CoverageException; import com.intellij.plugin.crap4j.coverage.EmmaCoverage; import com.intellij.psi.PsiJavaFile; import org.objectweb.asm.tree.analysis.AnalyzerException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CrapChecker { public static Map<String, Double> crapCheckFile(PsiJavaFile psiFile, Project project) throws IOException, CoverageException, AnalyzerException { FileHelper fileHelper = new FileHelper(project); List<String> classFiles = fileHelper.getClassFilePaths(psiFile.getVirtualFile()); Map<String, Double> coverageMap = EmmaCoverage.getMethodCoverageMap(project, psiFile); CyclomaticComplexity cc = new CyclomaticComplexity(); List<MethodComplexity> methodComplexities = new ArrayList<MethodComplexity>(); for (String classFile : classFiles) { File input = new File(classFile); methodComplexities.addAll(cc.getMethodComplexitiesFor(input)); } Map<String, Double> crapMap = new HashMap<String, Double>(); for (MethodComplexity methodComplexity : methodComplexities) { - String sig = methodComplexity.getClassName() + "." + methodComplexity.getMethodName() + methodComplexity.getMethodDescriptor(); + String sig = methodComplexity.getMethodName() + methodComplexity.getMethodDescriptor(); double coverage = coverageMap.containsKey(sig) ? coverageMap.get(sig) : 0; double crap = (Math.pow(methodComplexity.getComplexity(), 2) * Math.pow(1 - coverage, 3)) + methodComplexity.getComplexity(); if (crap >= 30) { - crapMap.put(sig, crap); + crapMap.put(methodComplexity.getClassName() + "." + sig, crap); } } return crapMap; } }
false
true
public static Map<String, Double> crapCheckFile(PsiJavaFile psiFile, Project project) throws IOException, CoverageException, AnalyzerException { FileHelper fileHelper = new FileHelper(project); List<String> classFiles = fileHelper.getClassFilePaths(psiFile.getVirtualFile()); Map<String, Double> coverageMap = EmmaCoverage.getMethodCoverageMap(project, psiFile); CyclomaticComplexity cc = new CyclomaticComplexity(); List<MethodComplexity> methodComplexities = new ArrayList<MethodComplexity>(); for (String classFile : classFiles) { File input = new File(classFile); methodComplexities.addAll(cc.getMethodComplexitiesFor(input)); } Map<String, Double> crapMap = new HashMap<String, Double>(); for (MethodComplexity methodComplexity : methodComplexities) { String sig = methodComplexity.getClassName() + "." + methodComplexity.getMethodName() + methodComplexity.getMethodDescriptor(); double coverage = coverageMap.containsKey(sig) ? coverageMap.get(sig) : 0; double crap = (Math.pow(methodComplexity.getComplexity(), 2) * Math.pow(1 - coverage, 3)) + methodComplexity.getComplexity(); if (crap >= 30) { crapMap.put(sig, crap); } } return crapMap; }
public static Map<String, Double> crapCheckFile(PsiJavaFile psiFile, Project project) throws IOException, CoverageException, AnalyzerException { FileHelper fileHelper = new FileHelper(project); List<String> classFiles = fileHelper.getClassFilePaths(psiFile.getVirtualFile()); Map<String, Double> coverageMap = EmmaCoverage.getMethodCoverageMap(project, psiFile); CyclomaticComplexity cc = new CyclomaticComplexity(); List<MethodComplexity> methodComplexities = new ArrayList<MethodComplexity>(); for (String classFile : classFiles) { File input = new File(classFile); methodComplexities.addAll(cc.getMethodComplexitiesFor(input)); } Map<String, Double> crapMap = new HashMap<String, Double>(); for (MethodComplexity methodComplexity : methodComplexities) { String sig = methodComplexity.getMethodName() + methodComplexity.getMethodDescriptor(); double coverage = coverageMap.containsKey(sig) ? coverageMap.get(sig) : 0; double crap = (Math.pow(methodComplexity.getComplexity(), 2) * Math.pow(1 - coverage, 3)) + methodComplexity.getComplexity(); if (crap >= 30) { crapMap.put(methodComplexity.getClassName() + "." + sig, crap); } } return crapMap; }
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractCRDCreator.java b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractCRDCreator.java index 8f99926..36a24e6 100644 --- a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractCRDCreator.java +++ b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractCRDCreator.java @@ -1,96 +1,97 @@ package jp.ac.osaka_u.ist.sdl.ectec.analyzer.sourceanalyzer.crd; import java.util.ArrayList; import java.util.List; import jp.ac.osaka_u.ist.sdl.ectec.data.BlockType; import jp.ac.osaka_u.ist.sdl.ectec.data.CRD; import jp.ac.osaka_u.ist.sdl.ectec.settings.Constants; import org.eclipse.jdt.core.dom.ASTNode; /** * A class to create a crd for a given node * * @author k-hotta * */ public abstract class AbstractCRDCreator<T extends ASTNode> { /** * the node to be analyzed */ protected final T node; /** * the crd for the parent of this node */ protected final CRD parent; /** * the type of the block */ protected final BlockType bType; public AbstractCRDCreator(final T node, final CRD parent, final BlockType bType) { this.node = node; this.parent = parent; this.bType = bType; } /** * create a new instance of CRD for this block * * @return */ public CRD createCrd() { final String head = bType.getHead(); final String anchor = getAnchor(); final List<Long> ancestorIds = new ArrayList<Long>(); if (parent != null) { for (final long ancestorId : parent.getAncestors()) { ancestorIds.add(ancestorId); } + ancestorIds.add(parent.getId()); } final MetricsCalculator cmCalculator = new MetricsCalculator(); node.accept(cmCalculator); final int cm = cmCalculator.getCC() + cmCalculator.getFO(); final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm); final String fullText = (parent == null) ? thisCrdStr : parent .getFullText() + thisCrdStr; return new CRD(bType, head, anchor, cm, ancestorIds, fullText); } /** * get the string representation of THIS block * * @param head * @param anchor * @param cm * @return */ private String getStringCrdForThisBlock(final String head, final String anchor, final int cm) { final StringBuilder builder = new StringBuilder(); builder.append(head + ","); builder.append(anchor + ","); builder.append(cm + Constants.LINE_SEPARATOR); return builder.toString(); } /** * get the anchor of the block * * @return */ protected abstract String getAnchor(); }
true
true
public CRD createCrd() { final String head = bType.getHead(); final String anchor = getAnchor(); final List<Long> ancestorIds = new ArrayList<Long>(); if (parent != null) { for (final long ancestorId : parent.getAncestors()) { ancestorIds.add(ancestorId); } } final MetricsCalculator cmCalculator = new MetricsCalculator(); node.accept(cmCalculator); final int cm = cmCalculator.getCC() + cmCalculator.getFO(); final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm); final String fullText = (parent == null) ? thisCrdStr : parent .getFullText() + thisCrdStr; return new CRD(bType, head, anchor, cm, ancestorIds, fullText); }
public CRD createCrd() { final String head = bType.getHead(); final String anchor = getAnchor(); final List<Long> ancestorIds = new ArrayList<Long>(); if (parent != null) { for (final long ancestorId : parent.getAncestors()) { ancestorIds.add(ancestorId); } ancestorIds.add(parent.getId()); } final MetricsCalculator cmCalculator = new MetricsCalculator(); node.accept(cmCalculator); final int cm = cmCalculator.getCC() + cmCalculator.getFO(); final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm); final String fullText = (parent == null) ? thisCrdStr : parent .getFullText() + thisCrdStr; return new CRD(bType, head, anchor, cm, ancestorIds, fullText); }
diff --git a/CompactMobsEventHandler.java b/CompactMobsEventHandler.java index 96641f1..2281a0b 100644 --- a/CompactMobsEventHandler.java +++ b/CompactMobsEventHandler.java @@ -1,207 +1,208 @@ package compactMobs; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.entity.player.EntityInteractEvent; import compactMobs.Items.CompactMobsItems; public class CompactMobsEventHandler { @ForgeSubscribe public void entityInteract(EntityInteractEvent event) { if (event.entityPlayer != null && event.target != null) { //EntityInteractEvent event = (EntityInteractEvent)eevent; EntityPlayer player = event.entityPlayer; if (event.target instanceof EntityLiving) { EntityLiving entity = (EntityLiving) event.target; if (player.getCurrentEquippedItem() != null) { if (player.getCurrentEquippedItem().getItem() == CompactMobsItems.handCompactor) { NBTTagCompound nbttag; int charge = 0; if (player.getCurrentEquippedItem().hasTagCompound()) { nbttag = player.getCurrentEquippedItem().stackTagCompound; } else { nbttag = new NBTTagCompound(); } if (nbttag.hasKey("charge")) { charge = nbttag.getInteger("charge"); } if (charge == 0) { charge = player.getCurrentEquippedItem().getItem().getMaxDamage()-10; } else if (charge > 1) { if (charge - 10 <= 1) { charge = 1; } else { charge -= 10; } } ItemStack stack = player.getCurrentEquippedItem(); if (stack.getItemDamage() <= stack.getItem().getMaxDamage()*.05 && stack.getItemDamage() != 0 ) { charge = 0; if (player.inventory.hasItem(Item.coal.itemID)&&player.inventory.hasItem(CompactMobsItems.mobHolder.itemID)) { boolean space = false; boolean useS1 = false; boolean useS2 = false; int spot = 0; for (int i = 0; i< player.inventory.getSizeInventory(); i++) { if (player.inventory.getStackInSlot(i)==null) { space = true; spot = i; break; } else if(player.inventory.getStackInSlot(i).getItem()==Item.coal && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS1 = true; break; } else if(player.inventory.getStackInSlot(i).getItem()==CompactMobsItems.mobHolder && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS2 = true; break; } } if (space) { spawnParticles(player.worldObj, entity, player); if (!useS1) { player.inventory.consumeInventoryItem(Item.coal.itemID); } if (!useS2) { player.inventory.consumeInventoryItem(CompactMobsItems.mobHolder.itemID); } player.inventory.setInventorySlotContents(spot, compact(entity)); } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } nbttag.setInteger("charge", charge); player.getCurrentEquippedItem().setTagCompound(nbttag); //spawnParticles(player.worldObj, entity, player); + event.setCanceled(true); } } } } } public ItemStack compact(EntityLiving entity) { int id = EntityList.getEntityID(entity); ItemStack holder = new ItemStack(CompactMobsItems.fullMobHolder, 1); NBTTagCompound nbttag = holder.stackTagCompound; if (nbttag == null) { nbttag = new NBTTagCompound(); } nbttag.setInteger("entityId", id); if (entity instanceof EntityAgeable) { EntityAgeable entityAge = (EntityAgeable) entity; nbttag.setInteger("entityGrowingAge", entityAge.getGrowingAge()); } if (entity instanceof EntitySheep) { EntitySheep entitySheep = (EntitySheep) entity; nbttag.setBoolean("entitySheared", entitySheep.getSheared()); nbttag.setInteger("entityColor", entitySheep.getFleeceColor()); } if (CompactMobsCore.instance.useFullTagCompound) { NBTTagCompound entityTags = new NBTTagCompound(); NBTTagCompound var2 = new NBTTagCompound(); entity.writeToNBT(var2); nbttag.setCompoundTag("entityTags", var2); CompactMobsCore.instance.cmLog.info(var2.toString()); } String name = entity.getEntityName(); nbttag.setString("name", name); holder.setItemDamage(id); holder.setTagCompound(nbttag); entity.worldObj.removeEntity(entity); return holder; } public void spawnParticles(World world, EntityLiving entity, EntityPlayer player) { //CompactMobsCore.instance.cmLog.info("Got"); double xv, yv, zv; double py = player.posY, px = player.posX, pz = player.posZ; double x = entity.posX, y = entity.posY, z = entity.posZ; if (py - y > 0) { yv = (py - y) / 10; } else { yv = 0; } if (px - x > 0) { xv = (px - x) / 10; } else if (px - x < 0) { xv = (px - x) / 10; } else { xv = 0; } if (pz - z > 0) { zv = (pz - z) / 10; } else if (pz - z < 0) { zv = (pz - z) / 10; } else { zv = 0; } CompactMobsCore.instance.proxy.spawnParticle("explode", x + .5D, y + .5D, z + .5D, xv, yv, zv, 10); //this.worldObj.spawnParticle("smoke", this.xCoord+1.5D, this.yCoord+.5D, this.zCoord+.5, -.1, 0, 0); //world.spawnParticle("smoke", x+.5D, y+.5D, z+.5D, xv, yv, zv); } }
true
true
public void entityInteract(EntityInteractEvent event) { if (event.entityPlayer != null && event.target != null) { //EntityInteractEvent event = (EntityInteractEvent)eevent; EntityPlayer player = event.entityPlayer; if (event.target instanceof EntityLiving) { EntityLiving entity = (EntityLiving) event.target; if (player.getCurrentEquippedItem() != null) { if (player.getCurrentEquippedItem().getItem() == CompactMobsItems.handCompactor) { NBTTagCompound nbttag; int charge = 0; if (player.getCurrentEquippedItem().hasTagCompound()) { nbttag = player.getCurrentEquippedItem().stackTagCompound; } else { nbttag = new NBTTagCompound(); } if (nbttag.hasKey("charge")) { charge = nbttag.getInteger("charge"); } if (charge == 0) { charge = player.getCurrentEquippedItem().getItem().getMaxDamage()-10; } else if (charge > 1) { if (charge - 10 <= 1) { charge = 1; } else { charge -= 10; } } ItemStack stack = player.getCurrentEquippedItem(); if (stack.getItemDamage() <= stack.getItem().getMaxDamage()*.05 && stack.getItemDamage() != 0 ) { charge = 0; if (player.inventory.hasItem(Item.coal.itemID)&&player.inventory.hasItem(CompactMobsItems.mobHolder.itemID)) { boolean space = false; boolean useS1 = false; boolean useS2 = false; int spot = 0; for (int i = 0; i< player.inventory.getSizeInventory(); i++) { if (player.inventory.getStackInSlot(i)==null) { space = true; spot = i; break; } else if(player.inventory.getStackInSlot(i).getItem()==Item.coal && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS1 = true; break; } else if(player.inventory.getStackInSlot(i).getItem()==CompactMobsItems.mobHolder && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS2 = true; break; } } if (space) { spawnParticles(player.worldObj, entity, player); if (!useS1) { player.inventory.consumeInventoryItem(Item.coal.itemID); } if (!useS2) { player.inventory.consumeInventoryItem(CompactMobsItems.mobHolder.itemID); } player.inventory.setInventorySlotContents(spot, compact(entity)); } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } nbttag.setInteger("charge", charge); player.getCurrentEquippedItem().setTagCompound(nbttag); //spawnParticles(player.worldObj, entity, player); } } } } }
public void entityInteract(EntityInteractEvent event) { if (event.entityPlayer != null && event.target != null) { //EntityInteractEvent event = (EntityInteractEvent)eevent; EntityPlayer player = event.entityPlayer; if (event.target instanceof EntityLiving) { EntityLiving entity = (EntityLiving) event.target; if (player.getCurrentEquippedItem() != null) { if (player.getCurrentEquippedItem().getItem() == CompactMobsItems.handCompactor) { NBTTagCompound nbttag; int charge = 0; if (player.getCurrentEquippedItem().hasTagCompound()) { nbttag = player.getCurrentEquippedItem().stackTagCompound; } else { nbttag = new NBTTagCompound(); } if (nbttag.hasKey("charge")) { charge = nbttag.getInteger("charge"); } if (charge == 0) { charge = player.getCurrentEquippedItem().getItem().getMaxDamage()-10; } else if (charge > 1) { if (charge - 10 <= 1) { charge = 1; } else { charge -= 10; } } ItemStack stack = player.getCurrentEquippedItem(); if (stack.getItemDamage() <= stack.getItem().getMaxDamage()*.05 && stack.getItemDamage() != 0 ) { charge = 0; if (player.inventory.hasItem(Item.coal.itemID)&&player.inventory.hasItem(CompactMobsItems.mobHolder.itemID)) { boolean space = false; boolean useS1 = false; boolean useS2 = false; int spot = 0; for (int i = 0; i< player.inventory.getSizeInventory(); i++) { if (player.inventory.getStackInSlot(i)==null) { space = true; spot = i; break; } else if(player.inventory.getStackInSlot(i).getItem()==Item.coal && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS1 = true; break; } else if(player.inventory.getStackInSlot(i).getItem()==CompactMobsItems.mobHolder && player.inventory.getStackInSlot(i).stackSize == 1) { space = true; spot = i; useS2 = true; break; } } if (space) { spawnParticles(player.worldObj, entity, player); if (!useS1) { player.inventory.consumeInventoryItem(Item.coal.itemID); } if (!useS2) { player.inventory.consumeInventoryItem(CompactMobsItems.mobHolder.itemID); } player.inventory.setInventorySlotContents(spot, compact(entity)); } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } else { CompactMobsCore.instance.proxy.spawnParticle("flame", entity.posX+.5D, entity.posY + .5D, entity.posZ + .5D, 0, 0, 0, 10); } } nbttag.setInteger("charge", charge); player.getCurrentEquippedItem().setTagCompound(nbttag); //spawnParticles(player.worldObj, entity, player); event.setCanceled(true); } } } } }
diff --git a/src/webctdbexport/jdbc/DumpUsers.java b/src/webctdbexport/jdbc/DumpUsers.java index 56d2918..07b9c1e 100755 --- a/src/webctdbexport/jdbc/DumpUsers.java +++ b/src/webctdbexport/jdbc/DumpUsers.java @@ -1,117 +1,117 @@ /** * */ package webctdbexport.jdbc; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.hibernate.Session; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import webctdbexport.db.LearningContext; import webctdbexport.jdbc.model.Person; import webctdbexport.test.TestRepository; import webctdbexport.tools.DumpUtils; import webctdbexport.utils.DbUtils; //import webctdbexport.utils.MoodleRepository; /** Dump all users and their own file areas in whole database ?! * * @author cmg * */ public class DumpUsers { private static final String DONE_FILE = "done.ts"; static Logger logger = Logger.getLogger(DumpUsers.class.getName()); /** * @param args */ public static void main(String[] args) { if (args.length<3) { System.err.println("Usage: <jdbc.properties> <outputdir> <filedir> [usernames...]"); System.exit(-1); } File outputdir = new File(args[1]); if (!outputdir.exists() || !outputdir.canWrite() || !outputdir.isDirectory()) { logger.log(Level.SEVERE, "Output directory does not exist or is not writable: "+outputdir); System.exit(-1); } File filedir = new File(args[2]); if (!filedir.exists() || !filedir.canWrite() || !filedir.isDirectory()) { logger.log(Level.SEVERE, "File directory does not exist or is not writable: "+filedir); System.exit(-1); } Connection conn = JdbcUtils.getConnection(args[0]); try { logger.log(Level.INFO, "output folders to "+outputdir); List<BigDecimal> personIds = null; if (args.length<=3) { logger.log(Level.INFO, "Dump all users..."); - MoodleRepository.getPersonIds(conn); + personIds = MoodleRepository.getPersonIds(conn); logger.log(Level.INFO, "Found "+personIds.size()+" active nondemo users"); } else { personIds = new LinkedList<BigDecimal>(); for (int ai=3; ai<args.length; ai++) { Person p = MoodleRepository.getPersonByWebctId(conn, args[ai]); if (p==null) logger.log(Level.WARNING,"Could not find user "+args[ai]); else personIds.add(p.getId()); } } for (BigDecimal personId : personIds) { Person p = MoodleRepository.getPerson(conn, personId); if (p==null) { logger.log(Level.WARNING,"Could not find Person "+personId); continue; } String username = p.getWebctId(); if (username==null || username.length()<3) { logger.log(Level.WARNING,"Ignoring user "+username+" (short username)"); continue; } logger.log(Level.INFO, "Dump Person "+username); // learning contexts... JSONObject listing = MoodleRepository.getListingForUser(conn, username, true, true); List<JSONObject> items = new LinkedList<JSONObject>(); if (listing.getJSONArray("list").length()==0) { logger.log(Level.INFO,"Skip user "+username+" (no folder, etc.)"); continue; } String user2 = username.substring(0,2); String user3 = username.substring(0,3); File userdir = new File(new File(new File(new File(outputdir, "user"), user2), user3), username); userdir.mkdirs(); DumpUtils.writeResponse(listing, userdir); //DumpUtils.addPersonItems(items, listing, "/"); DumpUtils.addItems(items, listing, "/"); DumpAll.processItems(conn, items, outputdir, filedir); } logger.log(Level.INFO, "Done all users"); } catch (Exception e) { logger.log(Level.SEVERE, "Error", e); } finally { try { conn.close(); } catch (Throwable ignore) {} } } }
true
true
public static void main(String[] args) { if (args.length<3) { System.err.println("Usage: <jdbc.properties> <outputdir> <filedir> [usernames...]"); System.exit(-1); } File outputdir = new File(args[1]); if (!outputdir.exists() || !outputdir.canWrite() || !outputdir.isDirectory()) { logger.log(Level.SEVERE, "Output directory does not exist or is not writable: "+outputdir); System.exit(-1); } File filedir = new File(args[2]); if (!filedir.exists() || !filedir.canWrite() || !filedir.isDirectory()) { logger.log(Level.SEVERE, "File directory does not exist or is not writable: "+filedir); System.exit(-1); } Connection conn = JdbcUtils.getConnection(args[0]); try { logger.log(Level.INFO, "output folders to "+outputdir); List<BigDecimal> personIds = null; if (args.length<=3) { logger.log(Level.INFO, "Dump all users..."); MoodleRepository.getPersonIds(conn); logger.log(Level.INFO, "Found "+personIds.size()+" active nondemo users"); } else { personIds = new LinkedList<BigDecimal>(); for (int ai=3; ai<args.length; ai++) { Person p = MoodleRepository.getPersonByWebctId(conn, args[ai]); if (p==null) logger.log(Level.WARNING,"Could not find user "+args[ai]); else personIds.add(p.getId()); } } for (BigDecimal personId : personIds) { Person p = MoodleRepository.getPerson(conn, personId); if (p==null) { logger.log(Level.WARNING,"Could not find Person "+personId); continue; } String username = p.getWebctId(); if (username==null || username.length()<3) { logger.log(Level.WARNING,"Ignoring user "+username+" (short username)"); continue; } logger.log(Level.INFO, "Dump Person "+username); // learning contexts... JSONObject listing = MoodleRepository.getListingForUser(conn, username, true, true); List<JSONObject> items = new LinkedList<JSONObject>(); if (listing.getJSONArray("list").length()==0) { logger.log(Level.INFO,"Skip user "+username+" (no folder, etc.)"); continue; } String user2 = username.substring(0,2); String user3 = username.substring(0,3); File userdir = new File(new File(new File(new File(outputdir, "user"), user2), user3), username); userdir.mkdirs(); DumpUtils.writeResponse(listing, userdir); //DumpUtils.addPersonItems(items, listing, "/"); DumpUtils.addItems(items, listing, "/"); DumpAll.processItems(conn, items, outputdir, filedir); } logger.log(Level.INFO, "Done all users"); } catch (Exception e) { logger.log(Level.SEVERE, "Error", e); } finally { try { conn.close(); } catch (Throwable ignore) {} } }
public static void main(String[] args) { if (args.length<3) { System.err.println("Usage: <jdbc.properties> <outputdir> <filedir> [usernames...]"); System.exit(-1); } File outputdir = new File(args[1]); if (!outputdir.exists() || !outputdir.canWrite() || !outputdir.isDirectory()) { logger.log(Level.SEVERE, "Output directory does not exist or is not writable: "+outputdir); System.exit(-1); } File filedir = new File(args[2]); if (!filedir.exists() || !filedir.canWrite() || !filedir.isDirectory()) { logger.log(Level.SEVERE, "File directory does not exist or is not writable: "+filedir); System.exit(-1); } Connection conn = JdbcUtils.getConnection(args[0]); try { logger.log(Level.INFO, "output folders to "+outputdir); List<BigDecimal> personIds = null; if (args.length<=3) { logger.log(Level.INFO, "Dump all users..."); personIds = MoodleRepository.getPersonIds(conn); logger.log(Level.INFO, "Found "+personIds.size()+" active nondemo users"); } else { personIds = new LinkedList<BigDecimal>(); for (int ai=3; ai<args.length; ai++) { Person p = MoodleRepository.getPersonByWebctId(conn, args[ai]); if (p==null) logger.log(Level.WARNING,"Could not find user "+args[ai]); else personIds.add(p.getId()); } } for (BigDecimal personId : personIds) { Person p = MoodleRepository.getPerson(conn, personId); if (p==null) { logger.log(Level.WARNING,"Could not find Person "+personId); continue; } String username = p.getWebctId(); if (username==null || username.length()<3) { logger.log(Level.WARNING,"Ignoring user "+username+" (short username)"); continue; } logger.log(Level.INFO, "Dump Person "+username); // learning contexts... JSONObject listing = MoodleRepository.getListingForUser(conn, username, true, true); List<JSONObject> items = new LinkedList<JSONObject>(); if (listing.getJSONArray("list").length()==0) { logger.log(Level.INFO,"Skip user "+username+" (no folder, etc.)"); continue; } String user2 = username.substring(0,2); String user3 = username.substring(0,3); File userdir = new File(new File(new File(new File(outputdir, "user"), user2), user3), username); userdir.mkdirs(); DumpUtils.writeResponse(listing, userdir); //DumpUtils.addPersonItems(items, listing, "/"); DumpUtils.addItems(items, listing, "/"); DumpAll.processItems(conn, items, outputdir, filedir); } logger.log(Level.INFO, "Done all users"); } catch (Exception e) { logger.log(Level.SEVERE, "Error", e); } finally { try { conn.close(); } catch (Throwable ignore) {} } }
diff --git a/apacheds-configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/v155/InterceptorsPage.java b/apacheds-configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/v155/InterceptorsPage.java index 09d7884a6..3e8c2dfe8 100644 --- a/apacheds-configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/v155/InterceptorsPage.java +++ b/apacheds-configuration/src/main/java/org/apache/directory/studio/apacheds/configuration/editor/v155/InterceptorsPage.java @@ -1,88 +1,88 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.apacheds.configuration.editor.v155; import org.apache.directory.studio.apacheds.configuration.ApacheDSConfigurationPluginConstants; import org.apache.directory.studio.apacheds.configuration.editor.SaveableFormPage; import org.apache.directory.studio.apacheds.configuration.editor.ServerConfigurationEditor; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.editor.FormPage; import org.eclipse.ui.forms.widgets.ScrolledForm; /** * This class represents the Interceptors Page of the Server Configuration Editor. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class InterceptorsPage extends FormPage implements SaveableFormPage { /** The Page ID*/ public static final String ID = ServerConfigurationEditor.ID + ".V155.InterceptorsPage"; //$NON-NLS-1$ /** The Page Title */ private static final String TITLE = Messages.getString( "InterceptorsPage.Interceptors" ); //$NON-NLS-1$ /** The Master/Details Block */ private InterceptorsMasterDetailsBlock masterDetailsBlock; /** * Creates a new instance of InterceptorsPage. * * @param editor * the associated editor */ public InterceptorsPage( FormEditor editor ) { super( editor, ID, TITLE ); } /* (non-Javadoc) * @see org.eclipse.ui.forms.editor.FormPage#createFormContent(org.eclipse.ui.forms.IManagedForm) */ protected void createFormContent( IManagedForm managedForm ) { PlatformUI.getWorkbench().getHelpSystem().setHelp( getPartControl(), - ApacheDSConfigurationPluginConstants.PLUGIN_ID + "." + "configuration_editor_154" ); //$NON-NLS-1$ //$NON-NLS-2$ + ApacheDSConfigurationPluginConstants.PLUGIN_ID + "." + "configuration_editor_155" ); //$NON-NLS-1$ //$NON-NLS-2$ final ScrolledForm form = managedForm.getForm(); form.setText( Messages.getString( "InterceptorsPage.Interceptors" ) ); //$NON-NLS-1$ masterDetailsBlock = new InterceptorsMasterDetailsBlock( this ); masterDetailsBlock.createContent( managedForm ); } /* (non-Javadoc) * @see org.apache.directory.studio.apacheds.configuration.editor.SavableWizardPage#save() */ public void save() { if ( masterDetailsBlock != null ) { masterDetailsBlock.save(); } } }
true
true
protected void createFormContent( IManagedForm managedForm ) { PlatformUI.getWorkbench().getHelpSystem().setHelp( getPartControl(), ApacheDSConfigurationPluginConstants.PLUGIN_ID + "." + "configuration_editor_154" ); //$NON-NLS-1$ //$NON-NLS-2$ final ScrolledForm form = managedForm.getForm(); form.setText( Messages.getString( "InterceptorsPage.Interceptors" ) ); //$NON-NLS-1$ masterDetailsBlock = new InterceptorsMasterDetailsBlock( this ); masterDetailsBlock.createContent( managedForm ); }
protected void createFormContent( IManagedForm managedForm ) { PlatformUI.getWorkbench().getHelpSystem().setHelp( getPartControl(), ApacheDSConfigurationPluginConstants.PLUGIN_ID + "." + "configuration_editor_155" ); //$NON-NLS-1$ //$NON-NLS-2$ final ScrolledForm form = managedForm.getForm(); form.setText( Messages.getString( "InterceptorsPage.Interceptors" ) ); //$NON-NLS-1$ masterDetailsBlock = new InterceptorsMasterDetailsBlock( this ); masterDetailsBlock.createContent( managedForm ); }
diff --git a/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java b/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java index 81ee2b43..6c5f972c 100644 --- a/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java +++ b/NCore/src/main/java/fr/ribesg/bukkit/ncore/common/AsyncPermAccessor.java @@ -1,175 +1,177 @@ package fr.ribesg.bukkit.ncore.common; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * This tool allow Asynchronous access to a Player's permission. * The {@link #init(org.bukkit.plugin.Plugin, int)} method should be * called by at least one Plugin synchronously before any sync or async * access. * <b> * Note: There is a maximum of {@link #updateDelay} seconds delay between * this tool's state and the reality. This tool should not be used for * critical checks. * </b> * * @author Ribesg */ public final class AsyncPermAccessor { // ########################### // // ## Public static methods ## // // ########################### // /** * Checks if a Player had a Permission on the last update. * * @param playerName the player's name * @param permissionNode the permission to check * * @return true if the provided Player had the provided Permission on * the last update, false otherwise */ public static boolean has(final String playerName, final String permissionNode) { checkState(); return instance._has(playerName, permissionNode); } /** * Checks if a Player was Op on the last update. * * @param playerName the player's name * * @return true if the provided Player was Op on the last update, * false otherwise */ public static boolean isOp(final String playerName) { checkState(); return instance._isOp(playerName); } /** * Create the unique instance. * <p/> * Should be called sync. * * @param updateDelay the delay between updates, in seconds. * The lower, the heaviest. */ public static void init(final Plugin plugin, final int updateDelay) { if (instance == null) { instance = new AsyncPermAccessor(plugin, updateDelay); } } // ################### // // ## Static object ## // // ################### // /** The unique instance of this tool. */ private static AsyncPermAccessor instance; /** Checks if the tool has been initialized. */ private static void checkState() { if (instance == null) { throw new IllegalStateException("AsyncPermAccessor has not been initialized"); } } // ######################## // // ## Non-static content ## // // ######################## // /** * Will store the permissions per player. Sets will be backed by * Concurrent maps. */ private final ConcurrentMap<String, Set<String>> permissions; /** * Will store all connected op players. This Set will be backed by * a Concurrent map. */ private final Set<String> ops; /** The plugin on which the task is attached. */ private final Plugin plugin; /** The update rate, in seconds. */ private final int updateDelay; /** * Construct the AsyncPermAccessor. * * @param plugin the plugin on which the taks will be attached * @param updateDelay the update rate, in seconds */ private AsyncPermAccessor(final Plugin plugin, final int updateDelay) { this.permissions = new ConcurrentHashMap<>(); this.ops = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); this.plugin = plugin; this.updateDelay = updateDelay; update(); launchUpdateTask(); } /** @see #has(String, String) */ private boolean _has(final String playerName, final String permissionNode) { final Set<String> playerPerms = this.permissions.get(playerName); return playerPerms != null && playerPerms.contains(permissionNode); } /** @see #isOp(String) */ private boolean _isOp(final String playerName) { return this.ops.contains(playerName); } /** Update all permissions and op state of all connected players. */ private void update() { for (final Player player : Bukkit.getOnlinePlayers()) { updatePlayer(player); } } /** Update all permissions and op state of the provided player. */ private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); + } else { + playerPerms.clear(); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { if (perm.getValue()) { playerPerms.add(perm.getPermission()); } } this.permissions.put(playerName, playerPerms); } /** Launch the update task. */ private void launchUpdateTask() { final long tickDelay = this.updateDelay * 20L; Bukkit.getScheduler().runTaskTimer(this.plugin, new BukkitRunnable() { @Override public void run() { AsyncPermAccessor.this.update(); } }, tickDelay, tickDelay); } }
true
true
private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { if (perm.getValue()) { playerPerms.add(perm.getPermission()); } } this.permissions.put(playerName, playerPerms); }
private void updatePlayer(final Player player) { final String playerName = player.getName(); if (player.isOp()) { this.ops.add(playerName); } else { this.ops.remove(playerName); } Set<String> playerPerms = this.permissions.get(playerName); if (playerPerms == null) { playerPerms = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>()); } else { playerPerms.clear(); } for (final PermissionAttachmentInfo perm : player.getEffectivePermissions()) { if (perm.getValue()) { playerPerms.add(perm.getPermission()); } } this.permissions.put(playerName, playerPerms); }
diff --git a/src/ibis/satin/impl/Inlets.java b/src/ibis/satin/impl/Inlets.java index f1423a87..a95b8183 100644 --- a/src/ibis/satin/impl/Inlets.java +++ b/src/ibis/satin/impl/Inlets.java @@ -1,214 +1,214 @@ package ibis.satin.impl; import ibis.ipl.IbisIdentifier; public abstract class Inlets extends Aborts { // trace back from the exception, and execute inlets / empty imlets back to // the root // during this, prematurely send result messages. void handleInlet(InvocationRecord r) { InvocationRecord oldParent; int oldParentStamp; IbisIdentifier oldParentOwner; if (r.inletExecuted) { System.err.print("r"); return; } if (r.parentLocals == null) { System.err.println("empty inlet in handleInlet"); handleEmptyInlet(r); return; } onStack.push(r); oldParent = parent; oldParentStamp = parentStamp; oldParentOwner = parentOwner; parentStamp = r.stamp; parentOwner = r.owner; parent = r; try { if (INLET_DEBUG) { System.err.println("SATIN '" + ident.name() + ": calling inlet caused by remote exception"); } r.parentLocals.handleException(r.spawnId, r.eek, r); r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); } catch (Throwable t) { // The inlet has thrown an exception itself. // The semantics of this: throw the exception to the parent, // And execute the inlet if it has one (might be an empty one). // Also, the other children of the parent must be aborted. r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); if (INLET_DEBUG) { System.err.println("Got an exception from exception handler! " + t); // t.printStackTrace(); System.err.println("r = " + r); System.err.println("r.parent = " + r.parent); } if (r.parent == null) { System.err - .println("An inlet threw an exception, but there is no parent that handles it." + .println("An inlet threw an exception, but there is no parent that handles it: " + t); // t.printStackTrace(); throw new Error(t); // System.exit(1); } if (ABORT_STATS) { aborts++; } synchronized (this) { // also kill the parent itself. // It is either on the stack or on a remote machine. // Here, this is OK, the child threw an exception, // the parent did not catch it, and must therefore die. r.parent.aborted = true; r.parent.eek = t; // rethrow exception killChildrenOf(r.parent.stamp, r.parent.owner); } if (!r.parentOwner.equals(ident)) { if (INLET_DEBUG || STEAL_DEBUG) { System.err.println("SATIN '" + ident.name() + ": prematurely sending exception result"); } sendResult(r.parent, null); return; } // two cases here: empty inlet or normal inlet if (r.parent.parentLocals == null) { // empty inlet handleEmptyInlet(r.parent); } else { // normal inlet handleInlet(r.parent); } } } // trace back from the exception, and execute inlets / empty imlets back to // the root // during this, prematurely send result messages. private void handleEmptyInlet(InvocationRecord r) { // if r does not have parentLocals, this means // that the PARENT does not have a try catch block around the spawn. // there is thus no inlet to call in the parent. if (r.eek == null) return; if (r.parent == null) return; // if(r.parenLocals != null) return; if (ASSERTS && r.parentLocals != null) { System.err.println("parenlocals is not null in empty inlet"); System.exit(1); } // if(INLET_DEBUG) { out.println("SATIN '" + ident.name() + ": Got exception, empty inlet: " + r.eek + ": " + r.eek.getMessage()); r.eek.printStackTrace(); // } InvocationRecord curr = r; synchronized (this) { // also kill the parent itself. // It is either on the stack or on a remote machine. // Here, this is OK, the child threw an exception, // the parent did not catch it, and must therefore die. r.parent.aborted = true; r.parent.eek = r.eek; // rethrow exception killChildrenOf(r.parent.stamp, r.parent.owner); } if (!r.parentOwner.equals(ident)) { if (INLET_DEBUG || STEAL_DEBUG) { System.err.println("SATIN '" + ident.name() + ": prematurely sending exception result"); } sendResult(r.parent, null); return; } // now the recursion step if (r.parent.parentLocals != null) { // parent has inlet handleInlet(r.parent); } else { handleEmptyInlet(r.parent); } } void addToExceptionList(InvocationRecord r) { if (ASSERTS) { assertLocked(this); } exceptionList.add(r); gotExceptions = true; if (INLET_DEBUG) { out.println("SATIN '" + ident.name() + ": got remote exception!"); } } // both here and in handleEmpty inlets: sendResult NOW if parentOwner is on // remote machine void handleExceptions() { if (ASSERTS && !ABORTS) { System.err .println("cannot handle inlets, set ABORTS to true in Config.java"); System.exit(1); } InvocationRecord r; while (true) { synchronized (this) { r = exceptionList.removeIndex(0); if (r == null) { gotExceptions = false; return; } } if (INLET_DEBUG) { out.println("SATIN '" + ident.name() + ": handling remote exception: " + r.eek + ", inv = " + r); } // If there is an inlet, call it. handleInlet(r); r.spawnCounter.value--; if (ASSERTS && r.spawnCounter.value < 0) { out.println("Just made spawncounter < 0"); new Exception().printStackTrace(); System.exit(1); } if (INLET_DEBUG) { out.println("SATIN '" + ident.name() + ": handling remote exception DONE"); } } } }
true
true
void handleInlet(InvocationRecord r) { InvocationRecord oldParent; int oldParentStamp; IbisIdentifier oldParentOwner; if (r.inletExecuted) { System.err.print("r"); return; } if (r.parentLocals == null) { System.err.println("empty inlet in handleInlet"); handleEmptyInlet(r); return; } onStack.push(r); oldParent = parent; oldParentStamp = parentStamp; oldParentOwner = parentOwner; parentStamp = r.stamp; parentOwner = r.owner; parent = r; try { if (INLET_DEBUG) { System.err.println("SATIN '" + ident.name() + ": calling inlet caused by remote exception"); } r.parentLocals.handleException(r.spawnId, r.eek, r); r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); } catch (Throwable t) { // The inlet has thrown an exception itself. // The semantics of this: throw the exception to the parent, // And execute the inlet if it has one (might be an empty one). // Also, the other children of the parent must be aborted. r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); if (INLET_DEBUG) { System.err.println("Got an exception from exception handler! " + t); // t.printStackTrace(); System.err.println("r = " + r); System.err.println("r.parent = " + r.parent); } if (r.parent == null) { System.err .println("An inlet threw an exception, but there is no parent that handles it." + t); // t.printStackTrace(); throw new Error(t); // System.exit(1); } if (ABORT_STATS) { aborts++; } synchronized (this) { // also kill the parent itself. // It is either on the stack or on a remote machine. // Here, this is OK, the child threw an exception, // the parent did not catch it, and must therefore die. r.parent.aborted = true; r.parent.eek = t; // rethrow exception killChildrenOf(r.parent.stamp, r.parent.owner); } if (!r.parentOwner.equals(ident)) { if (INLET_DEBUG || STEAL_DEBUG) { System.err.println("SATIN '" + ident.name() + ": prematurely sending exception result"); } sendResult(r.parent, null); return; } // two cases here: empty inlet or normal inlet if (r.parent.parentLocals == null) { // empty inlet handleEmptyInlet(r.parent); } else { // normal inlet handleInlet(r.parent); } } }
void handleInlet(InvocationRecord r) { InvocationRecord oldParent; int oldParentStamp; IbisIdentifier oldParentOwner; if (r.inletExecuted) { System.err.print("r"); return; } if (r.parentLocals == null) { System.err.println("empty inlet in handleInlet"); handleEmptyInlet(r); return; } onStack.push(r); oldParent = parent; oldParentStamp = parentStamp; oldParentOwner = parentOwner; parentStamp = r.stamp; parentOwner = r.owner; parent = r; try { if (INLET_DEBUG) { System.err.println("SATIN '" + ident.name() + ": calling inlet caused by remote exception"); } r.parentLocals.handleException(r.spawnId, r.eek, r); r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); } catch (Throwable t) { // The inlet has thrown an exception itself. // The semantics of this: throw the exception to the parent, // And execute the inlet if it has one (might be an empty one). // Also, the other children of the parent must be aborted. r.inletExecuted = true; // restore these, there may be more spawns afterwards... parentStamp = oldParentStamp; parentOwner = oldParentOwner; parent = oldParent; onStack.pop(); if (INLET_DEBUG) { System.err.println("Got an exception from exception handler! " + t); // t.printStackTrace(); System.err.println("r = " + r); System.err.println("r.parent = " + r.parent); } if (r.parent == null) { System.err .println("An inlet threw an exception, but there is no parent that handles it: " + t); // t.printStackTrace(); throw new Error(t); // System.exit(1); } if (ABORT_STATS) { aborts++; } synchronized (this) { // also kill the parent itself. // It is either on the stack or on a remote machine. // Here, this is OK, the child threw an exception, // the parent did not catch it, and must therefore die. r.parent.aborted = true; r.parent.eek = t; // rethrow exception killChildrenOf(r.parent.stamp, r.parent.owner); } if (!r.parentOwner.equals(ident)) { if (INLET_DEBUG || STEAL_DEBUG) { System.err.println("SATIN '" + ident.name() + ": prematurely sending exception result"); } sendResult(r.parent, null); return; } // two cases here: empty inlet or normal inlet if (r.parent.parentLocals == null) { // empty inlet handleEmptyInlet(r.parent); } else { // normal inlet handleInlet(r.parent); } } }
diff --git a/src/com/rhoward/LDomino.java b/src/com/rhoward/LDomino.java index 16f10b0..99fe300 100644 --- a/src/com/rhoward/LDomino.java +++ b/src/com/rhoward/LDomino.java @@ -1,65 +1,65 @@ package com.rhoward; public class LDomino extends Domino { public LDomino(Block.BlockType type, int x, int y) { super(type, x, y); } @Override public Domino rotate() { LDomino newState = new LDomino(this.type, this.x, this.y); newState.rotateState = this.rotateState; newState.rotateState = newState.nextRotation(); return newState; } @Override public Domino translate(int x, int y) { LDomino translated = new LDomino(this.type, this.x + x, this.y + y); translated.rotateState = this.rotateState; return translated; } @Override public String getGrid() { String grid; switch (rotateState) { case NORMAL: grid = "10,10,11"; break; + case RIGHT: + grid = "111,100"; + break; case DOWN: grid = "11,01,01"; break; case LEFT: grid = "001,111"; break; - case RIGHT: - grid = "111,001"; - break; default: grid = ""; break; } return grid; } @Override public int getHeight() { if ((this.rotateState == RotateState.NORMAL) || (this.rotateState == RotateState.DOWN)) return 3; else return 2; } @Override public int getWidth() { if ((this.rotateState == RotateState.NORMAL) || (this.rotateState == RotateState.DOWN)) return 2; else return 3; } }
false
true
public String getGrid() { String grid; switch (rotateState) { case NORMAL: grid = "10,10,11"; break; case DOWN: grid = "11,01,01"; break; case LEFT: grid = "001,111"; break; case RIGHT: grid = "111,001"; break; default: grid = ""; break; } return grid; }
public String getGrid() { String grid; switch (rotateState) { case NORMAL: grid = "10,10,11"; break; case RIGHT: grid = "111,100"; break; case DOWN: grid = "11,01,01"; break; case LEFT: grid = "001,111"; break; default: grid = ""; break; } return grid; }
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java b/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java index f8cb0be4..d33b7a0d 100644 --- a/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java +++ b/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java @@ -1,370 +1,370 @@ /* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD modeler, Finite element mesher, Plugin architecture. Copyright (C) 2006, by EADS CRC Copyright (C) 2007,2008,2009,2010, by EADS France This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.jcae.mesh.amibe.algos3d; import org.jcae.mesh.amibe.ds.Mesh; import org.jcae.mesh.amibe.ds.HalfEdge; import org.jcae.mesh.amibe.ds.TriangleHE; import org.jcae.mesh.amibe.ds.AbstractHalfEdge; import org.jcae.mesh.amibe.ds.Triangle; import org.jcae.mesh.amibe.ds.Vertex; import org.jcae.mesh.amibe.util.QSortedTree; import org.jcae.mesh.amibe.util.PAVLSortedTree; import java.util.Stack; import java.util.Iterator; import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public abstract class AbstractAlgoHalfEdge { Mesh mesh; int nrFinal = 0; int nrTriangles = 0; double tolerance = 0.0; double maxEdgeLength = -1.0; int processed = 0; int swapped = 0; int notProcessed = 0; int notInTree = 0; private int progressBarStatus = 10000; private boolean noSwapAfterProcessing = false; double minCos = 0.95; boolean moreTriangles = false; QSortedTree<HalfEdge> tree = new PAVLSortedTree<HalfEdge>(); protected abstract void preProcessAllHalfEdges(); protected abstract void postProcessAllHalfEdges(); protected abstract boolean canProcessEdge(HalfEdge e); protected abstract HalfEdge processEdge(HalfEdge e, double cost); protected abstract double cost(HalfEdge e); protected abstract Logger thisLogger(); private static final String dumpFile = "/tmp/jcae.dump"; AbstractAlgoHalfEdge(final Mesh m) { mesh = m; } public final void compute() { thisLogger().info("Run "+getClass().getName()); preProcessAllHalfEdges(); thisLogger().info("Compute initial tree"); computeTree(); postComputeTree(); thisLogger().info("Initial number of triangles: "+countInnerTriangles(mesh)); processAllHalfEdges(); thisLogger().info("Final number of triangles: "+countInnerTriangles(mesh)); } public void setProgressBarStatus(int n) { progressBarStatus = n; } public static int countInnerTriangles(final Mesh mesh) { int ret = 0; for (Triangle af: mesh.getTriangles()) { if (af.isWritable()) ret++; } return ret; } /** * Ensure that edge orientation is fixed and does not depend on hashcodes. This method * must be used when entering canProcessEdge() and processEdge(). */ static HalfEdge uniqueOrientation(HalfEdge current) { if (current.hasAttributes(AbstractHalfEdge.MARKED) || !current.hasSymmetricEdge()) return current; if (current.sym().hasAttributes(AbstractHalfEdge.MARKED) || current.hasAttributes(AbstractHalfEdge.OUTER)) return current.sym(); return current; } private void computeTree() { // Compute edge cost nrTriangles = 0; for (Triangle af: mesh.getTriangles()) { if (!af.isWritable()) continue; TriangleHE f = (TriangleHE) af; nrTriangles++; HalfEdge e = f.getAbstractHalfEdge(); for (int i = 0; i < 3; i++) { e = e.next(); HalfEdge h = uniqueOrientation(e); if (!tree.contains(h)) addToTree(h); } } } void postComputeTree() { } // This routine is needed by DecimateHalfedge. void preProcessEdge() { } final void addToTree(final HalfEdge e) { if (!e.origin().isReadable() || !e.destination().isReadable()) return; double val = cost(e); // If an edge will not be processed because of its cost, it is // better to not put it in the tree. One drawback though is // that tree.size() is not equal to the total number of edges, // and output displayed by postProcessAllHalfEdges() may thus // not be very useful. if (nrFinal != 0 || val <= tolerance) { tree.insert(e, val); e.setAttributes(AbstractHalfEdge.MARKED); } } final void removeFromTree(final HalfEdge e) { for (Iterator<AbstractHalfEdge> it = e.fanIterator(); it.hasNext(); ) { HalfEdge f = (HalfEdge) it.next(); HalfEdge h = uniqueOrientation(f); if (!tree.remove(h)) notInTree++; h.clearAttributes(AbstractHalfEdge.MARKED); assert !tree.contains(h); } } private boolean processAllHalfEdges() { Stack<HalfEdge> stackNotProcessedObject = new Stack<HalfEdge>(); Stack<Double> stackNotProcessedValue = new Stack<Double>(); double cost = -1.0; while (!tree.isEmpty() && (nrFinal == 0 || (moreTriangles && nrTriangles < nrFinal) || (!moreTriangles && nrTriangles > nrFinal))) { preProcessEdge(); HalfEdge current = null; Iterator<QSortedTree.Node<HalfEdge>> itt = tree.iterator(); if (processed > 0 && (processed % progressBarStatus) == 0) thisLogger().info("Edges processed: "+processed); while (itt.hasNext()) { QSortedTree.Node<HalfEdge> q = itt.next(); current = q.getData(); cost = q.getValue(); if (nrFinal == 0 && cost > tolerance) break; if (canProcessEdge(current)) break; if (thisLogger().isLoggable(Level.FINE)) thisLogger().fine("Edge not processed: "+current); notProcessed++; // Add a penalty to edges which could not have been // processed. This has to be done outside this loop, // because PAVLSortedTree instances must not be modified // when walked through. if (nrFinal == 0) { stackNotProcessedObject.push(current); - if (tolerance > 0.0) + if (tolerance != 0.0) stackNotProcessedValue.push(Double.valueOf(cost+0.7*(tolerance - cost))); else // tolerance = cost = 0 stackNotProcessedValue.push(Double.valueOf(1.0)); } else { stackNotProcessedObject.push(current); double penalty = tree.getRootValue()*0.7; if (penalty == 0.0) penalty = 1.0; stackNotProcessedValue.push(Double.valueOf(cost+penalty)); } current = null; } if ((nrFinal == 0 && cost > tolerance) || current == null) break; // Update costs for edges which were not contracted while (stackNotProcessedObject.size() > 0) { double newCost = stackNotProcessedValue.pop().doubleValue(); HalfEdge f = stackNotProcessedObject.pop(); tree.update(f, newCost); } current = processEdge(current, cost); afterProcessHook(); processed++; if (noSwapAfterProcessing || minCos < -1.0) continue; // Loop around current.apex with // current = current.nextApexLoop(); // to check all edges which have current.apex // as apical vertex and swap them if this improves // mesh quality. Vertex o = current.origin(); boolean redo = true; while(redo) { redo = false; while(true) { if (current.checkSwap3D(minCos, maxEdgeLength) >= 0.0) { // Swap edge for (int i = 0; i < 3; i++) { current = current.next(); removeFromTree(current); } HalfEdge sym = current.sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } Vertex a = current.apex(); current = (HalfEdge) mesh.edgeSwap(current); swapped++; redo = true; // Now current = (ona) assert a == current.apex(); for (int i = 0; i < 3; i++) { current = current.next(); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } sym = current.next().sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); for (Iterator<AbstractHalfEdge> it = sym.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } } else { current = current.nextApexLoop(); if (current.origin() == o) break; } } } afterSwapHook(); } postProcessAllHalfEdges(); return processed > 0; } public void setNoSwapAfterProcessing(boolean noSwapAfterProcessing) { this.noSwapAfterProcessing = noSwapAfterProcessing; } final void dumpState() { ObjectOutputStream out = null; try { out = new ObjectOutputStream(new FileOutputStream(dumpFile)); out.writeObject(mesh); out.writeObject(tree); appendDumpState(out); out.close(); } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } } void appendDumpState(ObjectOutputStream out) throws IOException { } @SuppressWarnings("unchecked") final boolean restoreState() { try { FileInputStream istream = new FileInputStream(dumpFile); ObjectInputStream q = new ObjectInputStream(istream); System.out.println("Loading restored state"); mesh = (Mesh) q.readObject(); tree = (QSortedTree<HalfEdge>) q.readObject(); appendRestoreState(q); System.out.println("... Done."); q.close(); assert mesh.isValid(); } catch (FileNotFoundException ex) { return false; } catch (Exception ex) { ex.printStackTrace(); System.exit(-1); } return true; } void appendRestoreState(ObjectInputStream q) throws IOException { } protected void afterProcessHook() { } protected void afterSwapHook() { } }
true
true
private boolean processAllHalfEdges() { Stack<HalfEdge> stackNotProcessedObject = new Stack<HalfEdge>(); Stack<Double> stackNotProcessedValue = new Stack<Double>(); double cost = -1.0; while (!tree.isEmpty() && (nrFinal == 0 || (moreTriangles && nrTriangles < nrFinal) || (!moreTriangles && nrTriangles > nrFinal))) { preProcessEdge(); HalfEdge current = null; Iterator<QSortedTree.Node<HalfEdge>> itt = tree.iterator(); if (processed > 0 && (processed % progressBarStatus) == 0) thisLogger().info("Edges processed: "+processed); while (itt.hasNext()) { QSortedTree.Node<HalfEdge> q = itt.next(); current = q.getData(); cost = q.getValue(); if (nrFinal == 0 && cost > tolerance) break; if (canProcessEdge(current)) break; if (thisLogger().isLoggable(Level.FINE)) thisLogger().fine("Edge not processed: "+current); notProcessed++; // Add a penalty to edges which could not have been // processed. This has to be done outside this loop, // because PAVLSortedTree instances must not be modified // when walked through. if (nrFinal == 0) { stackNotProcessedObject.push(current); if (tolerance > 0.0) stackNotProcessedValue.push(Double.valueOf(cost+0.7*(tolerance - cost))); else // tolerance = cost = 0 stackNotProcessedValue.push(Double.valueOf(1.0)); } else { stackNotProcessedObject.push(current); double penalty = tree.getRootValue()*0.7; if (penalty == 0.0) penalty = 1.0; stackNotProcessedValue.push(Double.valueOf(cost+penalty)); } current = null; } if ((nrFinal == 0 && cost > tolerance) || current == null) break; // Update costs for edges which were not contracted while (stackNotProcessedObject.size() > 0) { double newCost = stackNotProcessedValue.pop().doubleValue(); HalfEdge f = stackNotProcessedObject.pop(); tree.update(f, newCost); } current = processEdge(current, cost); afterProcessHook(); processed++; if (noSwapAfterProcessing || minCos < -1.0) continue; // Loop around current.apex with // current = current.nextApexLoop(); // to check all edges which have current.apex // as apical vertex and swap them if this improves // mesh quality. Vertex o = current.origin(); boolean redo = true; while(redo) { redo = false; while(true) { if (current.checkSwap3D(minCos, maxEdgeLength) >= 0.0) { // Swap edge for (int i = 0; i < 3; i++) { current = current.next(); removeFromTree(current); } HalfEdge sym = current.sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } Vertex a = current.apex(); current = (HalfEdge) mesh.edgeSwap(current); swapped++; redo = true; // Now current = (ona) assert a == current.apex(); for (int i = 0; i < 3; i++) { current = current.next(); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } sym = current.next().sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); for (Iterator<AbstractHalfEdge> it = sym.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } } else { current = current.nextApexLoop(); if (current.origin() == o) break; } } } afterSwapHook(); } postProcessAllHalfEdges(); return processed > 0; }
private boolean processAllHalfEdges() { Stack<HalfEdge> stackNotProcessedObject = new Stack<HalfEdge>(); Stack<Double> stackNotProcessedValue = new Stack<Double>(); double cost = -1.0; while (!tree.isEmpty() && (nrFinal == 0 || (moreTriangles && nrTriangles < nrFinal) || (!moreTriangles && nrTriangles > nrFinal))) { preProcessEdge(); HalfEdge current = null; Iterator<QSortedTree.Node<HalfEdge>> itt = tree.iterator(); if (processed > 0 && (processed % progressBarStatus) == 0) thisLogger().info("Edges processed: "+processed); while (itt.hasNext()) { QSortedTree.Node<HalfEdge> q = itt.next(); current = q.getData(); cost = q.getValue(); if (nrFinal == 0 && cost > tolerance) break; if (canProcessEdge(current)) break; if (thisLogger().isLoggable(Level.FINE)) thisLogger().fine("Edge not processed: "+current); notProcessed++; // Add a penalty to edges which could not have been // processed. This has to be done outside this loop, // because PAVLSortedTree instances must not be modified // when walked through. if (nrFinal == 0) { stackNotProcessedObject.push(current); if (tolerance != 0.0) stackNotProcessedValue.push(Double.valueOf(cost+0.7*(tolerance - cost))); else // tolerance = cost = 0 stackNotProcessedValue.push(Double.valueOf(1.0)); } else { stackNotProcessedObject.push(current); double penalty = tree.getRootValue()*0.7; if (penalty == 0.0) penalty = 1.0; stackNotProcessedValue.push(Double.valueOf(cost+penalty)); } current = null; } if ((nrFinal == 0 && cost > tolerance) || current == null) break; // Update costs for edges which were not contracted while (stackNotProcessedObject.size() > 0) { double newCost = stackNotProcessedValue.pop().doubleValue(); HalfEdge f = stackNotProcessedObject.pop(); tree.update(f, newCost); } current = processEdge(current, cost); afterProcessHook(); processed++; if (noSwapAfterProcessing || minCos < -1.0) continue; // Loop around current.apex with // current = current.nextApexLoop(); // to check all edges which have current.apex // as apical vertex and swap them if this improves // mesh quality. Vertex o = current.origin(); boolean redo = true; while(redo) { redo = false; while(true) { if (current.checkSwap3D(minCos, maxEdgeLength) >= 0.0) { // Swap edge for (int i = 0; i < 3; i++) { current = current.next(); removeFromTree(current); } HalfEdge sym = current.sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); removeFromTree(sym); } Vertex a = current.apex(); current = (HalfEdge) mesh.edgeSwap(current); swapped++; redo = true; // Now current = (ona) assert a == current.apex(); for (int i = 0; i < 3; i++) { current = current.next(); for (Iterator<AbstractHalfEdge> it = current.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } sym = current.next().sym(); for (int i = 0; i < 2; i++) { sym = sym.next(); for (Iterator<AbstractHalfEdge> it = sym.fanIterator(); it.hasNext(); ) { HalfEdge e = uniqueOrientation((HalfEdge) it.next()); addToTree(e); } } } else { current = current.nextApexLoop(); if (current.origin() == o) break; } } } afterSwapHook(); } postProcessAllHalfEdges(); return processed > 0; }
diff --git a/src/core/org/apache/hadoop/security/authorize/ProxyUsers.java b/src/core/org/apache/hadoop/security/authorize/ProxyUsers.java index f8c27c2b4..0dd8a42ea 100644 --- a/src/core/org/apache/hadoop/security/authorize/ProxyUsers.java +++ b/src/core/org/apache/hadoop/security/authorize/ProxyUsers.java @@ -1,152 +1,152 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.security.authorize; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.StringUtils; public class ProxyUsers { private static final String CONF_HOSTS = ".hosts"; public static final String CONF_GROUPS = ".groups"; public static final String CONF_HADOOP_PROXYUSER = "hadoop.proxyuser."; public static final String CONF_HADOOP_PROXYUSER_RE = "hadoop\\.proxyuser\\."; private static Configuration conf=null; // list of groups and hosts per proxyuser private static Map<String, Collection<String>> proxyGroups = new HashMap<String, Collection<String>>(); private static Map<String, Collection<String>> proxyHosts = new HashMap<String, Collection<String>>(); /** * reread the conf and get new values for "hadoop.proxyuser.*.groups/hosts" */ public static synchronized void refreshSuperUserGroupsConfiguration(Configuration cn) { conf = cn; // remove alle existing stuff proxyGroups.clear(); proxyHosts.clear(); // get all the new keys for groups String regex = CONF_HADOOP_PROXYUSER_RE+"[^.]*\\"+CONF_GROUPS; Map<String,String> allMatchKeys = conf.getValByRegex(regex); for(Entry<String, String> entry : allMatchKeys.entrySet()) { proxyGroups.put(entry.getKey(), StringUtils.getStringCollection(entry.getValue())); } // now hosts regex = CONF_HADOOP_PROXYUSER_RE+"[^.]*\\"+CONF_HOSTS; allMatchKeys = conf.getValByRegex(regex); for(Entry<String, String> entry : allMatchKeys.entrySet()) { proxyHosts.put(entry.getKey(), StringUtils.getStringCollection(entry.getValue())); } } /** * Returns configuration key for effective user groups allowed for a superuser * * @param userName name of the superuser * @return configuration key for superuser groups */ public static String getProxySuperuserGroupConfKey(String userName) { return ProxyUsers.CONF_HADOOP_PROXYUSER+userName+ProxyUsers.CONF_GROUPS; } /** * Return configuration key for superuser ip addresses * * @param userName name of the superuser * @return configuration key for superuser ip-addresses */ public static String getProxySuperuserIpConfKey(String userName) { return ProxyUsers.CONF_HADOOP_PROXYUSER+userName+ProxyUsers.CONF_HOSTS; } /** * Authorize the superuser which is doing doAs * * @param user ugi of the effective or proxy user which contains a real user * @param remoteAddress the ip address of client * @param newConf configuration * @throws AuthorizationException */ - public static void authorize(UserGroupInformation user, String remoteAddress, + public static synchronized void authorize(UserGroupInformation user, String remoteAddress, Configuration newConf) throws AuthorizationException { if(conf == null) { refreshSuperUserGroupsConfiguration(newConf); } if (user.getRealUser() == null) { return; } boolean groupAuthorized = false; boolean ipAuthorized = false; UserGroupInformation superUser = user.getRealUser(); Collection<String> allowedUserGroups = proxyGroups.get( getProxySuperuserGroupConfKey(superUser.getShortUserName())); if (!allowedUserGroups.isEmpty()) { for (String group : user.getGroupNames()) { if (allowedUserGroups.contains(group)) { groupAuthorized = true; break; } } } if (!groupAuthorized) { throw new AuthorizationException("User: " + superUser.getUserName() + " is not allowed to impersonate " + user.getUserName()); } Collection<String> ipList = proxyHosts.get( getProxySuperuserIpConfKey(superUser.getShortUserName())); if (!ipList.isEmpty()) { for (String allowedHost : ipList) { InetAddress hostAddr; try { hostAddr = InetAddress.getByName(allowedHost); } catch (UnknownHostException e) { continue; } if (hostAddr.getHostAddress().equals(remoteAddress)) { // Authorization is successful ipAuthorized = true; } } } if(!ipAuthorized) { throw new AuthorizationException("Unauthorized connection for super-user: " + superUser.getUserName() + " from IP " + remoteAddress); } } }
true
true
public static void authorize(UserGroupInformation user, String remoteAddress, Configuration newConf) throws AuthorizationException { if(conf == null) { refreshSuperUserGroupsConfiguration(newConf); } if (user.getRealUser() == null) { return; } boolean groupAuthorized = false; boolean ipAuthorized = false; UserGroupInformation superUser = user.getRealUser(); Collection<String> allowedUserGroups = proxyGroups.get( getProxySuperuserGroupConfKey(superUser.getShortUserName())); if (!allowedUserGroups.isEmpty()) { for (String group : user.getGroupNames()) { if (allowedUserGroups.contains(group)) { groupAuthorized = true; break; } } } if (!groupAuthorized) { throw new AuthorizationException("User: " + superUser.getUserName() + " is not allowed to impersonate " + user.getUserName()); } Collection<String> ipList = proxyHosts.get( getProxySuperuserIpConfKey(superUser.getShortUserName())); if (!ipList.isEmpty()) { for (String allowedHost : ipList) { InetAddress hostAddr; try { hostAddr = InetAddress.getByName(allowedHost); } catch (UnknownHostException e) { continue; } if (hostAddr.getHostAddress().equals(remoteAddress)) { // Authorization is successful ipAuthorized = true; } } } if(!ipAuthorized) { throw new AuthorizationException("Unauthorized connection for super-user: " + superUser.getUserName() + " from IP " + remoteAddress); } }
public static synchronized void authorize(UserGroupInformation user, String remoteAddress, Configuration newConf) throws AuthorizationException { if(conf == null) { refreshSuperUserGroupsConfiguration(newConf); } if (user.getRealUser() == null) { return; } boolean groupAuthorized = false; boolean ipAuthorized = false; UserGroupInformation superUser = user.getRealUser(); Collection<String> allowedUserGroups = proxyGroups.get( getProxySuperuserGroupConfKey(superUser.getShortUserName())); if (!allowedUserGroups.isEmpty()) { for (String group : user.getGroupNames()) { if (allowedUserGroups.contains(group)) { groupAuthorized = true; break; } } } if (!groupAuthorized) { throw new AuthorizationException("User: " + superUser.getUserName() + " is not allowed to impersonate " + user.getUserName()); } Collection<String> ipList = proxyHosts.get( getProxySuperuserIpConfKey(superUser.getShortUserName())); if (!ipList.isEmpty()) { for (String allowedHost : ipList) { InetAddress hostAddr; try { hostAddr = InetAddress.getByName(allowedHost); } catch (UnknownHostException e) { continue; } if (hostAddr.getHostAddress().equals(remoteAddress)) { // Authorization is successful ipAuthorized = true; } } } if(!ipAuthorized) { throw new AuthorizationException("Unauthorized connection for super-user: " + superUser.getUserName() + " from IP " + remoteAddress); } }
diff --git a/src/main/java/eu/europeana/api2/web/model/xml/kml/KmlResponse.java b/src/main/java/eu/europeana/api2/web/model/xml/kml/KmlResponse.java index 737179d7..e883341d 100644 --- a/src/main/java/eu/europeana/api2/web/model/xml/kml/KmlResponse.java +++ b/src/main/java/eu/europeana/api2/web/model/xml/kml/KmlResponse.java @@ -1,30 +1,30 @@ package eu.europeana.api2.web.model.xml.kml; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import eu.europeana.corelib.definitions.solr.beans.BriefBean; @XmlRootElement(name="kml") public class KmlResponse { @XmlElement(name="Document") public Document document = new Document(); public void setItems(List<BriefBean> results) { for (BriefBean bean : results) { Placemark placemark = new Placemark(); placemark.name = bean.getTitle()[0]; StringBuilder sb = new StringBuilder(); - sb.append(bean.getEdmPlaceLongitude()[0]); + sb.append(bean.getEdmPlaceLongitude()); sb.append(","); - sb.append(bean.getEdmPlaceLatitude()[0]); + sb.append(bean.getEdmPlaceLatitude()); sb.append(",0"); placemark.point.coordinates = sb.toString(); document.placemarks.add(placemark); } } }
false
true
public void setItems(List<BriefBean> results) { for (BriefBean bean : results) { Placemark placemark = new Placemark(); placemark.name = bean.getTitle()[0]; StringBuilder sb = new StringBuilder(); sb.append(bean.getEdmPlaceLongitude()[0]); sb.append(","); sb.append(bean.getEdmPlaceLatitude()[0]); sb.append(",0"); placemark.point.coordinates = sb.toString(); document.placemarks.add(placemark); } }
public void setItems(List<BriefBean> results) { for (BriefBean bean : results) { Placemark placemark = new Placemark(); placemark.name = bean.getTitle()[0]; StringBuilder sb = new StringBuilder(); sb.append(bean.getEdmPlaceLongitude()); sb.append(","); sb.append(bean.getEdmPlaceLatitude()); sb.append(",0"); placemark.point.coordinates = sb.toString(); document.placemarks.add(placemark); } }
diff --git a/modules/resin/src/com/caucho/jsp/PageContextImpl.java b/modules/resin/src/com/caucho/jsp/PageContextImpl.java index 9ee152c64..00f85b034 100644 --- a/modules/resin/src/com/caucho/jsp/PageContextImpl.java +++ b/modules/resin/src/com/caucho/jsp/PageContextImpl.java @@ -1,2209 +1,2210 @@ /* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.jsp; import com.caucho.el.EL; import com.caucho.el.ExprEnv; import com.caucho.jsp.cfg.JspPropertyGroup; import com.caucho.jsp.el.*; import com.caucho.jstl.JstlPageContext; import com.caucho.server.http.AbstractHttpRequest; import com.caucho.server.http.AbstractResponseStream; import com.caucho.server.http.CauchoRequest; import com.caucho.server.http.CauchoResponse; import com.caucho.server.http.RequestAdapter; import com.caucho.server.http.ToCharResponseAdapter; import com.caucho.server.webapp.RequestDispatcherImpl; import com.caucho.server.webapp.WebApp; import com.caucho.util.CharBuffer; import com.caucho.util.DisplayableException; import com.caucho.util.HashMapImpl; import com.caucho.util.L10N; import com.caucho.util.NullEnumeration; import com.caucho.vfs.ClientDisconnectException; import com.caucho.vfs.FlushBuffer; import com.caucho.vfs.Path; import com.caucho.vfs.TempCharBuffer; import com.caucho.xpath.VarEnv; import org.w3c.dom.Node; import javax.el.ELContext; import javax.el.ELContextEvent; import javax.el.ELContextListener; import javax.el.ELResolver; import javax.el.ValueExpression; import javax.servlet.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.ErrorData; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.SkipPageException; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.VariableResolver; import javax.servlet.jsp.jstl.core.Config; import javax.servlet.jsp.jstl.fmt.LocalizationContext; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.JspFragment; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; public class PageContextImpl extends PageContext implements ExprEnv, JstlPageContext, VariableResolver { private static final Logger log = Logger.getLogger(PageContextImpl.class.getName()); private static final L10N L = new L10N(PageContextImpl.class); private WebApp _webApp; private JspWriterAdapter _jspAdapter = new JspWriterAdapter(); private JspServletOutputStream _jspOutputStream = new JspServletOutputStream(this); private Map<String,Object> _attributes; private Servlet _servlet; private HttpServletRequest _request; private ServletResponse _servletResponse; private CauchoResponse _response; private ToCharResponseAdapter _responseAdapter; private HttpSession _session; private JspWriter _topOut; private JspWriter _out; private String _errorPage; protected boolean _isFilled; private AbstractResponseStream _responseStream; private BodyResponseStream _bodyResponseStream; private JspPrintWriter _jspPrintWriter; private int _bufferSize = 8192; private boolean autoFlush; private BodyContentImpl _bodyOut; private Locale _locale; private BundleManager _bundleManager; private VarEnv _varEnv; private Node _nodeEnv; private final CharBuffer _cb = new CharBuffer(); private VariableResolver _varResolver; private PageELContext _elContextValue; private PageELContext _elContext; private ELResolver _elResolver; private javax.el.FunctionMapper _functionMapper; private PageVariableMapper _variableMapper; private boolean _hasException; private HashMap<String,Method> _functionMap; private ExpressionEvaluatorImpl _expressionEvaluator; private ELContextListener[] _elContextListeners; PageContextImpl() { _attributes = new HashMapImpl<String,Object>(); _bodyResponseStream = new BodyResponseStream(); _bodyResponseStream.start(); _jspPrintWriter = new JspPrintWriter(); } public PageContextImpl(WebApp webApp, Servlet servlet) { this(); if (webApp == null) throw new NullPointerException(); _webApp = webApp; _servlet = servlet; if (servlet instanceof Page) { Page page = (Page) servlet; _functionMap = page._caucho_getFunctionMap(); } else _functionMap = null; } public PageContextImpl(WebApp webApp, HashMap<String,Method> functionMap) { _webApp = webApp; _functionMap = functionMap; } public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPage, boolean needsSession, int bufferSize, boolean autoFlush) { HttpSession session = null; if (needsSession) session = ((HttpServletRequest) request).getSession(true); ServletConfig config = servlet.getServletConfig(); WebApp app = (WebApp) request.getServletContext(); _webApp = app; initialize(servlet, app, request, response, errorPage, session, bufferSize, autoFlush, false); } public void initialize(Servlet servlet, WebApp app, ServletRequest request, ServletResponse response, String errorPage, HttpSession session, int bufferSize, boolean autoFlush, boolean isPrintNullAsBlank) { _webApp = app; _servlet = servlet; _request = (HttpServletRequest) request; _servletResponse = response; if (response instanceof CauchoResponse && bufferSize <= TempCharBuffer.SIZE) { _response = (CauchoResponse) response; _responseAdapter = null; } else { // JSP.12.2.3 - JSP must use PrintWriter _responseAdapter = ToCharResponseAdapter.create((HttpServletResponse) response); _response = _responseAdapter; try { // jsp/017m response.setBufferSize(bufferSize); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } _responseStream = _response.getResponseStream(); _topOut = _jspAdapter; _responseStream.setAutoFlush(autoFlush); _jspAdapter.init(null, _responseStream); _jspAdapter.setPrintNullAsBlank(isPrintNullAsBlank); if (bufferSize != TempCharBuffer.SIZE) { try { _responseStream.setBufferSize(bufferSize); } catch (Exception e) { log.log(Level.FINE, e.toString(), e); } } // needed for includes from static pages _bufferSize = bufferSize; this.autoFlush = autoFlush; _session = session; _out = _topOut; _errorPage = errorPage; _locale = null; // jsp/1059, jsp/3147 // XXX: recycling is important for performance reasons _elContext = null; if (_elContextValue != null) _elContextValue.clear(); _hasException = false; //if (_attributes.size() > 0) // _attributes.clear(); _isFilled = false; _nodeEnv = null; if (servlet instanceof Page) { Page page = (Page) servlet; _functionMap = page._caucho_getFunctionMap(); } else _functionMap = null; } protected void init() { // XXX: important for performance reasons // jsp/1059, jsp/3147 _elContext = null; if (_elContextValue != null) _elContextValue.clear(); } protected void setOut(JspWriter out) { _out = out; } protected void clearAttributes() { _attributes.clear(); } /** * Returns the page attribute with the given name. * * @param name the attribute name. * * @return the attribute's value. */ public Object getAttribute(String name) { if (name == null) throw new NullPointerException(L.l("getAttribute must have a non-null name")); Object value = _attributes.get(name); if (value != null) return value; else if (! _isFilled) { fillAttribute(); value = _attributes.get(name); } if (value != null) { } else if (name.equals(OUT)) { // jsp/162d return _out; } return value; } /** * Sets the page attribute with the given name. * * @param name the attribute name. * @param attribute the new value */ public void setAttribute(String name, Object attribute) { if (name == null) throw new NullPointerException(L.l("setAttribute must have a non-null name")); if (attribute != null) _attributes.put(name, attribute); else _attributes.remove(name); } /** * Sets the page attribute with the given name. * * @param name the attribute name. * @param attribute the new value */ public Object putAttribute(String name, Object attribute) { if (name == null) throw new NullPointerException(L.l("putAttribute must have a non-null name")); if (attribute != null) return _attributes.put(name, attribute); else return _attributes.remove(name); } /** * Removes a named attribute from the page context. * * @param name the name of the attribute to remove */ public void removeAttribute(String name) { if (name == null) throw new NullPointerException(L.l("removeAttribute must have a non-null name")); _attributes.remove(name); // jsp/162b if (_request != null) _request.removeAttribute(name); if (_session != null) { try { _session.removeAttribute(name); } catch (IllegalStateException e) { // jsp/162f log.log(Level.FINE, e.toString(), e); } } if (_webApp != null) _webApp.removeAttribute(name); } private Enumeration<String> getAttributeNames() { if (! _isFilled) fillAttribute(); return Collections.enumeration(_attributes.keySet()); } /** * Fills the predefined page content _attributes with their values. */ protected void fillAttribute() { _isFilled = true; _attributes.put(PAGE, _servlet); _attributes.put(PAGECONTEXT, this); _attributes.put(REQUEST, getCauchoRequest()); _attributes.put(RESPONSE, getCauchoResponse()); if (_servlet != null) _attributes.put(CONFIG, _servlet.getServletConfig()); if (getSession() != null) _attributes.put(SESSION, getSession()); _attributes.put(APPLICATION, getApplication()); } public Object getAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return getAttribute(name); case REQUEST_SCOPE: return getCauchoRequest().getAttribute(name); case SESSION_SCOPE: { HttpSession session = getSession(); return session != null ? session.getValue(name) : null; } case APPLICATION_SCOPE: return getApplication().getAttribute(name); default: throw new IllegalArgumentException(); } } public void setAttribute(String name, Object value, int scope) { switch (scope) { case PAGE_SCOPE: setAttribute(name, value); break; case REQUEST_SCOPE: getCauchoRequest().setAttribute(name, value); break; case SESSION_SCOPE: if (getSession() != null) getSession().putValue(name, value); break; case APPLICATION_SCOPE: getApplication().setAttribute(name, value); break; default: throw new IllegalArgumentException(); } } public void removeAttribute(String name, int scope) { if (name == null) throw new NullPointerException(L.l("removeAttribute must have a non-null name")); switch (scope) { case PAGE_SCOPE: if (name != null) _attributes.remove(name); break; case REQUEST_SCOPE: getCauchoRequest().removeAttribute(name); break; case SESSION_SCOPE: if (getSession() != null) getSession().removeValue(name); break; case APPLICATION_SCOPE: getApplication().removeAttribute(name); break; default: throw new IllegalArgumentException(); } } public Enumeration getAttributeNames(int scope) { switch (scope) { case PAGE_SCOPE: return getAttributeNames(); case REQUEST_SCOPE: return getCauchoRequest().getAttributeNames(); case SESSION_SCOPE: if (getSession() != null) return new StringArrayEnum(getSession().getValueNames()); else return NullEnumeration.create(); case APPLICATION_SCOPE: return getApplication().getAttributeNames(); default: throw new IllegalArgumentException(); } } public Enumeration getAttributeNamesInScope(int scope) { return getAttributeNames(scope); } /** * Finds an attribute in any of the scopes from page to webApp. * * @param name the attribute name. * * @return the attribute value */ public Object findAttribute(String name) { Object value; if ((value = getAttribute(name)) != null) return value; HttpServletRequest req = getCauchoRequest(); if (req != null && (value = getCauchoRequest().getAttribute(name)) != null) return value; HttpSession session = getSession(); if (session != null) { try { value = session.getAttribute(name); } catch (IllegalStateException e) { // jsp/162e log.log(Level.FINE, e.toString(), e); } if (value != null) return value; } return getServletContext().getAttribute(name); } /** * Return the scope of the named attribute. * * @param name the name of the attribute. * * @return the scope of the attribute */ public int getAttributesScope(String name) { if (getAttribute(name) != null) return PAGE_SCOPE; if (getCauchoRequest().getAttribute(name) != null) return REQUEST_SCOPE; HttpSession session = getSession(); if (session != null && session.getValue(name) != null) return SESSION_SCOPE; if (getApplication().getAttribute(name) != null) return APPLICATION_SCOPE; return 0; } /** * Sets the attribute map. */ public Map<String,Object> setMap(Map<String,Object> map) { Map<String,Object> oldMap = _attributes; _attributes = map; return oldMap; } /** * Returns the current writer. */ public JspWriter getOut() { return _out; } /** * Pushes a new BodyContent onto the JspWriter stack. */ public BodyContent pushBody() { BodyContentImpl body; if (_bodyOut != null) { body = _bodyOut; _bodyOut = null; } else body = BodyContentImpl.allocate(); CauchoResponse response = getCauchoResponse(); body.init(_out); _out = body; response.setForbidForward(true); try { _bodyResponseStream.flushBuffer(); } catch (IOException e) { } _bodyResponseStream.start(); _bodyResponseStream.setWriter(body); _bodyResponseStream.setEncoding(response.getCharacterEncoding()); response.setResponseStream(_bodyResponseStream); return body; } /** * Pushes a new writer onto the JspWriter stack. */ public JspWriter pushBody(Writer writer) { if (writer == _out) return null; JspWriter oldWriter = _out; StreamJspWriter jspWriter; jspWriter = new StreamJspWriter(); jspWriter.init(_out, writer); _out = jspWriter; getCauchoResponse().setForbidForward(true); _bodyResponseStream.setWriter(writer); getCauchoResponse().setResponseStream(_bodyResponseStream); return oldWriter; } /** * Pops the BodyContent from the JspWriter stack. * * @return the enclosing writer */ @Override public JspWriter popBody() { BodyContentImpl bodyOut = (BodyContentImpl) _out; _out = bodyOut.getEnclosingWriter(); try { _bodyResponseStream.flushBuffer(); //if (_writeStream != null) // _writeStream.flushBuffer(); } catch (IOException e) { log.log(Level.WARNING, e.toString(), e); } if (_out instanceof StreamJspWriter) { StreamJspWriter writer = (StreamJspWriter) _out; _bodyResponseStream.setWriter(writer.getWriter()); if (_response != null) _bodyResponseStream.setEncoding(_response.getCharacterEncoding()); } else if (_out instanceof JspWriterAdapter) { if (getCauchoResponse() != null) { getCauchoResponse().setResponseStream(_responseStream); getCauchoResponse().setForbidForward(false); } } else if (_out instanceof BodyContentImpl) { BodyContentImpl body = (BodyContentImpl) _out; _bodyResponseStream.setWriter(body.getWriter()); if (_response != null) _bodyResponseStream.setEncoding(_response.getCharacterEncoding()); } return _out; } /** * Pops the BodyContent from the JspWriter stack. * * @return the enclosing writer */ public JspWriter popAndReleaseBody() throws IOException { BodyContentImpl body = (BodyContentImpl) getOut(); JspWriter out = popBody(); releaseBody(body); return out; } public void releaseBody(BodyContentImpl out) throws IOException { if (_bodyOut == null) { out.releaseNoFree(); _bodyOut = out; } else out.release(); } /** * Pops the BodyContent from the JspWriter stack. * * @param oldWriter the old writer */ public JspWriter setWriter(JspWriter oldWriter) { if (_out == oldWriter) return oldWriter; /* if (_out instanceof FlushBuffer) { try { ((FlushBuffer) _out).flushBuffer(); } catch (IOException e) { } } */ try { if (_out instanceof FlushBuffer) ((FlushBuffer) _out).flushBuffer(); } catch (IOException e) { } _out = oldWriter; // jsp/18eg if (_out instanceof StreamJspWriter) { StreamJspWriter writer = (StreamJspWriter) _out; _bodyResponseStream.setWriter(writer.getWriter()); } else if (_out instanceof JspWriterAdapter) { if (getCauchoResponse() != null) { getCauchoResponse().setResponseStream(_responseStream); getCauchoResponse().setForbidForward(false); } } else if (_out instanceof BodyContentImpl) { BodyContentImpl body = (BodyContentImpl) _out; _bodyResponseStream.setWriter(body.getWriter()); } return oldWriter; // getCauchoResponse().setWriter(_os); } /** * Returns the top writer. */ public PrintWriter getTopWriter() throws IOException { CauchoResponse response = getCauchoResponse(); AbstractResponseStream currentStream = response.getResponseStream(); response.setResponseStream(_responseStream); try { return response.getWriter(); } finally { response.setResponseStream(currentStream); } } /** * Returns the response output stream. */ ServletOutputStream getOutputStream() { try { return getCauchoResponse().getOutputStream(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns the underlying servlet for the page. */ public Object getPage() { return _servlet; } /** * Returns the servlet request for the page. */ @Override public HttpServletRequest getRequest() { return _request; } /** * Returns the servlet response for the page. */ @Override public HttpServletResponse getResponse() { return getCauchoResponse(); } /** * Returns the servlet response for the page. */ public CauchoResponse getCauchoResponse() { return _response; } /** * Returns the servlet response for the page. */ public HttpServletRequest getCauchoRequest() { return _request; } public HttpSession getSession() { if (_session == null) { HttpServletRequest req = getCauchoRequest(); if (req != null) _session = req.getSession(false); } return _session; } /** * Returns the session, throwing an IllegalStateException if it's * not available. */ public HttpSession getSessionScope() { if (_session == null) _session = getCauchoRequest().getSession(false); if (_session == null) throw new IllegalStateException(L.l("session is not available")); return _session; } public ServletConfig getServletConfig() { return _servlet.getServletConfig(); } /** * Returns the page's servlet context. */ public ServletContext getServletContext() { return _webApp; } /** * Returns the page's webApp. */ public WebApp getApplication() { return _webApp; } /** * Returns the page's error page. */ public String getErrorPage() { return _errorPage; } /** * Sets the page's error page. */ public void setErrorPage(String errorPage) { _errorPage = errorPage; } public Exception getException() { return (Exception) getThrowable(); } /** * Returns the Throwable stored by the error page. */ public Throwable getThrowable() { Throwable exn = (Throwable) getCauchoRequest().getAttribute(EXCEPTION); if (exn == null) exn = (Throwable) getCauchoRequest().getAttribute("javax.servlet.error.exception_type"); if (exn == null) exn = (Throwable) getCauchoRequest().getAttribute("javax.servlet.jsp:jspException"); return exn; } public void include(String relativeUrl) throws ServletException, IOException { include(relativeUrl, false); } /** * Include another servlet into the current output stream. * * @param relativeUrl url relative to the current request. */ public void include(String relativeUrl, String query, boolean flush) throws ServletException, IOException { if (! "".equals(query)) { relativeUrl = encode(relativeUrl, query); } include(relativeUrl, flush); } public StringBuilder encode(String relativeUrl) { StringBuilder sb = new StringBuilder(); sb.append(relativeUrl); if (relativeUrl.indexOf('?') >= 0) sb.append('&'); else sb.append('?'); return sb; } private String encode(String relativeUrl, String query) { StringBuilder sb = new StringBuilder(); sb.append(relativeUrl); sb = encode(sb, query); return sb.toString(); } public StringBuilder encode(StringBuilder sb, String query) { int len = query.length(); for (int i = 0; i < len; i++) { char ch = query.charAt(i); switch (ch) { case ' ': sb.append('+'); break; case '+': sb.append("%2b"); break; case '%': sb.append("%25"); break; case '&': sb.append("%3D"); break; default: sb.append(ch); break; } } return sb; } /** * Include another servlet into the current output stream. * * @param relativeUrl url relative to the current request. */ public void include(String relativeUrl, boolean flush) throws ServletException, IOException { RequestDispatcher rd = null; HttpServletRequest req = (HttpServletRequest) getCauchoRequest(); HttpServletResponse res = (HttpServletResponse) getResponse(); if (relativeUrl != null && ! relativeUrl.startsWith("/")) { String path = RequestAdapter.getPageServletPath(req); String pathInfo = RequestAdapter.getPagePathInfo(req); String servletPath = req.getServletPath(); if (path != null) { // jsp/15du vs jsp/15lk (tck) if (pathInfo != null && ! path.equals(servletPath)) path += pathInfo; } else if (pathInfo != null) path = pathInfo; else path = "/"; int p = path.lastIndexOf('/'); if (p >= 0) { _cb.clear(); _cb.append(path, 0, p + 1); _cb.append(relativeUrl); rd = getServletContext().getRequestDispatcher(_cb.toString()); } } if (rd == null) rd = req.getRequestDispatcher(relativeUrl); if (rd == null) throw new ServletException(L.l("unknown including page `{0}'.", relativeUrl)); // the FlushBuffer needs to happen to deal with OpenSymphony (Bug#1710) // jsp/17e9, 15lc, 15m4 if (! flush) { } else if (_out instanceof FlushBuffer) ((FlushBuffer) _out).flushBuffer(); else if (flush) _out.flush(); rd.include(req, res); } /** * Include another servlet into the current output stream. * * @param relativeUrl url relative to the current request. */ public void forward(String relativeUrl, String query) throws ServletException, IOException { if (! "".equals(query)) relativeUrl = encode(relativeUrl, query); forward(relativeUrl); } /** * Forward a subrequest relative to the current url. Absolute URLs * are relative to the context root. * * @param relativeUrl url relative to the current file */ public void forward(String relativeUrl) throws ServletException, IOException { if (_bufferSize == 0) { // jsp/15m3, tck if (_out instanceof FlushBuffer) ((FlushBuffer) _out).flushBuffer(); else _out.flush(); } RequestDispatcher rd = null; HttpServletRequest req = (HttpServletRequest) getCauchoRequest(); HttpServletResponse res = (HttpServletResponse) getResponse(); if (res.isCommitted() && ! _webApp.isAllowForwardAfterFlush()) throw new IllegalStateException(L.l("can't forward after writing HTTP headers")); else if (! _webApp.isAllowForwardAfterFlush()) _out.clear(); //jsp/183n jsp/18kl jsp/1625 while (_out instanceof BodyContentImpl) { popBody(); } if (relativeUrl != null && ! relativeUrl.startsWith("/")) { String servletPath = RequestAdapter.getPageServletPath(req); int p = servletPath.lastIndexOf('/'); if (p >= 0) { _cb.clear(); _cb.append(servletPath, 0, p + 1); _cb.append(relativeUrl); rd = getServletContext().getRequestDispatcher(_cb.toString()); } } if (rd == null) rd = req.getRequestDispatcher(relativeUrl); if (rd == null) throw new ServletException(L.l("unknown forwarding page: `{0}'", relativeUrl)); // rd.forward(req, res); rd.forward(req, _servletResponse); //_out.close(); _responseStream.close(); } /** * Handles an exception caught in the JSP page. * * @param e the caught exception */ public void handlePageException(Exception e) throws ServletException, IOException { handlePageException((Throwable) e); } /** * Handles an exception caught in the JSP page. * * @param e the caught exception */ public void handlePageException(Throwable e) throws ServletException, IOException { if (e instanceof SkipPageException) return; HttpServletRequest request = getCauchoRequest(); request.setAttribute("javax.servlet.jsp.jspException", e); CauchoResponse response = getCauchoResponse(); response.setForbidForward(false); response.setResponseStream(_responseStream); response.killCache(); response.setNoCache(true); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); _hasException = true; if (e instanceof ClientDisconnectException) throw (ClientDisconnectException) e; if (! (_servlet instanceof Page)) { } else if (getApplication() == null || getApplication().getJsp() == null || ! getApplication().getJsp().isRecompileOnError()) { } else if (e instanceof OutOfMemoryError) { } else if (e instanceof Error) { try { Path workDir = getApplication().getAppDir().lookup("WEB-INF/work"); String className = _servlet.getClass().getName(); Path path = workDir.lookup(className.replace('.', '/') + ".class"); log.warning("Removing " + path + " due to " + e); path.remove(); } catch (Exception e1) { } Page page = (Page) _servlet; page._caucho_unload(); if (! page.isDead()) { page.setDead(); page.destroy(); } } _topOut.clearBuffer(); if (_errorPage != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, e.toString(), e); } else if (e instanceof DisplayableException) { log.warning(e.getMessage()); } else { log.log(Level.WARNING, e.toString(), e); } getCauchoRequest().setAttribute(EXCEPTION, e); getCauchoRequest().setAttribute("javax.servlet.error.exception", e); getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e); getCauchoRequest().setAttribute("javax.servlet.error.request_uri", getCauchoRequest().getRequestURI()); try { RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage); if (rd instanceof RequestDispatcherImpl) { getCauchoResponse().setHasError(true); ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse()); } else { if (rd != null) { getCauchoResponse().killCache(); getCauchoResponse().setNoCache(true); rd.forward(getCauchoRequest(), getCauchoResponse()); } else { log.log(Level.FINE, e.toString(), e); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } } } catch (FileNotFoundException e2) { log.log(Level.WARNING, e.toString(), e2); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } catch (IOException e2) { log.log(Level.FINE, e.toString(), e2); } return; } /* if (_servlet instanceof Page && ! (e instanceof LineMapException)) { LineMap lineMap = ((Page) _servlet)._caucho_getLineMap(); if (lineMap != null) e = new JspLineException(e, lineMap); } */ if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new ServletException(e); } } /** * Returns the error data */ public ErrorData getErrorData() { String uri = (String) getCauchoRequest().getAttribute(AbstractHttpRequest.ERROR_URI); if (uri == null) return null; Integer status = (Integer) getCauchoRequest().getAttribute(AbstractHttpRequest.STATUS_CODE); return new ErrorData(getThrowable(), status == null ? 0 : status.intValue(), (String) getCauchoRequest().getAttribute(AbstractHttpRequest.ERROR_URI), (String) getCauchoRequest().getAttribute(AbstractHttpRequest.SERVLET_NAME)); } /** * Returns the variable resolver */ public javax.servlet.jsp.el.VariableResolver getVariableResolver() { return this; } /** * Returns the expression evaluator */ public ExpressionEvaluator getExpressionEvaluator() { if (_expressionEvaluator == null) _expressionEvaluator = new ExpressionEvaluatorImpl(getELContext()); return _expressionEvaluator; } /** * Returns the expression evaluator */ public ELContext getELContext() { if (_elContext != null) return _elContext; if (_elContextValue == null) { WebApp webApp = getApplication(); JspApplicationContextImpl jspContext = webApp.getJspApplicationContext(); if (_elResolver == null) { ELResolver[] resolverArray = jspContext.getELResolverArray(); _elResolver = new PageContextELResolver(this, resolverArray); } if (_functionMapper == null) _functionMapper = new PageFunctionMapper(); if (_variableMapper == null) _variableMapper = new PageVariableMapper(); _elContextValue = new PageELContext(); if (_elContextListeners == null) _elContextListeners = jspContext.getELListenerArray(); } _elContext = _elContextValue; if (_elContextListeners.length > 0) { ELContextEvent event = new ELContextEvent(_elContext); for (int i = 0; i < _elContextListeners.length; i++) { _elContextListeners[i].contextCreated(event); } } return _elContext; } /** * Given a relative url, return the absolute url. * * @param value the relative url * * @return the absolute url. */ private String getRelativeUrl(String value) { if (value.length() > 0 && value.charAt(0) == '/') return value; ServletContext context = getServletContext(); String contextPath = RequestAdapter.getPageContextPath(getCauchoRequest()); String uri = RequestAdapter.getPageURI(getCauchoRequest()); String relPath = uri.substring(contextPath.length()); int p = relPath.lastIndexOf('/'); String urlPwd = p <= 0 ? "/" : relPath.substring(0, p + 1); return urlPwd + value; } /** * Releases the context. */ public void release() { try { _servlet = null; if (_attributes.size() > 0) _attributes.clear(); /* XXX: if (! autoFlush && response instanceof Response) ((Response) response).setDisableAutoFlush(false); */ getCauchoResponse().setResponseStream(_responseStream); // getCauchoResponse().setFlushBuffer(null); _request = null; _webApp = null; _session = null; while (_out instanceof AbstractJspWriter) { if (_out instanceof AbstractJspWriter) _out = ((AbstractJspWriter) _out).popWriter(); } JspWriter out = _out; _out = null; _topOut = null; _nodeEnv = null; if (_elContext != null) _elContext.clear(); _jspOutputStream.release(); AbstractResponseStream responseStream = _responseStream; _responseStream = null; ToCharResponseAdapter resAdapt = _responseAdapter; _responseAdapter = null; if (resAdapt != null) { // jsp/15l3 resAdapt.finish(); //_responseAdapter.close(); ToCharResponseAdapter.free(resAdapt); } /* // server/137q if (! _hasException && responseStream != null) responseStream.close(); */ _servletResponse = null; _response = null; } catch (IOException e) { _out = null; } } /** * Returns the localized message appropriate for the current context. */ public String getLocalizedMessage(String key, Object []args, String basename) { Object lc = basename; if (lc == null) lc = getAttribute("caucho.bundle"); if (lc == null) lc = Config.find(this, Config.FMT_LOCALIZATION_CONTEXT); return getLocalizedMessage(lc, key, args, basename); } /** * Returns the localized message appropriate for the current context. */ public String getLocalizedMessage(Object lc, String key, Object []args, String basename) { String bundleString = null; // jsp/1c51, jsp/1c54 String prefix = (String) getAttribute("caucho.bundle.prefix"); // jsp/1c3x if (key == null) key = ""; if (prefix != null) key = prefix + key; if (lc == null) { lc = basename; if (lc == null || "".equals(lc)) lc = getAttribute("caucho.bundle"); if (lc == null) lc = Config.find(this, Config.FMT_LOCALIZATION_CONTEXT); } Locale locale = null; if (lc instanceof LocalizationContext) { ResourceBundle bundle = ((LocalizationContext) lc).getResourceBundle(); locale = ((LocalizationContext) lc).getLocale(); try { if (bundle != null) bundleString = bundle.getString(key); } catch (Exception e) { } } else if (lc instanceof String) { LocalizationContext loc = getBundle((String) lc); locale = loc.getLocale(); ResourceBundle bundle = loc.getResourceBundle(); try { if (bundle != null) bundleString = bundle.getString(key); } catch (Exception e) { } } if (bundleString == null) return "???" + key + "???"; else if (args == null || args.length == 0) return bundleString; if (locale == null) locale = getLocale(); if (locale != null) return new MessageFormat(bundleString, locale).format(args); else return new MessageFormat(bundleString).format(args); } /** * Returns the localized message appropriate for the current context. */ public LocalizationContext getBundle(String name) { Object localeObj = Config.find(this, Config.FMT_LOCALE); LocalizationContext bundle = null; BundleManager manager = getBundleManager(); if (localeObj instanceof Locale) { Locale locale = (Locale) localeObj; bundle = manager.getBundle(name, locale); } else if (localeObj instanceof String) { Locale locale = getLocale((String) localeObj, null); bundle = manager.getBundle(name, locale); } else { String acceptLanguage = getCauchoRequest().getHeader("Accept-Language"); if (acceptLanguage != null) { String cacheKey = name + acceptLanguage; bundle = manager.getBundle(name, cacheKey, getCauchoRequest().getLocales()); } } if (bundle != null) return bundle; Object fallback = Config.find(this, Config.FMT_FALLBACK_LOCALE); if (fallback instanceof Locale) { Locale locale = (Locale) fallback; bundle = manager.getBundle(name, locale); } else if (fallback instanceof String) { String localeName = (String) fallback; Locale locale = getLocale(localeName, null); bundle = manager.getBundle(name, locale); } if (bundle != null) return bundle; bundle = manager.getBundle(name); if (bundle != null) return bundle; else { return BundleManager.NULL_BUNDLE; } } /** * Returns the currently active locale. */ public Locale getLocale() { if (_locale != null) return _locale; _locale = getLocaleImpl(); if (_locale != null) getResponse().setLocale(_locale); return _locale; } /** * Returns the currently active locale. */ private Locale getLocaleImpl() { Object localeObj = Config.find(this, Config.FMT_LOCALIZATION_CONTEXT); LocalizationContext lc; Locale locale = null; if (localeObj instanceof LocalizationContext) { lc = (LocalizationContext) localeObj; locale = lc.getLocale(); if (locale != null) return locale; } localeObj = Config.find(this, Config.FMT_LOCALE); if (localeObj instanceof Locale) return (Locale) localeObj; else if (localeObj instanceof String) return getLocale((String) localeObj, null); lc = (LocalizationContext) getAttribute("caucho.bundle"); if (lc != null) locale = lc.getLocale(); if (locale != null) return locale; String acceptLanguage = getCauchoRequest().getHeader("Accept-Language"); if (acceptLanguage != null) { Enumeration e = getCauchoRequest().getLocales(); if (e != null && e.hasMoreElements()) locale = (Locale) e.nextElement(); } localeObj = Config.find(this, Config.FMT_FALLBACK_LOCALE); if (localeObj instanceof Locale) return (Locale) localeObj; else if (localeObj instanceof String) return getLocale((String) localeObj, null); else return null; } public static Locale getLocale(String value, String variant) { Locale locale = null; int len = value.length(); CharBuffer cb = new CharBuffer(); int i = 0; char ch = 0; for (; i < len && (ch = value.charAt(i)) != '_' && ch != '-'; i++) cb.append(ch); String language = cb.toString(); if (ch == '_' || ch == '-') { cb.clear(); for (i++; i < len && (ch = value.charAt(i)) != '_' && ch != '-'; i++) cb.append(ch); String country = cb.toString(); if (variant != null && ! variant.equals("")) return new Locale(language, country, variant); else return new Locale(language, country); } else if (variant != null && ! variant.equals("")) return new Locale(language, "", variant); else return new Locale(language, ""); } public static void printBody(BodyContentImpl body, boolean isEscaped) throws IOException { JspWriter out = body.getEnclosingWriter(); CharBuffer string = body.getCharBuffer(); char []cBuf = string.getBuffer(); int length = string.length() - 1; for (; length >= 0; length--) { char ch = cBuf[length]; if (ch != ' ' && ch != '\n' && ch != '\t' && ch != '\r') break; } length++; int i; for (i = 0; i < length; i++) { char ch = cBuf[i]; if (ch != ' ' && ch != '\n' && ch != '\t' && ch != '\r') break; } if (! isEscaped) { out.write(cBuf, i, length - i); return; } for (; i < length; i++) { char ch = cBuf[i]; switch (ch) { case '<': out.write("&lt;"); break; case '>': out.write("&gt;"); break; case '&': out.write("&amp;"); break; case '\'': out.write("&#039;"); break; case '"': out.write("&#034;"); break; default: out.write((char) ch); break; } } } /** * Evaluates the fragment, returing the string value. */ public String invoke(JspFragment fragment) throws JspException, IOException { if (fragment == null) return ""; BodyContentImpl body = (BodyContentImpl) pushBody(); try { fragment.invoke(body); return body.getString(); } finally { popBody(); body.release(); } } /** * Evaluates the fragment, returing the string value. */ public String invokeTrim(JspFragment fragment) throws JspException, IOException { if (fragment == null) return ""; BodyContentImpl body = (BodyContentImpl) pushBody(); try { fragment.invoke(body); return body.getTrimString(); } finally { popBody(); body.release(); } } /** * Evaluates the fragment, returing a reader */ public Reader invokeReader(JspFragment fragment) throws JspException, IOException { if (fragment == null) return null; BodyContentImpl body = (BodyContentImpl) pushBody(); try { fragment.invoke(body); return body.getReader(); } finally { popBody(); body.release(); } } /** * Parses a boolean value. */ static public boolean toBoolean(String value) { if (value == null) return false; else if (value.equalsIgnoreCase("true")) return true; else if (value.equalsIgnoreCase("false")) return false; else return value.trim().equalsIgnoreCase("true"); } /** * Set/Remove a page attribute. */ public void defaultSetOrRemove(String var, Object value) { if (value != null) putAttribute(var, value); else removeAttribute(var); } /** * Set/Remove a page attribute. */ public void pageSetOrRemove(String var, Object value) { if (value != null) _attributes.put(var, value); else _attributes.remove(var); } /** * Set/Remove a request attribute. */ public void requestSetOrRemove(String var, Object value) { if (value != null) getCauchoRequest().setAttribute(var, value); else getCauchoRequest().removeAttribute(var); } /** * Set/Remove a session attribute. */ public void sessionSetOrRemove(String var, Object value) { if (value != null) getSession().setAttribute(var, value); else getSession().removeAttribute(var); } /** * Set/Remove an webApp attribute. */ public void applicationSetOrRemove(String var, Object value) { if (value != null) getApplication().setAttribute(var, value); else getApplication().removeAttribute(var); } /** * Returns true if the EL ignores exceptions */ public boolean isIgnoreException() { JspPropertyGroup jsp = getApplication().getJsp(); return (jsp == null || jsp.isIgnoreELException()); } /** * Returns the XPath variable environment corresponding to this page */ public VarEnv getVarEnv() { if (_varEnv == null) _varEnv = new PageVarEnv(); return _varEnv; } /** * Returns the XPath node environment corresponding to this page */ public Node getNodeEnv() { return _nodeEnv; } /** * Returns the XPath node environment corresponding to this page */ public void setNodeEnv(Node node) { _nodeEnv = node; } /** * Creates an expression. */ public ValueExpression createExpr(ValueExpression expr, String exprString, Class type) { if (_variableMapper == null || _variableMapper.isConstant()) return expr; return JspUtil.createValueExpression(getELContext(), type, exprString); } /** * Finds an attribute in any of the scopes from page to webApp. * * @param name the attribute name. * * @return the attribute value */ public Object resolveVariable(String name) throws javax.el.ELException { Object value = findAttribute(name); if (value != null) return value; ELContext elContext = getELContext(); /* if (_elContext == null) _elContext = EL.getEnvironment(); */ return elContext.getELResolver().getValue(elContext, null, name); } /** * Returns the bundle manager. */ private BundleManager getBundleManager() { if (_bundleManager == null) _bundleManager = BundleManager.create(); return _bundleManager; } /** * Represents the XPath environment for this page. */ public class PageVarEnv extends VarEnv { /** * Returns the value corresponding to the name. */ public Object getValue(String name) { Object value = findAttribute(name); if (value != null) return value; int p = name.indexOf(':'); if (p < 0) { // jsp/1m43, TCK throw new javax.el.ELException(L.l("'{0}' is an unknown variable", name)); } String prefix = name.substring(0, p); String suffix = name.substring(p + 1); if (prefix.equals("param")) return getCauchoRequest().getParameter(suffix); else if (prefix.equals("header")) return ((HttpServletRequest) getCauchoRequest()).getHeader(suffix); else if (prefix.equals("cookie")) { Cookie cookie; HttpServletRequest request = (HttpServletRequest) getCauchoRequest(); if (request instanceof CauchoRequest) cookie = ((CauchoRequest) request).getCookie(suffix); else cookie = null; if (cookie != null) return cookie.getValue(); else return null; } else if (prefix.equals("initParam")) return getApplication().getInitParameter(suffix); else if (prefix.equals("pageScope")) { return getAttribute(suffix); } else if (prefix.equals("requestScope")) return getCauchoRequest().getAttribute(suffix); else if (prefix.equals("sessionScope")) return getSession().getAttribute(suffix); else if (prefix.equals("applicationScope")) return getApplication().getAttribute(suffix); else return null; } } static class StringArrayEnum implements Enumeration { private int _index; private String []_values; StringArrayEnum(String []values) { _values = values; } public boolean hasMoreElements() { return _index < _values.length; } public Object nextElement() { return _values[_index++]; } } public class PageELContext extends ServletELContext { private HashMap<Class,Object> _contextMap; public PageELContext() { } @Override public Object getContext(Class key) { if (key == JspContext.class) return PageContextImpl.this; if (key == null) throw new NullPointerException(); else if (_contextMap != null) return _contextMap.get(key); else return null; } @Override public void putContext(Class key, Object contextObject) { if (key == null) throw new NullPointerException(); if (_contextMap == null) _contextMap = new HashMap<Class,Object>(8); _contextMap.put(key, contextObject); } public void clear() { if (_contextMap != null) _contextMap.clear(); setLocale(null); } public PageContextImpl getPageContext() { return PageContextImpl.this; } @Override public ServletContext getApplication() { return PageContextImpl.this.getApplication(); } @Override public Object getApplicationScope() { return new PageContextAttributeMap(PageContextImpl.this, APPLICATION_SCOPE); } @Override public HttpServletRequest getRequest() { return (HttpServletRequest) PageContextImpl.this.getRequest(); } @Override public Object getRequestScope() { return new PageContextAttributeMap(PageContextImpl.this, REQUEST_SCOPE); } @Override public Object getSessionScope() { return new PageContextAttributeMap(PageContextImpl.this, SESSION_SCOPE); } public ELResolver getELResolver() { return _elResolver; } public javax.el.FunctionMapper getFunctionMapper() { return _functionMapper; } public javax.el.VariableMapper getVariableMapper() { return _variableMapper; } public String toString() { return getClass().getSimpleName() + "[" + PageContextImpl.this + "]"; } } public class PageFunctionMapper extends javax.el.FunctionMapper { public Method resolveFunction(String prefix, String localName) { if (_functionMap != null) return _functionMap.get(prefix + ":" + localName); else return null; } } public class PageVariableMapper extends ImplicitVariableMapper { private HashMap<String,ValueExpression> _map; final boolean isConstant() { return _map == null || _map.size() == 0; } public ValueExpression resolveVariable(String var) { if (_map != null) { ValueExpression expr = _map.get(var); if (expr != null) return expr; } Object value = PageContextImpl.this.resolveVariable(var); if (value instanceof ValueExpression) return (ValueExpression) value; ValueExpression expr; expr = super.resolveVariable(var); return expr; } public ValueExpression setVariable(String var, ValueExpression expr) { // ValueExpression oldValue = getVariable(var); if (_map == null) { _map = new HashMap<String,ValueExpression>(); } _map.put(var, expr); return expr; } public String toString() { return getClass().getSimpleName() + "[" + PageContextImpl.this + "]"; } } }
true
true
public void handlePageException(Throwable e) throws ServletException, IOException { if (e instanceof SkipPageException) return; HttpServletRequest request = getCauchoRequest(); request.setAttribute("javax.servlet.jsp.jspException", e); CauchoResponse response = getCauchoResponse(); response.setForbidForward(false); response.setResponseStream(_responseStream); response.killCache(); response.setNoCache(true); _hasException = true; if (e instanceof ClientDisconnectException) throw (ClientDisconnectException) e; if (! (_servlet instanceof Page)) { } else if (getApplication() == null || getApplication().getJsp() == null || ! getApplication().getJsp().isRecompileOnError()) { } else if (e instanceof OutOfMemoryError) { } else if (e instanceof Error) { try { Path workDir = getApplication().getAppDir().lookup("WEB-INF/work"); String className = _servlet.getClass().getName(); Path path = workDir.lookup(className.replace('.', '/') + ".class"); log.warning("Removing " + path + " due to " + e); path.remove(); } catch (Exception e1) { } Page page = (Page) _servlet; page._caucho_unload(); if (! page.isDead()) { page.setDead(); page.destroy(); } } _topOut.clearBuffer(); if (_errorPage != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, e.toString(), e); } else if (e instanceof DisplayableException) { log.warning(e.getMessage()); } else { log.log(Level.WARNING, e.toString(), e); } getCauchoRequest().setAttribute(EXCEPTION, e); getCauchoRequest().setAttribute("javax.servlet.error.exception", e); getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e); getCauchoRequest().setAttribute("javax.servlet.error.request_uri", getCauchoRequest().getRequestURI()); try { RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage); if (rd instanceof RequestDispatcherImpl) { getCauchoResponse().setHasError(true); ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse()); } else { if (rd != null) { getCauchoResponse().killCache(); getCauchoResponse().setNoCache(true); rd.forward(getCauchoRequest(), getCauchoResponse()); } else { log.log(Level.FINE, e.toString(), e); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } } } catch (FileNotFoundException e2) { log.log(Level.WARNING, e.toString(), e2); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } catch (IOException e2) { log.log(Level.FINE, e.toString(), e2); } return; } /* if (_servlet instanceof Page && ! (e instanceof LineMapException)) { LineMap lineMap = ((Page) _servlet)._caucho_getLineMap(); if (lineMap != null) e = new JspLineException(e, lineMap); } */ if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new ServletException(e); } }
public void handlePageException(Throwable e) throws ServletException, IOException { if (e instanceof SkipPageException) return; HttpServletRequest request = getCauchoRequest(); request.setAttribute("javax.servlet.jsp.jspException", e); CauchoResponse response = getCauchoResponse(); response.setForbidForward(false); response.setResponseStream(_responseStream); response.killCache(); response.setNoCache(true); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); _hasException = true; if (e instanceof ClientDisconnectException) throw (ClientDisconnectException) e; if (! (_servlet instanceof Page)) { } else if (getApplication() == null || getApplication().getJsp() == null || ! getApplication().getJsp().isRecompileOnError()) { } else if (e instanceof OutOfMemoryError) { } else if (e instanceof Error) { try { Path workDir = getApplication().getAppDir().lookup("WEB-INF/work"); String className = _servlet.getClass().getName(); Path path = workDir.lookup(className.replace('.', '/') + ".class"); log.warning("Removing " + path + " due to " + e); path.remove(); } catch (Exception e1) { } Page page = (Page) _servlet; page._caucho_unload(); if (! page.isDead()) { page.setDead(); page.destroy(); } } _topOut.clearBuffer(); if (_errorPage != null) { if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, e.toString(), e); } else if (e instanceof DisplayableException) { log.warning(e.getMessage()); } else { log.log(Level.WARNING, e.toString(), e); } getCauchoRequest().setAttribute(EXCEPTION, e); getCauchoRequest().setAttribute("javax.servlet.error.exception", e); getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e); getCauchoRequest().setAttribute("javax.servlet.error.request_uri", getCauchoRequest().getRequestURI()); try { RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage); if (rd instanceof RequestDispatcherImpl) { getCauchoResponse().setHasError(true); ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse()); } else { if (rd != null) { getCauchoResponse().killCache(); getCauchoResponse().setNoCache(true); rd.forward(getCauchoRequest(), getCauchoResponse()); } else { log.log(Level.FINE, e.toString(), e); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } } } catch (FileNotFoundException e2) { log.log(Level.WARNING, e.toString(), e2); throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.", _errorPage)); } catch (IOException e2) { log.log(Level.FINE, e.toString(), e2); } return; } /* if (_servlet instanceof Page && ! (e instanceof LineMapException)) { LineMap lineMap = ((Page) _servlet)._caucho_getLineMap(); if (lineMap != null) e = new JspLineException(e, lineMap); } */ if (e instanceof ServletException) { throw (ServletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new ServletException(e); } }
diff --git a/src/com/emcewen/ultimateplexremote/ManualActivity.java b/src/com/emcewen/ultimateplexremote/ManualActivity.java index c610009..3bb9625 100644 --- a/src/com/emcewen/ultimateplexremote/ManualActivity.java +++ b/src/com/emcewen/ultimateplexremote/ManualActivity.java @@ -1,62 +1,62 @@ package com.emcewen.ultimateplexremote; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.app.Activity; import android.content.Intent; public class ManualActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manual); } @Override protected void onDestroy() { // Unregister since the activity is about to be closed. super.onDestroy(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); //Setup the rescan button listener Button rescanBtn = (Button) findViewById(R.id.btnRescan); rescanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rescanButton(v); } }); //Setup the connect button listener Button connectBtn = (Button) findViewById(R.id.btnConnect); - rescanBtn.setOnClickListener(new View.OnClickListener() { + connectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connectButton(v); } }); } protected void connectButton(View v) { } protected void rescanButton(View v) { Intent entryIntent = new Intent(this,EntryActivity.class); finish(); startActivity(entryIntent); overridePendingTransition(0,0); } }
true
true
protected void onResume() { // TODO Auto-generated method stub super.onResume(); //Setup the rescan button listener Button rescanBtn = (Button) findViewById(R.id.btnRescan); rescanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rescanButton(v); } }); //Setup the connect button listener Button connectBtn = (Button) findViewById(R.id.btnConnect); rescanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connectButton(v); } }); }
protected void onResume() { // TODO Auto-generated method stub super.onResume(); //Setup the rescan button listener Button rescanBtn = (Button) findViewById(R.id.btnRescan); rescanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rescanButton(v); } }); //Setup the connect button listener Button connectBtn = (Button) findViewById(R.id.btnConnect); connectBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { connectButton(v); } }); }
diff --git a/plugins/jvm/java/src/org/nwnx/nwnx2/jvm/TestRunner.java b/plugins/jvm/java/src/org/nwnx/nwnx2/jvm/TestRunner.java index bde5ab8..b83cbbb 100644 --- a/plugins/jvm/java/src/org/nwnx/nwnx2/jvm/TestRunner.java +++ b/plugins/jvm/java/src/org/nwnx/nwnx2/jvm/TestRunner.java @@ -1,126 +1,126 @@ package org.nwnx.nwnx2.jvm; import org.nwnx.nwnx2.jvm.constants.*; public class TestRunner { public static void init() { System.out.println("Initializing TestRunner. This class runs various sanity tests and benchmarks."); System.out.println("If anything in this class makes your server crash, something is wrong and NEEDs to be fixed!"); System.out.println("You need to load a module that has at least one event firing on a creature sometime."); NWObject.setObjectInvalidIsNull(true); NWObject.registerObjectHandler(new NWObject.ObjectHandler() { public NWObject handleObjectClass(NWObject obj, boolean valid, int objectType, String resRef, String tag) { return obj; } }); NWEffect.registerEffectHandler(new NWEffect.EffectHandler() { public NWEffect handleEffectClass(NWEffect eff) { return eff; } }); NWItemProperty.registerItemPropertyHandler(new NWItemProperty.ItemPropertyHandler() { public NWItemProperty handleItemPropertyClass(NWItemProperty prp) { return prp; } }); ResMan.addResManListener(new ResManListener() { @Override public byte[] demandRes(String resRef) { System.out.println("Demand ResRef: " + resRef); if (resRef.equals("resmantest.2da")) { System.out.println("Returning our own 2da table!"); return "2DA V2.0\r\n\r\n A B\r\n0 a1 b1\r\n1 a2 b2\r\n".getBytes(); } return null; } }); Scheduler.addSchedulerListener(new SchedulerListener() { @Override public void postFlushQueues(int remainingTokens) { } @Override public void missedToken(NWObject objSelf, String token) { } @Override public void event(NWObject objSelf, String event) { int objType = NWScript.getObjectType(objSelf); String name = NWScript.getName(objSelf, false); System.out.println("event on " + objSelf.getObjectId() + ": " + event + ", name = " + name + ", type = " + objType); String testResman = NWScript.get2DAString("resmantest", "A", 1); - if (testResman != "a1") - throw new RuntimeException("ResMan not working; expected 'a1', got '" + testResman + "'"); + if (!testResman.equals("a2")) + throw new RuntimeException("ResMan not working; expected 'a2', got '" + testResman + "'"); System.out.println("Tested Resman hook: " + testResman); if (objType == ObjectType.CREATURE) { System.out.println("Testing placing a temporary effect and retrieving it."); System.out.println("Creating a effect."); NWEffect e = NWScript.effectDeaf(); System.out.println("Applying effect: " + e.getEffectId()); NWScript.applyEffectToObject(1, e, objSelf, 7f); System.out.println("Retrieving effects."); NWEffect[] e2 = NWScript.getEffects(objSelf); String ret = ""; for (NWEffect ee : e2) ret += ee.getEffectId() + " "; System.out.println("The creature has " + e2.length + " effects on himself: " + ret); System.out.println("Testing retrieving all objects in that area."); NWObject area = NWScript.getArea(objSelf); NWObject[] objInArea = NWScript.getObjectsInArea(area); System.out.println("There are " + objInArea.length + " objects in that area."); System.out.println("Testing retrieving all faction members."); NWObject[] members = NWScript.getFactionMembers(objSelf,false); System.out.println("There are " + members.length + " members."); System.out.println("Running a generic useless benchmark (Should be around 150ms, give or take)"); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) NWScript.getPosition(objSelf); long time = System.currentTimeMillis() - start; System.out.println("100000 times getPosition() took " + time + " ms"); if (event.equals("creature_hb")) { System.out.println("Testing SCO/RCO on oid " + objSelf.getObjectId()); byte[] data = SCORCO.saveObject(objSelf); System.out.println("got " + data.length + " bytes."); NWObject rco = SCORCO.loadObject(data, NWScript.getLocation(objSelf), null); if (rco != null) { System.out.println("RCO worked, name of duplicated object is: " + NWScript.getName(rco, true)); System.out.println("RCO worked, oid of duplicated object is: " + rco.getObjectId()); NWScript.destroyObject(rco, 0f); } else { throw new RuntimeException("RCO failed."); } } System.out.println("Press Ctrl+C when you're bored. You should see the shutdown handler print a farewell message."); } } @Override public void context(NWObject objSelf) { } }); } @SuppressWarnings("unused") private static void setup() { } @SuppressWarnings("unused") private static void shutdown() { System.out.println("Shutdown! Byebye, thanks for all the fish!"); } }
true
true
public static void init() { System.out.println("Initializing TestRunner. This class runs various sanity tests and benchmarks."); System.out.println("If anything in this class makes your server crash, something is wrong and NEEDs to be fixed!"); System.out.println("You need to load a module that has at least one event firing on a creature sometime."); NWObject.setObjectInvalidIsNull(true); NWObject.registerObjectHandler(new NWObject.ObjectHandler() { public NWObject handleObjectClass(NWObject obj, boolean valid, int objectType, String resRef, String tag) { return obj; } }); NWEffect.registerEffectHandler(new NWEffect.EffectHandler() { public NWEffect handleEffectClass(NWEffect eff) { return eff; } }); NWItemProperty.registerItemPropertyHandler(new NWItemProperty.ItemPropertyHandler() { public NWItemProperty handleItemPropertyClass(NWItemProperty prp) { return prp; } }); ResMan.addResManListener(new ResManListener() { @Override public byte[] demandRes(String resRef) { System.out.println("Demand ResRef: " + resRef); if (resRef.equals("resmantest.2da")) { System.out.println("Returning our own 2da table!"); return "2DA V2.0\r\n\r\n A B\r\n0 a1 b1\r\n1 a2 b2\r\n".getBytes(); } return null; } }); Scheduler.addSchedulerListener(new SchedulerListener() { @Override public void postFlushQueues(int remainingTokens) { } @Override public void missedToken(NWObject objSelf, String token) { } @Override public void event(NWObject objSelf, String event) { int objType = NWScript.getObjectType(objSelf); String name = NWScript.getName(objSelf, false); System.out.println("event on " + objSelf.getObjectId() + ": " + event + ", name = " + name + ", type = " + objType); String testResman = NWScript.get2DAString("resmantest", "A", 1); if (testResman != "a1") throw new RuntimeException("ResMan not working; expected 'a1', got '" + testResman + "'"); System.out.println("Tested Resman hook: " + testResman); if (objType == ObjectType.CREATURE) { System.out.println("Testing placing a temporary effect and retrieving it."); System.out.println("Creating a effect."); NWEffect e = NWScript.effectDeaf(); System.out.println("Applying effect: " + e.getEffectId()); NWScript.applyEffectToObject(1, e, objSelf, 7f); System.out.println("Retrieving effects."); NWEffect[] e2 = NWScript.getEffects(objSelf); String ret = ""; for (NWEffect ee : e2) ret += ee.getEffectId() + " "; System.out.println("The creature has " + e2.length + " effects on himself: " + ret); System.out.println("Testing retrieving all objects in that area."); NWObject area = NWScript.getArea(objSelf); NWObject[] objInArea = NWScript.getObjectsInArea(area); System.out.println("There are " + objInArea.length + " objects in that area."); System.out.println("Testing retrieving all faction members."); NWObject[] members = NWScript.getFactionMembers(objSelf,false); System.out.println("There are " + members.length + " members."); System.out.println("Running a generic useless benchmark (Should be around 150ms, give or take)"); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) NWScript.getPosition(objSelf); long time = System.currentTimeMillis() - start; System.out.println("100000 times getPosition() took " + time + " ms"); if (event.equals("creature_hb")) { System.out.println("Testing SCO/RCO on oid " + objSelf.getObjectId()); byte[] data = SCORCO.saveObject(objSelf); System.out.println("got " + data.length + " bytes."); NWObject rco = SCORCO.loadObject(data, NWScript.getLocation(objSelf), null); if (rco != null) { System.out.println("RCO worked, name of duplicated object is: " + NWScript.getName(rco, true)); System.out.println("RCO worked, oid of duplicated object is: " + rco.getObjectId()); NWScript.destroyObject(rco, 0f); } else { throw new RuntimeException("RCO failed."); } } System.out.println("Press Ctrl+C when you're bored. You should see the shutdown handler print a farewell message."); } } @Override public void context(NWObject objSelf) { } }); }
public static void init() { System.out.println("Initializing TestRunner. This class runs various sanity tests and benchmarks."); System.out.println("If anything in this class makes your server crash, something is wrong and NEEDs to be fixed!"); System.out.println("You need to load a module that has at least one event firing on a creature sometime."); NWObject.setObjectInvalidIsNull(true); NWObject.registerObjectHandler(new NWObject.ObjectHandler() { public NWObject handleObjectClass(NWObject obj, boolean valid, int objectType, String resRef, String tag) { return obj; } }); NWEffect.registerEffectHandler(new NWEffect.EffectHandler() { public NWEffect handleEffectClass(NWEffect eff) { return eff; } }); NWItemProperty.registerItemPropertyHandler(new NWItemProperty.ItemPropertyHandler() { public NWItemProperty handleItemPropertyClass(NWItemProperty prp) { return prp; } }); ResMan.addResManListener(new ResManListener() { @Override public byte[] demandRes(String resRef) { System.out.println("Demand ResRef: " + resRef); if (resRef.equals("resmantest.2da")) { System.out.println("Returning our own 2da table!"); return "2DA V2.0\r\n\r\n A B\r\n0 a1 b1\r\n1 a2 b2\r\n".getBytes(); } return null; } }); Scheduler.addSchedulerListener(new SchedulerListener() { @Override public void postFlushQueues(int remainingTokens) { } @Override public void missedToken(NWObject objSelf, String token) { } @Override public void event(NWObject objSelf, String event) { int objType = NWScript.getObjectType(objSelf); String name = NWScript.getName(objSelf, false); System.out.println("event on " + objSelf.getObjectId() + ": " + event + ", name = " + name + ", type = " + objType); String testResman = NWScript.get2DAString("resmantest", "A", 1); if (!testResman.equals("a2")) throw new RuntimeException("ResMan not working; expected 'a2', got '" + testResman + "'"); System.out.println("Tested Resman hook: " + testResman); if (objType == ObjectType.CREATURE) { System.out.println("Testing placing a temporary effect and retrieving it."); System.out.println("Creating a effect."); NWEffect e = NWScript.effectDeaf(); System.out.println("Applying effect: " + e.getEffectId()); NWScript.applyEffectToObject(1, e, objSelf, 7f); System.out.println("Retrieving effects."); NWEffect[] e2 = NWScript.getEffects(objSelf); String ret = ""; for (NWEffect ee : e2) ret += ee.getEffectId() + " "; System.out.println("The creature has " + e2.length + " effects on himself: " + ret); System.out.println("Testing retrieving all objects in that area."); NWObject area = NWScript.getArea(objSelf); NWObject[] objInArea = NWScript.getObjectsInArea(area); System.out.println("There are " + objInArea.length + " objects in that area."); System.out.println("Testing retrieving all faction members."); NWObject[] members = NWScript.getFactionMembers(objSelf,false); System.out.println("There are " + members.length + " members."); System.out.println("Running a generic useless benchmark (Should be around 150ms, give or take)"); long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) NWScript.getPosition(objSelf); long time = System.currentTimeMillis() - start; System.out.println("100000 times getPosition() took " + time + " ms"); if (event.equals("creature_hb")) { System.out.println("Testing SCO/RCO on oid " + objSelf.getObjectId()); byte[] data = SCORCO.saveObject(objSelf); System.out.println("got " + data.length + " bytes."); NWObject rco = SCORCO.loadObject(data, NWScript.getLocation(objSelf), null); if (rco != null) { System.out.println("RCO worked, name of duplicated object is: " + NWScript.getName(rco, true)); System.out.println("RCO worked, oid of duplicated object is: " + rco.getObjectId()); NWScript.destroyObject(rco, 0f); } else { throw new RuntimeException("RCO failed."); } } System.out.println("Press Ctrl+C when you're bored. You should see the shutdown handler print a farewell message."); } } @Override public void context(NWObject objSelf) { } }); }
diff --git a/src/bll/DisplayController.java b/src/bll/DisplayController.java index 9adb291..8ea4c7d 100644 --- a/src/bll/DisplayController.java +++ b/src/bll/DisplayController.java @@ -1,59 +1,59 @@ package bll; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import dal.PictureData; /** * @author Simen Sollie & Kristine Svaboe * @since 2013-11-04 */ public class DisplayController { /** * Manage list with pictures */ private PictureController pictureController; public DisplayController(PictureController pictureController){ this.pictureController = pictureController; } public List<PictureViewModel> getPictureObjects(boolean random) throws IOException{ ArrayList<PictureViewModel> po = new ArrayList<PictureViewModel>(); List<PictureData> sortedPictureList = pictureController.getSortedPictureDataFromDb(); int i = 1; for (PictureData p : sortedPictureList){ if (!p.isRemoveFlag()){ PictureViewModel pvm = new PictureViewModel(getBufImage(p), p.getId()); po.add(pvm); i++; } - if (i > 99){ + if (i > 100){ break; } } if (random = true){ Collections.shuffle(po); } return po; } private BufferedImage getBufImage(PictureData p) throws IOException{ // URL testUrl = new URL("http://pbs.twimg.com/media/BXrietbIgAAiroP.jpg"); URL imageUrl = new URL(p.getUrlStd()); InputStream in = imageUrl.openStream();; BufferedImage image = ImageIO.read(in); in.close(); return image; } }
true
true
public List<PictureViewModel> getPictureObjects(boolean random) throws IOException{ ArrayList<PictureViewModel> po = new ArrayList<PictureViewModel>(); List<PictureData> sortedPictureList = pictureController.getSortedPictureDataFromDb(); int i = 1; for (PictureData p : sortedPictureList){ if (!p.isRemoveFlag()){ PictureViewModel pvm = new PictureViewModel(getBufImage(p), p.getId()); po.add(pvm); i++; } if (i > 99){ break; } } if (random = true){ Collections.shuffle(po); } return po; }
public List<PictureViewModel> getPictureObjects(boolean random) throws IOException{ ArrayList<PictureViewModel> po = new ArrayList<PictureViewModel>(); List<PictureData> sortedPictureList = pictureController.getSortedPictureDataFromDb(); int i = 1; for (PictureData p : sortedPictureList){ if (!p.isRemoveFlag()){ PictureViewModel pvm = new PictureViewModel(getBufImage(p), p.getId()); po.add(pvm); i++; } if (i > 100){ break; } } if (random = true){ Collections.shuffle(po); } return po; }
diff --git a/process-manager/process-manager-ejb/src/main/java/com/silverpeas/processManager/ProcessFilter.java b/process-manager/process-manager-ejb/src/main/java/com/silverpeas/processManager/ProcessFilter.java index eb084e5de..3a53f9b6c 100644 --- a/process-manager/process-manager-ejb/src/main/java/com/silverpeas/processManager/ProcessFilter.java +++ b/process-manager/process-manager-ejb/src/main/java/com/silverpeas/processManager/ProcessFilter.java @@ -1,210 +1,210 @@ /** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.processManager; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.silverpeas.form.DataRecord; import com.silverpeas.form.Field; import com.silverpeas.form.FieldTemplate; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.RecordTemplate; import com.silverpeas.form.filter.FilterManager; import com.silverpeas.form.record.GenericFieldTemplate; import com.silverpeas.workflow.api.WorkflowException; import com.silverpeas.workflow.api.instance.ProcessInstance; import com.silverpeas.workflow.api.model.ProcessModel; import com.silverpeas.workflow.api.model.State; /** * A ProcessFilter is used to select some process from all the process. */ public class ProcessFilter { /** * Builds a process filter which can be used to select process intance of a given process model. */ public ProcessFilter(ProcessModel model, String role, String lang) throws ProcessManagerException { RecordTemplate rowTemplate = model.getRowTemplate(role, lang); filter = new FilterManager(rowTemplate, lang); RecordTemplate folderTemplate = null; try { folderTemplate = model.getDataFolder() .toRecordTemplate(role, lang, false); } catch (WorkflowException e1) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e1); } try { // Affichage d'une liste déroulante des états possibles GenericFieldTemplate state = new GenericFieldTemplate("instance.state", "text"); State[] states = model.getStates(); String values = ""; for (int s = 0; s < states.length; s++) { if (s != 0) values += "##"; values += ((State) states[s]).getLabel(role, lang); } // state.addParameter("keys", // "A qualifier##Correction en attente##Correction en cours"); state.addParameter("keys", values); filter.addFieldParameter("instance.state", state); // Affichage d'une liste déroulante pour chaque donnée multivaluée FieldTemplate[] fields = rowTemplate.getFieldTemplates(); FieldTemplate field = null; for (int f = 2; f < fields.length; f++) { field = fields[f]; FieldTemplate folderField = folderTemplate.getFieldTemplate(field .getFieldName()); Map<String, String> parameters = folderField.getParameters(lang); if (parameters != null && (parameters.containsKey("values") || parameters - .containsKey("keys"))) { + .containsKey("keys") || folderField.getTypeName().equals("jdbc"))) { filter.addFieldParameter(field.getFieldName(), folderField); } } } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e); } } /** * Returns the form which can be used to fill the filter criteria. */ public Form getPresentationForm() throws ProcessManagerException { try { return filter.getCriteriaForm(); } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e); } } /** * Get the current criteria. */ public DataRecord getCriteriaRecord() throws ProcessManagerException { if (criteria == null) { try { criteria = filter.getEmptyCriteriaRecord(); } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_RECORD", e); } } return criteria; } /** * Set the current criteria. */ public void setCriteriaRecord(DataRecord criteria) { this.criteria = criteria; } /** * Copy the criteria filled in another context but shared by this filter. We ignore all the form * exception, since this copy is only done to simplify the user life. */ public void copySharedCriteria(ProcessFilter source) { DataRecord copiedCriteria = null; String[] criteriaNames = null; try { copiedCriteria = source.getCriteriaRecord(); criteriaNames = source.filter.getCriteriaTemplate().getFieldNames(); this.getCriteriaRecord(); } catch (ProcessManagerException ignored) { return; } catch (FormException ignored) { return; } Field criteriumField; for (int i = 0; i < criteriaNames.length; i++) { try { criteriumField = criteria.getField(criteriaNames[i]); if (criteriumField != null && copiedCriteria != null) criteriumField.setValue(copiedCriteria.getField(criteriaNames[i]) .getValue(""), ""); } catch (FormException ignored) { continue; } } } /** * Returns the collapse status of the filter panel. */ public String getCollapse() { return collapse; } /** * Set the collapse status of the filter panel. */ public void setCollapse(String collapse) { if ("false".equals(collapse)) this.collapse = "false"; else this.collapse = "true"; } /** * Returns only the process instance matching the filter. */ public DataRecord[] filter(ProcessInstance[] allInstances, String role, String lang) throws ProcessManagerException { try { List<DataRecord> allRecords = new ArrayList<DataRecord>(); for (int i = 0; i < allInstances.length; i++) { allRecords.add(allInstances[i].getRowDataRecord(role, lang)); } if (getCriteriaRecord() != null) { allRecords = filter.filter(criteria, allRecords); } return allRecords.toArray(new DataRecord[0]); } catch (WorkflowException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_USE_CRITERIA_RECORD", e); } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_USE_CRITERIA_RECORD", e); } } private FilterManager filter = null; private String collapse = "true"; private DataRecord criteria; }
true
true
public ProcessFilter(ProcessModel model, String role, String lang) throws ProcessManagerException { RecordTemplate rowTemplate = model.getRowTemplate(role, lang); filter = new FilterManager(rowTemplate, lang); RecordTemplate folderTemplate = null; try { folderTemplate = model.getDataFolder() .toRecordTemplate(role, lang, false); } catch (WorkflowException e1) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e1); } try { // Affichage d'une liste déroulante des états possibles GenericFieldTemplate state = new GenericFieldTemplate("instance.state", "text"); State[] states = model.getStates(); String values = ""; for (int s = 0; s < states.length; s++) { if (s != 0) values += "##"; values += ((State) states[s]).getLabel(role, lang); } // state.addParameter("keys", // "A qualifier##Correction en attente##Correction en cours"); state.addParameter("keys", values); filter.addFieldParameter("instance.state", state); // Affichage d'une liste déroulante pour chaque donnée multivaluée FieldTemplate[] fields = rowTemplate.getFieldTemplates(); FieldTemplate field = null; for (int f = 2; f < fields.length; f++) { field = fields[f]; FieldTemplate folderField = folderTemplate.getFieldTemplate(field .getFieldName()); Map<String, String> parameters = folderField.getParameters(lang); if (parameters != null && (parameters.containsKey("values") || parameters .containsKey("keys"))) { filter.addFieldParameter(field.getFieldName(), folderField); } } } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e); } }
public ProcessFilter(ProcessModel model, String role, String lang) throws ProcessManagerException { RecordTemplate rowTemplate = model.getRowTemplate(role, lang); filter = new FilterManager(rowTemplate, lang); RecordTemplate folderTemplate = null; try { folderTemplate = model.getDataFolder() .toRecordTemplate(role, lang, false); } catch (WorkflowException e1) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e1); } try { // Affichage d'une liste déroulante des états possibles GenericFieldTemplate state = new GenericFieldTemplate("instance.state", "text"); State[] states = model.getStates(); String values = ""; for (int s = 0; s < states.length; s++) { if (s != 0) values += "##"; values += ((State) states[s]).getLabel(role, lang); } // state.addParameter("keys", // "A qualifier##Correction en attente##Correction en cours"); state.addParameter("keys", values); filter.addFieldParameter("instance.state", state); // Affichage d'une liste déroulante pour chaque donnée multivaluée FieldTemplate[] fields = rowTemplate.getFieldTemplates(); FieldTemplate field = null; for (int f = 2; f < fields.length; f++) { field = fields[f]; FieldTemplate folderField = folderTemplate.getFieldTemplate(field .getFieldName()); Map<String, String> parameters = folderField.getParameters(lang); if (parameters != null && (parameters.containsKey("values") || parameters .containsKey("keys") || folderField.getTypeName().equals("jdbc"))) { filter.addFieldParameter(field.getFieldName(), folderField); } } } catch (FormException e) { throw new ProcessManagerException("ProcessFilter", "processFilter.FAIL_TO_CREATE_CRITERIA_FORM", e); } }
diff --git a/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java b/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java index 4deb8af..0f1ab9a 100644 --- a/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java +++ b/river/src/main/java/org/jboss/marshalling/river/RiverMarshaller.java @@ -1,1382 +1,1381 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.marshalling.river; import java.io.Externalizable; import java.io.IOException; import java.io.InvalidClassException; import java.io.InvalidObjectException; import java.io.NotSerializableException; import java.io.ObjectOutput; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import org.jboss.marshalling.AbstractMarshaller; import org.jboss.marshalling.ClassExternalizerFactory; import org.jboss.marshalling.ClassTable; import org.jboss.marshalling.Externalizer; import org.jboss.marshalling.MarshallerObjectOutput; import org.jboss.marshalling.MarshallingConfiguration; import org.jboss.marshalling.ObjectResolver; import org.jboss.marshalling.ObjectTable; import org.jboss.marshalling.UTFUtils; import org.jboss.marshalling.reflect.SerializableClass; import org.jboss.marshalling.reflect.SerializableClassRegistry; import org.jboss.marshalling.reflect.SerializableField; import org.jboss.marshalling.util.IdentityIntMap; import static org.jboss.marshalling.river.Protocol.*; /** * */ public class RiverMarshaller extends AbstractMarshaller { private final IdentityIntMap<Object> instanceCache; private final IdentityIntMap<Class<?>> classCache; private final IdentityHashMap<Class<?>, Externalizer> externalizers; private int instanceSeq; private int classSeq; private final SerializableClassRegistry registry; private RiverObjectOutputStream objectOutputStream; private ObjectOutput objectOutput; private BlockMarshaller blockMarshaller; protected RiverMarshaller(final RiverMarshallerFactory marshallerFactory, final SerializableClassRegistry registry, final MarshallingConfiguration configuration) throws IOException { super(marshallerFactory, configuration); if (configuredVersion > MAX_VERSION) { throw new IOException("Unsupported protocol version " + configuredVersion); } this.registry = registry; final float loadFactor = 0x0.5p0f; instanceCache = new IdentityIntMap<Object>((int) ((double)configuration.getInstanceCount() / (double)loadFactor), loadFactor); classCache = new IdentityIntMap<Class<?>>((int) ((double)configuration.getClassCount() / (double)loadFactor), loadFactor); externalizers = new IdentityHashMap<Class<?>, Externalizer>(configuration.getClassCount()); } protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { if (configuredVersion >= 2) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } return; } write(ID_REPEAT_OBJECT_FAR); writeInt(rid); return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; if (configuredVersion >= 2) { - final int cid = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(classObj, -1); + final int cid = BASIC_CLASSES_V2.get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { break; } default: { write(cid); return; } } } write(ID_NEW_OBJECT); - write(ID_CLASS_CLASS); writeClassClass(classObj); instanceCache.put(classObj, instanceSeq++); return; } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { if (configuredVersion >= 2) { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_CLASS); writeByte(((Byte) obj).byteValue()); } return; } case ID_BOOLEAN_CLASS: { if (configuredVersion >= 2) { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_CLASS); writeBoolean(((Boolean) obj).booleanValue()); } return; } case ID_CHARACTER_CLASS: { if (configuredVersion >= 2) { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHARACTER_CLASS); writeChar(((Character) obj).charValue()); } return; } case ID_DOUBLE_CLASS: { if (configuredVersion >= 2) { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_CLASS); writeDouble(((Double) obj).doubleValue()); } return; } case ID_FLOAT_CLASS: { if (configuredVersion >= 2) { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_CLASS); writeFloat(((Float) obj).floatValue()); } return; } case ID_INTEGER_CLASS: { if (configuredVersion >= 2) { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INTEGER_CLASS); writeInt(((Integer) obj).intValue()); } return; } case ID_LONG_CLASS: { if (configuredVersion >= 2) { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_CLASS); writeLong(((Long) obj).longValue()); } return; } case ID_SHORT_CLASS: { if (configuredVersion >= 2) { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_CLASS); writeShort(((Short) obj).shortValue()); } return; } case ID_STRING_CLASS: { final String string = (String) obj; if (configuredVersion >= 2) { final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 256) { write(ID_STRING_SMALL); write(len); } else if (len <= 65336) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } flush(); UTFUtils.writeUTFBytes(byteOutput, string); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_STRING_CLASS); writeString(string); } if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_ARRAY_CLASS); writeInt(len); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_ARRAY_CLASS); writeInt(len); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHAR_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { instanceCache.put(obj, instanceSeq++); final double[] doubles = (double[]) obj; final int len = doubles.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeObjectArrayClass(objClass); writeInt(len); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (obj instanceof Serializable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } } private void writeBooleanArray(final boolean[] booleans) throws IOException { final int len = booleans.length; final int bc = len & ~7; for (int i = 0; i < bc;) { write( (booleans[i++] ? 1 : 0) | (booleans[i++] ? 2 : 0) | (booleans[i++] ? 4 : 0) | (booleans[i++] ? 8 : 0) | (booleans[i++] ? 16 : 0) | (booleans[i++] ? 32 : 0) | (booleans[i++] ? 64 : 0) | (booleans[i++] ? 128 : 0) ); } if (bc < len) { int out = 0; int bit = 1; for (int i = bc; i < len; i++) { if (booleans[i]) out |= bit; bit <<= 1; } write(out); } } private void writeEndBlock() throws IOException { final BlockMarshaller blockMarshaller = this.blockMarshaller; if (blockMarshaller != null) { blockMarshaller.flush(); writeByte(ID_END_BLOCK_DATA); } } protected ObjectOutput getObjectOutput() { final ObjectOutput output = objectOutput; return output == null ? configuredVersion == 0 ? (objectOutput = new MarshallerObjectOutput(this)) : (objectOutput = getBlockMarshaller()) : output; } protected BlockMarshaller getBlockMarshaller() { final BlockMarshaller blockMarshaller = this.blockMarshaller; return blockMarshaller == null ? (this.blockMarshaller = new BlockMarshaller(this, bufferSize)) : blockMarshaller; } private RiverObjectOutputStream getObjectOutputStream() throws IOException { final RiverObjectOutputStream objectOutputStream = this.objectOutputStream; return objectOutputStream == null ? this.objectOutputStream = createObjectOutputStream() : objectOutputStream; } private final PrivilegedExceptionAction<RiverObjectOutputStream> createObjectOutputStreamAction = new PrivilegedExceptionAction<RiverObjectOutputStream>() { public RiverObjectOutputStream run() throws IOException { return new RiverObjectOutputStream(configuredVersion == 0 ? RiverMarshaller.this : getBlockMarshaller(), RiverMarshaller.this); } }; private RiverObjectOutputStream createObjectOutputStream() throws IOException { try { return AccessController.doPrivileged(createObjectOutputStreamAction); } catch (PrivilegedActionException e) { throw (IOException) e.getCause(); } } protected void doWriteSerializableObject(final SerializableClass info, final Object obj, final Class<?> objClass) throws IOException { final Class<?> superclass = objClass.getSuperclass(); if (Serializable.class.isAssignableFrom(superclass)) { doWriteSerializableObject(registry.lookup(superclass), obj, superclass); } if (info.hasWriteObject()) { final RiverObjectOutputStream objectOutputStream = getObjectOutputStream(); final SerializableClass oldInfo = objectOutputStream.swapClass(info); final Object oldObj = objectOutputStream.swapCurrent(obj); final RiverObjectOutputStream.State restoreState = objectOutputStream.start(); boolean ok = false; try { info.callWriteObject(obj, objectOutputStream); writeEndBlock(); objectOutputStream.finish(restoreState); objectOutputStream.swapCurrent(oldObj); objectOutputStream.swapClass(oldInfo); ok = true; } finally { if (! ok) { objectOutputStream.fullReset(); } } } else { doWriteFields(info, obj); } } protected void doWriteFields(final SerializableClass info, final Object obj) throws IOException { final SerializableField[] serializableFields = info.getFields(); for (SerializableField serializableField : serializableFields) { try { final Field field = serializableField.getField(); switch (serializableField.getKind()) { case BOOLEAN: { writeBoolean(field.getBoolean(obj)); break; } case BYTE: { writeByte(field.getByte(obj)); break; } case SHORT: { writeShort(field.getShort(obj)); break; } case INT: { writeInt(field.getInt(obj)); break; } case CHAR: { writeChar(field.getChar(obj)); break; } case LONG: { writeLong(field.getLong(obj)); break; } case DOUBLE: { writeDouble(field.getDouble(obj)); break; } case FLOAT: { writeFloat(field.getFloat(obj)); break; } case OBJECT: { doWriteObject(field.get(obj), serializableField.isUnshared()); break; } } } catch (IllegalAccessException e) { final InvalidObjectException ioe = new InvalidObjectException("Unexpected illegal access exception"); ioe.initCause(e); throw ioe; } } } protected void writeProxyClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewProxyClass(objClass); } } protected void writeNewProxyClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_PROXY_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_PROXY_CLASS); final String[] names = classResolver.getProxyInterfaces(objClass); writeInt(names.length); for (String name : names) { writeString(name); } classCache.put(objClass, classSeq++); if (configuredVersion == 1) { final BlockMarshaller blockMarshaller = getBlockMarshaller(); classResolver.annotateProxyClass(blockMarshaller, objClass); writeEndBlock(); } else { classResolver.annotateProxyClass(this, objClass); } } } protected void writeEnumClass(final Class<? extends Enum> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewEnumClass(objClass); } } protected void writeNewEnumClass(final Class<? extends Enum> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_ENUM_TYPE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_ENUM_TYPE_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } } protected void writeClassClass(final Class<?> classObj) throws IOException { write(ID_CLASS_CLASS); writeClass(classObj); // not cached } protected void writeObjectArrayClass(final Class<?> objClass) throws IOException { write(ID_OBJECT_ARRAY_TYPE_CLASS); writeClass(objClass.getComponentType()); classCache.put(objClass, classSeq++); } protected void writeClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewClass(objClass); } } private static final IdentityIntMap<Class<?>> BASIC_CLASSES; private static final IdentityIntMap<Class<?>> BASIC_CLASSES_V2; static { final IdentityIntMap<Class<?>> map = new IdentityIntMap<Class<?>>(0x0.6p0f); map.put(byte.class, ID_PRIM_BYTE); map.put(boolean.class, ID_PRIM_BOOLEAN); map.put(char.class, ID_PRIM_CHAR); map.put(double.class, ID_PRIM_DOUBLE); map.put(float.class, ID_PRIM_FLOAT); map.put(int.class, ID_PRIM_INT); map.put(long.class, ID_PRIM_LONG); map.put(short.class, ID_PRIM_SHORT); map.put(void.class, ID_VOID); map.put(Byte.class, ID_BYTE_CLASS); map.put(Boolean.class, ID_BOOLEAN_CLASS); map.put(Character.class, ID_CHARACTER_CLASS); map.put(Double.class, ID_DOUBLE_CLASS); map.put(Float.class, ID_FLOAT_CLASS); map.put(Integer.class, ID_INTEGER_CLASS); map.put(Long.class, ID_LONG_CLASS); map.put(Short.class, ID_SHORT_CLASS); map.put(Void.class, ID_VOID_CLASS); map.put(Object.class, ID_OBJECT_CLASS); map.put(Class.class, ID_CLASS_CLASS); map.put(String.class, ID_STRING_CLASS); map.put(Enum.class, ID_ENUM_CLASS); map.put(byte[].class, ID_BYTE_ARRAY_CLASS); map.put(boolean[].class, ID_BOOLEAN_ARRAY_CLASS); map.put(char[].class, ID_CHAR_ARRAY_CLASS); map.put(double[].class, ID_DOUBLE_ARRAY_CLASS); map.put(float[].class, ID_FLOAT_ARRAY_CLASS); map.put(int[].class, ID_INT_ARRAY_CLASS); map.put(long[].class, ID_LONG_ARRAY_CLASS); map.put(short[].class, ID_SHORT_ARRAY_CLASS); BASIC_CLASSES = map.clone(); map.put(ArrayList.class, ID_CC_ARRAY_LIST); map.put(LinkedList.class, ID_CC_LINKED_LIST); map.put(HashSet.class, ID_CC_HASH_SET); map.put(LinkedHashSet.class, ID_CC_LINKED_HASH_SET); map.put(TreeSet.class, ID_CC_TREE_SET); map.put(IdentityHashMap.class, ID_CC_IDENTITY_HASH_MAP); map.put(HashMap.class, ID_CC_HASH_MAP); map.put(Hashtable.class, ID_CC_HASHTABLE); map.put(LinkedHashMap.class, ID_CC_LINKED_HASH_MAP); map.put(TreeMap.class, ID_CC_TREE_MAP); map.put(emptyListClass, ID_EMPTY_LIST_OBJECT); // special case map.put(singletonListClass, ID_SINGLETON_LIST_OBJECT); // special case map.put(emptySetClass, ID_EMPTY_SET_OBJECT); // special case map.put(singletonSetClass, ID_SINGLETON_SET_OBJECT); // special case map.put(emptyMapClass, ID_EMPTY_MAP_OBJECT); // special case map.put(singletonMapClass, ID_SINGLETON_MAP_OBJECT); // special case BASIC_CLASSES_V2 = map; } protected void writeNewClass(final Class<?> objClass) throws IOException { if (objClass.isEnum()) { writeNewEnumClass(objClass.asSubclass(Enum.class)); } else if (Proxy.isProxyClass(objClass)) { writeNewProxyClass(objClass); } else if (objClass.isArray()) { writeObjectArrayClass(objClass); } else if (! objClass.isInterface() && Serializable.class.isAssignableFrom(objClass)) { if (Externalizable.class.isAssignableFrom(objClass)) { writeNewExternalizableClass(objClass); } else { writeNewSerializableClass(objClass); } } else { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_PLAIN_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_PLAIN_CLASS); writeString(classResolver.getClassName(objClass)); doAnnotateClass(objClass); classCache.put(objClass, classSeq++); } } } private void writeClassTableData(final Class<?> objClass, final ClassTable.Writer classTableWriter) throws IOException { if (configuredVersion == 1) { classTableWriter.writeClass(getBlockMarshaller(), objClass); writeEndBlock(); } else { classTableWriter.writeClass(this, objClass); } } protected boolean writeKnownClass(final Class<?> objClass) throws IOException { int i = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(objClass, -1); if (i != -1) { write(i); return true; } i = classCache.get(objClass, -1); if (i != -1) { if (configuredVersion >= 2) { final int diff = i - classSeq; if (diff >= -256) { write(ID_REPEAT_CLASS_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_CLASS_NEARISH); writeShort(diff); } return true; } write(ID_REPEAT_CLASS_FAR); writeInt(i); return true; } return false; } protected void writeSerializableClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewSerializableClass(objClass); } } protected void writeNewSerializableClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_SERIALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { final SerializableClass info = registry.lookup(objClass); if (configuredVersion > 0 && info.hasWriteObject()) { write(ID_WRITE_OBJECT_CLASS); } else { write(ID_SERIALIZABLE_CLASS); } writeString(classResolver.getClassName(objClass)); writeLong(info.getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); final SerializableField[] fields = info.getFields(); final int cnt = fields.length; writeInt(cnt); for (int i = 0; i < cnt; i++) { SerializableField field = fields[i]; writeUTF(field.getName()); try { writeClass(field.getType()); } catch (ClassNotFoundException e) { throw new InvalidClassException("Class of field was unloaded"); } writeBoolean(field.isUnshared()); } } writeClass(objClass.getSuperclass()); } protected void writeExternalizableClass(final Class<?> objClass) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizableClass(objClass); } } protected void writeNewExternalizableClass(final Class<?> objClass) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_EXTERNALIZABLE_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_EXTERNALIZABLE_CLASS); writeString(classResolver.getClassName(objClass)); writeLong(registry.lookup(objClass).getEffectiveSerialVersionUID()); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } } protected void writeExternalizerClass(final Class<?> objClass, final Externalizer externalizer) throws IOException { if (! writeKnownClass(objClass)) { writeNewExternalizerClass(objClass, externalizer); } } protected void writeNewExternalizerClass(final Class<?> objClass, final Externalizer externalizer) throws IOException { ClassTable.Writer classTableWriter = classTable.getClassWriter(objClass); if (classTableWriter != null) { write(ID_PREDEFINED_EXTERNALIZER_CLASS); classCache.put(objClass, classSeq++); writeClassTableData(objClass, classTableWriter); } else { write(ID_EXTERNALIZER_CLASS); writeString(classResolver.getClassName(objClass)); classCache.put(objClass, classSeq++); doAnnotateClass(objClass); } writeObject(externalizer); } protected void doAnnotateClass(final Class<?> objClass) throws IOException { if (configuredVersion == 1) { classResolver.annotateClass(getBlockMarshaller(), objClass); writeEndBlock(); } else { classResolver.annotateClass(this, objClass); } } public void clearInstanceCache() throws IOException { instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(ID_CLEAR_INSTANCE_CACHE); } } public void clearClassCache() throws IOException { classCache.clear(); externalizers.clear(); classSeq = 0; instanceCache.clear(); instanceSeq = 0; if (byteOutput != null) { write(ID_CLEAR_CLASS_CACHE); } } protected void doStart() throws IOException { super.doStart(); final int configuredVersion = this.configuredVersion; if (configuredVersion > 0) { writeByte(configuredVersion); } } private void writeString(String string) throws IOException { writeInt(string.length()); flush(); UTFUtils.writeUTFBytes(byteOutput, string); } // Replace writeUTF with a faster, non-scanning version public void writeUTF(final String string) throws IOException { writeInt(string.length()); flush(); UTFUtils.writeUTFBytes(byteOutput, string); } }
false
true
protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { if (configuredVersion >= 2) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } return; } write(ID_REPEAT_OBJECT_FAR); writeInt(rid); return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; if (configuredVersion >= 2) { final int cid = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { break; } default: { write(cid); return; } } } write(ID_NEW_OBJECT); write(ID_CLASS_CLASS); writeClassClass(classObj); instanceCache.put(classObj, instanceSeq++); return; } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { if (configuredVersion >= 2) { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_CLASS); writeByte(((Byte) obj).byteValue()); } return; } case ID_BOOLEAN_CLASS: { if (configuredVersion >= 2) { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_CLASS); writeBoolean(((Boolean) obj).booleanValue()); } return; } case ID_CHARACTER_CLASS: { if (configuredVersion >= 2) { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHARACTER_CLASS); writeChar(((Character) obj).charValue()); } return; } case ID_DOUBLE_CLASS: { if (configuredVersion >= 2) { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_CLASS); writeDouble(((Double) obj).doubleValue()); } return; } case ID_FLOAT_CLASS: { if (configuredVersion >= 2) { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_CLASS); writeFloat(((Float) obj).floatValue()); } return; } case ID_INTEGER_CLASS: { if (configuredVersion >= 2) { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INTEGER_CLASS); writeInt(((Integer) obj).intValue()); } return; } case ID_LONG_CLASS: { if (configuredVersion >= 2) { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_CLASS); writeLong(((Long) obj).longValue()); } return; } case ID_SHORT_CLASS: { if (configuredVersion >= 2) { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_CLASS); writeShort(((Short) obj).shortValue()); } return; } case ID_STRING_CLASS: { final String string = (String) obj; if (configuredVersion >= 2) { final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 256) { write(ID_STRING_SMALL); write(len); } else if (len <= 65336) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } flush(); UTFUtils.writeUTFBytes(byteOutput, string); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_STRING_CLASS); writeString(string); } if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_ARRAY_CLASS); writeInt(len); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_ARRAY_CLASS); writeInt(len); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHAR_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { instanceCache.put(obj, instanceSeq++); final double[] doubles = (double[]) obj; final int len = doubles.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeObjectArrayClass(objClass); writeInt(len); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (obj instanceof Serializable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } }
protected void doWriteObject(final Object original, final boolean unshared) throws IOException { final ClassExternalizerFactory classExternalizerFactory = this.classExternalizerFactory; final ObjectResolver objectResolver = this.objectResolver; Object obj = original; Class<?> objClass; int id; boolean isArray, isEnum; SerializableClass info; boolean unreplaced = true; final int configuredVersion = this.configuredVersion; try { for (;;) { if (obj == null) { write(ID_NULL); return; } final int rid; if (! unshared && (rid = instanceCache.get(obj, -1)) != -1) { if (configuredVersion >= 2) { final int diff = rid - instanceSeq; if (diff >= -256) { write(ID_REPEAT_OBJECT_NEAR); write(diff); } else if (diff >= -65536) { write(ID_REPEAT_OBJECT_NEARISH); writeShort(diff); } return; } write(ID_REPEAT_OBJECT_FAR); writeInt(rid); return; } final ObjectTable.Writer objectTableWriter; if (! unshared && (objectTableWriter = objectTable.getObjectWriter(obj)) != null) { write(ID_PREDEFINED_OBJECT); if (configuredVersion == 1) { objectTableWriter.writeObject(getBlockMarshaller(), obj); writeEndBlock(); } else { objectTableWriter.writeObject(this, obj); } return; } objClass = obj.getClass(); id = (configuredVersion >= 2 ? BASIC_CLASSES_V2 : BASIC_CLASSES).get(objClass, -1); // First, non-replaceable classes if (id == ID_CLASS_CLASS) { final Class<?> classObj = (Class<?>) obj; if (configuredVersion >= 2) { final int cid = BASIC_CLASSES_V2.get(classObj, -1); switch (cid) { case -1: case ID_SINGLETON_MAP_OBJECT: case ID_SINGLETON_SET_OBJECT: case ID_SINGLETON_LIST_OBJECT: case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { break; } default: { write(cid); return; } } } write(ID_NEW_OBJECT); writeClassClass(classObj); instanceCache.put(classObj, instanceSeq++); return; } isEnum = obj instanceof Enum; isArray = objClass.isArray(); // objects with id != -1 will never make use of the "info" param in *any* way info = isArray || isEnum || id != -1 ? null : registry.lookup(objClass); // replace once - objects with id != -1 will not have replacement methods but might be globally replaced if (unreplaced) { if (info != null) { // check for a user replacement if (info.hasWriteReplace()) { obj = info.callWriteReplace(obj); } } // Check for a global replacement obj = objectResolver.writeReplace(obj); if (obj != original) { unreplaced = false; continue; } else { break; } } else { break; } } if (isEnum) { // objClass cannot equal Enum.class because it is abstract final Enum<?> theEnum = (Enum<?>) obj; // enums are always shared write(ID_NEW_OBJECT); writeEnumClass(theEnum.getDeclaringClass()); writeString(theEnum.name()); instanceCache.put(obj, instanceSeq++); return; } // Now replaceable classes switch (id) { case ID_BYTE_CLASS: { if (configuredVersion >= 2) { write(ID_BYTE_OBJECT); writeByte(((Byte) obj).byteValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_CLASS); writeByte(((Byte) obj).byteValue()); } return; } case ID_BOOLEAN_CLASS: { if (configuredVersion >= 2) { write(((Boolean) obj).booleanValue() ? ID_BOOLEAN_OBJECT_TRUE : ID_BOOLEAN_OBJECT_FALSE); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_CLASS); writeBoolean(((Boolean) obj).booleanValue()); } return; } case ID_CHARACTER_CLASS: { if (configuredVersion >= 2) { write(ID_CHARACTER_OBJECT); writeChar(((Character) obj).charValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHARACTER_CLASS); writeChar(((Character) obj).charValue()); } return; } case ID_DOUBLE_CLASS: { if (configuredVersion >= 2) { write(ID_DOUBLE_OBJECT); writeDouble(((Double) obj).doubleValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_CLASS); writeDouble(((Double) obj).doubleValue()); } return; } case ID_FLOAT_CLASS: { if (configuredVersion >= 2) { write(ID_FLOAT_OBJECT); writeFloat(((Float) obj).floatValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_CLASS); writeFloat(((Float) obj).floatValue()); } return; } case ID_INTEGER_CLASS: { if (configuredVersion >= 2) { write(ID_INTEGER_OBJECT); writeInt(((Integer) obj).intValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INTEGER_CLASS); writeInt(((Integer) obj).intValue()); } return; } case ID_LONG_CLASS: { if (configuredVersion >= 2) { write(ID_LONG_OBJECT); writeLong(((Long) obj).longValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_CLASS); writeLong(((Long) obj).longValue()); } return; } case ID_SHORT_CLASS: { if (configuredVersion >= 2) { write(ID_SHORT_OBJECT); writeShort(((Short) obj).shortValue()); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_CLASS); writeShort(((Short) obj).shortValue()); } return; } case ID_STRING_CLASS: { final String string = (String) obj; if (configuredVersion >= 2) { final int len = string.length(); if (len == 0) { write(ID_STRING_EMPTY); // don't cache empty strings return; } else if (len <= 256) { write(ID_STRING_SMALL); write(len); } else if (len <= 65336) { write(ID_STRING_MEDIUM); writeShort(len); } else { write(ID_STRING_LARGE); writeInt(len); } flush(); UTFUtils.writeUTFBytes(byteOutput, string); } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_STRING_CLASS); writeString(string); } if (unshared) { instanceCache.put(obj, -1); instanceSeq++; } else { instanceCache.put(obj, instanceSeq++); } return; } case ID_BYTE_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final byte[] bytes = (byte[]) obj; final int len = bytes.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BYTE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BYTE); write(bytes, 0, len); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BYTE_ARRAY_CLASS); writeInt(len); write(bytes, 0, len); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_BOOLEAN_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final boolean[] booleans = (boolean[]) obj; final int len = booleans.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_BOOLEAN); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_BOOLEAN); writeBooleanArray(booleans); } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_BOOLEAN_ARRAY_CLASS); writeInt(len); writeBooleanArray(booleans); } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CHAR_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final char[] chars = (char[]) obj; final int len = chars.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_CHAR); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_CHAR); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_CHAR_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeChar(chars[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SHORT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final short[] shorts = (short[]) obj; final int len = shorts.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_SHORT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_SHORT); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_SHORT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeShort(shorts[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_INT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final int[] ints = (int[]) obj; final int len = ints.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_INT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_INT); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_INT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeInt(ints[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_LONG_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final long[] longs = (long[]) obj; final int len = longs.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_LONG); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_LONG); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_LONG_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeLong(longs[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_FLOAT_ARRAY_CLASS: { if (! unshared) { instanceCache.put(obj, instanceSeq++); } final float[] floats = (float[]) obj; final int len = floats.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_FLOAT); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_FLOAT); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_FLOAT_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeFloat(floats[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_DOUBLE_ARRAY_CLASS: { instanceCache.put(obj, instanceSeq++); final double[] doubles = (double[]) obj; final int len = doubles.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); write(ID_PRIM_DOUBLE); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); write(ID_PRIM_DOUBLE); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); write(ID_DOUBLE_ARRAY_CLASS); writeInt(len); for (int i = 0; i < len; i ++) { writeDouble(doubles[i]); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_SET: case ID_CC_LINKED_HASH_SET: case ID_CC_TREE_SET: case ID_CC_ARRAY_LIST: case ID_CC_LINKED_LIST: { instanceCache.put(obj, instanceSeq++); final Collection<?> collection = (Collection<?>) obj; final int len = collection.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_SET) { doWriteObject(((TreeSet)collection).comparator(), false); } for (Object o : collection) { doWriteObject(o, false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_CC_HASH_MAP: case ID_CC_HASHTABLE: case ID_CC_IDENTITY_HASH_MAP: case ID_CC_LINKED_HASH_MAP: case ID_CC_TREE_MAP: { instanceCache.put(obj, instanceSeq++); final Map<?, ?> map = (Map<?, ?>) obj; final int len = map.size(); if (len == 0) { write(unshared ? ID_COLLECTION_EMPTY_UNSHARED : ID_COLLECTION_EMPTY); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } } else if (len <= 256) { write(unshared ? ID_COLLECTION_SMALL_UNSHARED : ID_COLLECTION_SMALL); write(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else if (len <= 65536) { write(unshared ? ID_COLLECTION_MEDIUM_UNSHARED : ID_COLLECTION_MEDIUM); writeShort(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } else { write(unshared ? ID_COLLECTION_LARGE_UNSHARED : ID_COLLECTION_LARGE); writeInt(len); write(id); if (id == ID_CC_TREE_MAP) { doWriteObject(((TreeMap)map).comparator(), false); } for (Map.Entry<?, ?> entry : map.entrySet()) { doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); } } if (unshared) { instanceCache.put(obj, -1); } return; } case ID_EMPTY_MAP_OBJECT: case ID_EMPTY_SET_OBJECT: case ID_EMPTY_LIST_OBJECT: { write(id); return; } case ID_SINGLETON_MAP_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); final Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); doWriteObject(entry.getKey(), false); doWriteObject(entry.getValue(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case ID_SINGLETON_LIST_OBJECT: case ID_SINGLETON_SET_OBJECT: { instanceCache.put(obj, instanceSeq++); write(id); doWriteObject(((Collection)obj).iterator().next(), false); if (unshared) { instanceCache.put(obj, -1); } return; } case -1: break; default: throw new NotSerializableException(objClass.getName()); } if (isArray) { instanceCache.put(obj, instanceSeq++); final Object[] objects = (Object[]) obj; final int len = objects.length; if (configuredVersion >= 2) { if (len == 0) { write(unshared ? ID_ARRAY_EMPTY_UNSHARED : ID_ARRAY_EMPTY); writeClass(objClass.getComponentType()); } else if (len <= 256) { write(unshared ? ID_ARRAY_SMALL_UNSHARED : ID_ARRAY_SMALL); write(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else if (len <= 65536) { write(unshared ? ID_ARRAY_MEDIUM_UNSHARED : ID_ARRAY_MEDIUM); writeShort(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } else { write(unshared ? ID_ARRAY_LARGE_UNSHARED : ID_ARRAY_LARGE); writeInt(len); writeClass(objClass.getComponentType()); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } } else { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeObjectArrayClass(objClass); writeInt(len); for (int i = 0; i < len; i++) { doWriteObject(objects[i], unshared); } } if (unshared) { instanceCache.put(obj, -1); } return; } // serialize proxies efficiently if (Proxy.isProxyClass(objClass)) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); writeProxyClass(objClass); doWriteObject(Proxy.getInvocationHandler(obj), false); if (unshared) { instanceCache.put(obj, -1); } return; } // it's a user type // user type #1: externalizer Externalizer externalizer; if (externalizers.containsKey(objClass)) { externalizer = externalizers.get(objClass); } else { externalizer = classExternalizerFactory.getExternalizer(objClass); externalizers.put(objClass, externalizer); } if (externalizer != null) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeExternalizerClass(objClass, externalizer); instanceCache.put(obj, instanceSeq++); final ObjectOutput objectOutput; objectOutput = getObjectOutput(); externalizer.writeExternal(obj, objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #2: externalizable if (obj instanceof Externalizable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); instanceCache.put(obj, instanceSeq++); final Externalizable ext = (Externalizable) obj; final ObjectOutput objectOutput = getObjectOutput(); writeExternalizableClass(objClass); ext.writeExternal(objectOutput); writeEndBlock(); if (unshared) { instanceCache.put(obj, -1); } return; } // user type #3: serializable if (obj instanceof Serializable) { write(unshared ? ID_NEW_OBJECT_UNSHARED : ID_NEW_OBJECT); writeSerializableClass(objClass); instanceCache.put(obj, instanceSeq++); doWriteSerializableObject(info, obj, objClass); if (unshared) { instanceCache.put(obj, -1); } return; } throw new NotSerializableException(objClass.getName()); } finally { if (! unreplaced && obj != original) { final int replId = instanceCache.get(obj, -1); if (replId != -1) { instanceCache.put(original, replId); } } } }
diff --git a/JSynthLib/core/CrossBreeder.java b/JSynthLib/core/CrossBreeder.java index 5913bb5..0931aeb 100644 --- a/JSynthLib/core/CrossBreeder.java +++ b/JSynthLib/core/CrossBreeder.java @@ -1,53 +1,52 @@ package core; /* * As of version 0.14 the actual functionality of the crossbreeder * dialog is hidden away in this file. It seems like a good idea to be * seperating functionality from GUI code, something I didn't do when * I first started JSynthLib. */ /** * @author bklock * @version $Id$ */ public class CrossBreeder { /** The patch we are working on. */ Patch p; /** The patch library we are working on. */ PatchBasket library; public void generateNewPatch() { try { Patch father = getRandomPatch(); Patch source; byte[] sysex = new byte[father.sysex.length]; p = new Patch(sysex); - p.comment = new StringBuffer(); // Clear the wrong "Invalid Manufacturer" comment! for (int i = 0; i < father.sysex.length; i++) { // look for a patch with same Driver and enough length do { source = getRandomPatch(); } while (source.driverNum != father.driverNum || source.sysex.length < i || source.deviceNum != father.deviceNum); p.sysex[i] = source.sysex[i]; } p.driverNum = father.driverNum; p.deviceNum = father.deviceNum; p.getDriver().calculateChecksum(p); } catch (Exception e) { ErrorMsg.reportError("Error", "Source Library Must be Focused", e); } } public Patch getCurrentPatch() { return p; } public void workFromLibrary (PatchBasket lib) { library = lib; } public Patch getRandomPatch() { int num = (int) (Math.random() * library.getPatchCollection().size()); return (Patch) (library.getPatchCollection().get(num)); } }
true
true
public void generateNewPatch() { try { Patch father = getRandomPatch(); Patch source; byte[] sysex = new byte[father.sysex.length]; p = new Patch(sysex); p.comment = new StringBuffer(); // Clear the wrong "Invalid Manufacturer" comment! for (int i = 0; i < father.sysex.length; i++) { // look for a patch with same Driver and enough length do { source = getRandomPatch(); } while (source.driverNum != father.driverNum || source.sysex.length < i || source.deviceNum != father.deviceNum); p.sysex[i] = source.sysex[i]; } p.driverNum = father.driverNum; p.deviceNum = father.deviceNum; p.getDriver().calculateChecksum(p); } catch (Exception e) { ErrorMsg.reportError("Error", "Source Library Must be Focused", e); } }
public void generateNewPatch() { try { Patch father = getRandomPatch(); Patch source; byte[] sysex = new byte[father.sysex.length]; p = new Patch(sysex); for (int i = 0; i < father.sysex.length; i++) { // look for a patch with same Driver and enough length do { source = getRandomPatch(); } while (source.driverNum != father.driverNum || source.sysex.length < i || source.deviceNum != father.deviceNum); p.sysex[i] = source.sysex[i]; } p.driverNum = father.driverNum; p.deviceNum = father.deviceNum; p.getDriver().calculateChecksum(p); } catch (Exception e) { ErrorMsg.reportError("Error", "Source Library Must be Focused", e); } }
diff --git a/tycho-its/src/test/java/org/eclipse/tycho/test/bug366967/NonUniqueBasedirsTest.java b/tycho-its/src/test/java/org/eclipse/tycho/test/bug366967/NonUniqueBasedirsTest.java index 990cf97f..0df5a46a 100644 --- a/tycho-its/src/test/java/org/eclipse/tycho/test/bug366967/NonUniqueBasedirsTest.java +++ b/tycho-its/src/test/java/org/eclipse/tycho/test/bug366967/NonUniqueBasedirsTest.java @@ -1,33 +1,33 @@ /******************************************************************************* * Copyright (c) 2012 SAP AG 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: * SAP AG - initial API and implementation *******************************************************************************/ package org.eclipse.tycho.test.bug366967; import org.apache.maven.it.VerificationException; import org.apache.maven.it.Verifier; import org.eclipse.tycho.test.AbstractTychoIntegrationTest; import org.junit.Assert; import org.junit.Test; public class NonUniqueBasedirsTest extends AbstractTychoIntegrationTest { @Test public void testNonUniqueBasedirFailure() throws Exception { Verifier verifier = getVerifier("/nonUniqueModuleBaseDir", false); try { verifier.executeGoal("clean"); Assert.fail("build failure expected"); } catch (VerificationException e) { // expected } - verifier.verifyTextInLog("Multiple modules with the same basedir are not supported"); + verifier.verifyTextInLog("Multiple modules within the same basedir are not supported"); } }
true
true
public void testNonUniqueBasedirFailure() throws Exception { Verifier verifier = getVerifier("/nonUniqueModuleBaseDir", false); try { verifier.executeGoal("clean"); Assert.fail("build failure expected"); } catch (VerificationException e) { // expected } verifier.verifyTextInLog("Multiple modules with the same basedir are not supported"); }
public void testNonUniqueBasedirFailure() throws Exception { Verifier verifier = getVerifier("/nonUniqueModuleBaseDir", false); try { verifier.executeGoal("clean"); Assert.fail("build failure expected"); } catch (VerificationException e) { // expected } verifier.verifyTextInLog("Multiple modules within the same basedir are not supported"); }
diff --git a/src/de/ing_poetter/binview/BinaryFormat.java b/src/de/ing_poetter/binview/BinaryFormat.java index 435168c..8feb995 100644 --- a/src/de/ing_poetter/binview/BinaryFormat.java +++ b/src/de/ing_poetter/binview/BinaryFormat.java @@ -1,292 +1,292 @@ /* * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see <http://www.gnu.org/licenses/> * */ package de.ing_poetter.binview; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.NoSuchElementException; import java.util.Vector; import javax.swing.table.AbstractTableModel; import de.ing_poetter.binview.variables.Variable; import de.ing_poetter.binview.variables.VariableFactory; /** * @author Lars P&ouml;tter * (<a href=mailto:[email protected]>[email protected]</a>) */ public class BinaryFormat extends AbstractTableModel { private static final long serialVersionUID = 1L; private final Vector<Variable> Variables = new Vector<Variable>(); public static BinaryFormat loadFromFile(final String fileName) { final File f = new File(fileName); return loadFromFile(f); } public static BinaryFormat loadFromFile(final File f) { final BinaryFormat res = new BinaryFormat(); if(true == f.canRead()) { BufferedReader br = null; InputStreamReader fr = null; try { fr = new InputStreamReader(new FileInputStream(f), Charset.forName("UTF-8")); br = new BufferedReader(fr); String curLine = null; do{ curLine = br.readLine(); if(null != curLine) { final Variable v = VariableFactory.createVariableFrom(curLine); res.addVariable(v); } }while(null != curLine); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } catch(final NoSuchElementException e) { e.printStackTrace(); } } return res; } public BinaryFormat() { } public void saveToFile(final File f) throws IOException { final FileWriter fw = new FileWriter(f); for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final String res = v.save(); fw.write(res + "\n"); } fw.close(); } public String aplyTo(final String source) { // false = 0; // true = 1; if(null == source) { return null; } final Vector<Boolean> bits = getBitsFromString(source); - String res = "Found " + bits.size() + " bits in Data !\n"; + String res = "Found " + bits.size() + " bits / " + bits.size()/8 + " bytes in Data !\n"; int maxDescriptionLength = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int curDescrLength = v.getDescriptionLength(); if(curDescrLength > maxDescriptionLength) { maxDescriptionLength = curDescrLength; } } // match bits with format int posInBits = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int numBits = v.getNumberBits(); if(posInBits + numBits > bits.size()) { res = res + "End of Data reached !\n"; break; } else { final boolean[] curData = new boolean[numBits]; for(int j = 0; j < numBits; j++) { curData[j] = bits.get(posInBits); posInBits++; } res = res + v.describeValue(curData, maxDescriptionLength) + "\n"; } } if(bits.size() > posInBits) { final int numAdditionalBits = bits.size() - posInBits; final StringBuilder sb = new StringBuilder(); for(int i = 0; i < numAdditionalBits; i++) { - final Boolean b = bits.get(posInBits); + final Boolean b = bits.get(posInBits + i); if(true == b) { sb.append('1'); } else { sb.append('0'); } } res = res + "Additional Data at end : " + sb.toString() + "\n"; } return res; } private Vector<Boolean> getBitsFromString(final String source) { final Vector<Boolean> bits = new Vector<Boolean>(); for(int i = 0; i < source.length(); i++) { final char c = source.charAt(i); switch(c) { case '0':bits.add(false);bits.add(false);bits.add(false);bits.add(false);break; case '1':bits.add(false);bits.add(false);bits.add(false);bits.add(true); break; case '2':bits.add(false);bits.add(false);bits.add(true); bits.add(false);break; case '3':bits.add(false);bits.add(false);bits.add(true); bits.add(true); break; case '4':bits.add(false);bits.add(true); bits.add(false);bits.add(false);break; case '5':bits.add(false);bits.add(true); bits.add(false);bits.add(true); break; case '6':bits.add(false);bits.add(true); bits.add(true); bits.add(false);break; case '7':bits.add(false);bits.add(true); bits.add(true); bits.add(true); break; case '8':bits.add(true); bits.add(false);bits.add(false);bits.add(false);break; case '9':bits.add(true); bits.add(false);bits.add(false);bits.add(true); break; case 'a': case 'A':bits.add(true); bits.add(false);bits.add(true); bits.add(false);break; case 'b': case 'B':bits.add(true); bits.add(false);bits.add(true); bits.add(true); break; case 'c': case 'C':bits.add(true); bits.add(true); bits.add(false);bits.add(false);break; case 'd': case 'D':bits.add(true); bits.add(true); bits.add(false);bits.add(true); break; case 'e': case 'E':bits.add(true); bits.add(true); bits.add(true); bits.add(false);break; case 'f': case 'F':bits.add(true); bits.add(true); bits.add(true); bits.add(true); break; case ' ': break; case '\n': break; case '\r': break; case '\t': break; default: if(0 != bits.size()) { // Crazy chars after data -> ignore + end of data reached // break is not getting us out of the for loop i = source.length(); } // else ignore crazy chars before data } } return bits; } private void addVariable(final Variable v) { if(null != v) { Variables.add(v); } } public void removeVariable(final int idx) { Variables.remove(idx); this.fireTableDataChanged(); } public void addVariableAt(final Variable v, final int idx) { Variables.add(idx, v); this.fireTableDataChanged(); } @Override public int getRowCount() { return Variables.size(); } @Override public int getColumnCount() { return 3; } @Override public Object getValueAt(final int rowIndex, final int columnIndex) { final Variable v = Variables.get(rowIndex); if(0 == columnIndex) { return v.getName(); } else if(1 == columnIndex) { return v.getTypeName(); } else { return v.getNumberBits(); } } @Override public String getColumnName(final int col) { if(0 == col) { return "Name"; } else if(1 == col) { return "type"; } else { return "number of Bits"; } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Class getColumnClass(final int c) { switch(c) { case 0: case 1:return String.class; case 2:return Integer.class; } return String.class; } }
false
true
public String aplyTo(final String source) { // false = 0; // true = 1; if(null == source) { return null; } final Vector<Boolean> bits = getBitsFromString(source); String res = "Found " + bits.size() + " bits in Data !\n"; int maxDescriptionLength = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int curDescrLength = v.getDescriptionLength(); if(curDescrLength > maxDescriptionLength) { maxDescriptionLength = curDescrLength; } } // match bits with format int posInBits = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int numBits = v.getNumberBits(); if(posInBits + numBits > bits.size()) { res = res + "End of Data reached !\n"; break; } else { final boolean[] curData = new boolean[numBits]; for(int j = 0; j < numBits; j++) { curData[j] = bits.get(posInBits); posInBits++; } res = res + v.describeValue(curData, maxDescriptionLength) + "\n"; } } if(bits.size() > posInBits) { final int numAdditionalBits = bits.size() - posInBits; final StringBuilder sb = new StringBuilder(); for(int i = 0; i < numAdditionalBits; i++) { final Boolean b = bits.get(posInBits); if(true == b) { sb.append('1'); } else { sb.append('0'); } } res = res + "Additional Data at end : " + sb.toString() + "\n"; } return res; }
public String aplyTo(final String source) { // false = 0; // true = 1; if(null == source) { return null; } final Vector<Boolean> bits = getBitsFromString(source); String res = "Found " + bits.size() + " bits / " + bits.size()/8 + " bytes in Data !\n"; int maxDescriptionLength = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int curDescrLength = v.getDescriptionLength(); if(curDescrLength > maxDescriptionLength) { maxDescriptionLength = curDescrLength; } } // match bits with format int posInBits = 0; for(int i = 0; i < Variables.size(); i++) { final Variable v = Variables.get(i); final int numBits = v.getNumberBits(); if(posInBits + numBits > bits.size()) { res = res + "End of Data reached !\n"; break; } else { final boolean[] curData = new boolean[numBits]; for(int j = 0; j < numBits; j++) { curData[j] = bits.get(posInBits); posInBits++; } res = res + v.describeValue(curData, maxDescriptionLength) + "\n"; } } if(bits.size() > posInBits) { final int numAdditionalBits = bits.size() - posInBits; final StringBuilder sb = new StringBuilder(); for(int i = 0; i < numAdditionalBits; i++) { final Boolean b = bits.get(posInBits + i); if(true == b) { sb.append('1'); } else { sb.append('0'); } } res = res + "Additional Data at end : " + sb.toString() + "\n"; } return res; }
diff --git a/demo/src/main/java/org/jboss/jdf/example/ticketmonster/util/CacheProducer.java b/demo/src/main/java/org/jboss/jdf/example/ticketmonster/util/CacheProducer.java index 054ff33..1381f92 100644 --- a/demo/src/main/java/org/jboss/jdf/example/ticketmonster/util/CacheProducer.java +++ b/demo/src/main/java/org/jboss/jdf/example/ticketmonster/util/CacheProducer.java @@ -1,87 +1,87 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jdf.example.ticketmonster.util; import java.io.File; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.eviction.EvictionStrategy; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.transaction.LockingMode; import org.infinispan.transaction.TransactionMode; import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; import org.infinispan.util.concurrent.IsolationLevel; import com.google.inject.Inject; /** * Producer for the {@link EmbeddedCacheManager} instance used by the application. Defines * the default configuration for caches. * * @author Marius Bogoevici * */ @ApplicationScoped public class CacheProducer { @Inject @DataDir private String dataDir; /** * C * @return */ @Produces @ApplicationScoped public EmbeddedCacheManager getCacheContainer() { GlobalConfiguration glob = new GlobalConfigurationBuilder() .nonClusteredDefault() //Helper method that gets you a default constructed GlobalConfiguration, preconfigured for use in LOCAL mode .globalJmxStatistics().enable() //This method allows enables the jmx statistics of the global configuration. .build(); //Builds the GlobalConfiguration object Configuration loc = new ConfigurationBuilder() .jmxStatistics().enable() //Enable JMX statistics .clustering().cacheMode(CacheMode.LOCAL) //Set Cache mode to LOCAL - Data is not replicated. .transaction().transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new GenericTransactionManagerLookup()) .lockingMode(LockingMode.PESSIMISTIC) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) //Sets the isolation level of locking .eviction().maxEntries(4).strategy(EvictionStrategy.LIRS) //Sets 4 as maximum number of entries in a cache instance and uses the LIRS strategy - an efficient low inter-reference recency set replacement policy to improve buffer cache performance - .loaders().passivation(false).addFileCacheStore().location(dataDir + File.pathSeparator + "TicketMonster-CacheStore").purgeOnStartup(true) //Disable passivation and adds a FileCacheStore that is Purged on Startup + .loaders().passivation(false).addFileCacheStore().location(dataDir + File.separator + "TicketMonster-CacheStore").purgeOnStartup(true) //Disable passivation and adds a FileCacheStore that is Purged on Startup .build(); //Builds the Configuration object return new DefaultCacheManager(glob, loc, true); } public void cleanUp(@Disposes EmbeddedCacheManager manager) { manager.stop(); } }
true
true
public EmbeddedCacheManager getCacheContainer() { GlobalConfiguration glob = new GlobalConfigurationBuilder() .nonClusteredDefault() //Helper method that gets you a default constructed GlobalConfiguration, preconfigured for use in LOCAL mode .globalJmxStatistics().enable() //This method allows enables the jmx statistics of the global configuration. .build(); //Builds the GlobalConfiguration object Configuration loc = new ConfigurationBuilder() .jmxStatistics().enable() //Enable JMX statistics .clustering().cacheMode(CacheMode.LOCAL) //Set Cache mode to LOCAL - Data is not replicated. .transaction().transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new GenericTransactionManagerLookup()) .lockingMode(LockingMode.PESSIMISTIC) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) //Sets the isolation level of locking .eviction().maxEntries(4).strategy(EvictionStrategy.LIRS) //Sets 4 as maximum number of entries in a cache instance and uses the LIRS strategy - an efficient low inter-reference recency set replacement policy to improve buffer cache performance .loaders().passivation(false).addFileCacheStore().location(dataDir + File.pathSeparator + "TicketMonster-CacheStore").purgeOnStartup(true) //Disable passivation and adds a FileCacheStore that is Purged on Startup .build(); //Builds the Configuration object return new DefaultCacheManager(glob, loc, true); }
public EmbeddedCacheManager getCacheContainer() { GlobalConfiguration glob = new GlobalConfigurationBuilder() .nonClusteredDefault() //Helper method that gets you a default constructed GlobalConfiguration, preconfigured for use in LOCAL mode .globalJmxStatistics().enable() //This method allows enables the jmx statistics of the global configuration. .build(); //Builds the GlobalConfiguration object Configuration loc = new ConfigurationBuilder() .jmxStatistics().enable() //Enable JMX statistics .clustering().cacheMode(CacheMode.LOCAL) //Set Cache mode to LOCAL - Data is not replicated. .transaction().transactionMode(TransactionMode.TRANSACTIONAL) .transactionManagerLookup(new GenericTransactionManagerLookup()) .lockingMode(LockingMode.PESSIMISTIC) .locking().isolationLevel(IsolationLevel.REPEATABLE_READ) //Sets the isolation level of locking .eviction().maxEntries(4).strategy(EvictionStrategy.LIRS) //Sets 4 as maximum number of entries in a cache instance and uses the LIRS strategy - an efficient low inter-reference recency set replacement policy to improve buffer cache performance .loaders().passivation(false).addFileCacheStore().location(dataDir + File.separator + "TicketMonster-CacheStore").purgeOnStartup(true) //Disable passivation and adds a FileCacheStore that is Purged on Startup .build(); //Builds the Configuration object return new DefaultCacheManager(glob, loc, true); }
diff --git a/server-main/src/test/java/org/powertac/server/ServerMessageReceiverTests.java b/server-main/src/test/java/org/powertac/server/ServerMessageReceiverTests.java index 7de2666..8c6cf2f 100644 --- a/server-main/src/test/java/org/powertac/server/ServerMessageReceiverTests.java +++ b/server-main/src/test/java/org/powertac/server/ServerMessageReceiverTests.java @@ -1,49 +1,48 @@ package org.powertac.server; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.*; import javax.jms.TextMessage; import org.junit.Before; import org.junit.Test; import org.powertac.common.Broker; import org.powertac.common.XMLMessageConverter; import org.powertac.common.interfaces.BrokerProxy; import org.powertac.common.msg.BrokerAuthentication; import org.springframework.test.util.ReflectionTestUtils; public class ServerMessageReceiverTests { ServerMessageReceiver receiver; BrokerProxy brokerProxy; XMLMessageConverter converter; @Before public void before() { receiver = new ServerMessageReceiver(); brokerProxy = mock(BrokerProxy.class); converter = mock(XMLMessageConverter.class); ReflectionTestUtils.setField(receiver, "brokerProxy", brokerProxy); ReflectionTestUtils.setField(receiver, "converter", converter); } @Test public void testOnMessage() throws Exception { - BrokerAuthentication ba = new BrokerAuthentication(); Broker broker = new Broker("abc"); - ba.setBroker(broker); + BrokerAuthentication ba = new BrokerAuthentication(broker); String xml = converter.toXML(ba); TextMessage message = mock(TextMessage.class); when(message.getText()).thenReturn(xml); when(converter.fromXML(any(String.class))).thenReturn(ba); receiver.onMessage(message); verify(brokerProxy).routeMessage(ba); } }
false
true
public void testOnMessage() throws Exception { BrokerAuthentication ba = new BrokerAuthentication(); Broker broker = new Broker("abc"); ba.setBroker(broker); String xml = converter.toXML(ba); TextMessage message = mock(TextMessage.class); when(message.getText()).thenReturn(xml); when(converter.fromXML(any(String.class))).thenReturn(ba); receiver.onMessage(message); verify(brokerProxy).routeMessage(ba); }
public void testOnMessage() throws Exception { Broker broker = new Broker("abc"); BrokerAuthentication ba = new BrokerAuthentication(broker); String xml = converter.toXML(ba); TextMessage message = mock(TextMessage.class); when(message.getText()).thenReturn(xml); when(converter.fromXML(any(String.class))).thenReturn(ba); receiver.onMessage(message); verify(brokerProxy).routeMessage(ba); }
diff --git a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/sourcelookup/ExternalArchiveSourceContainerTests.java b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/sourcelookup/ExternalArchiveSourceContainerTests.java index 5ab7749cc..9b9e73bc6 100755 --- a/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/sourcelookup/ExternalArchiveSourceContainerTests.java +++ b/org.eclipse.jdt.debug.tests/tests/org/eclipse/jdt/debug/tests/sourcelookup/ExternalArchiveSourceContainerTests.java @@ -1,154 +1,154 @@ /******************************************************************************* * Copyright (c) 2004, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.debug.tests.sourcelookup; import java.io.File; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.sourcelookup.ISourceContainer; import org.eclipse.debug.core.sourcelookup.ISourceLookupDirector; import org.eclipse.debug.core.sourcelookup.containers.ExternalArchiveSourceContainer; import org.eclipse.debug.core.sourcelookup.containers.ZipEntryStorage; import org.eclipse.jdt.debug.testplugin.JavaTestPlugin; import org.eclipse.jdt.debug.tests.AbstractDebugTest; import org.eclipse.jdt.internal.launching.JavaSourceLookupDirector; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.LibraryLocation; /** * Tests external archive source containers */ public class ExternalArchiveSourceContainerTests extends AbstractDebugTest { public ExternalArchiveSourceContainerTests(String name) { super(name); } /** * Returns the JREs source archive. * * @return * @throws Exception */ protected ExternalArchiveSourceContainer getContainer(boolean detect, boolean duplicates) throws Exception { ISourceLookupDirector director = new JavaSourceLookupDirector(); director.initializeParticipants(); director.setFindDuplicates(duplicates); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(JavaRuntime.getDefaultVMInstall()); for (int i = 0; i < locations.length; i++) { LibraryLocation location = locations[i]; IPath path = location.getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(path.toOSString(), detect); director.setSourceContainers(new ISourceContainer[]{container}); return container; } } - assertTrue("Did not find JRE source archive", false); + assertTrue("Did not find JRE source archive. This failure is expected if you are running the tests with a JRE that does not contain source.", false); return null; } /** * Returns the source archive at the specified path within this plug-in. */ protected ExternalArchiveSourceContainer getContainer(String path, boolean detect, boolean duplicates) throws Exception { ISourceLookupDirector director = new JavaSourceLookupDirector(); director.initializeParticipants(); director.setFindDuplicates(duplicates); IPath p = new Path(path); File file = JavaTestPlugin.getDefault().getFileInPlugin(p); assertTrue("file " + path + " does not exist", file != null && file.exists()); ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(file.getAbsolutePath(), detect); director.setSourceContainers(new ISourceContainer[]{container}); return container; } /** * Tests creation and restoring from a memento. * * @throws Exception */ public void testArchiveSourceContainerMemento() throws Exception { ExternalArchiveSourceContainer container = getContainer(true, false); assertFalse(container.isComposite()); assertTrue(container.isDetectRoot()); String memento = container.getType().getMemento(container); ExternalArchiveSourceContainer restore = (ExternalArchiveSourceContainer) container.getType().createSourceContainer(memento); assertEquals("Directory source container memento failed", container, restore); assertFalse(restore.isComposite()); assertTrue(restore.isDetectRoot()); } public void testAutoDetectRootSourceLookupPositive() throws Exception { ExternalArchiveSourceContainer container = getContainer(true, false); Object[] objects = container.findSourceElements("java/lang/Object.java"); assertEquals("Expected 1 result", 1, objects.length); ZipEntryStorage storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "Object.java", storage.getName()); } public void testAutoDetectRootSourceLookupNegative() throws Exception { ExternalArchiveSourceContainer container = getContainer(true, false); Object[] objects = container.findSourceElements("java/lang/FileNotFound.java"); assertEquals("Expected 0 files", 0, objects.length); } public void testSourceLookupPositive() throws Exception { ExternalArchiveSourceContainer container = getContainer(false, false); Object[] objects = container.findSourceElements("java/lang/Object.java"); assertEquals("Expected 1 result", 1, objects.length); ZipEntryStorage storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "Object.java", storage.getName()); } public void testSourceLookupNegative() throws Exception { ExternalArchiveSourceContainer container = getContainer(false, false); Object[] objects = container.findSourceElements("java/lang/FileNotFound.java"); assertEquals("Expected 0 files", 0, objects.length); } public void testPartiallyQualifiedSourceLookupPositive() throws Exception { ExternalArchiveSourceContainer container = getContainer(false, false); Object[] objects = container.findSourceElements("lang/Object.java"); assertEquals("Expected 1 result", 1, objects.length); ZipEntryStorage storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "Object.java", storage.getName()); } public void testAutoDetectUnqualifiedSourceLookupPositive() throws Exception { ExternalArchiveSourceContainer container = getContainer(true, false); // force detection Object[] objects = container.findSourceElements("java/lang/Object.java"); // then search for unqualified file objects = container.findSourceElements("Object.java"); assertEquals("Expected 1 result", 1, objects.length); ZipEntryStorage storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "Object.java", storage.getName()); } public void testAutoDetectMultipleRoots() throws Exception { ExternalArchiveSourceContainer container = getContainer("testresources/source-test.zip", true, false); // find .java file Object[] objects = container.findSourceElements("one/two/Three.java"); assertEquals("Expected 1 result", 1, objects.length); ZipEntryStorage storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "Three.java", storage.getName()); // find .txt file objects = container.findSourceElements("another/file-b.txt"); storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "file-b.txt", storage.getName()); // find another .txt file objects = container.findSourceElements("folder/file-c.txt"); storage = (ZipEntryStorage) objects[0]; assertEquals("Wrong file", "file-c.txt", storage.getName()); } }
true
true
protected ExternalArchiveSourceContainer getContainer(boolean detect, boolean duplicates) throws Exception { ISourceLookupDirector director = new JavaSourceLookupDirector(); director.initializeParticipants(); director.setFindDuplicates(duplicates); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(JavaRuntime.getDefaultVMInstall()); for (int i = 0; i < locations.length; i++) { LibraryLocation location = locations[i]; IPath path = location.getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(path.toOSString(), detect); director.setSourceContainers(new ISourceContainer[]{container}); return container; } } assertTrue("Did not find JRE source archive", false); return null; }
protected ExternalArchiveSourceContainer getContainer(boolean detect, boolean duplicates) throws Exception { ISourceLookupDirector director = new JavaSourceLookupDirector(); director.initializeParticipants(); director.setFindDuplicates(duplicates); LibraryLocation[] locations = JavaRuntime.getLibraryLocations(JavaRuntime.getDefaultVMInstall()); for (int i = 0; i < locations.length; i++) { LibraryLocation location = locations[i]; IPath path = location.getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { ExternalArchiveSourceContainer container = new ExternalArchiveSourceContainer(path.toOSString(), detect); director.setSourceContainers(new ISourceContainer[]{container}); return container; } } assertTrue("Did not find JRE source archive. This failure is expected if you are running the tests with a JRE that does not contain source.", false); return null; }
diff --git a/src/msf/DatabaseImpl.java b/src/msf/DatabaseImpl.java index ab5ac46..d942f1c 100644 --- a/src/msf/DatabaseImpl.java +++ b/src/msf/DatabaseImpl.java @@ -1,325 +1,325 @@ package msf; import java.util.*; import java.sql.*; import java.io.*; import graph.Route; /* implement the old MSF RPC database calls in a way Armitage likes */ public class DatabaseImpl implements RpcConnection { protected Connection db; protected Map queries; protected String workspaceid = "0"; protected String hFilter = null; protected String sFilter = null; protected Route[] rFilter = null; protected String[] oFilter = null; private static String join(List items, String delim) { StringBuffer result = new StringBuffer(); Iterator i = items.iterator(); while (i.hasNext()) { result.append(i.next()); if (i.hasNext()) { result.append(delim); } } return result.toString(); } public void setWorkspace(String name) { try { List spaces = executeQuery("SELECT DISTINCT * FROM workspaces"); Iterator i = spaces.iterator(); while (i.hasNext()) { Map temp = (Map)i.next(); if (name.equals(temp.get("name"))) { workspaceid = temp.get("id") + ""; queries = build(); } } } catch (Exception ex) { throw new RuntimeException(ex); } } public void setDebug(boolean d) { } public DatabaseImpl() { queries = build(); } /* marshall the type into something we'd rather deal with */ protected Object fixResult(Object o) { if (o instanceof java.sql.Timestamp) { return new Long(((Timestamp)o).getTime()); } return o; } protected int executeUpdate(String query) throws Exception { Statement s = db.createStatement(); return s.executeUpdate(query); } /* execute the query and return a linked list of the results..., whee?!? */ protected List executeQuery(String query) throws Exception { List results = new LinkedList(); Statement s = db.createStatement(); ResultSet r = s.executeQuery(query); while (r.next()) { Map row = new HashMap(); ResultSetMetaData m = r.getMetaData(); int c = m.getColumnCount(); for (int i = 1; i <= c; i++) { row.put(m.getColumnLabel(i), fixResult(r.getObject(i))); } results.add(row); } return results; } private boolean checkRoute(String address) { for (int x = 0; x < rFilter.length; x++) { if (rFilter[x].shouldRoute(address)) return true; } return false; } private boolean checkOS(String os) { String os_l = os.toLowerCase(); for (int x = 0; x < oFilter.length; x++) { if (os_l.indexOf(oFilter[x]) != -1) return true; } return false; } public List filterByRoute(List rows, int max) { if (rFilter != null || oFilter != null) { Iterator i = rows.iterator(); while (i.hasNext()) { Map entry = (Map)i.next(); if (rFilter != null && entry.containsKey("address")) { if (!checkRoute(entry.get("address") + "")) { i.remove(); continue; } } else if (rFilter != null && entry.containsKey("host")) { if (!checkRoute(entry.get("host") + "")) { i.remove(); continue; } } if (oFilter != null && entry.containsKey("os_name")) { if (!checkOS(entry.get("os_name") + "")) i.remove(); } } if (rows.size() > max) { rows.subList(max, rows.size()).clear(); } } return rows; } public void connect(String dbstring, String user, String password) throws Exception { db = DriverManager.getConnection(dbstring, user, password); setWorkspace("default"); } public Object execute(String methodName) throws IOException { return execute(methodName, new Object[0]); } protected Map build() { Map temp = new HashMap(); /* this is an optimization. If we have a network or OS filter, we need to pull back all host/service records and filter them here. If we do not have these types of filters, then we can let the database do the heavy lifting and limit the size of the final result there. */ String limit1 = rFilter == null && oFilter == null ? "512" : "30000"; String limit2 = rFilter == null && oFilter == null ? "12288" : "100000"; temp.put("db.creds", "SELECT DISTINCT creds.*, hosts.address as host, services.name as sname, services.port as port, services.proto as proto FROM creds, services, hosts WHERE services.id = creds.service_id AND hosts.id = services.host_id AND hosts.workspace_id = " + workspaceid); /* db.creds2 exists to prevent duplicate entries for the stuff I care about */ temp.put("db.creds2", "SELECT DISTINCT creds.user, creds.pass, hosts.address as host, services.name as sname, services.port as port, services.proto as proto, creds.ptype FROM creds, services, hosts WHERE services.id = creds.service_id AND hosts.id = services.host_id AND hosts.workspace_id = " + workspaceid); if (hFilter != null) { temp.put("db.hosts", "SELECT DISTINCT hosts.* FROM hosts, services, sessions WHERE hosts.workspace_id = " + workspaceid + " AND " + hFilter + " LIMIT " + limit1); } else { temp.put("db.hosts", "SELECT DISTINCT hosts.* FROM hosts WHERE hosts.workspace_id = " + workspaceid + " LIMIT " + limit1); } temp.put("db.services", "SELECT DISTINCT services.*, hosts.address as host FROM services, (" + temp.get("db.hosts") + ") as hosts WHERE hosts.id = services.host_id LIMIT " + limit2); temp.put("db.loots", "SELECT DISTINCT loots.*, hosts.address as host FROM loots, hosts WHERE hosts.id = loots.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.workspaces", "SELECT DISTINCT * FROM workspaces"); temp.put("db.notes", "SELECT DISTINCT notes.*, hosts.address as host FROM notes, hosts WHERE hosts.id = notes.host_id AND hosts.workspace_id = " + workspaceid); temp.put("db.clients", "SELECT DISTINCT clients.*, hosts.address as host FROM clients, hosts WHERE hosts.id = clients.host_id AND hosts.workspace_id = " + workspaceid); return temp; } public Object execute(String methodName, Object[] params) throws IOException { try { if (queries.containsKey(methodName)) { String query = queries.get(methodName) + ""; Map result = new HashMap(); if (methodName.equals("db.services")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 12288)); } else if (methodName.equals("db.hosts")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 512)); } else { result.put(methodName.substring(3), executeQuery(query)); } return result; } else if (methodName.equals("db.vulns")) { //List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto FROM vulns, hosts, services WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id"); //List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host FROM vulns, hosts WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL"); List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto, refs.name as refs FROM vulns, hosts, services, vulns_refs, refs WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, refs.name as refs FROM vulns, hosts, refs, vulns_refs WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); a.addAll(b); Map result = new HashMap(); result.put("vulns", a); return result; } else if (methodName.equals("db.clear")) { executeUpdate("DELETE FROM hosts"); executeUpdate("DELETE FROM services"); executeUpdate("DELETE FROM events"); executeUpdate("DELETE FROM notes"); executeUpdate("DELETE FROM creds"); executeUpdate("DELETE FROM loots"); executeUpdate("DELETE FROM vulns"); return new HashMap(); } else if (methodName.equals("db.filter")) { /* I'd totally do parameterized queries if I wasn't building this damned query dynamically. Hence it'll have to do. */ Map values = (Map)params[0]; rFilter = null; oFilter = null; List hosts = new LinkedList(); List srvcs = new LinkedList(); if ((values.get("session") + "").equals("1")) { - hosts.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); + hosts.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL AND sessions.close_reason IS NULL"); //srvcs.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); } if (values.containsKey("hosts") && (values.get("hosts") + "").length() > 0) { String h = values.get("hosts") + ""; if (!h.matches("[0-9a-fA-F\\.:\\%\\_/, ]+")) { System.err.println("Host value did not validate!"); return new HashMap(); } String[] routes = h.split(",\\s+"); rFilter = new Route[routes.length]; for (int x = 0; x < routes.length; x++) { rFilter[x] = new Route(routes[x]); } } if (values.containsKey("ports") && (values.get("ports") + "").length() > 0) { List ports = new LinkedList(); List ports2 = new LinkedList(); String[] p = (values.get("ports") + "").split(",\\s+"); for (int x = 0; x < p.length; x++) { if (!p[x].matches("[0-9]+")) { return new HashMap(); } ports.add("services.port = " + p[x]); //ports2.add("s.port = " + p[x]); } hosts.add("services.host_id = hosts.id"); hosts.add("(" + join(ports, " OR ") + ")"); } if (values.containsKey("os") && (values.get("os") + "").length() > 0) { oFilter = (values.get("os") + "").toLowerCase().split(",\\s+"); } if (hosts.size() == 0) { hFilter = null; } else { hFilter = join(hosts, " AND "); } queries = build(); return new HashMap(); } else if (methodName.equals("db.fix_creds")) { Map values = (Map)params[0]; PreparedStatement stmt = null; stmt = db.prepareStatement("UPDATE creds SET ptype = 'smb_hash' WHERE creds.user = ? AND creds.pass = ?"); stmt.setString(1, values.get("user") + ""); stmt.setString(2, values.get("pass") + ""); Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else if (methodName.equals("db.report_host")) { Map values = (Map)params[0]; String host = values.get("host") + ""; PreparedStatement stmt = null; if (values.containsKey("os_name") && values.containsKey("os_flavor")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = ?, os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, values.get("os_flavor") + ""); stmt.setString(3, host); } else if (values.containsKey("os_name")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = '', os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, host); } else { return new HashMap(); } Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else { System.err.println("Need to implement: " + methodName); } } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return new HashMap(); } }
true
true
public Object execute(String methodName, Object[] params) throws IOException { try { if (queries.containsKey(methodName)) { String query = queries.get(methodName) + ""; Map result = new HashMap(); if (methodName.equals("db.services")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 12288)); } else if (methodName.equals("db.hosts")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 512)); } else { result.put(methodName.substring(3), executeQuery(query)); } return result; } else if (methodName.equals("db.vulns")) { //List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto FROM vulns, hosts, services WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id"); //List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host FROM vulns, hosts WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL"); List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto, refs.name as refs FROM vulns, hosts, services, vulns_refs, refs WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, refs.name as refs FROM vulns, hosts, refs, vulns_refs WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); a.addAll(b); Map result = new HashMap(); result.put("vulns", a); return result; } else if (methodName.equals("db.clear")) { executeUpdate("DELETE FROM hosts"); executeUpdate("DELETE FROM services"); executeUpdate("DELETE FROM events"); executeUpdate("DELETE FROM notes"); executeUpdate("DELETE FROM creds"); executeUpdate("DELETE FROM loots"); executeUpdate("DELETE FROM vulns"); return new HashMap(); } else if (methodName.equals("db.filter")) { /* I'd totally do parameterized queries if I wasn't building this damned query dynamically. Hence it'll have to do. */ Map values = (Map)params[0]; rFilter = null; oFilter = null; List hosts = new LinkedList(); List srvcs = new LinkedList(); if ((values.get("session") + "").equals("1")) { hosts.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); //srvcs.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); } if (values.containsKey("hosts") && (values.get("hosts") + "").length() > 0) { String h = values.get("hosts") + ""; if (!h.matches("[0-9a-fA-F\\.:\\%\\_/, ]+")) { System.err.println("Host value did not validate!"); return new HashMap(); } String[] routes = h.split(",\\s+"); rFilter = new Route[routes.length]; for (int x = 0; x < routes.length; x++) { rFilter[x] = new Route(routes[x]); } } if (values.containsKey("ports") && (values.get("ports") + "").length() > 0) { List ports = new LinkedList(); List ports2 = new LinkedList(); String[] p = (values.get("ports") + "").split(",\\s+"); for (int x = 0; x < p.length; x++) { if (!p[x].matches("[0-9]+")) { return new HashMap(); } ports.add("services.port = " + p[x]); //ports2.add("s.port = " + p[x]); } hosts.add("services.host_id = hosts.id"); hosts.add("(" + join(ports, " OR ") + ")"); } if (values.containsKey("os") && (values.get("os") + "").length() > 0) { oFilter = (values.get("os") + "").toLowerCase().split(",\\s+"); } if (hosts.size() == 0) { hFilter = null; } else { hFilter = join(hosts, " AND "); } queries = build(); return new HashMap(); } else if (methodName.equals("db.fix_creds")) { Map values = (Map)params[0]; PreparedStatement stmt = null; stmt = db.prepareStatement("UPDATE creds SET ptype = 'smb_hash' WHERE creds.user = ? AND creds.pass = ?"); stmt.setString(1, values.get("user") + ""); stmt.setString(2, values.get("pass") + ""); Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else if (methodName.equals("db.report_host")) { Map values = (Map)params[0]; String host = values.get("host") + ""; PreparedStatement stmt = null; if (values.containsKey("os_name") && values.containsKey("os_flavor")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = ?, os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, values.get("os_flavor") + ""); stmt.setString(3, host); } else if (values.containsKey("os_name")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = '', os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, host); } else { return new HashMap(); } Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else { System.err.println("Need to implement: " + methodName); } } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return new HashMap(); }
public Object execute(String methodName, Object[] params) throws IOException { try { if (queries.containsKey(methodName)) { String query = queries.get(methodName) + ""; Map result = new HashMap(); if (methodName.equals("db.services")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 12288)); } else if (methodName.equals("db.hosts")) { result.put(methodName.substring(3), filterByRoute(executeQuery(query), 512)); } else { result.put(methodName.substring(3), executeQuery(query)); } return result; } else if (methodName.equals("db.vulns")) { //List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto FROM vulns, hosts, services WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id"); //List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host FROM vulns, hosts WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL"); List a = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, services.port as port, services.proto as proto, refs.name as refs FROM vulns, hosts, services, vulns_refs, refs WHERE hosts.id = vulns.host_id AND services.id = vulns.service_id AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); List b = executeQuery("SELECT DISTINCT vulns.*, hosts.address as host, refs.name as refs FROM vulns, hosts, refs, vulns_refs WHERE hosts.id = vulns.host_id AND vulns.service_id IS NULL AND vulns_refs.vuln_id = vulns.id AND vulns_refs.ref_id = refs.id AND hosts.workspace_id = " + workspaceid); a.addAll(b); Map result = new HashMap(); result.put("vulns", a); return result; } else if (methodName.equals("db.clear")) { executeUpdate("DELETE FROM hosts"); executeUpdate("DELETE FROM services"); executeUpdate("DELETE FROM events"); executeUpdate("DELETE FROM notes"); executeUpdate("DELETE FROM creds"); executeUpdate("DELETE FROM loots"); executeUpdate("DELETE FROM vulns"); return new HashMap(); } else if (methodName.equals("db.filter")) { /* I'd totally do parameterized queries if I wasn't building this damned query dynamically. Hence it'll have to do. */ Map values = (Map)params[0]; rFilter = null; oFilter = null; List hosts = new LinkedList(); List srvcs = new LinkedList(); if ((values.get("session") + "").equals("1")) { hosts.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL AND sessions.close_reason IS NULL"); //srvcs.add("sessions.host_id = hosts.id AND sessions.closed_at IS NULL"); } if (values.containsKey("hosts") && (values.get("hosts") + "").length() > 0) { String h = values.get("hosts") + ""; if (!h.matches("[0-9a-fA-F\\.:\\%\\_/, ]+")) { System.err.println("Host value did not validate!"); return new HashMap(); } String[] routes = h.split(",\\s+"); rFilter = new Route[routes.length]; for (int x = 0; x < routes.length; x++) { rFilter[x] = new Route(routes[x]); } } if (values.containsKey("ports") && (values.get("ports") + "").length() > 0) { List ports = new LinkedList(); List ports2 = new LinkedList(); String[] p = (values.get("ports") + "").split(",\\s+"); for (int x = 0; x < p.length; x++) { if (!p[x].matches("[0-9]+")) { return new HashMap(); } ports.add("services.port = " + p[x]); //ports2.add("s.port = " + p[x]); } hosts.add("services.host_id = hosts.id"); hosts.add("(" + join(ports, " OR ") + ")"); } if (values.containsKey("os") && (values.get("os") + "").length() > 0) { oFilter = (values.get("os") + "").toLowerCase().split(",\\s+"); } if (hosts.size() == 0) { hFilter = null; } else { hFilter = join(hosts, " AND "); } queries = build(); return new HashMap(); } else if (methodName.equals("db.fix_creds")) { Map values = (Map)params[0]; PreparedStatement stmt = null; stmt = db.prepareStatement("UPDATE creds SET ptype = 'smb_hash' WHERE creds.user = ? AND creds.pass = ?"); stmt.setString(1, values.get("user") + ""); stmt.setString(2, values.get("pass") + ""); Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else if (methodName.equals("db.report_host")) { Map values = (Map)params[0]; String host = values.get("host") + ""; PreparedStatement stmt = null; if (values.containsKey("os_name") && values.containsKey("os_flavor")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = ?, os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, values.get("os_flavor") + ""); stmt.setString(3, host); } else if (values.containsKey("os_name")) { stmt = db.prepareStatement("UPDATE hosts SET os_name = ?, os_flavor = '', os_sp = '' WHERE hosts.address = ? AND hosts.workspace_id = " + workspaceid); stmt.setString(1, values.get("os_name") + ""); stmt.setString(2, host); } else { return new HashMap(); } Map result = new HashMap(); result.put("rows", new Integer(stmt.executeUpdate())); return result; } else { System.err.println("Need to implement: " + methodName); } } catch (Exception ex) { System.err.println(ex); ex.printStackTrace(); } return new HashMap(); }
diff --git a/robot/Multiplexor.java b/robot/Multiplexor.java index 9a32b79..ad86ae8 100644 --- a/robot/Multiplexor.java +++ b/robot/Multiplexor.java @@ -1,47 +1,49 @@ import lejos.nxt.I2CPort; import lejos.nxt.I2CSensor; public class Multiplexor extends I2CSensor{ private static byte direction; private static byte speed; public Multiplexor(I2CPort port){ super(port); setAddress(0x5A); } public static void main(String[] args){ } public void setMotors(int directionIndex, int speedIndex, int wheelIndex){ // sets up possible values if(directionIndex == -1){ direction = (byte)2; }else if(directionIndex == 0){ direction = (byte)0; } else if(speedIndex == 1){ direction = (byte)1; } if(speedIndex == 0){ speed = (byte)0; }else if(speedIndex == 1){ - speed = (byte)130; - } else if(speedIndex == 2){ + speed = (byte)90; + }else if(speedIndex == 2){ + speed = (byte)180; + } else if(speedIndex == 3){ speed = (byte)255; } switch (wheelIndex){ // left wheel case 0: sendData((byte)0x03,direction); sendData((byte)0x04,speed); break; // right wheel case 1: sendData((byte)0x01,direction); sendData((byte)0x02,speed); break; } } }
true
true
public void setMotors(int directionIndex, int speedIndex, int wheelIndex){ // sets up possible values if(directionIndex == -1){ direction = (byte)2; }else if(directionIndex == 0){ direction = (byte)0; } else if(speedIndex == 1){ direction = (byte)1; } if(speedIndex == 0){ speed = (byte)0; }else if(speedIndex == 1){ speed = (byte)130; } else if(speedIndex == 2){ speed = (byte)255; } switch (wheelIndex){ // left wheel case 0: sendData((byte)0x03,direction); sendData((byte)0x04,speed); break; // right wheel case 1: sendData((byte)0x01,direction); sendData((byte)0x02,speed); break; } }
public void setMotors(int directionIndex, int speedIndex, int wheelIndex){ // sets up possible values if(directionIndex == -1){ direction = (byte)2; }else if(directionIndex == 0){ direction = (byte)0; } else if(speedIndex == 1){ direction = (byte)1; } if(speedIndex == 0){ speed = (byte)0; }else if(speedIndex == 1){ speed = (byte)90; }else if(speedIndex == 2){ speed = (byte)180; } else if(speedIndex == 3){ speed = (byte)255; } switch (wheelIndex){ // left wheel case 0: sendData((byte)0x03,direction); sendData((byte)0x04,speed); break; // right wheel case 1: sendData((byte)0x01,direction); sendData((byte)0x02,speed); break; } }
diff --git a/src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java b/src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java index c6c3c1c5e..dc382d151 100644 --- a/src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java +++ b/src/net/java/sip/communicator/impl/gui/customcontrols/SIPCommFrame.java @@ -1,224 +1,226 @@ /* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.customcontrols; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.configuration.*; import net.java.sip.communicator.util.*; public abstract class SIPCommFrame extends JFrame { private Logger logger = Logger.getLogger(SIPCommFrame.class); ActionMap amap; InputMap imap; public SIPCommFrame() { this.setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); // In order to have the same icon when using option panes JOptionPane.getRootFrame().setIconImage( ImageLoader.getImage(ImageLoader.SIP_COMMUNICATOR_LOGO)); this.addWindowListener(new FrameWindowAdapter()); amap = this.getRootPane().getActionMap(); amap.put("close", new CloseAction()); imap = this.getRootPane().getInputMap( JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "close"); } /** * The action invoked when user presses Escape key. */ private class CloseAction extends AbstractAction { public void actionPerformed(ActionEvent e) { saveSizeAndLocation(); close(true); } } /** * Adds a key - action pair for this frame. * * @param keyStroke the key combination * @param action the action which will be executed when user presses the * given key combination */ protected void addKeyBinding(KeyStroke keyStroke, Action action) { String actionID = action.getClass().getName(); amap.put(actionID, action); imap.put(keyStroke, actionID); } /** * Before closing the application window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class FrameWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { saveSizeAndLocation(); close(false); } } /** * Saves the size and the location of this frame through the * <tt>ConfigurationService</tt>. */ private void saveSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); try { configService.setProperty( className + ".width", new Integer(getWidth())); configService.setProperty( className + ".height", new Integer(getHeight())); configService.setProperty( className + ".x", new Integer(getX())); configService.setProperty( className + ".y", new Integer(getY())); } catch (PropertyVetoException e1) { logger.error("The proposed property change " + "represents an unacceptable value"); } } /** * Sets window size and position. */ public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); String widthString = configService.getString( className + ".width"); String heightString = configService.getString( className + ".height"); String xString = configService.getString( className + ".x"); String yString = configService.getString( className + ".y"); int width = 0; int height = 0; int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; if(widthString != null && heightString != null) { width = new Integer(widthString).intValue(); height = new Integer(heightString).intValue(); if(width > 0 && height > 0 && width <= screenWidth && height <= screenHeight) this.setSize(width, height); } int x = 0; int y = 0; if(xString != null && yString != null) { x = new Integer(xString).intValue(); y = new Integer(yString).intValue(); if (x >= 0 && y >= 0) - this.setLocation(x, y); + this.setLocation(x, y); + else + this.setCenterLocation(); } else { this.setCenterLocation(); } } /** * Positions this window in the center of the screen. */ private void setCenterLocation() { this.setLocation( Toolkit.getDefaultToolkit().getScreenSize().width/2 - this.getWidth()/2, Toolkit.getDefaultToolkit().getScreenSize().height/2 - this.getHeight()/2 ); } /** * Overwrites the setVisible method in order to set the size and the * position of this window before showing it. */ public void setVisible(boolean isVisible) { if(isVisible) { this.pack(); this.setSizeAndLocation(); } super.setVisible(isVisible); } /** * Overwrites the dispose method in order to save the size and the position * of this window before closing it. */ public void dispose() { super.dispose(); this.saveSizeAndLocation(); } /** * All functions implemented in this method will be invoked when user * presses the Escape key. */ protected abstract void close(boolean isEscaped); }
true
true
public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); String widthString = configService.getString( className + ".width"); String heightString = configService.getString( className + ".height"); String xString = configService.getString( className + ".x"); String yString = configService.getString( className + ".y"); int width = 0; int height = 0; int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; if(widthString != null && heightString != null) { width = new Integer(widthString).intValue(); height = new Integer(heightString).intValue(); if(width > 0 && height > 0 && width <= screenWidth && height <= screenHeight) this.setSize(width, height); } int x = 0; int y = 0; if(xString != null && yString != null) { x = new Integer(xString).intValue(); y = new Integer(yString).intValue(); if (x >= 0 && y >= 0) this.setLocation(x, y); } else { this.setCenterLocation(); } }
public void setSizeAndLocation() { ConfigurationService configService = GuiActivator.getConfigurationService(); String className = this.getClass().getName(); String widthString = configService.getString( className + ".width"); String heightString = configService.getString( className + ".height"); String xString = configService.getString( className + ".x"); String yString = configService.getString( className + ".y"); int width = 0; int height = 0; int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; if(widthString != null && heightString != null) { width = new Integer(widthString).intValue(); height = new Integer(heightString).intValue(); if(width > 0 && height > 0 && width <= screenWidth && height <= screenHeight) this.setSize(width, height); } int x = 0; int y = 0; if(xString != null && yString != null) { x = new Integer(xString).intValue(); y = new Integer(yString).intValue(); if (x >= 0 && y >= 0) this.setLocation(x, y); else this.setCenterLocation(); } else { this.setCenterLocation(); } }
diff --git a/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java b/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java index 8b2c24941..b22957478 100644 --- a/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java +++ b/src/main/java/org/primefaces/component/behavior/ajax/AjaxBehaviorRenderer.java @@ -1,142 +1,142 @@ /* * Copyright 2010 Prime Technology. * * 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.primefaces.component.behavior.ajax; import javax.faces.FacesException; import javax.faces.component.ActionSource; import javax.faces.component.EditableValueHolder; import javax.faces.component.UIComponent; import javax.faces.component.UIParameter; import javax.faces.component.behavior.ClientBehavior; import javax.faces.component.behavior.ClientBehaviorContext; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.event.PhaseId; import javax.faces.render.ClientBehaviorRenderer; import javax.faces.render.FacesBehaviorRenderer; import org.primefaces.util.ComponentUtils; @FacesBehaviorRenderer(rendererType="org.primefaces.component.AjaxBehaviorRenderer") public class AjaxBehaviorRenderer extends ClientBehaviorRenderer { @Override public void decode(FacesContext context, UIComponent component, ClientBehavior behavior) { AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior; if(!ajaxBehavior.isDisabled()) { AjaxBehaviorEvent event = new AjaxBehaviorEvent(component, behavior); PhaseId phaseId = isImmediate(component, ajaxBehavior) ? PhaseId.APPLY_REQUEST_VALUES : PhaseId.INVOKE_APPLICATION; event.setPhaseId(phaseId); component.queueEvent(event); } } @Override public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) { AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior; FacesContext fc = behaviorContext.getFacesContext(); UIComponent component = behaviorContext.getComponent(); String clientId = component.getClientId(fc); String url = fc.getApplication().getViewHandler().getActionURL(fc, fc.getViewRoot().getViewId()); url = fc.getExternalContext().encodeResourceURL(url); UIComponent form = ComponentUtils.findParentForm(fc, component); if(form == null) { throw new FacesException("AjaxBehavior for : \"" + component.getClientId(fc) + "\" must be inside a form element"); } StringBuilder req = new StringBuilder(); req.append("PrimeFaces.ajax.AjaxRequest("); //url req.append("'").append(url).append("'"); //options req.append(",{formId:'").append(form.getClientId(fc)).append("'"); req.append(",async:").append(ajaxBehavior.isAsync()); req.append(",global:").append(ajaxBehavior.isGlobal()); //source - req.append(",source:'").append(clientId).append("'"); + req.append(",source:this"); //process String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId; req.append(",process:'").append(process).append("'"); //update if (ajaxBehavior.getUpdate() != null) { req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'"); } //behavior event req.append(",event:'").append(behaviorContext.getEventName()).append("'"); //callbacks if (ajaxBehavior.getOnstart() != null) req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}"); if (ajaxBehavior.getOnerror() != null) req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}"); if (ajaxBehavior.getOnsuccess() != null) req.append(",onsuccess:function(data, status, xhr, args){").append(ajaxBehavior.getOnsuccess()).append(";}"); if (ajaxBehavior.getOncomplete() != null) req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}"); req.append("}"); //params boolean firstParam = true, hasParam = false; for (UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { UIParameter parameter = (UIParameter) child; hasParam = true; if (firstParam) { firstParam = false; req.append(",{"); } else { req.append(","); } req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'"); } if (hasParam) req.append("}"); } req.append(");"); return req.toString(); } private boolean isImmediate(UIComponent component, AjaxBehavior ajaxBehavior) { boolean immediate = false; if (ajaxBehavior.isImmediateSet()) { immediate = ajaxBehavior.isImmediate(); } else if (component instanceof EditableValueHolder) { immediate = ((EditableValueHolder)component).isImmediate(); } else if (component instanceof ActionSource) { immediate = ((ActionSource)component).isImmediate(); } return immediate; } }
true
true
public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) { AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior; FacesContext fc = behaviorContext.getFacesContext(); UIComponent component = behaviorContext.getComponent(); String clientId = component.getClientId(fc); String url = fc.getApplication().getViewHandler().getActionURL(fc, fc.getViewRoot().getViewId()); url = fc.getExternalContext().encodeResourceURL(url); UIComponent form = ComponentUtils.findParentForm(fc, component); if(form == null) { throw new FacesException("AjaxBehavior for : \"" + component.getClientId(fc) + "\" must be inside a form element"); } StringBuilder req = new StringBuilder(); req.append("PrimeFaces.ajax.AjaxRequest("); //url req.append("'").append(url).append("'"); //options req.append(",{formId:'").append(form.getClientId(fc)).append("'"); req.append(",async:").append(ajaxBehavior.isAsync()); req.append(",global:").append(ajaxBehavior.isGlobal()); //source req.append(",source:'").append(clientId).append("'"); //process String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId; req.append(",process:'").append(process).append("'"); //update if (ajaxBehavior.getUpdate() != null) { req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'"); } //behavior event req.append(",event:'").append(behaviorContext.getEventName()).append("'"); //callbacks if (ajaxBehavior.getOnstart() != null) req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}"); if (ajaxBehavior.getOnerror() != null) req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}"); if (ajaxBehavior.getOnsuccess() != null) req.append(",onsuccess:function(data, status, xhr, args){").append(ajaxBehavior.getOnsuccess()).append(";}"); if (ajaxBehavior.getOncomplete() != null) req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}"); req.append("}"); //params boolean firstParam = true, hasParam = false; for (UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { UIParameter parameter = (UIParameter) child; hasParam = true; if (firstParam) { firstParam = false; req.append(",{"); } else { req.append(","); } req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'"); } if (hasParam) req.append("}"); } req.append(");"); return req.toString(); }
public String getScript(ClientBehaviorContext behaviorContext, ClientBehavior behavior) { AjaxBehavior ajaxBehavior = (AjaxBehavior) behavior; FacesContext fc = behaviorContext.getFacesContext(); UIComponent component = behaviorContext.getComponent(); String clientId = component.getClientId(fc); String url = fc.getApplication().getViewHandler().getActionURL(fc, fc.getViewRoot().getViewId()); url = fc.getExternalContext().encodeResourceURL(url); UIComponent form = ComponentUtils.findParentForm(fc, component); if(form == null) { throw new FacesException("AjaxBehavior for : \"" + component.getClientId(fc) + "\" must be inside a form element"); } StringBuilder req = new StringBuilder(); req.append("PrimeFaces.ajax.AjaxRequest("); //url req.append("'").append(url).append("'"); //options req.append(",{formId:'").append(form.getClientId(fc)).append("'"); req.append(",async:").append(ajaxBehavior.isAsync()); req.append(",global:").append(ajaxBehavior.isGlobal()); //source req.append(",source:this"); //process String process = ajaxBehavior.getProcess() != null ? ComponentUtils.findClientIds(fc, component, ajaxBehavior.getProcess()) : clientId; req.append(",process:'").append(process).append("'"); //update if (ajaxBehavior.getUpdate() != null) { req.append(",update:'").append(ComponentUtils.findClientIds(fc, component, ajaxBehavior.getUpdate())).append("'"); } //behavior event req.append(",event:'").append(behaviorContext.getEventName()).append("'"); //callbacks if (ajaxBehavior.getOnstart() != null) req.append(",onstart:function(xhr){").append(ajaxBehavior.getOnstart()).append(";}"); if (ajaxBehavior.getOnerror() != null) req.append(",onerror:function(xhr, status, error){").append(ajaxBehavior.getOnerror()).append(";}"); if (ajaxBehavior.getOnsuccess() != null) req.append(",onsuccess:function(data, status, xhr, args){").append(ajaxBehavior.getOnsuccess()).append(";}"); if (ajaxBehavior.getOncomplete() != null) req.append(",oncomplete:function(xhr, status, args){").append(ajaxBehavior.getOncomplete()).append(";}"); req.append("}"); //params boolean firstParam = true, hasParam = false; for (UIComponent child : component.getChildren()) { if (child instanceof UIParameter) { UIParameter parameter = (UIParameter) child; hasParam = true; if (firstParam) { firstParam = false; req.append(",{"); } else { req.append(","); } req.append("'").append(parameter.getName()).append("':'").append(parameter.getValue()).append("'"); } if (hasParam) req.append("}"); } req.append(");"); return req.toString(); }
diff --git a/src/de/danoeh/antennapod/feed/FeedItem.java b/src/de/danoeh/antennapod/feed/FeedItem.java index a80460ec..9b9375f2 100644 --- a/src/de/danoeh/antennapod/feed/FeedItem.java +++ b/src/de/danoeh/antennapod/feed/FeedItem.java @@ -1,308 +1,308 @@ package de.danoeh.antennapod.feed; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import de.danoeh.antennapod.PodcastApp; import de.danoeh.antennapod.asynctask.ImageLoader; import de.danoeh.antennapod.storage.DBReader; import de.danoeh.antennapod.util.ShownotesProvider; /** * Data Object for a XML message * * @author daniel */ public class FeedItem extends FeedComponent implements ImageLoader.ImageWorkerTaskResource, ShownotesProvider { /** * The id/guid that can be found in the rss/atom feed. Might not be set. */ private String itemIdentifier; private String title; /** * The description of a feeditem. */ private String description; /** * The content of the content-encoded tag of a feeditem. */ private String contentEncoded; private String link; private Date pubDate; private FeedMedia media; private Feed feed; private long feedId; private boolean read; private String paymentLink; private List<Chapter> chapters; public FeedItem() { this.read = true; } /** * This constructor should be used for creating test objects. * */ public FeedItem(long id, String title, String itemIdentifier, String link, Date pubDate, boolean read, Feed feed) { this.id = id; this.title = title; this.itemIdentifier = itemIdentifier; this.link = link; this.pubDate = (pubDate != null) ? (Date) pubDate.clone() : null; this.read = read; this.feed = feed; } public void updateFromOther(FeedItem other) { super.updateFromOther(other); if (other.title != null) { title = other.title; } if (other.getDescription() != null) { description = other.getDescription(); } if (other.getContentEncoded() != null) { contentEncoded = other.contentEncoded; } if (other.link != null) { link = other.link; } if (other.pubDate != null && other.pubDate != pubDate) { pubDate = other.pubDate; } if (other.media != null) { if (media == null) { - media = other.media; + setMedia(other.media); } else if (media.compareWithOther(other)) { media.updateFromOther(other); } } if (other.paymentLink != null) { paymentLink = other.paymentLink; } if (other.chapters != null) { if (chapters == null) { chapters = other.chapters; } } } /** * Returns the value that uniquely identifies this FeedItem. If the * itemIdentifier attribute is not null, it will be returned. Else it will * try to return the title. If the title is not given, it will use the link * of the entry. */ public String getIdentifyingValue() { if (itemIdentifier != null) { return itemIdentifier; } else if (title != null) { return title; } else { return link; } } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public Date getPubDate() { if (pubDate != null) { return (Date) pubDate.clone(); } else { return null; } } public void setPubDate(Date pubDate) { if (pubDate != null) { this.pubDate = (Date) pubDate.clone(); } else { this.pubDate = null; } } public FeedMedia getMedia() { return media; } /** * Sets the media object of this FeedItem. If the given * FeedMedia object is not null, it's 'item'-attribute value * will also be set to this item. * */ public void setMedia(FeedMedia media) { this.media = media; if (media != null && media.getItem() != this) { media.setItem(this); } } public Feed getFeed() { return feed; } public void setFeed(Feed feed) { this.feed = feed; } public boolean isRead() { return read || isInProgress(); } public void setRead(boolean read) { this.read = read; } private boolean isInProgress() { return (media != null && media.isInProgress()); } public String getContentEncoded() { return contentEncoded; } public void setContentEncoded(String contentEncoded) { this.contentEncoded = contentEncoded; } public String getPaymentLink() { return paymentLink; } public void setPaymentLink(String paymentLink) { this.paymentLink = paymentLink; } public List<Chapter> getChapters() { return chapters; } public void setChapters(List<Chapter> chapters) { this.chapters = chapters; } public String getItemIdentifier() { return itemIdentifier; } public void setItemIdentifier(String itemIdentifier) { this.itemIdentifier = itemIdentifier; } public boolean hasMedia() { return media != null; } private boolean isPlaying() { if (media != null) { return media.isPlaying(); } return false; } @Override public Callable<String> loadShownotes() { return new Callable<String>() { @Override public String call() throws Exception { if (contentEncoded == null || description == null) { DBReader.loadExtraInformationOfFeedItem(PodcastApp.getInstance(), FeedItem.this); } return (contentEncoded != null) ? contentEncoded : description; } }; } public enum State { NEW, IN_PROGRESS, READ, PLAYING } public State getState() { if (hasMedia()) { if (isPlaying()) { return State.PLAYING; } if (isInProgress()) { return State.IN_PROGRESS; } } return (isRead() ? State.READ : State.NEW); } @Override public InputStream openImageInputStream() { InputStream out = null; if (hasMedia()) { out = media.openImageInputStream(); } if (out == null && feed.getImage() != null) { out = feed.getImage().openImageInputStream(); } return out; } @Override public InputStream reopenImageInputStream(InputStream input) { InputStream out = null; if (hasMedia()) { out = media.reopenImageInputStream(input); } if (out == null && feed.getImage() != null) { out = feed.getImage().reopenImageInputStream(input); } return out; } @Override public String getImageLoaderCacheKey() { String out = null; if (hasMedia()) { out = media.getImageLoaderCacheKey(); } if (out == null && feed.getImage() != null) { out = feed.getImage().getImageLoaderCacheKey(); } return out; } public long getFeedId() { return feedId; } public void setFeedId(long feedId) { this.feedId = feedId; } }
true
true
public void updateFromOther(FeedItem other) { super.updateFromOther(other); if (other.title != null) { title = other.title; } if (other.getDescription() != null) { description = other.getDescription(); } if (other.getContentEncoded() != null) { contentEncoded = other.contentEncoded; } if (other.link != null) { link = other.link; } if (other.pubDate != null && other.pubDate != pubDate) { pubDate = other.pubDate; } if (other.media != null) { if (media == null) { media = other.media; } else if (media.compareWithOther(other)) { media.updateFromOther(other); } } if (other.paymentLink != null) { paymentLink = other.paymentLink; } if (other.chapters != null) { if (chapters == null) { chapters = other.chapters; } } }
public void updateFromOther(FeedItem other) { super.updateFromOther(other); if (other.title != null) { title = other.title; } if (other.getDescription() != null) { description = other.getDescription(); } if (other.getContentEncoded() != null) { contentEncoded = other.contentEncoded; } if (other.link != null) { link = other.link; } if (other.pubDate != null && other.pubDate != pubDate) { pubDate = other.pubDate; } if (other.media != null) { if (media == null) { setMedia(other.media); } else if (media.compareWithOther(other)) { media.updateFromOther(other); } } if (other.paymentLink != null) { paymentLink = other.paymentLink; } if (other.chapters != null) { if (chapters == null) { chapters = other.chapters; } } }
diff --git a/src/com/nononsenseapps/ui/ListPagerAdapter.java b/src/com/nononsenseapps/ui/ListPagerAdapter.java index 3f8b24f8..dbb4002b 100644 --- a/src/com/nononsenseapps/ui/ListPagerAdapter.java +++ b/src/com/nononsenseapps/ui/ListPagerAdapter.java @@ -1,88 +1,88 @@ /** * */ package com.nononsenseapps.ui; import com.nononsenseapps.notepad.NotePad; import com.nononsenseapps.notepad.NotesListFragment; import com.nononsenseapps.support.app.FragmentPagerAdapter; import com.nononsenseapps.support.app.FragmentStatePagerAdapter; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.database.Cursor; import android.database.DataSetObserver; import android.os.Bundle; /** * Each page in the view pager displays a different list which is handled by a * different cursor adapter * */ public class ListPagerAdapter extends FragmentPagerAdapter { private final ExtrasCursorAdapter wrappedAdapter; private final int countAdjust; private final DataSetObserver subObserver; public ListPagerAdapter(Context context, final FragmentManager fm, final ExtrasCursorAdapter wrappedAdapter, final int countAdjust) { super(context, fm); this.wrappedAdapter = wrappedAdapter; this.countAdjust = countAdjust; subObserver = new DataSetObserver() { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { - notifyDataSetChanged(); + // Probably destroying the loader } }; if (wrappedAdapter != null) wrappedAdapter.registerDataSetObserver(subObserver); } @Override public Fragment getItem(int pos) { long id = wrappedAdapter.getItemId(pos); Bundle arguments = new Bundle(); arguments.putLong(NotesListFragment.LISTID, id); NotesListFragment list = new NotesListFragment(); list.setArguments(arguments); return list; } @Override public long getItemId(int position) { return wrappedAdapter.getItemId(position); } @Override public int getCount() { return wrappedAdapter.getCount() + countAdjust; } @Override public CharSequence getPageTitle(int position) { CharSequence title = null; if (wrappedAdapter != null) { Cursor c = (Cursor) wrappedAdapter.getItem(position); if (c != null && !c.isAfterLast() && !c.isBeforeFirst()) { title = c.getString(c .getColumnIndex(NotePad.Lists.COLUMN_NAME_TITLE)); } else { title = wrappedAdapter.getExtraItem(position); } } return title; } }
true
true
public ListPagerAdapter(Context context, final FragmentManager fm, final ExtrasCursorAdapter wrappedAdapter, final int countAdjust) { super(context, fm); this.wrappedAdapter = wrappedAdapter; this.countAdjust = countAdjust; subObserver = new DataSetObserver() { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetChanged(); } }; if (wrappedAdapter != null) wrappedAdapter.registerDataSetObserver(subObserver); }
public ListPagerAdapter(Context context, final FragmentManager fm, final ExtrasCursorAdapter wrappedAdapter, final int countAdjust) { super(context, fm); this.wrappedAdapter = wrappedAdapter; this.countAdjust = countAdjust; subObserver = new DataSetObserver() { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { // Probably destroying the loader } }; if (wrappedAdapter != null) wrappedAdapter.registerDataSetObserver(subObserver); }
diff --git a/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java b/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java index 853a7ca19..3b6364f57 100644 --- a/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java +++ b/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java @@ -1,595 +1,597 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.gui.panel; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Point; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragGestureRecognizer; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceContext; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.TransferHandler; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.UnitState; /** * The transferhandler that is capable of creating ImageSelection objects. * Those ImageSelection objects are Transferable. The DefaultTransferHandler * should be attached to JPanels or custom JLabels. */ public final class DefaultTransferHandler extends TransferHandler { private static Logger logger = Logger.getLogger(DefaultTransferHandler.class.getName()); public static final DataFlavor flavor = new DataFlavor(ImageSelection.class, "ImageSelection"); private final Canvas canvas; private final FreeColPanel parentPanel; /** * The constructor to use. * @param canvas The <code>Canvas</code>. * @param parentPanel The layered pane that holds all kinds of information. */ public DefaultTransferHandler(Canvas canvas, FreeColPanel parentPanel) { this.canvas = canvas; this.parentPanel = parentPanel; } /** * Returns the action that can be done to an ImageSelection on the given component. * @return The action that can be done to an ImageSelection on the given component. */ public int getSourceActions(JComponent comp) { return COPY_OR_MOVE; } /** * Returns 'true' if the given component can import a selection of the * flavor that is indicated by the second parameter, 'false' otherwise. * @param comp The component that needs to be checked. * @param flavor The flavor that needs to be checked for. * @return 'true' if the given component can import a selection of the * flavor that is indicated by the second parameter, 'false' otherwise. */ public boolean canImport(JComponent comp, DataFlavor[] flavor) { if (!(comp instanceof UnitLabel) && !(comp instanceof GoodsLabel) && !(comp instanceof MarketLabel) && !(comp instanceof JPanel) && !(comp instanceof JLabel)) { return false; } for (int i = 0; i < flavor.length; i++) { if (flavor[i].equals(DefaultTransferHandler.flavor)) { return true; } } return false; } /** * Creates a Transferable (an ImageSelection to be precise) of the * data that is represented by the given component and returns that * object. * @param comp The component to create a Transferable of. * @return The resulting Transferable (an ImageSelection object). */ public Transferable createTransferable(JComponent comp) { if (comp instanceof UnitLabel) { return new ImageSelection((UnitLabel)comp); } else if (comp instanceof GoodsLabel) { return new ImageSelection((GoodsLabel)comp); } else if (comp instanceof MarketLabel) { return new ImageSelection((MarketLabel)comp); } return null; } /** * Imports the data represented by the given Transferable into * the given component. Returns 'true' on success, 'false' otherwise. * @param comp The component to import the data to. * @param t The Transferable that holds the data. * @return 'true' on success, 'false' otherwise. */ public boolean importData(JComponent comp, Transferable t) { try { JLabel data; /* This variable is used to temporarily keep the old selected unit, while moving cargo from one carrier to another: */ UnitLabel oldSelectedUnit = null; // Check flavor. if (t.isDataFlavorSupported(DefaultTransferHandler.flavor)) { data = (JLabel)t.getTransferData(DefaultTransferHandler.flavor); } else { logger.warning("Data flavor is not supported!"); return false; } // Do not allow a transferable to be dropped upon itself: if (comp == data) { return false; } // Make sure we don't drop onto other Labels. if (comp instanceof UnitLabel) { /* If the unit/cargo is dropped on a carrier in port (EuropePanel.InPortPanel), then the ship is selected and the unit is added to its cargo. If not, assume that the user wished to drop the unit/cargo on the panel below. */ if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof EuropePanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((EuropePanel) parentPanel).getSelectedUnitLabel(); } ((EuropePanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((EuropePanel) parentPanel).getCargoPanel(); } else if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof ColonyPanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((ColonyPanel) parentPanel).getSelectedUnitLabel(); } ((ColonyPanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((ColonyPanel) parentPanel).getCargoPanel(); } else { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } // This is because we use an extra panel for layout in this particular case; may find a better solution later. try { if ((JComponent)comp.getParent() instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { comp = (JComponent)comp.getParent(); } } catch (ClassCastException e) {} } } else if ((comp instanceof GoodsLabel) || (comp instanceof MarketLabel)) { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } } // t is already in comp: if (data.getParent() == comp) { return false; } if (data instanceof UnitLabel) { // Check if the unit can be dragged to comp. Unit unit = ((UnitLabel)data).getUnit(); if (unit.isUnderRepair()) { return false; } if ((unit.getState() == UnitState.TO_AMERICA) && (!(comp instanceof EuropePanel.ToEuropePanel))) { return false; } if ((unit.getState() == UnitState.TO_EUROPE) && (!(comp instanceof EuropePanel.ToAmericaPanel))) { return false; } if ((unit.getState() != UnitState.TO_AMERICA) && ((comp instanceof EuropePanel.ToEuropePanel))) { return false; } if (!unit.isNaval() && (comp instanceof EuropePanel.InPortPanel || comp instanceof ColonyPanel.InPortPanel || comp instanceof EuropePanel.ToEuropePanel || comp instanceof EuropePanel.ToAmericaPanel)) { return false; } if (comp instanceof EuropePanel.MarketPanel || comp instanceof ColonyPanel.WarehousePanel) { return false; } if (unit.isNaval() && (comp instanceof EuropePanel.DocksPanel || comp instanceof ColonyPanel.OutsideColonyPanel || comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel || comp instanceof ColonyPanel.TilePanel.ASingleTilePanel || comp instanceof CargoPanel)) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Do this in the 'add'-methods instead: //data.getParent().remove(data); if (comp instanceof EuropePanel.ToEuropePanel) { ((EuropePanel.ToEuropePanel)comp).add(data, true); } else if (comp instanceof EuropePanel.ToAmericaPanel) { ((EuropePanel.ToAmericaPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.DocksPanel) { ((EuropePanel.DocksPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { ((ColonyPanel.BuildingsPanel.ASingleBuildingPanel) comp).add(data, true); } else if (comp instanceof ColonyPanel.OutsideColonyPanel) { ((ColonyPanel.OutsideColonyPanel) comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.TilePanel.ASingleTilePanel) { ((ColonyPanel.TilePanel.ASingleTilePanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if ((oldSelectedUnit).getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof GoodsLabel) { // Check if the unit can be dragged to comp. GoodsLabel label = ((GoodsLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getGoods().getType(), label.getGoods().getAmount(), false); if (amount == -1) { return false; } label.getGoods().setAmount(amount); + } else if (label.getGoods().getAmount() > 100) { + label.getGoods().setAmount(100); } if (!(comp instanceof ColonyPanel.WarehousePanel || comp instanceof CargoPanel || comp instanceof EuropePanel.MarketPanel) || (comp instanceof CargoPanel && !((CargoPanel) comp).isActive())) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { //data.getParent().remove(data); if (comp instanceof ColonyPanel.WarehousePanel) { ((ColonyPanel.WarehousePanel)comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.MarketPanel) { ((EuropePanel.MarketPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if (oldSelectedUnit.getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof MarketLabel) { // Check if the unit can be dragged to comp. MarketLabel label = ((MarketLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getType(), label.getAmount(), true); if (amount == -1) { return false; } label.setAmount(amount); } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Be not removing MarketLabels from their home. -sjm //data.getParent().remove(data); if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); return true; } } logger.warning("The dragged component is of an invalid type."); } catch (Exception e) { // TODO: Suggest a reconnect. StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); } return false; } /** * Displays an input dialog box where the user should specify a goods transfer amount. */ private int getAmount(GoodsType goodsType, int available, boolean needToPay) { return canvas.showSelectAmountDialog(goodsType, available, needToPay); } /*__________________________________________________ Methods/inner-classes below have been copied from TransferHandler in order to allow partial loading. -------------------------------------------------- */ private static FreeColDragGestureRecognizer recognizer = null; public void exportAsDrag(JComponent comp, InputEvent e, int action) { int srcActions = getSourceActions(comp); int dragAction = srcActions & action; if (!(e instanceof MouseEvent)) { dragAction = NONE; } if (dragAction != NONE && !GraphicsEnvironment.isHeadless()) { if (recognizer == null) { recognizer = new FreeColDragGestureRecognizer(new FreeColDragHandler()); } recognizer.gestured(comp, (MouseEvent) e , srcActions, dragAction); } else { exportDone(comp, null, NONE); } } /** * This is the default drag handler for drag and drop operations that * use the <code>TransferHandler</code>. */ private static class FreeColDragHandler implements DragGestureListener, DragSourceListener { private boolean scrolls; // --- DragGestureListener methods ----------------------------------- /** * A Drag gesture has been recognized. */ public void dragGestureRecognized(DragGestureEvent dge) { JComponent c = (JComponent) dge.getComponent(); DefaultTransferHandler th = (DefaultTransferHandler) c.getTransferHandler(); Transferable t = th.createTransferable(c); if (t != null) { scrolls = c.getAutoscrolls(); c.setAutoscrolls(false); try { if (c instanceof JLabel && ((JLabel) c).getIcon() instanceof ImageIcon) { Toolkit tk = Toolkit.getDefaultToolkit(); ImageIcon imageIcon = ((ImageIcon) ((JLabel) c).getIcon()); Dimension bestSize = tk.getBestCursorSize(imageIcon.getIconWidth(), imageIcon.getIconHeight()); if (bestSize.width == 0 || bestSize.height == 0) { dge.startDrag(null, t, this); return; } Image image; if (bestSize.width > bestSize.height) { bestSize.height = (int) ((((double) bestSize.width) / ((double) imageIcon.getIconWidth())) * imageIcon.getIconHeight()); } else { bestSize.width = (int) ((((double) bestSize.height) / ((double) imageIcon.getIconHeight())) * imageIcon.getIconWidth()); } image = imageIcon.getImage().getScaledInstance(bestSize.width, bestSize.height, Image.SCALE_DEFAULT); /* We have to use a MediaTracker to ensure that the image has been scaled before we use it. */ MediaTracker mt = new MediaTracker(c); mt.addImage(image, 0, bestSize.width, bestSize.height); try { mt.waitForID(0); } catch (InterruptedException e) { dge.startDrag(null, t, this); return; } Point point = new Point(bestSize.width / 2, bestSize.height / 2); Cursor cursor; try { cursor = tk.createCustomCursor(image, point, "freeColDragIcon"); } catch (RuntimeException re) { cursor = null; } //Point point = new Point(0, 0); dge.startDrag(cursor, t, this); } else { dge.startDrag(null, t, this); } return; } catch (RuntimeException re) { c.setAutoscrolls(scrolls); } } th.exportDone(c, null, NONE); } // --- DragSourceListener methods ----------------------------------- /** * as the hotspot enters a platform dependent drop site. */ public void dragEnter(DragSourceDragEvent dsde) { } /** * as the hotspot moves over a platform dependent drop site. */ public void dragOver(DragSourceDragEvent dsde) { } /** * as the hotspot exits a platform dependent drop site. */ public void dragExit(DragSourceEvent dsde) { } /** * as the operation completes. */ public void dragDropEnd(DragSourceDropEvent dsde) { DragSourceContext dsc = dsde.getDragSourceContext(); JComponent c = (JComponent)dsc.getComponent(); if (dsde.getDropSuccess()) { ((DefaultTransferHandler) c.getTransferHandler()).exportDone(c, dsc.getTransferable(), dsde.getDropAction()); } else { ((DefaultTransferHandler) c.getTransferHandler()).exportDone(c, null, NONE); } c.setAutoscrolls(scrolls); } public void dropActionChanged(DragSourceDragEvent dsde) { DragSourceContext dsc = dsde.getDragSourceContext(); JComponent comp = (JComponent)dsc.getComponent(); updatePartialChosen(comp, dsde.getUserAction() == MOVE); } private void updatePartialChosen(JComponent comp, boolean partialChosen) { if (comp instanceof GoodsLabel) { ((GoodsLabel) comp).setPartialChosen(partialChosen); } else if (comp instanceof MarketLabel) { ((MarketLabel) comp).setPartialChosen(partialChosen); } } } private static class FreeColDragGestureRecognizer extends DragGestureRecognizer { FreeColDragGestureRecognizer(DragGestureListener dgl) { super(DragSource.getDefaultDragSource(), null, NONE, dgl); } void gestured(JComponent c, MouseEvent e, int srcActions, int action) { setComponent(c); setSourceActions(srcActions); appendEvent(e); fireDragGestureRecognized(action, e.getPoint()); } /** * register this DragGestureRecognizer's Listeners with the Component. */ protected void registerListeners() { } /** * unregister this DragGestureRecognizer's Listeners with the Component. * * subclasses must override this method */ protected void unregisterListeners() { } } }
true
true
public boolean importData(JComponent comp, Transferable t) { try { JLabel data; /* This variable is used to temporarily keep the old selected unit, while moving cargo from one carrier to another: */ UnitLabel oldSelectedUnit = null; // Check flavor. if (t.isDataFlavorSupported(DefaultTransferHandler.flavor)) { data = (JLabel)t.getTransferData(DefaultTransferHandler.flavor); } else { logger.warning("Data flavor is not supported!"); return false; } // Do not allow a transferable to be dropped upon itself: if (comp == data) { return false; } // Make sure we don't drop onto other Labels. if (comp instanceof UnitLabel) { /* If the unit/cargo is dropped on a carrier in port (EuropePanel.InPortPanel), then the ship is selected and the unit is added to its cargo. If not, assume that the user wished to drop the unit/cargo on the panel below. */ if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof EuropePanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((EuropePanel) parentPanel).getSelectedUnitLabel(); } ((EuropePanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((EuropePanel) parentPanel).getCargoPanel(); } else if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof ColonyPanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((ColonyPanel) parentPanel).getSelectedUnitLabel(); } ((ColonyPanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((ColonyPanel) parentPanel).getCargoPanel(); } else { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } // This is because we use an extra panel for layout in this particular case; may find a better solution later. try { if ((JComponent)comp.getParent() instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { comp = (JComponent)comp.getParent(); } } catch (ClassCastException e) {} } } else if ((comp instanceof GoodsLabel) || (comp instanceof MarketLabel)) { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } } // t is already in comp: if (data.getParent() == comp) { return false; } if (data instanceof UnitLabel) { // Check if the unit can be dragged to comp. Unit unit = ((UnitLabel)data).getUnit(); if (unit.isUnderRepair()) { return false; } if ((unit.getState() == UnitState.TO_AMERICA) && (!(comp instanceof EuropePanel.ToEuropePanel))) { return false; } if ((unit.getState() == UnitState.TO_EUROPE) && (!(comp instanceof EuropePanel.ToAmericaPanel))) { return false; } if ((unit.getState() != UnitState.TO_AMERICA) && ((comp instanceof EuropePanel.ToEuropePanel))) { return false; } if (!unit.isNaval() && (comp instanceof EuropePanel.InPortPanel || comp instanceof ColonyPanel.InPortPanel || comp instanceof EuropePanel.ToEuropePanel || comp instanceof EuropePanel.ToAmericaPanel)) { return false; } if (comp instanceof EuropePanel.MarketPanel || comp instanceof ColonyPanel.WarehousePanel) { return false; } if (unit.isNaval() && (comp instanceof EuropePanel.DocksPanel || comp instanceof ColonyPanel.OutsideColonyPanel || comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel || comp instanceof ColonyPanel.TilePanel.ASingleTilePanel || comp instanceof CargoPanel)) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Do this in the 'add'-methods instead: //data.getParent().remove(data); if (comp instanceof EuropePanel.ToEuropePanel) { ((EuropePanel.ToEuropePanel)comp).add(data, true); } else if (comp instanceof EuropePanel.ToAmericaPanel) { ((EuropePanel.ToAmericaPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.DocksPanel) { ((EuropePanel.DocksPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { ((ColonyPanel.BuildingsPanel.ASingleBuildingPanel) comp).add(data, true); } else if (comp instanceof ColonyPanel.OutsideColonyPanel) { ((ColonyPanel.OutsideColonyPanel) comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.TilePanel.ASingleTilePanel) { ((ColonyPanel.TilePanel.ASingleTilePanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if ((oldSelectedUnit).getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof GoodsLabel) { // Check if the unit can be dragged to comp. GoodsLabel label = ((GoodsLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getGoods().getType(), label.getGoods().getAmount(), false); if (amount == -1) { return false; } label.getGoods().setAmount(amount); } if (!(comp instanceof ColonyPanel.WarehousePanel || comp instanceof CargoPanel || comp instanceof EuropePanel.MarketPanel) || (comp instanceof CargoPanel && !((CargoPanel) comp).isActive())) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { //data.getParent().remove(data); if (comp instanceof ColonyPanel.WarehousePanel) { ((ColonyPanel.WarehousePanel)comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.MarketPanel) { ((EuropePanel.MarketPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if (oldSelectedUnit.getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof MarketLabel) { // Check if the unit can be dragged to comp. MarketLabel label = ((MarketLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getType(), label.getAmount(), true); if (amount == -1) { return false; } label.setAmount(amount); } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Be not removing MarketLabels from their home. -sjm //data.getParent().remove(data); if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); return true; } } logger.warning("The dragged component is of an invalid type."); } catch (Exception e) { // TODO: Suggest a reconnect. StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); } return false; }
public boolean importData(JComponent comp, Transferable t) { try { JLabel data; /* This variable is used to temporarily keep the old selected unit, while moving cargo from one carrier to another: */ UnitLabel oldSelectedUnit = null; // Check flavor. if (t.isDataFlavorSupported(DefaultTransferHandler.flavor)) { data = (JLabel)t.getTransferData(DefaultTransferHandler.flavor); } else { logger.warning("Data flavor is not supported!"); return false; } // Do not allow a transferable to be dropped upon itself: if (comp == data) { return false; } // Make sure we don't drop onto other Labels. if (comp instanceof UnitLabel) { /* If the unit/cargo is dropped on a carrier in port (EuropePanel.InPortPanel), then the ship is selected and the unit is added to its cargo. If not, assume that the user wished to drop the unit/cargo on the panel below. */ if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof EuropePanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((EuropePanel) parentPanel).getSelectedUnitLabel(); } ((EuropePanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((EuropePanel) parentPanel).getCargoPanel(); } else if (((UnitLabel) comp).getUnit().isCarrier() && ((UnitLabel) comp).getParent() instanceof ColonyPanel.InPortPanel) { if (data instanceof UnitLabel && ((UnitLabel) data).getUnit().getLocation() instanceof Unit || data instanceof GoodsLabel && ((GoodsLabel) data).getGoods().getLocation() instanceof Unit) { oldSelectedUnit = ((ColonyPanel) parentPanel).getSelectedUnitLabel(); } ((ColonyPanel) parentPanel).setSelectedUnitLabel((UnitLabel) comp); comp = ((ColonyPanel) parentPanel).getCargoPanel(); } else { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } // This is because we use an extra panel for layout in this particular case; may find a better solution later. try { if ((JComponent)comp.getParent() instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { comp = (JComponent)comp.getParent(); } } catch (ClassCastException e) {} } } else if ((comp instanceof GoodsLabel) || (comp instanceof MarketLabel)) { try { comp = (JComponent)comp.getParent(); } catch (ClassCastException e) { return false; } } // t is already in comp: if (data.getParent() == comp) { return false; } if (data instanceof UnitLabel) { // Check if the unit can be dragged to comp. Unit unit = ((UnitLabel)data).getUnit(); if (unit.isUnderRepair()) { return false; } if ((unit.getState() == UnitState.TO_AMERICA) && (!(comp instanceof EuropePanel.ToEuropePanel))) { return false; } if ((unit.getState() == UnitState.TO_EUROPE) && (!(comp instanceof EuropePanel.ToAmericaPanel))) { return false; } if ((unit.getState() != UnitState.TO_AMERICA) && ((comp instanceof EuropePanel.ToEuropePanel))) { return false; } if (!unit.isNaval() && (comp instanceof EuropePanel.InPortPanel || comp instanceof ColonyPanel.InPortPanel || comp instanceof EuropePanel.ToEuropePanel || comp instanceof EuropePanel.ToAmericaPanel)) { return false; } if (comp instanceof EuropePanel.MarketPanel || comp instanceof ColonyPanel.WarehousePanel) { return false; } if (unit.isNaval() && (comp instanceof EuropePanel.DocksPanel || comp instanceof ColonyPanel.OutsideColonyPanel || comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel || comp instanceof ColonyPanel.TilePanel.ASingleTilePanel || comp instanceof CargoPanel)) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Do this in the 'add'-methods instead: //data.getParent().remove(data); if (comp instanceof EuropePanel.ToEuropePanel) { ((EuropePanel.ToEuropePanel)comp).add(data, true); } else if (comp instanceof EuropePanel.ToAmericaPanel) { ((EuropePanel.ToAmericaPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.DocksPanel) { ((EuropePanel.DocksPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.BuildingsPanel.ASingleBuildingPanel) { ((ColonyPanel.BuildingsPanel.ASingleBuildingPanel) comp).add(data, true); } else if (comp instanceof ColonyPanel.OutsideColonyPanel) { ((ColonyPanel.OutsideColonyPanel) comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof ColonyPanel.TilePanel.ASingleTilePanel) { ((ColonyPanel.TilePanel.ASingleTilePanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if ((oldSelectedUnit).getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof GoodsLabel) { // Check if the unit can be dragged to comp. GoodsLabel label = ((GoodsLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getGoods().getType(), label.getGoods().getAmount(), false); if (amount == -1) { return false; } label.getGoods().setAmount(amount); } else if (label.getGoods().getAmount() > 100) { label.getGoods().setAmount(100); } if (!(comp instanceof ColonyPanel.WarehousePanel || comp instanceof CargoPanel || comp instanceof EuropePanel.MarketPanel) || (comp instanceof CargoPanel && !((CargoPanel) comp).isActive())) { return false; } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { //data.getParent().remove(data); if (comp instanceof ColonyPanel.WarehousePanel) { ((ColonyPanel.WarehousePanel)comp).add(data, true); } else if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else if (comp instanceof EuropePanel.MarketPanel) { ((EuropePanel.MarketPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); if (oldSelectedUnit != null) { if (oldSelectedUnit.getParent() instanceof EuropePanel.InPortPanel) { ((EuropePanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } else { ((ColonyPanel) parentPanel).setSelectedUnit(oldSelectedUnit.getUnit()); } } return true; } } else if (data instanceof MarketLabel) { // Check if the unit can be dragged to comp. MarketLabel label = ((MarketLabel)data); // Import the data. if (label.isPartialChosen()) { int amount = getAmount(label.getType(), label.getAmount(), true); if (amount == -1) { return false; } label.setAmount(amount); } if (comp instanceof JLabel) { logger.warning("Oops, I thought we didn't have to write this part."); return true; } else if (comp instanceof JPanel) { // Be not removing MarketLabels from their home. -sjm //data.getParent().remove(data); if (comp instanceof CargoPanel) { ((CargoPanel)comp).add(data, true); } else { logger.warning("The receiving component is of an invalid type."); return false; } comp.revalidate(); return true; } } logger.warning("The dragged component is of an invalid type."); } catch (Exception e) { // TODO: Suggest a reconnect. StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); logger.warning(sw.toString()); } return false; }
diff --git a/src/com/example/diceindark/DiceRender.java b/src/com/example/diceindark/DiceRender.java index 1505b2a..17201eb 100644 --- a/src/com/example/diceindark/DiceRender.java +++ b/src/com/example/diceindark/DiceRender.java @@ -1,101 +1,105 @@ package com.example.diceindark; import java.util.Random; import javax.microedition.khronos.opengles.GL10; import android.util.Log; import com.example.framework.gl.Animation; import com.example.framework.gl.Camera2D; import com.example.framework.gl.SpriteBatcher; import com.example.framework.gl.TextureRegion; import com.example.framework.impl.GLGraphics; public class DiceRender { static final float FRUSTUM_WIDTH = 10; static final float FRUSTUM_HEIGHT = 15; GLGraphics glGraphics; DiceScreen dice; Camera2D cam; SpriteBatcher batcher; int direction=0; public DiceRender(GLGraphics glGraphics, SpriteBatcher batcher, DiceScreen dice){ this.glGraphics= glGraphics; this.dice=dice; this.cam= new Camera2D(glGraphics, FRUSTUM_WIDTH, FRUSTUM_HEIGHT); this.batcher=batcher; } public void render(){ cam.setViewportAndMatrices(); renderDice(); } public void renderDice() { TextureRegion keyFrame; GL10 gl = glGraphics.getGL(); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); batcher.beginBatch(Assets.items); Die die = dice.dice.get(dice.currentDie); + if(die.sides==4){ switch(dice.state){ case DiceScreen.DICE_READY: direction=0; - if(die.hasResult && die.sides==4) + if(die.hasResult) batcher.drawSprite(die.position.x+4, die.position.y+7, FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(die.result-1)); else batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(0)); break; case DiceScreen.DICE_SHAKING: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+FRUSTUM_HEIGHT*die.rand.nextFloat(),FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; default: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; } + } + else + batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(0)); /*switch(dice.currentDie){ case 0: renderD4(); break; case 1: renderD6(); break; default: break; }*/ batcher.endBatch(); gl.glDisable(GL10.GL_BLEND); } private void renderD4(){ switch(dice.state){ case DiceScreen.DICE_READY: Die D4 = dice.dice.get(dice.currentDie); if(D4.hasResult){ batcher.drawSprite(D4.position.x, D4.position.y, FRUSTUM_HEIGHT,FRUSTUM_WIDTH, Assets.D4.get(D4.result-1)); } else batcher.drawSprite(D4.position.x, D4.position.y, Die.DIE_HEIGHT, Die.DIE_WIDTH, Assets.D4.get(0)); } } private void renderD6(){ } }
false
true
public void renderDice() { TextureRegion keyFrame; GL10 gl = glGraphics.getGL(); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); batcher.beginBatch(Assets.items); Die die = dice.dice.get(dice.currentDie); switch(dice.state){ case DiceScreen.DICE_READY: direction=0; if(die.hasResult && die.sides==4) batcher.drawSprite(die.position.x+4, die.position.y+7, FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(die.result-1)); else batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(0)); break; case DiceScreen.DICE_SHAKING: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+FRUSTUM_HEIGHT*die.rand.nextFloat(),FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; default: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; } /*switch(dice.currentDie){ case 0: renderD4(); break; case 1: renderD6(); break; default: break; }*/
public void renderDice() { TextureRegion keyFrame; GL10 gl = glGraphics.getGL(); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); batcher.beginBatch(Assets.items); Die die = dice.dice.get(dice.currentDie); if(die.sides==4){ switch(dice.state){ case DiceScreen.DICE_READY: direction=0; if(die.hasResult) batcher.drawSprite(die.position.x+4, die.position.y+7, FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(die.result-1)); else batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(0)); break; case DiceScreen.DICE_SHAKING: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+FRUSTUM_HEIGHT*die.rand.nextFloat(),FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; default: keyFrame = Assets.D4_anim.getKeyFrames(dice.stateTime, Animation.ANIMATION_LOOPING); batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT,keyFrame); break; } } else batcher.drawSprite(die.position.x+4, die.position.y+7,FRUSTUM_WIDTH, FRUSTUM_HEIGHT, Assets.D4.get(0)); /*switch(dice.currentDie){ case 0: renderD4(); break; case 1: renderD6(); break; default: break; }*/
diff --git a/src/org/acm_team/games/questforadventure/Main.java b/src/org/acm_team/games/questforadventure/Main.java index 7e42dab..a363975 100644 --- a/src/org/acm_team/games/questforadventure/Main.java +++ b/src/org/acm_team/games/questforadventure/Main.java @@ -1,65 +1,67 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.acm_team.games.questforadventure; import java.io.*; import java.util.*; import javax.swing.JFileChooser; /** * * @author fusion2004 */ public class Main { public void update() { } /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // init BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Command c = new Command(); //FileDialog fail = new FileDialog(null); // welcome player System.out.println("* Welcome to the QuestForAdventure Engine"); System.out.println("* Created by fusion2004 and acm-team"); System.out.println("* QFA-E v0.01 Alpha"); System.out.println(""); Command c = new Command(); /* * MAIN CONTROL LOOP */ while(true) { // THE MAGIC + System.out.println("Whoops, it seems that the magic smoke has been let out of the loop!"); + break; } // IT HAPPENS UP THERE ^ /* System.out.print("> "); String lol = br.readLine(); System.out.println("out: "+lol); // load game //JFileChooser fc = new JFileChooser(); //fc.showOpenDialog(fc); System.out.println("* Loading game.xml ..."); // init game //out.add(" . . . A new adventurer approaches the town of Quel'sara . . ."); //out.add("As the player comes near, a town greeter appears from somewhere just out of sight and waves the player over."); //out.add("\"Welcome to the town of Quel'sara, friend! ... I'm sorry, I seem to be getting a bit old for this; be you a lad or a lass?\""); */ } }
true
true
public static void main(String[] args) throws IOException { // init BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Command c = new Command(); //FileDialog fail = new FileDialog(null); // welcome player System.out.println("* Welcome to the QuestForAdventure Engine"); System.out.println("* Created by fusion2004 and acm-team"); System.out.println("* QFA-E v0.01 Alpha"); System.out.println(""); Command c = new Command(); /* * MAIN CONTROL LOOP */ while(true) { // THE MAGIC } // IT HAPPENS UP THERE ^ /* System.out.print("> "); String lol = br.readLine(); System.out.println("out: "+lol); // load game //JFileChooser fc = new JFileChooser(); //fc.showOpenDialog(fc); System.out.println("* Loading game.xml ..."); // init game //out.add(" . . . A new adventurer approaches the town of Quel'sara . . ."); //out.add("As the player comes near, a town greeter appears from somewhere just out of sight and waves the player over."); //out.add("\"Welcome to the town of Quel'sara, friend! ... I'm sorry, I seem to be getting a bit old for this; be you a lad or a lass?\""); */ }
public static void main(String[] args) throws IOException { // init BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Command c = new Command(); //FileDialog fail = new FileDialog(null); // welcome player System.out.println("* Welcome to the QuestForAdventure Engine"); System.out.println("* Created by fusion2004 and acm-team"); System.out.println("* QFA-E v0.01 Alpha"); System.out.println(""); Command c = new Command(); /* * MAIN CONTROL LOOP */ while(true) { // THE MAGIC System.out.println("Whoops, it seems that the magic smoke has been let out of the loop!"); break; } // IT HAPPENS UP THERE ^ /* System.out.print("> "); String lol = br.readLine(); System.out.println("out: "+lol); // load game //JFileChooser fc = new JFileChooser(); //fc.showOpenDialog(fc); System.out.println("* Loading game.xml ..."); // init game //out.add(" . . . A new adventurer approaches the town of Quel'sara . . ."); //out.add("As the player comes near, a town greeter appears from somewhere just out of sight and waves the player over."); //out.add("\"Welcome to the town of Quel'sara, friend! ... I'm sorry, I seem to be getting a bit old for this; be you a lad or a lass?\""); */ }
diff --git a/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGraphML.java b/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGraphML.java index 9f38fcb7e..fff767f67 100644 --- a/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGraphML.java +++ b/ExportPlugin/src/org/gephi/io/exporter/plugin/ExporterGraphML.java @@ -1,732 +1,732 @@ /* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <[email protected]>, Sebastien Heymann <[email protected]> Website : http://www.gephi.org This file is part of Gephi. Gephi is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Gephi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Gephi. If not, see <http://www.gnu.org/licenses/>. */ package org.gephi.io.exporter.plugin; import java.awt.Color; import java.io.Writer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.gephi.data.attributes.api.AttributeColumn; import org.gephi.data.attributes.api.AttributeModel; import org.gephi.data.attributes.api.AttributeOrigin; import org.gephi.data.attributes.type.TimeInterval; import org.gephi.dynamic.DynamicUtilities; import org.gephi.dynamic.api.DynamicModel; import org.gephi.graph.api.Edge; import org.gephi.graph.api.EdgeIterable; import org.gephi.graph.api.Graph; import org.gephi.graph.api.GraphModel; import org.gephi.graph.api.HierarchicalGraph; import org.gephi.graph.api.Node; import org.gephi.graph.api.NodeData; import org.gephi.io.exporter.api.FileType; import org.gephi.io.exporter.spi.GraphExporter; import org.gephi.io.exporter.spi.CharacterExporter; import org.gephi.project.api.Workspace; import org.gephi.utils.longtask.spi.LongTask; import org.gephi.utils.progress.Progress; import org.gephi.utils.progress.ProgressTicket; import org.openide.util.NbBundle; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; /** * * @author Sebastien Heymann * @author Mathieu Bastian */ public class ExporterGraphML implements GraphExporter, CharacterExporter, LongTask { private boolean cancel = false; private ProgressTicket progressTicket; private Workspace workspace; private Writer writer; private boolean exportVisible; private GraphModel graphModel; private AttributeModel attributeModel; //Settings private boolean normalize = false; private boolean exportColors = true; private boolean exportPosition = true; private boolean exportSize = true; private boolean exportAttributes = true; private boolean exportHierarchy = false; //Settings Helper private float minSize; private float maxSize; private float minX; private float maxX; private float minY; private float maxY; private float minZ; private float maxZ; //Dynamic private TimeInterval visibleInterval; public boolean execute() { attributeModel = workspace.getLookup().lookup(AttributeModel.class); graphModel = workspace.getLookup().lookup(GraphModel.class); HierarchicalGraph graph = null; if (exportVisible) { graph = graphModel.getHierarchicalGraphVisible(); } else { graph = graphModel.getHierarchicalGraph(); } DynamicModel dynamicModel = workspace.getLookup().lookup(DynamicModel.class); visibleInterval = dynamicModel != null && exportVisible ? dynamicModel.getVisibleInterval() : new TimeInterval(); try { exportData(createDocument(), graph, attributeModel); } catch (Exception e) { graph.readUnlockAll(); throw new RuntimeException(e); } return !cancel; } public Document createDocument() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); final Document document = documentBuilder.newDocument(); document.setXmlVersion("1.0"); document.setXmlStandalone(true); return document; } private void transform(Document document) throws TransformerConfigurationException, TransformerException { Source source = new DOMSource(document); Result result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } /* public Schema getSchema() { try { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); return sf.newSchema(new URL("http://www.gexf.net/1.1draft/gexf.xsd")); } catch (MalformedURLException ex) { Exceptions.printStackTrace(ex); } catch (SAXException ex) { Exceptions.printStackTrace(ex); } return null; } */ public boolean exportData(Document document, HierarchicalGraph graph, AttributeModel model) throws Exception { Progress.start(progressTicket); graph.readLock(); //Options calculateMinMax(graph); //Calculate progress units count int max; if (graphModel.isHierarchical()) { HierarchicalGraph hgraph = graphModel.getHierarchicalGraph(); max = hgraph.getNodeCount() + hgraph.getEdgeCount(); } else { max = graph.getNodeCount() + graph.getEdgeCount(); } Progress.switchToDeterminate(progressTicket, max); Element root = document.createElementNS("http://graphml.graphdrawing.org/xmlns", "graphml"); document.appendChild(root); createKeys(document, root); Element graphE = createGraph(document, graph); root.appendChild(graphE); graph.readUnlockAll(); if (!cancel) { transform(document); } Progress.finish(progressTicket); return !cancel; } private void createKeys(Document document, Element root) { Element nodeLabelKeyE = document.createElement("key"); nodeLabelKeyE.setAttribute("id", "label"); nodeLabelKeyE.setAttribute("attr.name", "label"); nodeLabelKeyE.setAttribute("attr.type", "string"); nodeLabelKeyE.setAttribute("for", "node"); root.appendChild(nodeLabelKeyE); Element edgeLabelKeyE = document.createElement("key"); edgeLabelKeyE.setAttribute("id", "edgelabel"); edgeLabelKeyE.setAttribute("attr.name", "Edge Label"); edgeLabelKeyE.setAttribute("attr.type", "string"); edgeLabelKeyE.setAttribute("for", "edge"); root.appendChild(edgeLabelKeyE); Element weightKeyE = document.createElement("key"); weightKeyE.setAttribute("id", "weight"); weightKeyE.setAttribute("attr.name", "weight"); weightKeyE.setAttribute("attr.type", "double"); weightKeyE.setAttribute("for", "edge"); root.appendChild(weightKeyE); Element edgeIdKeyE = document.createElement("key"); edgeIdKeyE.setAttribute("id", "edgeid"); edgeIdKeyE.setAttribute("attr.name", "Edge Id"); edgeIdKeyE.setAttribute("attr.type", "string"); edgeIdKeyE.setAttribute("for", "edge"); root.appendChild(edgeIdKeyE); if (exportColors) { Element colorRKeyE = document.createElement("key"); colorRKeyE.setAttribute("id", "r"); colorRKeyE.setAttribute("attr.name", "r"); - colorRKeyE.setAttribute("attr.type", "integer"); + colorRKeyE.setAttribute("attr.type", "int"); colorRKeyE.setAttribute("for", "node"); root.appendChild(colorRKeyE); Element colorGKeyE = document.createElement("key"); colorGKeyE.setAttribute("id", "g"); colorGKeyE.setAttribute("attr.name", "g"); - colorGKeyE.setAttribute("attr.type", "integer"); + colorGKeyE.setAttribute("attr.type", "int"); colorGKeyE.setAttribute("for", "node"); root.appendChild(colorGKeyE); Element colorBKeyE = document.createElement("key"); colorBKeyE.setAttribute("id", "b"); colorBKeyE.setAttribute("attr.name", "b"); - colorBKeyE.setAttribute("attr.type", "integer"); + colorBKeyE.setAttribute("attr.type", "int"); colorBKeyE.setAttribute("for", "node"); root.appendChild(colorBKeyE); } if (exportPosition) { Element positionKeyE = document.createElement("key"); positionKeyE.setAttribute("id", "x"); positionKeyE.setAttribute("attr.name", "x"); positionKeyE.setAttribute("attr.type", "float"); positionKeyE.setAttribute("for", "node"); root.appendChild(positionKeyE); Element positionKey2E = document.createElement("key"); positionKey2E.setAttribute("id", "y"); positionKey2E.setAttribute("attr.name", "y"); positionKey2E.setAttribute("attr.type", "float"); positionKey2E.setAttribute("for", "node"); root.appendChild(positionKey2E); if (minZ != 0f || maxZ != 0f) { Element positionKey3E = document.createElement("key"); positionKey3E.setAttribute("id", "z"); positionKey3E.setAttribute("attr.name", "z"); positionKey3E.setAttribute("attr.type", "float"); positionKey3E.setAttribute("for", "node"); root.appendChild(positionKey3E); } } if (exportSize) { Element sizeKeyE = document.createElement("key"); sizeKeyE.setAttribute("id", "size"); sizeKeyE.setAttribute("attr.name", "size"); sizeKeyE.setAttribute("attr.type", "float"); sizeKeyE.setAttribute("for", "node"); root.appendChild(sizeKeyE); } //Attributes if (attributeModel != null && exportAttributes) { //Node attributes for (AttributeColumn column : attributeModel.getNodeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "node"); root.appendChild(attributeE); } } for (AttributeColumn column : attributeModel.getEdgeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { //Data or computed Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "edge"); root.appendChild(attributeE); } } } } private Element createGraph(Document document, Graph graph) throws Exception { Element graphE = document.createElement("graph"); if (graphModel.isDirected()) { graphE.setAttribute("edgedefault", "directed"); } else { graphE.setAttribute("edgedefault", "undirected"); // defaultValue } //Nodes createNodes(document, graphE, graph, null); //Edges createEdges(document, graphE, graph); return graphE; } private Element createAttribute(Document document, AttributeColumn column) { Element attributeE = document.createElement("key"); attributeE.setAttribute("id", column.getId()); attributeE.setAttribute("attr.name", column.getTitle()); switch (column.getType()) { case INT: attributeE.setAttribute("attr.type", "int"); break; default: attributeE.setAttribute("attr.type", column.getType().getTypeString().toLowerCase()); break; } if (column.getDefaultValue() != null) { Element defaultE = document.createElement("default"); Text defaultTextE = document.createTextNode(column.getDefaultValue().toString()); defaultE.appendChild(defaultTextE); } return attributeE; } private Element createNodeAttvalue(Document document, AttributeColumn column, Node n) throws Exception { int index = column.getIndex(); if (n.getNodeData().getAttributes().getValue(index) != null) { Object val = n.getNodeData().getAttributes().getValue(index); val = DynamicUtilities.getDynamicValue(val, visibleInterval.getLow(), visibleInterval.getHigh()); String value = val.toString(); String id = column.getId(); Element attvalueE = document.createElement("data"); attvalueE.setAttribute("key", id); attvalueE.setTextContent(value); return attvalueE; } return null; } private Element createEdgeAttvalue(Document document, AttributeColumn column, Edge e) throws Exception { int index = column.getIndex(); if (e.getEdgeData().getAttributes().getValue(index) != null) { Object val = e.getEdgeData().getAttributes().getValue(index); val = DynamicUtilities.getDynamicValue(val, visibleInterval.getLow(), visibleInterval.getHigh()); String value = val.toString(); String id = column.getId(); Element attvalueE = document.createElement("data"); attvalueE.setAttribute("key", id); attvalueE.setTextContent(value); return attvalueE; } return null; } private void createNodes(Document document, Element parentE, Graph graph, Node nodeParent) throws Exception { if (nodeParent != null) { Element graphE = document.createElement("graph"); if (graphModel.isDirected()) { graphE.setAttribute("edgedefault", "directed"); } else { graphE.setAttribute("edgedefault", "undirected"); // defaultValue } // we are inside the tree HierarchicalGraph hgraph = graphModel.getHierarchicalGraph(); for (Node n : hgraph.getChildren(nodeParent)) { Element childE = createNode(document, graph, n); graphE.appendChild(childE); } parentE.appendChild(graphE); } else if (exportHierarchy && graphModel.isHierarchical()) { // we are on the top of the tree HierarchicalGraph hgraph = graphModel.getHierarchicalGraph(); for (Node n : hgraph.getTopNodes()) { Element nodeE = createNode(document, hgraph, n); parentE.appendChild(nodeE); } } else { // there is no tree for (Node n : graph.getNodes()) { if (cancel) { break; } Element nodeE = createNode(document, graph, n); parentE.appendChild(nodeE); } } } private Element createNode(Document document, Graph graph, Node n) throws Exception { Element nodeE = document.createElement("node"); nodeE.setAttribute("id", n.getNodeData().getId()); //Label if (n.getNodeData().getLabel() != null && !n.getNodeData().getLabel().isEmpty()) { Element labelE = createNodeLabel(document, n); nodeE.appendChild(labelE); } //Attribute values if (attributeModel != null && exportAttributes) { for (AttributeColumn column : attributeModel.getNodeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { //Data or computed Element attvalueE = createNodeAttvalue(document, column, n); if (attvalueE != null) { nodeE.appendChild(attvalueE); } } } } //Viz if (exportSize) { Element sizeE = createNodeSize(document, n); nodeE.appendChild(sizeE); } if (exportColors) { Element colorE = createNodeColorR(document, n); nodeE.appendChild(colorE); colorE = createNodeColorG(document, n); nodeE.appendChild(colorE); colorE = createNodeColorB(document, n); nodeE.appendChild(colorE); } if (exportPosition) { Element positionXE = createNodePositionX(document, n); nodeE.appendChild(positionXE); Element positionYE = createNodePositionY(document, n); nodeE.appendChild(positionYE); if (minZ != 0f || maxZ != 0f) { Element positionZE = createNodePositionZ(document, n); nodeE.appendChild(positionZE); } } //Hierarchy if (exportHierarchy && graphModel.isHierarchical()) { HierarchicalGraph hgraph = graphModel.getHierarchicalGraph(); int childCount = hgraph.getChildrenCount(n); if (childCount != 0) { createNodes(document, nodeE, graph, n); } } Progress.progress(progressTicket); return nodeE; } private void createEdges(Document document, Element edgesE, Graph graph) throws Exception { EdgeIterable it; HierarchicalGraph hgraph = graphModel.getHierarchicalGraph(); if (exportHierarchy && graphModel.isHierarchical()) { it = hgraph.getEdgesTree(); } else { it = hgraph.getEdgesAndMetaEdges(); } for (Edge e : it.toArray()) { if (cancel) { break; } Element edgeE = createEdge(document, e); edgesE.appendChild(edgeE); } } private Element createEdge(Document document, Edge e) throws Exception { Element edgeE = document.createElement("edge"); edgeE.setAttribute("source", e.getSource().getNodeData().getId()); edgeE.setAttribute("target", e.getTarget().getNodeData().getId()); if (e.getEdgeData().getId() != null && !e.getEdgeData().getId().isEmpty() && !String.valueOf(e.getId()).equals(e.getEdgeData().getId())) { Element idE = createEdgeId(document, e); edgeE.appendChild(idE); } //Label if (e.getEdgeData().getLabel() != null && !e.getEdgeData().getLabel().isEmpty()) { Element labelE = createEdgeLabel(document, e); edgeE.appendChild(labelE); } Element weightE = createEdgeWeight(document, e); edgeE.appendChild(weightE); if (e.isDirected() && !graphModel.isDirected()) { edgeE.setAttribute("type", "directed"); } else if (!e.isDirected() && graphModel.isDirected()) { edgeE.setAttribute("type", "undirected"); } //Attribute values if (attributeModel != null) { for (AttributeColumn column : attributeModel.getEdgeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { //Data or computed Element attvalueE = createEdgeAttvalue(document, column, e); if (attvalueE != null) { edgeE.appendChild(attvalueE); } } } } Progress.progress(progressTicket); return edgeE; } private Element createNodeSize(Document document, Node n) throws Exception { Element sizeE = document.createElement("data"); float size = n.getNodeData().getSize(); if (normalize) { size = (size - minSize) / (maxSize - minSize); } sizeE.setAttribute("key", "size"); sizeE.setTextContent("" + size); return sizeE; } private Element createNodeColorR(Document document, Node n) throws Exception { int r = Math.round(n.getNodeData().r() * 255f); Element colorE = document.createElement("data"); colorE.setAttribute("key", "r"); colorE.setTextContent("" + r); return colorE; } private Element createNodeColorG(Document document, Node n) throws Exception { int g = Math.round(n.getNodeData().g() * 255f); Element colorE = document.createElement("data"); colorE.setAttribute("key", "g"); colorE.setTextContent("" + g); return colorE; } private Element createNodeColorB(Document document, Node n) throws Exception { int b = Math.round(n.getNodeData().b() * 255f); Element colorE = document.createElement("data"); colorE.setAttribute("key", "b"); colorE.setTextContent("" + b); return colorE; } private Element createNodePositionX(Document document, Node n) throws Exception { Element positionXE = document.createElement("data"); float x = n.getNodeData().x(); if (normalize && x != 0.0) { x = (x - minX) / (maxX - minX); } positionXE.setAttribute("key", "x"); positionXE.setTextContent("" + x); return positionXE; } private Element createNodePositionY(Document document, Node n) throws Exception { Element positionYE = document.createElement("data"); float y = n.getNodeData().y(); if (normalize && y != 0.0) { y = (y - minY) / (maxY - minY); } positionYE.setAttribute("key", "y"); positionYE.setTextContent("" + y); return positionYE; } private Element createNodePositionZ(Document document, Node n) throws Exception { Element positionZE = document.createElement("data"); float z = n.getNodeData().z(); if (normalize && z != 0.0) { z = (z - minZ) / (maxZ - minZ); } positionZE.setAttribute("key", "z"); positionZE.setTextContent("" + z); return positionZE; } private Element createNodeLabel(Document document, Node n) throws Exception { Element labelE = document.createElement("data"); labelE.setAttribute("key", "label"); labelE.setTextContent(n.getNodeData().getLabel()); return labelE; } private Element createEdgeId(Document document, Edge e) throws Exception { Element idE = document.createElement("data"); idE.setAttribute("key", "edgeid"); idE.setTextContent(e.getEdgeData().getId()); return idE; } private Element createEdgeWeight(Document document, Edge e) throws Exception { Element weightE = document.createElement("data"); weightE.setAttribute("key", "weight"); weightE.setTextContent(Float.toString(e.getWeight(visibleInterval.getLow(), visibleInterval.getHigh()))); return weightE; } private Element createEdgeLabel(Document document, Edge e) throws Exception { Element labelE = document.createElement("data"); labelE.setAttribute("key", "edgelabel"); labelE.setTextContent(e.getEdgeData().getLabel()); return labelE; } private void calculateMinMax(Graph graph) { minX = Float.POSITIVE_INFINITY; maxX = Float.NEGATIVE_INFINITY; minY = Float.POSITIVE_INFINITY; maxY = Float.NEGATIVE_INFINITY; minZ = Float.POSITIVE_INFINITY; maxZ = Float.NEGATIVE_INFINITY; minSize = Float.POSITIVE_INFINITY; maxSize = Float.NEGATIVE_INFINITY; for (Node node : graph.getNodes()) { NodeData nodeData = node.getNodeData(); minX = Math.min(minX, nodeData.x()); maxX = Math.max(maxX, nodeData.x()); minY = Math.min(minY, nodeData.y()); maxY = Math.max(maxY, nodeData.y()); minZ = Math.min(minZ, nodeData.z()); maxZ = Math.max(maxZ, nodeData.z()); minSize = Math.min(minSize, nodeData.getSize()); maxSize = Math.max(maxSize, nodeData.getSize()); } } public boolean cancel() { cancel = true; return true; } public void setProgressTicket(ProgressTicket progressTicket) { this.progressTicket = progressTicket; } public String getName() { return NbBundle.getMessage(getClass(), "ExporterGraphML_name"); } public FileType[] getFileTypes() { FileType ft = new FileType(".graphml", NbBundle.getMessage(getClass(), "fileType_GraphML_Name")); return new FileType[]{ft}; } public void setExportAttributes(boolean exportAttributes) { this.exportAttributes = exportAttributes; } public void setExportColors(boolean exportColors) { this.exportColors = exportColors; } public void setExportPosition(boolean exportPosition) { this.exportPosition = exportPosition; } public void setExportSize(boolean exportSize) { this.exportSize = exportSize; } public void setNormalize(boolean normalize) { this.normalize = normalize; } public boolean isExportAttributes() { return exportAttributes; } public boolean isExportColors() { return exportColors; } public boolean isExportPosition() { return exportPosition; } public boolean isExportSize() { return exportSize; } public boolean isNormalize() { return normalize; } public boolean isExportVisible() { return exportVisible; } public void setExportVisible(boolean exportVisible) { this.exportVisible = exportVisible; } public void setWriter(Writer writer) { this.writer = writer; } public Workspace getWorkspace() { return workspace; } public void setWorkspace(Workspace workspace) { this.workspace = workspace; } public boolean isExportHierarchy() { return exportHierarchy; } public void setExportHierarchy(boolean exportHierarchy) { this.exportHierarchy = exportHierarchy; } }
false
true
private void createKeys(Document document, Element root) { Element nodeLabelKeyE = document.createElement("key"); nodeLabelKeyE.setAttribute("id", "label"); nodeLabelKeyE.setAttribute("attr.name", "label"); nodeLabelKeyE.setAttribute("attr.type", "string"); nodeLabelKeyE.setAttribute("for", "node"); root.appendChild(nodeLabelKeyE); Element edgeLabelKeyE = document.createElement("key"); edgeLabelKeyE.setAttribute("id", "edgelabel"); edgeLabelKeyE.setAttribute("attr.name", "Edge Label"); edgeLabelKeyE.setAttribute("attr.type", "string"); edgeLabelKeyE.setAttribute("for", "edge"); root.appendChild(edgeLabelKeyE); Element weightKeyE = document.createElement("key"); weightKeyE.setAttribute("id", "weight"); weightKeyE.setAttribute("attr.name", "weight"); weightKeyE.setAttribute("attr.type", "double"); weightKeyE.setAttribute("for", "edge"); root.appendChild(weightKeyE); Element edgeIdKeyE = document.createElement("key"); edgeIdKeyE.setAttribute("id", "edgeid"); edgeIdKeyE.setAttribute("attr.name", "Edge Id"); edgeIdKeyE.setAttribute("attr.type", "string"); edgeIdKeyE.setAttribute("for", "edge"); root.appendChild(edgeIdKeyE); if (exportColors) { Element colorRKeyE = document.createElement("key"); colorRKeyE.setAttribute("id", "r"); colorRKeyE.setAttribute("attr.name", "r"); colorRKeyE.setAttribute("attr.type", "integer"); colorRKeyE.setAttribute("for", "node"); root.appendChild(colorRKeyE); Element colorGKeyE = document.createElement("key"); colorGKeyE.setAttribute("id", "g"); colorGKeyE.setAttribute("attr.name", "g"); colorGKeyE.setAttribute("attr.type", "integer"); colorGKeyE.setAttribute("for", "node"); root.appendChild(colorGKeyE); Element colorBKeyE = document.createElement("key"); colorBKeyE.setAttribute("id", "b"); colorBKeyE.setAttribute("attr.name", "b"); colorBKeyE.setAttribute("attr.type", "integer"); colorBKeyE.setAttribute("for", "node"); root.appendChild(colorBKeyE); } if (exportPosition) { Element positionKeyE = document.createElement("key"); positionKeyE.setAttribute("id", "x"); positionKeyE.setAttribute("attr.name", "x"); positionKeyE.setAttribute("attr.type", "float"); positionKeyE.setAttribute("for", "node"); root.appendChild(positionKeyE); Element positionKey2E = document.createElement("key"); positionKey2E.setAttribute("id", "y"); positionKey2E.setAttribute("attr.name", "y"); positionKey2E.setAttribute("attr.type", "float"); positionKey2E.setAttribute("for", "node"); root.appendChild(positionKey2E); if (minZ != 0f || maxZ != 0f) { Element positionKey3E = document.createElement("key"); positionKey3E.setAttribute("id", "z"); positionKey3E.setAttribute("attr.name", "z"); positionKey3E.setAttribute("attr.type", "float"); positionKey3E.setAttribute("for", "node"); root.appendChild(positionKey3E); } } if (exportSize) { Element sizeKeyE = document.createElement("key"); sizeKeyE.setAttribute("id", "size"); sizeKeyE.setAttribute("attr.name", "size"); sizeKeyE.setAttribute("attr.type", "float"); sizeKeyE.setAttribute("for", "node"); root.appendChild(sizeKeyE); } //Attributes if (attributeModel != null && exportAttributes) { //Node attributes for (AttributeColumn column : attributeModel.getNodeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "node"); root.appendChild(attributeE); } } for (AttributeColumn column : attributeModel.getEdgeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { //Data or computed Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "edge"); root.appendChild(attributeE); } } } }
private void createKeys(Document document, Element root) { Element nodeLabelKeyE = document.createElement("key"); nodeLabelKeyE.setAttribute("id", "label"); nodeLabelKeyE.setAttribute("attr.name", "label"); nodeLabelKeyE.setAttribute("attr.type", "string"); nodeLabelKeyE.setAttribute("for", "node"); root.appendChild(nodeLabelKeyE); Element edgeLabelKeyE = document.createElement("key"); edgeLabelKeyE.setAttribute("id", "edgelabel"); edgeLabelKeyE.setAttribute("attr.name", "Edge Label"); edgeLabelKeyE.setAttribute("attr.type", "string"); edgeLabelKeyE.setAttribute("for", "edge"); root.appendChild(edgeLabelKeyE); Element weightKeyE = document.createElement("key"); weightKeyE.setAttribute("id", "weight"); weightKeyE.setAttribute("attr.name", "weight"); weightKeyE.setAttribute("attr.type", "double"); weightKeyE.setAttribute("for", "edge"); root.appendChild(weightKeyE); Element edgeIdKeyE = document.createElement("key"); edgeIdKeyE.setAttribute("id", "edgeid"); edgeIdKeyE.setAttribute("attr.name", "Edge Id"); edgeIdKeyE.setAttribute("attr.type", "string"); edgeIdKeyE.setAttribute("for", "edge"); root.appendChild(edgeIdKeyE); if (exportColors) { Element colorRKeyE = document.createElement("key"); colorRKeyE.setAttribute("id", "r"); colorRKeyE.setAttribute("attr.name", "r"); colorRKeyE.setAttribute("attr.type", "int"); colorRKeyE.setAttribute("for", "node"); root.appendChild(colorRKeyE); Element colorGKeyE = document.createElement("key"); colorGKeyE.setAttribute("id", "g"); colorGKeyE.setAttribute("attr.name", "g"); colorGKeyE.setAttribute("attr.type", "int"); colorGKeyE.setAttribute("for", "node"); root.appendChild(colorGKeyE); Element colorBKeyE = document.createElement("key"); colorBKeyE.setAttribute("id", "b"); colorBKeyE.setAttribute("attr.name", "b"); colorBKeyE.setAttribute("attr.type", "int"); colorBKeyE.setAttribute("for", "node"); root.appendChild(colorBKeyE); } if (exportPosition) { Element positionKeyE = document.createElement("key"); positionKeyE.setAttribute("id", "x"); positionKeyE.setAttribute("attr.name", "x"); positionKeyE.setAttribute("attr.type", "float"); positionKeyE.setAttribute("for", "node"); root.appendChild(positionKeyE); Element positionKey2E = document.createElement("key"); positionKey2E.setAttribute("id", "y"); positionKey2E.setAttribute("attr.name", "y"); positionKey2E.setAttribute("attr.type", "float"); positionKey2E.setAttribute("for", "node"); root.appendChild(positionKey2E); if (minZ != 0f || maxZ != 0f) { Element positionKey3E = document.createElement("key"); positionKey3E.setAttribute("id", "z"); positionKey3E.setAttribute("attr.name", "z"); positionKey3E.setAttribute("attr.type", "float"); positionKey3E.setAttribute("for", "node"); root.appendChild(positionKey3E); } } if (exportSize) { Element sizeKeyE = document.createElement("key"); sizeKeyE.setAttribute("id", "size"); sizeKeyE.setAttribute("attr.name", "size"); sizeKeyE.setAttribute("attr.type", "float"); sizeKeyE.setAttribute("for", "node"); root.appendChild(sizeKeyE); } //Attributes if (attributeModel != null && exportAttributes) { //Node attributes for (AttributeColumn column : attributeModel.getNodeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "node"); root.appendChild(attributeE); } } for (AttributeColumn column : attributeModel.getEdgeTable().getColumns()) { if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) { //Data or computed Element attributeE = createAttribute(document, column); attributeE.setAttribute("for", "edge"); root.appendChild(attributeE); } } } }
diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java index cbb1fcae0..0c90300cc 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/PersistenceProviderImpl.java @@ -1,351 +1,351 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.openjpa.persistence; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.security.ProtectionDomain; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.LoadState; import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.ProviderUtil; import org.apache.openjpa.conf.BrokerValue; import org.apache.openjpa.conf.OpenJPAConfiguration; import org.apache.openjpa.conf.OpenJPAConfigurationImpl; import org.apache.openjpa.enhance.PCClassFileTransformer; import org.apache.openjpa.enhance.PCEnhancerAgent; import org.apache.openjpa.kernel.Bootstrap; import org.apache.openjpa.kernel.BrokerFactory; import org.apache.openjpa.lib.conf.Configuration; import org.apache.openjpa.lib.conf.ConfigurationProvider; import org.apache.openjpa.lib.conf.Configurations; import org.apache.openjpa.lib.log.Log; import org.apache.openjpa.lib.util.Localizer; import org.apache.openjpa.lib.util.Options; import org.apache.openjpa.meta.MetaDataModes; import org.apache.openjpa.meta.MetaDataRepository; import org.apache.openjpa.persistence.validation.ValidationUtils; import org.apache.openjpa.util.ClassResolver; /** * Bootstrapping class that allows the creation of a stand-alone * {@link EntityManager}. * * @see javax.persistence.Persistence#createEntityManagerFactory(String,Map) * @published */ public class PersistenceProviderImpl implements PersistenceProvider, ProviderUtil { static final String CLASS_TRANSFORMER_OPTIONS = "ClassTransformerOptions"; private static final String EMF_POOL = "EntityManagerFactoryPool"; private static final Localizer _loc = Localizer.forPackage(PersistenceProviderImpl.class); private Log _log; /** * Loads the entity manager specified by <code>name</code>, applying * the properties in <code>m</code> as overrides to the properties defined * in the XML configuration file for <code>name</code>. If <code>name</code> * is <code>null</code>, this method loads the XML in the resource * identified by <code>resource</code>, and uses the first resource found * when doing this lookup, regardless of the name specified in the XML * resource or the name of the jar that the resource is contained in. * This does no pooling of EntityManagersFactories. * @return EntityManagerFactory or null */ public OpenJPAEntityManagerFactory createEntityManagerFactory(String name, String resource, Map m) { PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(resource, name, m); if (cp == null) { return null; } BrokerFactory factory = getBrokerFactory(cp, poolValue, null); OpenJPAConfiguration conf = factory.getConfiguration(); _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); pd.checkPuNameCollisions(_log,name); loadAgent(_log, conf); // TODO - Can this be moved back to BrokerImpl.initialize()? // Create appropriate LifecycleEventManager loadValidator(_log, conf); // We need to wait to preload until after we get back a fully configured/instantiated // BrokerFactory. This is because it is possible that someone has extended OpenJPA // functions and they need to be allowed time to configure themselves before we go off and // start instanting configurable objects (ie:openjpa.MetaDataRepository). Don't catch // any exceptions here because we want to fail-fast. Options o = Configurations.parseProperties(Configurations.getProperties("openjpa.MetaDataRepository")); if(o.getBooleanProperty("Preload")){ conf.getMetaDataRepositoryInstance().preload(); } return JPAFacadeHelper.toEntityManagerFactory(factory); } catch (Exception e) { if (_log != null) { _log.error(_loc.get("create-emf-error", name), e); } /* * * Maintain 1.x behavior of throwing exceptions, even though * JPA2 9.2 - createEMF "must" return null for PU it can't handle. * * JPA 2.0 Specification Section 9.2 states: * "If a provider does not qualify as the provider for the named persistence unit, * it must return null when createEntityManagerFactory is invoked on it." * That specification compliance behavior has happened few lines above on null return. * Throwing runtime exception in the following code is valid (and useful) behavior * because the qualified provider has encountered an unexpected situation. */ throw PersistenceExceptions.toPersistenceException(e); } } private BrokerFactory getBrokerFactory(ConfigurationProvider cp, Object poolValue, ClassLoader loader) { // handle "true" and "false" if (poolValue instanceof String && ("true".equalsIgnoreCase((String) poolValue) || "false".equalsIgnoreCase((String) poolValue))) poolValue = Boolean.valueOf((String) poolValue); if (poolValue != null && !(poolValue instanceof Boolean)) { // we only support boolean settings for this option currently. throw new IllegalArgumentException(poolValue.toString()); } if (poolValue == null || !((Boolean) poolValue).booleanValue()) return Bootstrap.newBrokerFactory(cp, loader); else return Bootstrap.getBrokerFactory(cp, loader); } public OpenJPAEntityManagerFactory createEntityManagerFactory(String name, Map m) { return createEntityManagerFactory(name, null, m); } public OpenJPAEntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map m) { PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(pui, m); if (cp == null) return null; // add enhancer Exception transformerException = null; String ctOpts = (String) Configurations.getProperty(CLASS_TRANSFORMER_OPTIONS, pui.getProperties()); try { pui.addTransformer(new ClassTransformerImpl(cp, ctOpts, pui.getNewTempClassLoader(), newConfigurationImpl())); } catch (Exception e) { // fail gracefully transformerException = e; } // if the BrokerImpl hasn't been specified, switch to the // non-finalizing one, since anything claiming to be a container // should be doing proper resource management. if (!Configurations.containsProperty(BrokerValue.KEY, cp.getProperties())) { cp.addProperty("openjpa." + BrokerValue.KEY, getDefaultBrokerAlias()); } BrokerFactory factory = getBrokerFactory(cp, poolValue, pui.getClassLoader()); if (transformerException != null) { Log log = factory.getConfiguration().getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isTraceEnabled()) { log.warn(_loc.get("transformer-registration-error-ex", pui), transformerException); } else { log.warn(_loc.get("transformer-registration-error", pui)); } } // Create appropriate LifecycleEventManager OpenJPAConfiguration conf = factory.getConfiguration(); _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); loadValidator(_log, conf); // We need to wait to preload until after we get back a fully configured/instantiated // BrokerFactory. This is because it is possible that someone has extended OpenJPA // functions and they need to be allowed time to configure themselves before we go off and // start instanting configurable objects (ie:openjpa.MetaDataRepository). Don't catch // any exceptions here because we want to fail-fast. Options o = Configurations.parseProperties(Configurations.getProperties("openjpa.MetaDataRepository")); if(o.getBooleanProperty("Preload")){ - conf.getAbstractBrokerFactoryInstance().preload(); + conf.getMetaDataRepositoryInstance().preload(); } return JPAFacadeHelper.toEntityManagerFactory(factory); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } } /* * Returns a ProviderUtil for use with entities managed by this * persistence provider. */ public ProviderUtil getProviderUtil() { return this; } /* * Returns a default Broker alias to be used when no openjpa.BrokerImpl * is specified. This method allows PersistenceProvider subclass to * override the default broker alias. */ protected String getDefaultBrokerAlias() { return BrokerValue.NON_FINALIZING_ALIAS; } /* * Return a new instance of Configuration subclass used by entity * enhancement in ClassTransformerImpl. If OpenJPAConfigurationImpl * instance is used, configuration options declared in configuration * sub-class will not be recognized and a warning is posted in the log. */ protected OpenJPAConfiguration newConfigurationImpl() { return new OpenJPAConfigurationImpl(); } /** * Java EE 5 class transformer. */ private static class ClassTransformerImpl implements ClassTransformer { private final ClassFileTransformer _trans; private ClassTransformerImpl(ConfigurationProvider cp, String props, final ClassLoader tmpLoader, OpenJPAConfiguration conf) { cp.setInto(conf); // use the temporary loader for everything conf.setClassResolver(new ClassResolver() { public ClassLoader getClassLoader(Class<?> context, ClassLoader env) { return tmpLoader; } }); conf.setReadOnly(Configuration.INIT_STATE_FREEZING); MetaDataRepository repos = conf.getMetaDataRepositoryInstance(); repos.setResolve(MetaDataModes.MODE_MAPPING, false); _trans = new PCClassFileTransformer(repos, Configurations.parseProperties(props), tmpLoader); } public byte[] transform(ClassLoader cl, String name, Class<?> previousVersion, ProtectionDomain pd, byte[] bytes) throws IllegalClassFormatException { return _trans.transform(cl, name, previousVersion, pd, bytes); } } /** * This private worker method will attempt load the PCEnhancerAgent. */ private void loadAgent(Log log, OpenJPAConfiguration conf) { if (conf.getDynamicEnhancementAgent() == true) { boolean res = PCEnhancerAgent.loadDynamicAgent(log); if(_log.isInfoEnabled() && res == true ){ _log.info(_loc.get("dynamic-agent")); } } } /** * This private worker method will attempt to setup the proper * LifecycleEventManager type based on if the javax.validation APIs are * available and a ValidatorImpl is required by the configuration. * @param log * @param conf * @throws if validation setup failed and was required by the config */ private void loadValidator(Log log, OpenJPAConfiguration conf) { if ((ValidationUtils.setupValidation(conf) == true) && _log.isInfoEnabled()) { _log.info(_loc.get("vlem-creation-info")); } } /** * Determines whether the specified object is loaded. * * @return LoadState.LOADED - if all implicit or explicit EAGER fetch * attributes are loaded * LoadState.NOT_LOADED - if any implicit or explicit EAGER fetch * attribute is not loaded * LoadState.UNKNOWN - if the entity is not managed by this * provider. */ public LoadState isLoaded(Object obj) { return isLoadedWithoutReference(obj, null); } /** * Determines whether the attribute on the specified object is loaded. This * method may access the value of the attribute to determine load state (but * currently does not). * * @return LoadState.LOADED - if the attribute is loaded. * LoadState.NOT_LOADED - if the attribute is not loaded or any * EAGER fetch attributes of the entity are not loaded. * LoadState.UNKNOWN - if the entity is not managed by this * provider or if it does not contain the persistent * attribute. */ public LoadState isLoadedWithReference(Object obj, String attr) { // TODO: Are there be any cases where OpenJPA will need to examine // the contents of a field to determine load state? If so, per JPA // contract, this method permits that sort of access. In the extremely // unlikely case that the the entity is managed by multiple providers, // even if it doesn't trigger loading in OpenJPA, accessing field data // could trigger loading by an alternate provider. return isLoadedWithoutReference(obj, attr); } /** * Determines whether the attribute on the specified object is loaded. This * method does not access the value of the attribute to determine load * state. * * @return LoadState.LOADED - if the attribute is loaded. * LoadState.NOT_LOADED - if the attribute is not loaded or any * EAGER fetch attributes of the entity are not loaded. * LoadState.UNKNOWN - if the entity is not managed by this * provider or if it does not contain the persistent * attribute. */ public LoadState isLoadedWithoutReference(Object obj, String attr) { if (obj == null) { return LoadState.UNKNOWN; } return OpenJPAPersistenceUtil.isLoaded(obj, attr); } }
true
true
public OpenJPAEntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map m) { PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(pui, m); if (cp == null) return null; // add enhancer Exception transformerException = null; String ctOpts = (String) Configurations.getProperty(CLASS_TRANSFORMER_OPTIONS, pui.getProperties()); try { pui.addTransformer(new ClassTransformerImpl(cp, ctOpts, pui.getNewTempClassLoader(), newConfigurationImpl())); } catch (Exception e) { // fail gracefully transformerException = e; } // if the BrokerImpl hasn't been specified, switch to the // non-finalizing one, since anything claiming to be a container // should be doing proper resource management. if (!Configurations.containsProperty(BrokerValue.KEY, cp.getProperties())) { cp.addProperty("openjpa." + BrokerValue.KEY, getDefaultBrokerAlias()); } BrokerFactory factory = getBrokerFactory(cp, poolValue, pui.getClassLoader()); if (transformerException != null) { Log log = factory.getConfiguration().getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isTraceEnabled()) { log.warn(_loc.get("transformer-registration-error-ex", pui), transformerException); } else { log.warn(_loc.get("transformer-registration-error", pui)); } } // Create appropriate LifecycleEventManager OpenJPAConfiguration conf = factory.getConfiguration(); _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); loadValidator(_log, conf); // We need to wait to preload until after we get back a fully configured/instantiated // BrokerFactory. This is because it is possible that someone has extended OpenJPA // functions and they need to be allowed time to configure themselves before we go off and // start instanting configurable objects (ie:openjpa.MetaDataRepository). Don't catch // any exceptions here because we want to fail-fast. Options o = Configurations.parseProperties(Configurations.getProperties("openjpa.MetaDataRepository")); if(o.getBooleanProperty("Preload")){ conf.getAbstractBrokerFactoryInstance().preload(); } return JPAFacadeHelper.toEntityManagerFactory(factory); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } }
public OpenJPAEntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo pui, Map m) { PersistenceProductDerivation pd = new PersistenceProductDerivation(); try { Object poolValue = Configurations.removeProperty(EMF_POOL, m); ConfigurationProvider cp = pd.load(pui, m); if (cp == null) return null; // add enhancer Exception transformerException = null; String ctOpts = (String) Configurations.getProperty(CLASS_TRANSFORMER_OPTIONS, pui.getProperties()); try { pui.addTransformer(new ClassTransformerImpl(cp, ctOpts, pui.getNewTempClassLoader(), newConfigurationImpl())); } catch (Exception e) { // fail gracefully transformerException = e; } // if the BrokerImpl hasn't been specified, switch to the // non-finalizing one, since anything claiming to be a container // should be doing proper resource management. if (!Configurations.containsProperty(BrokerValue.KEY, cp.getProperties())) { cp.addProperty("openjpa." + BrokerValue.KEY, getDefaultBrokerAlias()); } BrokerFactory factory = getBrokerFactory(cp, poolValue, pui.getClassLoader()); if (transformerException != null) { Log log = factory.getConfiguration().getLog(OpenJPAConfiguration.LOG_RUNTIME); if (log.isTraceEnabled()) { log.warn(_loc.get("transformer-registration-error-ex", pui), transformerException); } else { log.warn(_loc.get("transformer-registration-error", pui)); } } // Create appropriate LifecycleEventManager OpenJPAConfiguration conf = factory.getConfiguration(); _log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); loadValidator(_log, conf); // We need to wait to preload until after we get back a fully configured/instantiated // BrokerFactory. This is because it is possible that someone has extended OpenJPA // functions and they need to be allowed time to configure themselves before we go off and // start instanting configurable objects (ie:openjpa.MetaDataRepository). Don't catch // any exceptions here because we want to fail-fast. Options o = Configurations.parseProperties(Configurations.getProperties("openjpa.MetaDataRepository")); if(o.getBooleanProperty("Preload")){ conf.getMetaDataRepositoryInstance().preload(); } return JPAFacadeHelper.toEntityManagerFactory(factory); } catch (Exception e) { throw PersistenceExceptions.toPersistenceException(e); } }
diff --git a/src/plugins/Library/util/SkeletonBTreeMap.java b/src/plugins/Library/util/SkeletonBTreeMap.java index fd71490..f587608 100644 --- a/src/plugins/Library/util/SkeletonBTreeMap.java +++ b/src/plugins/Library/util/SkeletonBTreeMap.java @@ -1,1245 +1,1244 @@ /* 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.Library.util; import plugins.Library.io.serial.Serialiser.*; import plugins.Library.io.serial.IterableSerialiser; import plugins.Library.io.serial.ScheduledSerialiser; import plugins.Library.io.serial.MapSerialiser; import plugins.Library.io.serial.Translator; import plugins.Library.io.DataFormatException; import plugins.Library.util.exec.TaskAbortException; import plugins.Library.util.exec.TaskCompleteException; import plugins.Library.util.func.Tuples.$2; import plugins.Library.util.func.Tuples.$3; import java.util.Comparator; import java.util.Iterator; import java.util.Collection; import java.util.Map; import java.util.List; import java.util.LinkedHashMap; import java.util.ArrayList; // TODO NORM tidy this import java.util.Queue; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import plugins.Library.util.exec.Progress; import plugins.Library.util.exec.ProgressParts; import plugins.Library.util.exec.BaseCompositeProgress; import plugins.Library.io.serial.Serialiser; import plugins.Library.io.serial.ProgressTracker; import plugins.Library.util.exec.TaskCompleteException; import plugins.Library.util.concurrent.Scheduler; import java.util.Collections; import java.util.SortedSet; import java.util.SortedMap; import java.util.TreeSet; import java.util.TreeMap; import java.util.HashMap; import plugins.Library.util.Sorted; import plugins.Library.util.concurrent.ObjectProcessor; import plugins.Library.util.concurrent.Executors; import plugins.Library.util.event.TrackingSweeper; import plugins.Library.util.event.CountingSweeper; import plugins.Library.util.func.Closure; import plugins.Library.util.func.SafeClosure; import static plugins.Library.util.Maps.$K; /** ** {@link Skeleton} of a {@link BTreeMap}. DOCUMENT ** ** TODO HIGH get rid of uses of rnode.get(K). All other uses of rnode, as well ** as lnode and entries, have already been removed. This will allow us to ** re-implement the Node class. ** ** To the maintainer: this class is very very unstructured and a lot of the ** functionality should be split off elsewhere. Feel free to move stuff around. ** ** @author infinity0 */ public class SkeletonBTreeMap<K, V> extends BTreeMap<K, V> implements SkeletonMap<K, V> { /* ** Whether entries are "internal to" or "contained within" nodes, ie. ** are the entries for a node completely stored (including values) with ** that node in the serialised representation, or do they refer to other ** serialised data that is external to the node? ** ** This determines whether a {@link TreeMap} or a {@link SkeletonTreeMap} ** is used to back the entries in a node. ** ** Eg. a {@code BTreeMap<String, BTreeSet<TermEntry>>} would have this ** {@code true} for the map, and {@code false} for the map backing the set. */ //final protected boolean internal_entries; /* ** OPT HIGH disable for now, since I can't think of a good way to ** implement this tidily. ** ** three options: ** ** 0 have SkeletonNode use TreeMap when int_ent is true rather than ** SkeletonTreeMap but this will either break the Skeleton contract of ** deflate(), which expects isBare() to be true afterwards, or it will ** break the contract of isBare(), if we modifiy that method to return ** true for TreeMaps instead. ** ** - pros: uses an existing class, efficient ** - cons: breaks contracts (no foreseeable way to avoid), complicated ** to implement ** ** 1 have another class that extends SkeletonTreeMap which has one single ** boolean value isDeflated, alias *flate(K) to *flate(), and all those ** functions do is set that boolean. then override get() etc to throw ** DNLEx depending on the value of that boolean; and have SkeletonNode ** use this class when int_ent is true. ** ** - pros: simple, efficient OPT HIGH ** - cons: requires YetAnotherClass ** ** 2 don't have the internal_entries, and just use a dummy serialiser that ** copies task.data to task.meta for push tasks, and vice versa for pull ** tasks. ** ** - pros: simple to implement ** - cons: a hack, inefficient ** ** for now using option 2, will probably implement option 1 at some point.. */ /** ** Serialiser for the node objects. */ protected IterableSerialiser<SkeletonNode> nsrl; /** ** Serialiser for the value objects. */ protected MapSerialiser<K, V> vsrl; public void setSerialiser(IterableSerialiser<SkeletonNode> n, MapSerialiser<K, V> v) { if ((nsrl != null || vsrl != null) && !isLive()) { throw new IllegalStateException("Cannot change the serialiser when the structure is not live."); } nsrl = n; vsrl = v; ((SkeletonNode)root).setSerialiser(); } final public Comparator<PullTask<SkeletonNode>> CMP_PULL = new Comparator<PullTask<SkeletonNode>>() { /*@Override**/ public int compare(PullTask<SkeletonNode> t1, PullTask<SkeletonNode> t2) { return ((GhostNode)t1.meta).compareTo((GhostNode)t2.meta); } }; final public Comparator<PushTask<SkeletonNode>> CMP_PUSH = new Comparator<PushTask<SkeletonNode>>() { /*@Override**/ public int compare(PushTask<SkeletonNode> t1, PushTask<SkeletonNode> t2) { return t1.data.compareTo(t2.data); } }; final public Comparator<Map.Entry<K, V>> CMP_ENTRY = new Comparator<Map.Entry<K, V>>() { /*@Override**/ public int compare(Map.Entry<K, V> t1, Map.Entry<K, V> t2) { return SkeletonBTreeMap.this.compare(t1.getKey(), t2.getKey()); } }; public class SkeletonNode extends Node implements Skeleton<K, IterableSerialiser<SkeletonNode>> { protected int ghosts = 0; protected SkeletonNode(K lk, K rk, boolean lf, SkeletonTreeMap<K, V> map) { super(lk, rk, lf, map); setSerialiser(); } protected SkeletonNode(K lk, K rk, boolean lf) { this(lk, rk, lf, new SkeletonTreeMap<K, V>(comparator)); } protected SkeletonNode(K lk, K rk, boolean lf, SkeletonTreeMap<K, V> map, Collection<GhostNode> gh) { this(lk, rk, lf, map); _size = map.size(); if (!lf) { if (map.size()+1 != gh.size()) { throw new IllegalArgumentException("SkeletonNode: in constructing " + getName() + ", got size mismatch: map:" + map.size() + "; gh:" + gh.size()); } Iterator<GhostNode> it = gh.iterator(); for ($2<K, K> kp: iterKeyPairs()) { GhostNode ghost = it.next(); ghost.lkey = kp._0; ghost.rkey = kp._1; ghost.parent = this; _size += ghost._size; addChildNode(ghost); } ghosts = gh.size(); } } /** ** Set the value-serialiser for this node and all subnodes to match ** the one assigned for the entire tree. */ public void setSerialiser() { ((SkeletonTreeMap<K, V>)entries).setSerialiser(vsrl); if (!isLeaf()) { for (Node n: iterNodes()) { if (!n.isGhost()) { ((SkeletonNode)n).setSerialiser(); } } } } /** ** Create a {@link GhostNode} object that represents this node. */ public GhostNode makeGhost(Object meta) { GhostNode ghost = new GhostNode(lkey, rkey, totalSize()); ghost.setMeta(meta); return ghost; } /*@Override**/ public Object getMeta() { return null; } /*@Override**/ public void setMeta(Object m) { } /*@Override**/ public IterableSerialiser<SkeletonNode> getSerialiser() { return nsrl; } /*@Override**/ public boolean isLive() { if (ghosts > 0 || !((SkeletonTreeMap<K, V>)entries).isLive()) { return false; } if (!isLeaf()) { for (Node n: iterNodes()) { SkeletonNode skel = (SkeletonNode)n; if (!skel.isLive()) { return false; } } } return true; } /*@Override**/ public boolean isBare() { if (!isLeaf()) { if (ghosts < childCount()) { return false; } } return ((SkeletonTreeMap<K, V>)entries).isBare(); } /** ** Attaches a child {@link GhostNode}. ** ** It is '''assumed''' that there is already a {@link SkeletonNode} in ** its place; the ghost will replace it. It is up to the caller to ** ensure that this holds. ** ** @param ghost The GhostNode to attach */ protected void attachGhost(GhostNode ghost) { assert(!rnodes.get(ghost.lkey).isGhost()); ghost.parent = this; setChildNode(ghost); ++ghosts; } /** ** Attaches a child {@link SkeletonNode}. ** ** It is '''assumed''' that there is already a {@link GhostNode} in its ** place; the skeleton will replace it. It is up to the caller to ** ensure that this holds. ** ** @param skel The SkeletonNode to attach */ protected void attachSkeleton(SkeletonNode skel) { assert(rnodes.get(skel.lkey).isGhost()); setChildNode(skel); --ghosts; } /*@Override**/ public void deflate() throws TaskAbortException { if (!isLeaf()) { List<PushTask<SkeletonNode>> tasks = new ArrayList<PushTask<SkeletonNode>>(childCount() - ghosts); for (Node node: iterNodes()) { if (node.isGhost()) { continue; } if (!((SkeletonNode)node).isBare()) { ((SkeletonNode)node).deflate(); } tasks.add(new PushTask<SkeletonNode>((SkeletonNode)node)); } nsrl.push(tasks); for (PushTask<SkeletonNode> task: tasks) { try { attachGhost((GhostNode)task.meta); } catch (RuntimeException e) { throw new TaskAbortException("Could not deflate BTreeMap Node " + getRange(), e); } } } ((SkeletonTreeMap<K, V>)entries).deflate(); assert(isBare()); } // OPT make this parallel /*@Override**/ public void inflate() throws TaskAbortException { ((SkeletonTreeMap<K, V>)entries).inflate(); if (!isLeaf()) { for (Node node: iterNodes()) { inflate(node.lkey, true); } } assert(isLive()); } /*@Override**/ public void inflate(K key) throws TaskAbortException { inflate(key, false); } /** ** Deflates the node to the immediate right of the given key. ** ** Expects metadata to be of type {@link GhostNode}. ** ** @param key The key */ /*@Override**/ public void deflate(K key) throws TaskAbortException { if (isLeaf()) { return; } Node node = rnodes.get(key); if (node.isGhost()) { return; } if (!((SkeletonNode)node).isBare()) { throw new IllegalStateException("Cannot deflate non-bare BTreeMap node"); } PushTask<SkeletonNode> task = new PushTask<SkeletonNode>((SkeletonNode)node); try { nsrl.push(task); attachGhost((GhostNode)task.meta); // TODO LOW maybe just ignore all non-error abortions } catch (TaskCompleteException e) { assert(node.isGhost()); } catch (RuntimeException e) { throw new TaskAbortException("Could not deflate BTreeMap Node " + node.getRange(), e); } } /** ** Inflates the node to the immediate right of the given key. ** ** Passes metadata of type {@link GhostNode}. ** ** @param key The key ** @param auto Whether to recursively inflate the node's subnodes. */ public void inflate(K key, boolean auto) throws TaskAbortException { if (isLeaf()) { return; } Node node = rnodes.get(key); if (!node.isGhost()) { return; } PullTask<SkeletonNode> task = new PullTask<SkeletonNode>(node); try { nsrl.pull(task); postPullTask(task, this); if (auto) { task.data.inflate(); } } catch (TaskCompleteException e) { assert(!node.isGhost()); } catch (DataFormatException e) { throw new TaskAbortException("Could not inflate BTreeMap Node " + node.getRange(), e); } catch (RuntimeException e) { throw new TaskAbortException("Could not inflate BTreeMap Node " + node.getRange(), e); } } } public class GhostNode extends Node { /** ** Points to the parent {@link SkeletonNode}. ** ** Maintaining this field's value is a bitch, so I've tried to remove uses ** of this from the code. Currently, it is only used for the parent field ** a {@link DataFormatException}, which lets us retrieve the serialiser, ** progress, etc etc etc. TODO NORM somehow find another way of doing that ** so we can get rid of it completely. */ protected SkeletonNode parent; protected Object meta; protected GhostNode(K lk, K rk, SkeletonNode p, int s) { super(lk, rk, false, null); parent = p; _size = s; } protected GhostNode(K lk, K rk, int s) { this(lk, rk, null, s); } public Object getMeta() { return meta; } public void setMeta(Object m) { meta = m; } @Override public int nodeSize() { throw new DataNotLoadedException("BTreeMap Node not loaded: " + getRange(), parent, lkey, this); } @Override public int childCount() { throw new DataNotLoadedException("BTreeMap Node not loaded: " + getRange(), parent, lkey, this); } @Override public boolean isLeaf() { throw new DataNotLoadedException("BTreeMap Node not loaded: " + getRange(), parent, lkey, this); } @Override public Node nodeL(Node n) { // this method-call should never be reached in the B-tree algorithm throw new AssertionError("GhostNode: called nodeL()"); } @Override public Node nodeR(Node n) { // this method-call should never be reached in the B-tree algorithm throw new AssertionError("GhostNode: called nodeR()"); } @Override public Node selectNode(K key) { // this method-call should never be reached in the B-tree algorithm throw new AssertionError("GhostNode: called selectNode()"); } } public SkeletonBTreeMap(Comparator<? super K> cmp, int node_min) { super(cmp, node_min); } public SkeletonBTreeMap(int node_min) { super(node_min); } /** ** Post-processes a {@link PullTask} and returns the {@link SkeletonNode} ** pulled. ** ** The tree will be in a consistent state after the operation, if it was ** in a consistent state before it. */ protected SkeletonNode postPullTask(PullTask<SkeletonNode> task, SkeletonNode parent) throws DataFormatException { SkeletonNode node = task.data; GhostNode ghost = (GhostNode)task.meta; if (!compare0(ghost.lkey, node.lkey) || !compare0(ghost.rkey, node.rkey)) { throw new DataFormatException("BTreeMap Node lkey/rkey does not match", null, node); } parent.attachSkeleton(node); return node; } /** ** Post-processes a {@link PushTask} and returns the {@link GhostNode} ** pushed. ** ** The tree will be in a consistent state after the operation, if it was ** in a consistent state before it. */ protected GhostNode postPushTask(PushTask<SkeletonNode> task, SkeletonNode parent) { GhostNode ghost = (GhostNode)task.meta; parent.attachGhost(ghost); return ghost; } @Override protected Node newNode(K lk, K rk, boolean lf) { return new SkeletonNode(lk, rk, lf); } @Override protected void swapKey(K key, Node src, Node dst) { SkeletonTreeMap.swapKey(key, (SkeletonTreeMap<K, V>)src.entries, (SkeletonTreeMap<K, V>)dst.entries); } /*======================================================================== public interface SkeletonMap ========================================================================*/ /*@Override**/ public Object getMeta() { return null; } /*@Override**/ public void setMeta(Object m) { } /*@Override**/ public MapSerialiser<K, V> getSerialiser() { return vsrl; } /*@Override**/ public boolean isLive() { return ((SkeletonNode)root).isLive(); } /*@Override**/ public boolean isBare() { return ((SkeletonNode)root).isBare(); } /*@Override**/ public void deflate() throws TaskAbortException { ((SkeletonNode)root).deflate(); } // TODO NORM tidy this; this should proboably go in a serialiser // and then we will access the Progress of a submap with a task whose // metadata is (lkey, rkey), or something..(PROGRESS) BaseCompositeProgress pr_inf = new BaseCompositeProgress(); public BaseCompositeProgress getProgressInflate() { return pr_inf; } // REMOVE ME /** ** Parallel bulk-inflate. At the moment, this will inflate all the values ** of each nodes too. ** ** Not yet thread safe, but ideally it should be. See source for details. */ /*@Override**/ public void inflate() throws TaskAbortException { // TODO NORM adapt the algorithm to track partial loads of submaps (SUBMAP) // TODO NORM if we do that, we'll also need to make it thread-safe. (THREAD) // TODO NORM and do the PROGRESS stuff whilst we're at it if (!(nsrl instanceof ScheduledSerialiser)) { // TODO LOW could just use the code below - since the Scheduler would be // unavailable, the tasks could be executed in the current thread, and the // priority queue's comparator would turn it into depth-first search // automatically. ((SkeletonNode)root).inflate(); return; } final Queue<SkeletonNode> nodequeue = new PriorityQueue<SkeletonNode>(); Map<PullTask<SkeletonNode>, ProgressTracker<SkeletonNode, ?>> ids = null; ProgressTracker<SkeletonNode, ?> ntracker = null;; if (nsrl instanceof Serialiser.Trackable) { ids = new LinkedHashMap<PullTask<SkeletonNode>, ProgressTracker<SkeletonNode, ?>>(); ntracker = ((Serialiser.Trackable<SkeletonNode>)nsrl).getTracker(); // PROGRESS make a ProgressTracker track this instead of "pr_inf". pr_inf.setSubProgress(ProgressTracker.makePullProgressIterable(ids)); pr_inf.setSubject("Pulling all entries in B-tree"); } final ObjectProcessor<PullTask<SkeletonNode>, SkeletonNode, TaskAbortException> proc_pull = ((ScheduledSerialiser<SkeletonNode>)nsrl).pullSchedule( new PriorityBlockingQueue<PullTask<SkeletonNode>>(0x10, CMP_PULL), new LinkedBlockingQueue<$2<PullTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PullTask<SkeletonNode>, SkeletonNode>() ); //System.out.println("Using scheduler"); //int DEBUG_pushed = 0, DEBUG_popped = 0; try { nodequeue.add((SkeletonNode)root); // FIXME HIGH make a copy of the deflated root so that we can restore it if the // operation fails do { //System.out.println("pushed: " + DEBUG_pushed + "; popped: " + DEBUG_popped); // handle the inflated tasks and attach them to the tree. // THREAD progress tracker should prevent this from being run twice for the // same node, but what if we didn't use a progress tracker? hmm... while (proc_pull.hasCompleted()) { $3<PullTask<SkeletonNode>, SkeletonNode, TaskAbortException> res = proc_pull.accept(); PullTask<SkeletonNode> task = res._0; SkeletonNode parent = res._1; TaskAbortException ex = res._2; if (ex != null) { assert(!(ex instanceof plugins.Library.util.exec.TaskInProgressException)); // by contract of ScheduledSerialiser if (!(ex instanceof TaskCompleteException)) { // TODO LOW maybe dump it somewhere else and throw it at the end... throw ex; } // retrieve the inflated SkeletonNode and add it to the queue... GhostNode ghost = (GhostNode)task.meta; // THREAD race condition here... if another thread has inflated the task // but not yet attached the inflated node to the tree, the assertion fails. // could check to see if the Progress for the Task still exists, but the // performance of this depends on the GC freeing weak referents quickly... assert(!parent.rnodes.get(ghost.lkey).isGhost()); nodequeue.add((SkeletonNode)parent.rnodes.get(ghost.lkey)); } else { SkeletonNode node = postPullTask(task, parent); nodequeue.add(node); } //++DEBUG_popped; } // go through the nodequeue and add any child ghost nodes to the tasks queue while (!nodequeue.isEmpty()) { SkeletonNode node = nodequeue.remove(); // TODO HIGH this needs to be asynchronous ((SkeletonTreeMap<K, V>)node.entries).inflate(); // SUBMAP here if (node.isLeaf()) { continue; } for (Node next: node.iterNodes()) { // SUBMAP here if (!next.isGhost()) { SkeletonNode skel = (SkeletonNode)next; if (!skel.isLive()) { nodequeue.add(skel); } continue; } PullTask<SkeletonNode> task = new PullTask<SkeletonNode>((GhostNode)next); if (ids != null) { ids.put(task, ntracker); } ObjectProcessor.submitSafe(proc_pull, task, node); //++DEBUG_pushed; } } Thread.sleep(1000); } while (proc_pull.hasPending()); pr_inf.setEstimate(ProgressParts.TOTAL_FINALIZED); } catch (DataFormatException e) { throw new TaskAbortException("Bad data format", e); } catch (InterruptedException e) { throw new TaskAbortException("interrupted", e); } finally { proc_pull.close(); //System.out.println("pushed: " + DEBUG_pushed + "; popped: " + DEBUG_popped); //assert(DEBUG_pushed == DEBUG_popped); } } /*@Override**/ public void deflate(K key) throws TaskAbortException { throw new UnsupportedOperationException("not implemented"); } /*@Override**/ public void inflate(K key) throws TaskAbortException { // TODO NORM tidy up // OPT LOW could write a more efficient version by keeping track of // the already-inflated nodes so get() doesn't keep traversing down the // tree - would only improve performance from O(log(n)^2) to O(log(n)) so // not that big a priority for (;;) { try { get(key); break; } catch (DataNotLoadedException e) { e.getParent().inflate(e.getKey()); } } } /** ** @param putmap Entries to insert into this map ** @param remkey Keys to remove from this map ** @see #update(SortedSet, SortedSet, SortedMap, SafeClosure) */ public void update(SortedMap<K, V> putmap, SortedSet<K> remkey) throws TaskAbortException { update(null, remkey, putmap, null); } /** ** @param putkey Keys to insert into this map ** @param remkey Keys to remove from this map ** @param value_handler Closure to retrieve the value for each putkey ** @see #update(SortedSet, SortedSet, SortedMap, SafeClosure) */ public <X extends Exception> void update(SortedSet<K> putkey, SortedSet<K> remkey, Closure<Map.Entry<K, V>, X> value_handler) throws TaskAbortException { update(putkey, remkey, null, value_handler); } /** ** Asynchronously updates a remote B-tree. This uses two-pass merge/split ** algorithms (as opposed to the one-pass algorithms of the standard {@link ** BTreeMap}) since it assumes a copy-on-write backing data store, where ** the advantages (concurrency, etc) of one-pass algorithms disappear, and ** the disadvantages (unneeded merges/splits) remain. ** ** Unlike the (ideal design goal of the) inflate/deflate methods, this is ** designed to support accept only one concurrent update. It is up to the ** caller to ensure that this holds. TODO NORM enforce this somehow ** ** Currently, this method assumes that the root.isBare(). TODO NORM enforce ** this.. ** ** Note: {@code remkey} is not implemented yet. ** ** @throws UnsupportedOperationException if {@code remkey} is not empty */ protected <X extends Exception> void update( SortedSet<K> putkey, SortedSet<K> remkey, final SortedMap<K, V> putmap, Closure<Map.Entry<K, V>, X> value_handler ) throws TaskAbortException { if (value_handler == null) { // synchronous value callback - null, remkey, putmap, null assert(putkey == null); putkey = Sorted.keySet(putmap); } else { // asynchronous value callback - putkey, remkey, null, closure assert(putmap == null); } if (remkey != null && !remkey.isEmpty()) { throw new UnsupportedOperationException("SkeletonBTreeMap: update() currently only supports merge operations"); } /* ** The code below might seem confusing at first, because the action of ** the algorithm on a single node is split up into several asynchronous ** parts, which are not visually adjacent. Here is a more contiguous ** description of what happens to a single node between being inflated ** and then eventually deflated. ** ** Life cycle of a node: ** ** - node gets popped from inflated ** - enter InflateChildNodes ** - subnodes get pushed into proc_pull ** - (recurse for each subnode) ** - subnode gets popped from proc_pull ** - etc ** - split-subnodes get pushed into proc_push ** - wait for all: split-subnodes get popped from proc_push ** - enter SplitNode ** - for each item in the original node's DeflateNode ** - release the item and acquire it on ** - the parent's DeflateNode if the item is a separator ** - a new DeflateNode if the item is now in a split-node ** - for each split-node: ** - wait for all: values get popped from proc_val; SplitNode to close() ** - enter DeflateNode ** - split-node gets pushed into push_queue (except for root) ** */ final ObjectProcessor<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> proc_pull = ((ScheduledSerialiser<SkeletonNode>)nsrl).pullSchedule( new PriorityBlockingQueue<PullTask<SkeletonNode>>(0x10, CMP_PULL), new LinkedBlockingQueue<$2<PullTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>>() ); final ObjectProcessor<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> proc_push = ((ScheduledSerialiser<SkeletonNode>)nsrl).pushSchedule( new PriorityBlockingQueue<PushTask<SkeletonNode>>(0x10, CMP_PUSH), new LinkedBlockingQueue<$2<PushTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>>() ); /** ** Deposit for a value-retrieval operation */ class DeflateNode extends TrackingSweeper<K, SortedSet<K>> implements Runnable, SafeClosure<Map.Entry<K, V>> { final SkeletonNode node; final CountingSweeper<SkeletonNode> parNClo; protected DeflateNode(SkeletonNode n, CountingSweeper<SkeletonNode> pnc) { super(true, true, new TreeSet<K>(), null); parNClo = pnc; node = n; } /** ** Push this node. This is run when this sweeper is cleared, which ** happens after all the node's local values have been obtained, ** '''and''' the node has passed through SplitNode (which closes ** this sweeper). */ public void run() { if (parNClo == null) { // do not deflate the root assert(node == root); return; } ObjectProcessor.submitSafe(proc_push, new PushTask<SkeletonNode>(node), parNClo); } /** ** Update the key's value in the node. Runs whenever an entry is ** popped from proc_val. */ public void invoke(Map.Entry<K, V> en) { assert(node.entries.containsKey(en.getKey())); node.entries.put(en.getKey(), en.getValue()); } } // must be located after DeflateNode's class definition final ObjectProcessor<Map.Entry<K, V>, DeflateNode, X> proc_val = (value_handler == null)? null : new ObjectProcessor<Map.Entry<K, V>, DeflateNode, X>( new PriorityBlockingQueue<Map.Entry<K, V>>(0x10, CMP_ENTRY), new LinkedBlockingQueue<$2<Map.Entry<K, V>, X>>(), new HashMap<Map.Entry<K, V>, DeflateNode>(), value_handler, Executors.DEFAULT_EXECUTOR, true ); // Dummy constant for SplitNode final SortedMap<K, V> EMPTY_SORTEDMAP = new TreeMap<K, V>(); /** ** Deposit for a PushTask */ class SplitNode extends CountingSweeper<SkeletonNode> implements Runnable { final SkeletonNode node; /*final*/ SkeletonNode parent; final DeflateNode nodeVClo; /*final*/ SplitNode parNClo; /*final*/ DeflateNode parVClo; protected SplitNode(SkeletonNode n, SkeletonNode p, DeflateNode vc, SplitNode pnc, DeflateNode pvc) { super(true, false); node = n; parent = p; nodeVClo = vc; parNClo = pnc; parVClo = pvc; } /** ** Closes the node's DeflateNode, and (if appropriate) splits the ** node and updates the deposits for each key moved. This is run ** after all its children have been deflated. */ public void run() { // All subnodes have been deflated, so nothing else can possibly add keys // to this node. nodeVClo.close(); int sk = minKeysFor(node.nodeSize()); // No need to split if (sk == 0) { if (nodeVClo.isCleared()) { nodeVClo.run(); } return; } if (parent == null) { assert(parNClo == null && parVClo == null); // create a new parent, parNClo, parVClo // similar stuff as for InflateChildNodes but no merging parent = new SkeletonNode(null, null, false); parent.addAll(EMPTY_SORTEDMAP, Collections.singleton(node)); parVClo = new DeflateNode(parent, null); parNClo = new SplitNode(parent, null, parVClo, null, null); parNClo.acquire(node); parNClo.close(); root = parent; size = root.totalSize(); } Collection<K> keys = Sorted.select(Sorted.keySet(node.entries), sk); parent.split(node.lkey, keys, node.rkey); Iterable<Node> nodes = parent.iterNodes(node.lkey, node.rkey); SortedSet<K> held = nodeVClo.view(); // if synchronous, all values should have already been handled assert(proc_val != null || held.size() == 0); // reassign appropriate keys to parent sweeper for (K key: keys) { if (!held.contains(key)) { continue; } reassignKeyToSweeper(key, parVClo); } parNClo.open(); // for each split-node, create a sweeper that will run when all its (k,v) // pairs have been popped from value_complete for (Node nn: nodes) { SkeletonNode n = (SkeletonNode)nn; DeflateNode vClo = new DeflateNode(n, parNClo); // reassign appropriate keys to the split-node's sweeper SortedSet<K> subheld = BTreeMap.subSet(held, n.lkey, n.rkey); assert(subheld.isEmpty() || compareL(n.lkey, subheld.first()) < 0 && compareR(subheld.last(), n.rkey) < 0); for (K key: subheld) { reassignKeyToSweeper(key, vClo); } vClo.close(); if (vClo.isCleared()) { vClo.run(); } // if no keys were added parNClo.acquire(n); } // original (unsplit) node had a ticket on the parNClo sweeper, release it parNClo.release(node); parNClo.close(); assert(!parNClo.isCleared()); // we always have at least one node to deflate } /** ** When we move a key to another node (eg. to the parent, or to a new node ** resulting from the split), we must deassign it from the original node's ** sweeper and reassign it to the sweeper for the new node. ** ** NOTE: if the overall co-ordinator algorithm is ever made concurrent, ** this section MUST be made atomic ** ** @param key The key ** @param clo The sweeper to reassign the key to */ private void reassignKeyToSweeper(K key, DeflateNode clo) { clo.acquire(key); //assert(((UpdateValue)value_closures.get(key)).node == node); proc_val.update($K(key, (V)null), clo); // nodeVClo.release(key); // this is unnecessary since nodeVClo() will only be used if we did not // split its node (and never called this method) } } /** ** Deposit for a PullTask */ class InflateChildNodes implements SafeClosure<SkeletonNode> { final SkeletonNode parent; final SortedSet<K> putkey; final SplitNode parNClo; final DeflateNode parVClo; protected InflateChildNodes(SkeletonNode p, SortedSet<K> ki, SplitNode pnc, DeflateNode pvc) { parent = p; putkey = ki; parNClo = pnc; parVClo = pvc; } protected InflateChildNodes(SortedSet<K> ki) { this(null, ki, null, null); } /** ** Merge the relevant parts of the map into the node, and inflate its ** children. Runs whenever a node is popped from proc_pull. */ public void invoke(SkeletonNode node) { assert(compareL(node.lkey, putkey.first()) < 0); assert(compareR(putkey.last(), node.rkey) < 0); // closure to be called when all local values have been obtained DeflateNode vClo = new DeflateNode(node, parNClo); // closure to be called when all subnodes have been handled SplitNode nClo = new SplitNode(node, parent, vClo, parNClo, parVClo); // invalidate every totalSize cache directly after we inflate it node._size = -1; // OPT LOW if putkey is empty then skip // each key in putkey is either added to the local entries, or delegated to // the the relevant child node. if (node.isLeaf()) { // add all keys into the node, since there are no children. if (proc_val == null) { // OPT: could use a splice-merge here. for TreeMap, there is not an // easy way of doing this, nor will it likely make a lot of a difference. // however, if we re-implement SkeletonNode, this might become relevant. for (K key: putkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: putkey) { handleLocalPut(node, key, vClo); } } } else { // only add keys that already exist locally in the node. other keys // are delegated to the relevant child node. SortedSet<K> fkey = new TreeSet<K>(); Iterable<SortedSet<K>> range = Sorted.split(putkey, Sorted.keySet(node.entries), fkey); if (proc_val == null) { for (K key: fkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: fkey) { handleLocalPut(node, key, vClo); } } for (SortedSet<K> rng: range) { GhostNode n = (GhostNode)node.selectNode(rng.first()); PullTask<SkeletonNode> task = new PullTask<SkeletonNode>(n); nClo.acquire((SkeletonNode)null); // dirty hack. FIXME LOW // possibly re-design CountingSweeper to not care about types, or use CountingSweeper<Node> instead ObjectProcessor.submitSafe(proc_pull, task, new InflateChildNodes(node, rng, nClo, vClo)); } } nClo.close(); if (nClo.isCleared()) { nClo.run(); } // eg. if no child nodes need to be modified } /** ** Handle a planned local put to the node. ** ** Keys added locally have their values set to null. These will be updated ** with the correct values via UpdateValue, when the value-getter completes ** its operation on the key. We add the keys now, **before** the value is ** obtained, so that SplitNode can work out how to split the node as early ** as possible. ** ** @param n The node to put the key into ** @param key The key ** @param vClo The sweeper that tracks if the key's value has been obtained */ private void handleLocalPut(SkeletonNode n, K key, DeflateNode vClo) { // FIXME NOW // n is going to be bare so oldval will always be null. instead, pass the meta to the closure.. V oldval = n.entries.put(key, null); vClo.acquire(key); ObjectProcessor.submitSafe(proc_val, $K(key, oldval), vClo); } private void handleLocalRemove(SkeletonNode n, K key, TrackingSweeper<K, SortedSet<K>> vClo) { throw new UnsupportedOperationException("not implemented"); } } try { ((SkeletonTreeMap<K, V>)root.entries).inflate(); // FIXME HIGH make this asynchronous (new InflateChildNodes(putkey)).invoke((SkeletonNode)root); // FIXME HIGH make a copy of the deflated root so that we can restore it if the // operation fails do { while (proc_pull.hasCompleted()) { $3<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> res = proc_pull.accept(); PullTask<SkeletonNode> task = res._0; SafeClosure<SkeletonNode> clo = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PullTask aborted; handler not implemented yet", ex); } SkeletonNode node = postPullTask(task, ((InflateChildNodes)clo).parent); ((SkeletonTreeMap<K, V>)node.entries).inflate(); // FIXME HIGH make this asynchronous clo.invoke(node); } while (proc_push.hasCompleted()) { $3<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> res = proc_push.accept(); PushTask<SkeletonNode> task = res._0; CountingSweeper<SkeletonNode> sw = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PushTask aborted; handler not implemented yet", ex); } - postPushTask(task, ((SplitNode)sw).parent); + postPushTask(task, ((SplitNode)sw).node); sw.release(task.data); if (sw.isCleared()) { ((Runnable)sw).run(); } } Thread.sleep(1000); if (proc_val == null) { continue; } while (proc_val.hasCompleted()) { $3<Map.Entry<K, V>, DeflateNode, X> res = proc_val.accept(); Map.Entry<K, V> en = res._0; DeflateNode sw = res._1; X ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): value-retrieval aborted; handler not implemented yet", ex); } sw.invoke(en); sw.release(en.getKey()); if (sw.isCleared()) { SkeletonNode n = sw.node; ((SkeletonTreeMap<K, V>)n.entries).deflate(); // FIXME HIGH make this asynchronous sw.run(); } - System.out.println("ping: " + proc_val.size() + " left"); } } while (proc_pull.hasPending() || proc_push.hasPending() || (proc_val != null && proc_val.hasPending())); ((SkeletonTreeMap<K, V>)root.entries).deflate(); // FIXME HIGH make this asynchronous } catch (DataFormatException e) { throw new TaskAbortException("Bad data format", e); } catch (InterruptedException e) { throw new TaskAbortException("interrupted", e); } finally { proc_pull.close(); proc_push.close(); if (proc_val != null) { proc_val.close(); } } } /** ** Creates a translator for the nodes of the B-tree. This method is ** necessary because {@link NodeTranslator} is a non-static class. ** ** For an in-depth discussion on why that class is not static, see the ** class description for {@link BTreeMap.Node}. ** ** TODO LOW maybe store these in a WeakHashSet or something... will need to ** code equals() and hashCode() for that ** ** @param ktr Translator for the keys ** @param mtr Translator for each node's local entries map */ public <Q, R> NodeTranslator<Q, R> makeNodeTranslator(Translator<K, Q> ktr, Translator<SkeletonTreeMap<K, V>, R> mtr) { return new NodeTranslator<Q, R>(ktr, mtr); } /************************************************************************ ** DOCUMENT. ** ** For an in-depth discussion on why this class is not static, see the ** class description for {@link BTreeMap.Node}. ** ** @param <Q> Target type of key-translator ** @param <R> Target type of map-translater ** @author infinity0 */ public class NodeTranslator<Q, R> implements Translator<SkeletonNode, Map<String, Object>> { /** ** An optional translator for the keys. */ final Translator<K, Q> ktr; /** ** An optional translator for each node's local entries map. */ final Translator<SkeletonTreeMap<K, V>, R> mtr; public NodeTranslator(Translator<K, Q> k, Translator<SkeletonTreeMap<K, V>, R> m) { ktr = k; mtr = m; } /*@Override**/ public Map<String, Object> app(SkeletonNode node) { if (!node.isBare()) { throw new IllegalStateException("Cannot translate non-bare node " + node.getRange() + " size: " + node.nodeSize() + " ghosts: " + node.ghosts + " " + (root == node)); } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("lkey", (ktr == null)? node.lkey: ktr.app(node.lkey)); map.put("rkey", (ktr == null)? node.rkey: ktr.app(node.rkey)); map.put("entries", (mtr == null)? node.entries: mtr.app((SkeletonTreeMap<K, V>)node.entries)); if (!node.isLeaf()) { Map<Object, Integer> subnodes = new LinkedHashMap<Object, Integer>(); for ($3<K, Node, K> next: node.iterNodesK()) { GhostNode gh = (GhostNode)(next._1); subnodes.put(gh.getMeta(), gh.totalSize()); } map.put("subnodes", subnodes); } return map; } /*@Override**/ public SkeletonNode rev(Map<String, Object> map) throws DataFormatException { try { boolean notleaf = map.containsKey("subnodes"); List<GhostNode> gh = null; if (notleaf) { Map<Object, Integer> subnodes = (Map<Object, Integer>)map.get("subnodes"); gh = new ArrayList<GhostNode>(subnodes.size()); for (Map.Entry<Object, Integer> en: subnodes.entrySet()) { GhostNode ghost = new GhostNode(null, null, null, en.getValue()); ghost.setMeta(en.getKey()); gh.add(ghost); } } SkeletonNode node = new SkeletonNode( (ktr == null)? (K)map.get("lkey"): ktr.rev((Q)map.get("lkey")), (ktr == null)? (K)map.get("rkey"): ktr.rev((Q)map.get("rkey")), !notleaf, (mtr == null)? (SkeletonTreeMap<K, V>)map.get("entries") : mtr.rev((R)map.get("entries")), gh ); if (!node.isBare()) { throw new IllegalStateException("map-translator did not produce a bare SkeletonTreeMap: " + mtr); } verifyNodeIntegrity(node); return node; } catch (ClassCastException e) { throw new DataFormatException("Could not build SkeletonNode from data", e, map, null, null); } catch (IllegalArgumentException e) { throw new DataFormatException("Could not build SkeletonNode from data", e, map, null, null); } catch (IllegalStateException e) { throw new DataFormatException("Could not build SkeletonNode from data", e, map, null, null); } } } /************************************************************************ ** {@link Translator} with access to the members of {@link BTreeMap}. ** DOCUMENT. ** ** @author infinity0 */ public static class TreeTranslator<K, V> implements Translator<SkeletonBTreeMap<K, V>, Map<String, Object>> { final Translator<K, ?> ktr; final Translator<SkeletonTreeMap<K, V>, ?> mtr; public TreeTranslator(Translator<K, ?> k, Translator<SkeletonTreeMap<K, V>, ?> m) { ktr = k; mtr = m; } /*@Override**/ public Map<String, Object> app(SkeletonBTreeMap<K, V> tree) { if (tree.comparator() != null) { throw new UnsupportedOperationException("Sorry, this translator does not (yet) support comparators"); } Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("node_min", tree.NODE_MIN); map.put("size", tree.size); Map<String, Object> rmap = tree.makeNodeTranslator(ktr, mtr).app((SkeletonBTreeMap.SkeletonNode)tree.root); map.put("entries", rmap.get("entries")); if (!tree.root.isLeaf()) { map.put("subnodes", rmap.get("subnodes")); } return map; } /*@Override**/ public SkeletonBTreeMap<K, V> rev(Map<String, Object> map) throws DataFormatException { try { SkeletonBTreeMap<K, V> tree = new SkeletonBTreeMap<K, V>((Integer)map.get("node_min")); tree.size = (Integer)map.get("size"); // map.put("lkey", null); // NULLNOTICE: get() gives null which matches // map.put("rkey", null); // NULLNOTICE: get() gives null which matches tree.root = tree.makeNodeTranslator(ktr, mtr).rev(map); if (tree.size != tree.root.totalSize()) { throw new DataFormatException("Mismatched sizes - tree: " + tree.size + "; root: " + tree.root.totalSize(), null, null); } return tree; } catch (ClassCastException e) { throw new DataFormatException("Could not build SkeletonBTreeMap from data", e, map, null, null); } } } }
false
true
protected <X extends Exception> void update( SortedSet<K> putkey, SortedSet<K> remkey, final SortedMap<K, V> putmap, Closure<Map.Entry<K, V>, X> value_handler ) throws TaskAbortException { if (value_handler == null) { // synchronous value callback - null, remkey, putmap, null assert(putkey == null); putkey = Sorted.keySet(putmap); } else { // asynchronous value callback - putkey, remkey, null, closure assert(putmap == null); } if (remkey != null && !remkey.isEmpty()) { throw new UnsupportedOperationException("SkeletonBTreeMap: update() currently only supports merge operations"); } /* ** The code below might seem confusing at first, because the action of ** the algorithm on a single node is split up into several asynchronous ** parts, which are not visually adjacent. Here is a more contiguous ** description of what happens to a single node between being inflated ** and then eventually deflated. ** ** Life cycle of a node: ** ** - node gets popped from inflated ** - enter InflateChildNodes ** - subnodes get pushed into proc_pull ** - (recurse for each subnode) ** - subnode gets popped from proc_pull ** - etc ** - split-subnodes get pushed into proc_push ** - wait for all: split-subnodes get popped from proc_push ** - enter SplitNode ** - for each item in the original node's DeflateNode ** - release the item and acquire it on ** - the parent's DeflateNode if the item is a separator ** - a new DeflateNode if the item is now in a split-node ** - for each split-node: ** - wait for all: values get popped from proc_val; SplitNode to close() ** - enter DeflateNode ** - split-node gets pushed into push_queue (except for root) ** */ final ObjectProcessor<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> proc_pull = ((ScheduledSerialiser<SkeletonNode>)nsrl).pullSchedule( new PriorityBlockingQueue<PullTask<SkeletonNode>>(0x10, CMP_PULL), new LinkedBlockingQueue<$2<PullTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>>() ); final ObjectProcessor<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> proc_push = ((ScheduledSerialiser<SkeletonNode>)nsrl).pushSchedule( new PriorityBlockingQueue<PushTask<SkeletonNode>>(0x10, CMP_PUSH), new LinkedBlockingQueue<$2<PushTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>>() ); /** ** Deposit for a value-retrieval operation */ class DeflateNode extends TrackingSweeper<K, SortedSet<K>> implements Runnable, SafeClosure<Map.Entry<K, V>> { final SkeletonNode node; final CountingSweeper<SkeletonNode> parNClo; protected DeflateNode(SkeletonNode n, CountingSweeper<SkeletonNode> pnc) { super(true, true, new TreeSet<K>(), null); parNClo = pnc; node = n; } /** ** Push this node. This is run when this sweeper is cleared, which ** happens after all the node's local values have been obtained, ** '''and''' the node has passed through SplitNode (which closes ** this sweeper). */ public void run() { if (parNClo == null) { // do not deflate the root assert(node == root); return; } ObjectProcessor.submitSafe(proc_push, new PushTask<SkeletonNode>(node), parNClo); } /** ** Update the key's value in the node. Runs whenever an entry is ** popped from proc_val. */ public void invoke(Map.Entry<K, V> en) { assert(node.entries.containsKey(en.getKey())); node.entries.put(en.getKey(), en.getValue()); } } // must be located after DeflateNode's class definition final ObjectProcessor<Map.Entry<K, V>, DeflateNode, X> proc_val = (value_handler == null)? null : new ObjectProcessor<Map.Entry<K, V>, DeflateNode, X>( new PriorityBlockingQueue<Map.Entry<K, V>>(0x10, CMP_ENTRY), new LinkedBlockingQueue<$2<Map.Entry<K, V>, X>>(), new HashMap<Map.Entry<K, V>, DeflateNode>(), value_handler, Executors.DEFAULT_EXECUTOR, true ); // Dummy constant for SplitNode final SortedMap<K, V> EMPTY_SORTEDMAP = new TreeMap<K, V>(); /** ** Deposit for a PushTask */ class SplitNode extends CountingSweeper<SkeletonNode> implements Runnable { final SkeletonNode node; /*final*/ SkeletonNode parent; final DeflateNode nodeVClo; /*final*/ SplitNode parNClo; /*final*/ DeflateNode parVClo; protected SplitNode(SkeletonNode n, SkeletonNode p, DeflateNode vc, SplitNode pnc, DeflateNode pvc) { super(true, false); node = n; parent = p; nodeVClo = vc; parNClo = pnc; parVClo = pvc; } /** ** Closes the node's DeflateNode, and (if appropriate) splits the ** node and updates the deposits for each key moved. This is run ** after all its children have been deflated. */ public void run() { // All subnodes have been deflated, so nothing else can possibly add keys // to this node. nodeVClo.close(); int sk = minKeysFor(node.nodeSize()); // No need to split if (sk == 0) { if (nodeVClo.isCleared()) { nodeVClo.run(); } return; } if (parent == null) { assert(parNClo == null && parVClo == null); // create a new parent, parNClo, parVClo // similar stuff as for InflateChildNodes but no merging parent = new SkeletonNode(null, null, false); parent.addAll(EMPTY_SORTEDMAP, Collections.singleton(node)); parVClo = new DeflateNode(parent, null); parNClo = new SplitNode(parent, null, parVClo, null, null); parNClo.acquire(node); parNClo.close(); root = parent; size = root.totalSize(); } Collection<K> keys = Sorted.select(Sorted.keySet(node.entries), sk); parent.split(node.lkey, keys, node.rkey); Iterable<Node> nodes = parent.iterNodes(node.lkey, node.rkey); SortedSet<K> held = nodeVClo.view(); // if synchronous, all values should have already been handled assert(proc_val != null || held.size() == 0); // reassign appropriate keys to parent sweeper for (K key: keys) { if (!held.contains(key)) { continue; } reassignKeyToSweeper(key, parVClo); } parNClo.open(); // for each split-node, create a sweeper that will run when all its (k,v) // pairs have been popped from value_complete for (Node nn: nodes) { SkeletonNode n = (SkeletonNode)nn; DeflateNode vClo = new DeflateNode(n, parNClo); // reassign appropriate keys to the split-node's sweeper SortedSet<K> subheld = BTreeMap.subSet(held, n.lkey, n.rkey); assert(subheld.isEmpty() || compareL(n.lkey, subheld.first()) < 0 && compareR(subheld.last(), n.rkey) < 0); for (K key: subheld) { reassignKeyToSweeper(key, vClo); } vClo.close(); if (vClo.isCleared()) { vClo.run(); } // if no keys were added parNClo.acquire(n); } // original (unsplit) node had a ticket on the parNClo sweeper, release it parNClo.release(node); parNClo.close(); assert(!parNClo.isCleared()); // we always have at least one node to deflate } /** ** When we move a key to another node (eg. to the parent, or to a new node ** resulting from the split), we must deassign it from the original node's ** sweeper and reassign it to the sweeper for the new node. ** ** NOTE: if the overall co-ordinator algorithm is ever made concurrent, ** this section MUST be made atomic ** ** @param key The key ** @param clo The sweeper to reassign the key to */ private void reassignKeyToSweeper(K key, DeflateNode clo) { clo.acquire(key); //assert(((UpdateValue)value_closures.get(key)).node == node); proc_val.update($K(key, (V)null), clo); // nodeVClo.release(key); // this is unnecessary since nodeVClo() will only be used if we did not // split its node (and never called this method) } } /** ** Deposit for a PullTask */ class InflateChildNodes implements SafeClosure<SkeletonNode> { final SkeletonNode parent; final SortedSet<K> putkey; final SplitNode parNClo; final DeflateNode parVClo; protected InflateChildNodes(SkeletonNode p, SortedSet<K> ki, SplitNode pnc, DeflateNode pvc) { parent = p; putkey = ki; parNClo = pnc; parVClo = pvc; } protected InflateChildNodes(SortedSet<K> ki) { this(null, ki, null, null); } /** ** Merge the relevant parts of the map into the node, and inflate its ** children. Runs whenever a node is popped from proc_pull. */ public void invoke(SkeletonNode node) { assert(compareL(node.lkey, putkey.first()) < 0); assert(compareR(putkey.last(), node.rkey) < 0); // closure to be called when all local values have been obtained DeflateNode vClo = new DeflateNode(node, parNClo); // closure to be called when all subnodes have been handled SplitNode nClo = new SplitNode(node, parent, vClo, parNClo, parVClo); // invalidate every totalSize cache directly after we inflate it node._size = -1; // OPT LOW if putkey is empty then skip // each key in putkey is either added to the local entries, or delegated to // the the relevant child node. if (node.isLeaf()) { // add all keys into the node, since there are no children. if (proc_val == null) { // OPT: could use a splice-merge here. for TreeMap, there is not an // easy way of doing this, nor will it likely make a lot of a difference. // however, if we re-implement SkeletonNode, this might become relevant. for (K key: putkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: putkey) { handleLocalPut(node, key, vClo); } } } else { // only add keys that already exist locally in the node. other keys // are delegated to the relevant child node. SortedSet<K> fkey = new TreeSet<K>(); Iterable<SortedSet<K>> range = Sorted.split(putkey, Sorted.keySet(node.entries), fkey); if (proc_val == null) { for (K key: fkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: fkey) { handleLocalPut(node, key, vClo); } } for (SortedSet<K> rng: range) { GhostNode n = (GhostNode)node.selectNode(rng.first()); PullTask<SkeletonNode> task = new PullTask<SkeletonNode>(n); nClo.acquire((SkeletonNode)null); // dirty hack. FIXME LOW // possibly re-design CountingSweeper to not care about types, or use CountingSweeper<Node> instead ObjectProcessor.submitSafe(proc_pull, task, new InflateChildNodes(node, rng, nClo, vClo)); } } nClo.close(); if (nClo.isCleared()) { nClo.run(); } // eg. if no child nodes need to be modified } /** ** Handle a planned local put to the node. ** ** Keys added locally have their values set to null. These will be updated ** with the correct values via UpdateValue, when the value-getter completes ** its operation on the key. We add the keys now, **before** the value is ** obtained, so that SplitNode can work out how to split the node as early ** as possible. ** ** @param n The node to put the key into ** @param key The key ** @param vClo The sweeper that tracks if the key's value has been obtained */ private void handleLocalPut(SkeletonNode n, K key, DeflateNode vClo) { // FIXME NOW // n is going to be bare so oldval will always be null. instead, pass the meta to the closure.. V oldval = n.entries.put(key, null); vClo.acquire(key); ObjectProcessor.submitSafe(proc_val, $K(key, oldval), vClo); } private void handleLocalRemove(SkeletonNode n, K key, TrackingSweeper<K, SortedSet<K>> vClo) { throw new UnsupportedOperationException("not implemented"); } } try { ((SkeletonTreeMap<K, V>)root.entries).inflate(); // FIXME HIGH make this asynchronous (new InflateChildNodes(putkey)).invoke((SkeletonNode)root); // FIXME HIGH make a copy of the deflated root so that we can restore it if the // operation fails do { while (proc_pull.hasCompleted()) { $3<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> res = proc_pull.accept(); PullTask<SkeletonNode> task = res._0; SafeClosure<SkeletonNode> clo = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PullTask aborted; handler not implemented yet", ex); } SkeletonNode node = postPullTask(task, ((InflateChildNodes)clo).parent); ((SkeletonTreeMap<K, V>)node.entries).inflate(); // FIXME HIGH make this asynchronous clo.invoke(node); } while (proc_push.hasCompleted()) { $3<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> res = proc_push.accept(); PushTask<SkeletonNode> task = res._0; CountingSweeper<SkeletonNode> sw = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PushTask aborted; handler not implemented yet", ex); } postPushTask(task, ((SplitNode)sw).parent); sw.release(task.data); if (sw.isCleared()) { ((Runnable)sw).run(); } } Thread.sleep(1000); if (proc_val == null) { continue; } while (proc_val.hasCompleted()) { $3<Map.Entry<K, V>, DeflateNode, X> res = proc_val.accept(); Map.Entry<K, V> en = res._0; DeflateNode sw = res._1; X ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): value-retrieval aborted; handler not implemented yet", ex); } sw.invoke(en); sw.release(en.getKey()); if (sw.isCleared()) { SkeletonNode n = sw.node; ((SkeletonTreeMap<K, V>)n.entries).deflate(); // FIXME HIGH make this asynchronous sw.run(); } System.out.println("ping: " + proc_val.size() + " left"); } } while (proc_pull.hasPending() || proc_push.hasPending() || (proc_val != null && proc_val.hasPending())); ((SkeletonTreeMap<K, V>)root.entries).deflate(); // FIXME HIGH make this asynchronous } catch (DataFormatException e) { throw new TaskAbortException("Bad data format", e); } catch (InterruptedException e) { throw new TaskAbortException("interrupted", e); } finally { proc_pull.close(); proc_push.close(); if (proc_val != null) { proc_val.close(); } } }
protected <X extends Exception> void update( SortedSet<K> putkey, SortedSet<K> remkey, final SortedMap<K, V> putmap, Closure<Map.Entry<K, V>, X> value_handler ) throws TaskAbortException { if (value_handler == null) { // synchronous value callback - null, remkey, putmap, null assert(putkey == null); putkey = Sorted.keySet(putmap); } else { // asynchronous value callback - putkey, remkey, null, closure assert(putmap == null); } if (remkey != null && !remkey.isEmpty()) { throw new UnsupportedOperationException("SkeletonBTreeMap: update() currently only supports merge operations"); } /* ** The code below might seem confusing at first, because the action of ** the algorithm on a single node is split up into several asynchronous ** parts, which are not visually adjacent. Here is a more contiguous ** description of what happens to a single node between being inflated ** and then eventually deflated. ** ** Life cycle of a node: ** ** - node gets popped from inflated ** - enter InflateChildNodes ** - subnodes get pushed into proc_pull ** - (recurse for each subnode) ** - subnode gets popped from proc_pull ** - etc ** - split-subnodes get pushed into proc_push ** - wait for all: split-subnodes get popped from proc_push ** - enter SplitNode ** - for each item in the original node's DeflateNode ** - release the item and acquire it on ** - the parent's DeflateNode if the item is a separator ** - a new DeflateNode if the item is now in a split-node ** - for each split-node: ** - wait for all: values get popped from proc_val; SplitNode to close() ** - enter DeflateNode ** - split-node gets pushed into push_queue (except for root) ** */ final ObjectProcessor<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> proc_pull = ((ScheduledSerialiser<SkeletonNode>)nsrl).pullSchedule( new PriorityBlockingQueue<PullTask<SkeletonNode>>(0x10, CMP_PULL), new LinkedBlockingQueue<$2<PullTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>>() ); final ObjectProcessor<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> proc_push = ((ScheduledSerialiser<SkeletonNode>)nsrl).pushSchedule( new PriorityBlockingQueue<PushTask<SkeletonNode>>(0x10, CMP_PUSH), new LinkedBlockingQueue<$2<PushTask<SkeletonNode>, TaskAbortException>>(0x10), new HashMap<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>>() ); /** ** Deposit for a value-retrieval operation */ class DeflateNode extends TrackingSweeper<K, SortedSet<K>> implements Runnable, SafeClosure<Map.Entry<K, V>> { final SkeletonNode node; final CountingSweeper<SkeletonNode> parNClo; protected DeflateNode(SkeletonNode n, CountingSweeper<SkeletonNode> pnc) { super(true, true, new TreeSet<K>(), null); parNClo = pnc; node = n; } /** ** Push this node. This is run when this sweeper is cleared, which ** happens after all the node's local values have been obtained, ** '''and''' the node has passed through SplitNode (which closes ** this sweeper). */ public void run() { if (parNClo == null) { // do not deflate the root assert(node == root); return; } ObjectProcessor.submitSafe(proc_push, new PushTask<SkeletonNode>(node), parNClo); } /** ** Update the key's value in the node. Runs whenever an entry is ** popped from proc_val. */ public void invoke(Map.Entry<K, V> en) { assert(node.entries.containsKey(en.getKey())); node.entries.put(en.getKey(), en.getValue()); } } // must be located after DeflateNode's class definition final ObjectProcessor<Map.Entry<K, V>, DeflateNode, X> proc_val = (value_handler == null)? null : new ObjectProcessor<Map.Entry<K, V>, DeflateNode, X>( new PriorityBlockingQueue<Map.Entry<K, V>>(0x10, CMP_ENTRY), new LinkedBlockingQueue<$2<Map.Entry<K, V>, X>>(), new HashMap<Map.Entry<K, V>, DeflateNode>(), value_handler, Executors.DEFAULT_EXECUTOR, true ); // Dummy constant for SplitNode final SortedMap<K, V> EMPTY_SORTEDMAP = new TreeMap<K, V>(); /** ** Deposit for a PushTask */ class SplitNode extends CountingSweeper<SkeletonNode> implements Runnable { final SkeletonNode node; /*final*/ SkeletonNode parent; final DeflateNode nodeVClo; /*final*/ SplitNode parNClo; /*final*/ DeflateNode parVClo; protected SplitNode(SkeletonNode n, SkeletonNode p, DeflateNode vc, SplitNode pnc, DeflateNode pvc) { super(true, false); node = n; parent = p; nodeVClo = vc; parNClo = pnc; parVClo = pvc; } /** ** Closes the node's DeflateNode, and (if appropriate) splits the ** node and updates the deposits for each key moved. This is run ** after all its children have been deflated. */ public void run() { // All subnodes have been deflated, so nothing else can possibly add keys // to this node. nodeVClo.close(); int sk = minKeysFor(node.nodeSize()); // No need to split if (sk == 0) { if (nodeVClo.isCleared()) { nodeVClo.run(); } return; } if (parent == null) { assert(parNClo == null && parVClo == null); // create a new parent, parNClo, parVClo // similar stuff as for InflateChildNodes but no merging parent = new SkeletonNode(null, null, false); parent.addAll(EMPTY_SORTEDMAP, Collections.singleton(node)); parVClo = new DeflateNode(parent, null); parNClo = new SplitNode(parent, null, parVClo, null, null); parNClo.acquire(node); parNClo.close(); root = parent; size = root.totalSize(); } Collection<K> keys = Sorted.select(Sorted.keySet(node.entries), sk); parent.split(node.lkey, keys, node.rkey); Iterable<Node> nodes = parent.iterNodes(node.lkey, node.rkey); SortedSet<K> held = nodeVClo.view(); // if synchronous, all values should have already been handled assert(proc_val != null || held.size() == 0); // reassign appropriate keys to parent sweeper for (K key: keys) { if (!held.contains(key)) { continue; } reassignKeyToSweeper(key, parVClo); } parNClo.open(); // for each split-node, create a sweeper that will run when all its (k,v) // pairs have been popped from value_complete for (Node nn: nodes) { SkeletonNode n = (SkeletonNode)nn; DeflateNode vClo = new DeflateNode(n, parNClo); // reassign appropriate keys to the split-node's sweeper SortedSet<K> subheld = BTreeMap.subSet(held, n.lkey, n.rkey); assert(subheld.isEmpty() || compareL(n.lkey, subheld.first()) < 0 && compareR(subheld.last(), n.rkey) < 0); for (K key: subheld) { reassignKeyToSweeper(key, vClo); } vClo.close(); if (vClo.isCleared()) { vClo.run(); } // if no keys were added parNClo.acquire(n); } // original (unsplit) node had a ticket on the parNClo sweeper, release it parNClo.release(node); parNClo.close(); assert(!parNClo.isCleared()); // we always have at least one node to deflate } /** ** When we move a key to another node (eg. to the parent, or to a new node ** resulting from the split), we must deassign it from the original node's ** sweeper and reassign it to the sweeper for the new node. ** ** NOTE: if the overall co-ordinator algorithm is ever made concurrent, ** this section MUST be made atomic ** ** @param key The key ** @param clo The sweeper to reassign the key to */ private void reassignKeyToSweeper(K key, DeflateNode clo) { clo.acquire(key); //assert(((UpdateValue)value_closures.get(key)).node == node); proc_val.update($K(key, (V)null), clo); // nodeVClo.release(key); // this is unnecessary since nodeVClo() will only be used if we did not // split its node (and never called this method) } } /** ** Deposit for a PullTask */ class InflateChildNodes implements SafeClosure<SkeletonNode> { final SkeletonNode parent; final SortedSet<K> putkey; final SplitNode parNClo; final DeflateNode parVClo; protected InflateChildNodes(SkeletonNode p, SortedSet<K> ki, SplitNode pnc, DeflateNode pvc) { parent = p; putkey = ki; parNClo = pnc; parVClo = pvc; } protected InflateChildNodes(SortedSet<K> ki) { this(null, ki, null, null); } /** ** Merge the relevant parts of the map into the node, and inflate its ** children. Runs whenever a node is popped from proc_pull. */ public void invoke(SkeletonNode node) { assert(compareL(node.lkey, putkey.first()) < 0); assert(compareR(putkey.last(), node.rkey) < 0); // closure to be called when all local values have been obtained DeflateNode vClo = new DeflateNode(node, parNClo); // closure to be called when all subnodes have been handled SplitNode nClo = new SplitNode(node, parent, vClo, parNClo, parVClo); // invalidate every totalSize cache directly after we inflate it node._size = -1; // OPT LOW if putkey is empty then skip // each key in putkey is either added to the local entries, or delegated to // the the relevant child node. if (node.isLeaf()) { // add all keys into the node, since there are no children. if (proc_val == null) { // OPT: could use a splice-merge here. for TreeMap, there is not an // easy way of doing this, nor will it likely make a lot of a difference. // however, if we re-implement SkeletonNode, this might become relevant. for (K key: putkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: putkey) { handleLocalPut(node, key, vClo); } } } else { // only add keys that already exist locally in the node. other keys // are delegated to the relevant child node. SortedSet<K> fkey = new TreeSet<K>(); Iterable<SortedSet<K>> range = Sorted.split(putkey, Sorted.keySet(node.entries), fkey); if (proc_val == null) { for (K key: fkey) { node.entries.put(key, putmap.get(key)); } } else { for (K key: fkey) { handleLocalPut(node, key, vClo); } } for (SortedSet<K> rng: range) { GhostNode n = (GhostNode)node.selectNode(rng.first()); PullTask<SkeletonNode> task = new PullTask<SkeletonNode>(n); nClo.acquire((SkeletonNode)null); // dirty hack. FIXME LOW // possibly re-design CountingSweeper to not care about types, or use CountingSweeper<Node> instead ObjectProcessor.submitSafe(proc_pull, task, new InflateChildNodes(node, rng, nClo, vClo)); } } nClo.close(); if (nClo.isCleared()) { nClo.run(); } // eg. if no child nodes need to be modified } /** ** Handle a planned local put to the node. ** ** Keys added locally have their values set to null. These will be updated ** with the correct values via UpdateValue, when the value-getter completes ** its operation on the key. We add the keys now, **before** the value is ** obtained, so that SplitNode can work out how to split the node as early ** as possible. ** ** @param n The node to put the key into ** @param key The key ** @param vClo The sweeper that tracks if the key's value has been obtained */ private void handleLocalPut(SkeletonNode n, K key, DeflateNode vClo) { // FIXME NOW // n is going to be bare so oldval will always be null. instead, pass the meta to the closure.. V oldval = n.entries.put(key, null); vClo.acquire(key); ObjectProcessor.submitSafe(proc_val, $K(key, oldval), vClo); } private void handleLocalRemove(SkeletonNode n, K key, TrackingSweeper<K, SortedSet<K>> vClo) { throw new UnsupportedOperationException("not implemented"); } } try { ((SkeletonTreeMap<K, V>)root.entries).inflate(); // FIXME HIGH make this asynchronous (new InflateChildNodes(putkey)).invoke((SkeletonNode)root); // FIXME HIGH make a copy of the deflated root so that we can restore it if the // operation fails do { while (proc_pull.hasCompleted()) { $3<PullTask<SkeletonNode>, SafeClosure<SkeletonNode>, TaskAbortException> res = proc_pull.accept(); PullTask<SkeletonNode> task = res._0; SafeClosure<SkeletonNode> clo = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PullTask aborted; handler not implemented yet", ex); } SkeletonNode node = postPullTask(task, ((InflateChildNodes)clo).parent); ((SkeletonTreeMap<K, V>)node.entries).inflate(); // FIXME HIGH make this asynchronous clo.invoke(node); } while (proc_push.hasCompleted()) { $3<PushTask<SkeletonNode>, CountingSweeper<SkeletonNode>, TaskAbortException> res = proc_push.accept(); PushTask<SkeletonNode> task = res._0; CountingSweeper<SkeletonNode> sw = res._1; TaskAbortException ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): PushTask aborted; handler not implemented yet", ex); } postPushTask(task, ((SplitNode)sw).node); sw.release(task.data); if (sw.isCleared()) { ((Runnable)sw).run(); } } Thread.sleep(1000); if (proc_val == null) { continue; } while (proc_val.hasCompleted()) { $3<Map.Entry<K, V>, DeflateNode, X> res = proc_val.accept(); Map.Entry<K, V> en = res._0; DeflateNode sw = res._1; X ex = res._2; if (ex != null) { // FIXME HIGH throw new UnsupportedOperationException("SkeletonBTreeMap.update(): value-retrieval aborted; handler not implemented yet", ex); } sw.invoke(en); sw.release(en.getKey()); if (sw.isCleared()) { SkeletonNode n = sw.node; ((SkeletonTreeMap<K, V>)n.entries).deflate(); // FIXME HIGH make this asynchronous sw.run(); } } } while (proc_pull.hasPending() || proc_push.hasPending() || (proc_val != null && proc_val.hasPending())); ((SkeletonTreeMap<K, V>)root.entries).deflate(); // FIXME HIGH make this asynchronous } catch (DataFormatException e) { throw new TaskAbortException("Bad data format", e); } catch (InterruptedException e) { throw new TaskAbortException("interrupted", e); } finally { proc_pull.close(); proc_push.close(); if (proc_val != null) { proc_val.close(); } } }
diff --git a/src/com/jgaap/ui/JGAAP_UI_MainForm.java b/src/com/jgaap/ui/JGAAP_UI_MainForm.java index be1cd40..80df3b5 100644 --- a/src/com/jgaap/ui/JGAAP_UI_MainForm.java +++ b/src/com/jgaap/ui/JGAAP_UI_MainForm.java @@ -1,3043 +1,3043 @@ /* * JGAAP -- a graphical program for stylometric authorship attribution * Copyright (C) 2009,2011 by Patrick Juola * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jgaap.ui; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * JGAAP_UI_MainForm.java * * Created on Nov 2, 2010, 1:14:56 PM */ /** * * @author Patrick Brennan */ //Package Imports import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; import javax.swing.tree.TreePath; import javax.swing.table.DefaultTableModel; //import java.awt.event.*; import com.jgaap.generics.*; import com.jgaap.jgaapConstants; import com.jgaap.backend.API; import com.jgaap.backend.CSVIO; import com.jgaap.backend.Utils; import java.awt.Color; import java.io.IOException; public class JGAAP_UI_MainForm extends javax.swing.JFrame { private static final long serialVersionUID = 1L; JGAAP_UI_NotesDialog NotesPage = new JGAAP_UI_NotesDialog(JGAAP_UI_MainForm.this, true); JGAAP_UI_ResultsDialog ResultsPage = new JGAAP_UI_ResultsDialog(JGAAP_UI_MainForm.this, false); String[] Notes = new String [5]; DefaultListModel AnalysisMethodListBox_Model = new DefaultListModel(); DefaultListModel SelectedAnalysisMethodListBox_Model = new DefaultListModel(); DefaultListModel CanonicizerListBox_Model = new DefaultListModel(); DefaultListModel SelectedCanonicizerListBox_Model = new DefaultListModel(); DefaultListModel EventCullingListBox_Model = new DefaultListModel(); DefaultListModel SelectedEventCullingListBox_Model = new DefaultListModel(); DefaultListModel EventSetsListBox_Model = new DefaultListModel(); DefaultListModel SelectedEventSetsListBox_Model = new DefaultListModel(); DefaultListModel DistanceFunctionsListBox_Model = new DefaultListModel(); DefaultComboBoxModel LanguageComboBox_Model = new DefaultComboBoxModel(); DefaultTreeModel KnownAuthorsTree_Model = new DefaultTreeModel(new DefaultMutableTreeNode("Authors")); DefaultTableModel UnknownAuthorDocumentsTable_Model = new DefaultTableModel() { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { if (column == 0) { return true; } else { return false; } } }; DefaultTableModel DocumentsTable_Model = new DefaultTableModel() { private static final long serialVersionUID = 1L; @Override public boolean isCellEditable(int row, int column) { return false; } }; API JGAAP_API = new API(); JFileChooser FileChoser; String filepath = ".."; List<Canonicizer> CanonicizerMasterList = JGAAP_API.getAllCanonicizers(); List<EventDriver> EventDriverMasterList = JGAAP_API.getAllEventDrivers(); List<AnalysisDriver> AnalysisDriverMasterList = JGAAP_API.getAllAnalysisDrivers(); List<DistanceFunction> DistanceFunctionsMasterList = JGAAP_API.getAllDistanceFunctions(); List<EventCuller> EventCullersMasterList = JGAAP_API.getAllEventCullers(); List<Language> LanguagesMasterList = JGAAP_API.getAllLanguages(); List<EventDriver> SelectedEventDriverList = new ArrayList<EventDriver>(); List<EventCuller> SelectedEventCullersList = new ArrayList<EventCuller>(); List<AnalysisDriver> SelectedAnalysisDriverList = new ArrayList<AnalysisDriver>(); List<Canonicizer> SelectedCanonicizerList = new ArrayList<Canonicizer>(); List<Document> UnknownDocumentList = new ArrayList<Document>(); List<Document> KnownDocumentList = new ArrayList<Document>(); List<Document> DocumentList = new ArrayList<Document>(); List<String> AuthorList = new ArrayList<String>(); /** Creates new form JGAAP_UI_MainForm */ public JGAAP_UI_MainForm() { initComponents(); SanatizeMasterLists(); SetAnalysisMethodList(); SetDistanceFunctionList(); SetCanonicizerList(); SetEventSetList(); SetEventCullingList(); SetUnknownDocumentColumns(); SetKnownDocumentTree(); SetDocumentColumns(); SetLanguagesList(); SelectedEventDriverList.clear(); SelectedAnalysisDriverList.clear(); CheckMinimumRequirements(); // DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings({ "deprecation" }) // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { helpDialog = new javax.swing.JDialog(); helpCloseButton = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); JGAAP_TabbedPane = new javax.swing.JTabbedPane(); JGAAP_DocumentsPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree(); DocumentsPanel_AddDocumentsButton = new javax.swing.JButton(); DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton(); DocumentsPanel_AddAuthorButton = new javax.swing.JButton(); DocumentsPanel_EditAuthorButton = new javax.swing.JButton(); DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton(); DocumentsPanel_NotesButton = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox(); JGAAP_CanonicizerPanel = new javax.swing.JPanel(); CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton(); jLabel27 = new javax.swing.JLabel(); CanonicizersPanel_NotesButton = new javax.swing.JButton(); jScrollPane11 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea(); CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton(); CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton(); jScrollPane12 = new javax.swing.JScrollPane(); CanonicizersPanel_CanonicizerListBox = new javax.swing.JList(); jScrollPane13 = new javax.swing.JScrollPane(); CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList(); CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton(); jLabel31 = new javax.swing.JLabel(); jScrollPane20 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsTable = new javax.swing.JTable(); jScrollPane21 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea(); CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton(); CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton(); CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); JGAAP_EventSetsPanel = new javax.swing.JPanel(); EventSetsPanel_NotesButton = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jScrollPane9 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetListBox = new javax.swing.JList(); jScrollPane10 = new javax.swing.JScrollPane(); EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList(); EventSetsPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane6 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea(); EventSetsPanel_AddEventSetButton = new javax.swing.JButton(); EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton(); EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton(); EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton(); JGAAP_EventCullingPanel = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); EventCullingPanel_NotesButton = new javax.swing.JButton(); jScrollPane14 = new javax.swing.JScrollPane(); EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList(); EventCullingPanel_AddEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton(); EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane15 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingListBox = new javax.swing.JList(); jScrollPane16 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea(); jLabel18 = new javax.swing.JLabel(); JGAAP_AnalysisMethodPanel = new javax.swing.JPanel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); AnalysisMethodPanel_NotesButton = new javax.swing.JButton(); jScrollPane17 = new javax.swing.JScrollPane(); AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel(); jScrollPane18 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList(); jLabel28 = new javax.swing.JLabel(); jScrollPane19 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea(); jScrollPane22 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList(); jLabel35 = new javax.swing.JLabel(); jScrollPane23 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea(); jLabel36 = new javax.swing.JLabel(); AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel(); jLabel37 = new javax.swing.JLabel(); JGAAP_ReviewPanel = new javax.swing.JPanel(); ReviewPanel_ProcessButton = new javax.swing.JButton(); ReviewPanel_DocumentsLabel = new javax.swing.JLabel(); jScrollPane24 = new javax.swing.JScrollPane(); ReviewPanel_DocumentsTable = new javax.swing.JTable(); ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel(); ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel(); ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel(); jScrollPane25 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventSetListBox = new javax.swing.JList(); jScrollPane26 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList(); jScrollPane27 = new javax.swing.JScrollPane(); ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); Next_Button = new javax.swing.JButton(); Review_Button = new javax.swing.JButton(); JGAAP_MenuBar = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); BatchSaveMenuItem = new javax.swing.JMenuItem(); BatchLoadMenuItem = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); ProblemAMenuItem = new javax.swing.JMenuItem(); ProblemBMenuItem = new javax.swing.JMenuItem(); ProblemCMenuItem = new javax.swing.JMenuItem(); ProblemDMenuItem = new javax.swing.JMenuItem(); ProblemEMenuItem = new javax.swing.JMenuItem(); ProblemFMenuItem = new javax.swing.JMenuItem(); ProblemGMenuItem = new javax.swing.JMenuItem(); ProblemHMenuItem = new javax.swing.JMenuItem(); ProblemIMenuItem = new javax.swing.JMenuItem(); ProblemJMenuItem = new javax.swing.JMenuItem(); ProblemKMenuItem = new javax.swing.JMenuItem(); ProblemLMenuItem = new javax.swing.JMenuItem(); ProblemMMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); helpDialog.setTitle("About"); helpDialog.setMinimumSize(new java.awt.Dimension(520, 300)); helpDialog.setResizable(false); helpCloseButton.setText("close"); helpCloseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpCloseButtonActionPerformed(evt); } }); jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24)); jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel11.setText("JGAAP 5.0"); jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0"); - jLabel13.setText("©2011 EVL lab"); + jLabel13.setText("©2011 EVL lab"); jLabel23.setForeground(new java.awt.Color(0, 0, 255)); jLabel23.setText("http://evllabs.com"); jLabel23.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel23MouseClicked(evt); } }); jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N jLabel25.setForeground(new java.awt.Color(0, 0, 255)); jLabel25.setText("http://jgaap.com"); jLabel25.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel25MouseClicked(evt); } }); jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane()); helpDialog.getContentPane().setLayout(helpDialogLayout); helpDialogLayout.setHorizontalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addComponent(jLabel24) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel26)) .addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(199, 199, 199) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel23) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel13) .addComponent(jLabel25)))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); helpDialogLayout.setVerticalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel24) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11) .addGap(44, 44, 44))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel23) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel25) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(helpCloseButton) .addComponent(jLabel13)) .addContainerGap()) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("JGAAP"); JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel1.setText("Unknown Authors"); jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel2.setText("Known Authors"); DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model); DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN); DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true); DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable); DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model); DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true); jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree); DocumentsPanel_AddDocumentsButton.setText("Add Document"); DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_RemoveDocumentsButton.setText("Remove Document"); DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_AddAuthorButton.setLabel("Add Author"); DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddAuthorButtonActionPerformed(evt); } }); DocumentsPanel_EditAuthorButton.setLabel("Edit Author"); DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_EditAuthorButtonActionPerformed(evt); } }); DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author"); DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveAuthorButtonActionPerformed(evt); } }); DocumentsPanel_NotesButton.setLabel("Notes"); DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_NotesButtonActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel10.setText("Language"); DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model); DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_LanguageComboBoxActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel); JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout); JGAAP_DocumentsPanelLayout.setHorizontalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE) .addComponent(DocumentsPanel_NotesButton)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddDocumentsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveDocumentsButton)) .addComponent(jLabel2)) .addGap(512, 512, 512)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_EditAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveAuthorButton))) .addContainerGap()) ); JGAAP_DocumentsPanelLayout.setVerticalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(DocumentsPanel_NotesButton) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveDocumentsButton) .addComponent(DocumentsPanel_AddDocumentsButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveAuthorButton) .addComponent(DocumentsPanel_EditAuthorButton) .addComponent(DocumentsPanel_AddAuthorButton)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel); CanonicizersPanel_RemoveCanonicizerButton.setText("←"); CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt); } }); jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel27.setText("Documents"); CanonicizersPanel_NotesButton.setLabel("Notes"); CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_NotesButtonActionPerformed(evt); } }); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true); jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox); CanonicizersPanel_AddCanonicizerButton.setText("→"); CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt); } }); CanonicizersPanel_AddAllCanonicizersButton.setText("All"); CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt); } }); CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model); CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseMoved(evt); } }); jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox); CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model); CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt); } }); jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox); CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear"); CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt); } }); jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel31.setText("Document's Current Canonicizers"); CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model); jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true); jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox); CanonicizersPanel_SetToDocumentButton.setText("Set to Doc"); CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentButtonActionPerformed(evt); } }); CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type"); CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt); } }); CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs"); CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToAllDocumentsActionPerformed(evt); } }); jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel29.setText("Selected"); jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel30.setText("Canonicizers"); jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel32.setText("Canonicizer Description"); jLabel33.setText("Note: These buttons are used to add"); jLabel34.setText("selected canonicizers to documents."); javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel); JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout); JGAAP_CanonicizerPanelLayout.setHorizontalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel30) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addComponent(jLabel33) .addComponent(jLabel34)) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jLabel29) .addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel27) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE) .addComponent(CanonicizersPanel_NotesButton)))) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel32) .addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_CanonicizerPanelLayout.setVerticalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel27) .addComponent(jLabel30) .addComponent(jLabel29)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(CanonicizersPanel_NotesButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_AddCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_AddAllCanonicizersButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_SetToDocumentButton))) .addGap(6, 6, 6) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel33) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel34) .addGap(18, 18, 18)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_SetToDocumentTypeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel31) .addComponent(jLabel32)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel); EventSetsPanel_NotesButton.setLabel("Notes"); EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_NotesButtonActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel6.setText("Event Drivers"); jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel7.setText("Parameters"); jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel8.setText("Event Driver Description"); jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel9.setText("Selected"); EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model); EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseClicked(evt); } }); EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseMoved(evt); } }); jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox); EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt); } }); EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt); } }); jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox); EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel); EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout); EventSetsPanel_ParametersPanelLayout.setHorizontalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 344, Short.MAX_VALUE) ); EventSetsPanel_ParametersPanelLayout.setVerticalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventSetsPanel_EventSetDescriptionTextBox.setColumns(20); EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true); EventSetsPanel_EventSetDescriptionTextBox.setRows(5); EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true); jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox); EventSetsPanel_AddEventSetButton.setText("→"); EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddEventSetButtonActionPerformed(evt); } }); EventSetsPanel_RemoveEventSetButton.setText("←"); EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveEventSetButtonActionPerformed(evt); } }); EventSetsPanel_AddAllEventSetsButton.setText("All"); EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt); } }); EventSetsPanel_RemoveAllEventSetsButton.setText("Clear"); EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel); JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout); JGAAP_EventSetsPanelLayout.setHorizontalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE) .addComponent(EventSetsPanel_NotesButton)) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventSetsPanelLayout.setVerticalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jLabel9)) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(EventSetsPanel_NotesButton) .addComponent(jLabel7))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(EventSetsPanel_AddEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_AddAllEventSetsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveAllEventSetsButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel); jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel15.setText("Event Culling"); jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel16.setText("Parameters"); jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel17.setText("Selected"); EventCullingPanel_NotesButton.setLabel("Notes"); EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_NotesButtonActionPerformed(evt); } }); EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt); } }); jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox); EventCullingPanel_AddEventCullingButton.setText("→"); EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveEventCullingButton.setText("←"); EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_AddAllEventCullingButton.setText("All"); EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveAllEventCullingButton.setText("Clear"); EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel); EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout); EventCullingPanel_ParametersPanelLayout.setHorizontalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 343, Short.MAX_VALUE) ); EventCullingPanel_ParametersPanelLayout.setVerticalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model); EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseMoved(evt); } }); jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox); EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20); EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true); EventCullingPanel_EventCullingDescriptionTextbox.setRows(5); EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true); jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox); jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel18.setText("Event Culling Description"); javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel); JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout); JGAAP_EventCullingPanelLayout.setHorizontalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE) .addComponent(EventCullingPanel_NotesButton)) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventCullingPanelLayout.setVerticalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel17) .addComponent(jLabel16)) .addComponent(EventCullingPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(EventCullingPanel_AddEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_AddAllEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveAllEventCullingButton) .addGap(107, 107, 107))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel); jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel20.setText("Analysis Methods"); jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel21.setText("AM Parameters"); jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel22.setText("Selected"); AnalysisMethodPanel_NotesButton.setLabel("Notes"); AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_NotesButtonActionPerformed(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox); AnalysisMethodPanel_AddAnalysisMethodButton.setText("→"); AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("←"); AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All"); AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear"); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel); AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout); AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 125, Short.MAX_VALUE) ); AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model); AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox); jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel28.setText("Distance Function Description"); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true); jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox); AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model); AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt); } }); jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox); jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel35.setText("Distance Functions"); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true); jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox); jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel36.setText("Analysis Method Description"); AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel); AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout); AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 128, Short.MAX_VALUE) ); jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel37.setText("DF Parameters"); javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel); JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout); JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE) .addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE) .addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel22) .addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_NotesButton)) .addComponent(jLabel37))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel28) .addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_AnalysisMethodPanelLayout.setVerticalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22) .addComponent(AnalysisMethodPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel37) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton)) .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel35) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel28) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel); ReviewPanel_ProcessButton.setLabel("Process"); ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReviewPanel_ProcessButtonActionPerformed(evt); } }); ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_DocumentsLabel.setText("Documents"); ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsLabelMouseClicked(evt); } }); ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model); ReviewPanel_DocumentsTable.setEnabled(false); ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsTableMouseClicked(evt); } }); jScrollPane24.setViewportView(ReviewPanel_DocumentsTable); ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventSetLabel.setText("Event Driver"); ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventCullingLabel.setText("Event Culling"); ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingLabelMouseClicked(evt); } }); ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods"); ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventSetListBox.setEnabled(false); ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetListBoxMouseClicked(evt); } }); jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox); ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventCullingListBox.setEnabled(false); ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox); ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false); ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox); javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel); JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout); JGAAP_ReviewPanelLayout.setHorizontalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_ProcessButton) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ReviewPanel_SelectedEventSetLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_ReviewPanelLayout.setVerticalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(ReviewPanel_DocumentsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ReviewPanel_SelectedEventSetLabel) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ReviewPanel_ProcessButton) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel); Next_Button.setText("Next →"); Next_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Next_ButtonActionPerformed(evt); } }); Review_Button.setText("Finish & Review"); Review_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Review_ButtonActionPerformed(evt); } }); jMenu1.setText("File"); jMenu4.setText("Batch Documents"); BatchSaveMenuItem.setText("Save Documents"); BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchSaveMenuItemActionPerformed(evt); } }); jMenu4.add(BatchSaveMenuItem); BatchLoadMenuItem.setText("Load Documents"); BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchLoadMenuItemActionPerformed(evt); } }); jMenu4.add(BatchLoadMenuItem); jMenu1.add(jMenu4); jMenu2.setText("AAAC Problems"); ProblemAMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemBMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemCMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemDMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemEMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(KeyEvent.VK_E, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemFMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemGMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemHMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemIMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemJMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemKMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemLMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemMMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemAMenuItem.setText("Problem A"); ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemAMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemAMenuItem); ProblemBMenuItem.setText("Problem B"); ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemBMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemBMenuItem); ProblemCMenuItem.setText("Problem C"); ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemCMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemCMenuItem); ProblemDMenuItem.setText("Problem D"); ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemDMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemDMenuItem); ProblemEMenuItem.setText("Problem E"); ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemEMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemEMenuItem); ProblemFMenuItem.setText("Problem F"); ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemFMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemFMenuItem); ProblemGMenuItem.setText("Problem G"); ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemGMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemGMenuItem); ProblemHMenuItem.setText("Problem H"); ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemHMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemHMenuItem); ProblemIMenuItem.setText("Problem I"); ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemIMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemIMenuItem); ProblemJMenuItem.setText("Problem J"); ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemJMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemJMenuItem); ProblemKMenuItem.setText("Problem K"); ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemKMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemKMenuItem); ProblemLMenuItem.setText("Problem L"); ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemLMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemLMenuItem); ProblemMMenuItem.setText("Problem M"); ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemMMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemMMenuItem); jMenu1.add(jMenu2); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); jMenu1.add(exitMenuItem); JGAAP_MenuBar.add(jMenu1); helpMenu.setText("Help"); aboutMenuItem.setText("About.."); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); JGAAP_MenuBar.add(helpMenu); setJMenuBar(JGAAP_MenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(Review_Button) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Next_Button))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Next_Button) .addComponent(Review_Button)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void ReviewPanel_ProcessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReviewPanel_ProcessButtonActionPerformed try { JGAAP_API.clearResults(); JGAAP_API.execute(); List<Document> unknowns = JGAAP_API.getUnknownDocuments(); StringBuffer buffer = new StringBuffer(); for (Document unknown : unknowns) { buffer.append(unknown.getResult()); } //ResultsPage.DisplayResults(buffer.toString()); ResultsPage.AddResults(buffer.toString()); ResultsPage.setVisible(true); } catch (Exception e){ } }//GEN-LAST:event_ReviewPanel_ProcessButtonActionPerformed private void LoadProblemMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadProblemMenuItemActionPerformed // TODO add your handling code here: }//GEN-LAST:event_LoadProblemMenuItemActionPerformed private void BatchLoadMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BatchLoadMenuItemActionPerformed FileChoser = new JFileChooser(filepath); int choice = FileChoser.showOpenDialog(JGAAP_UI_MainForm.this); if (choice == JFileChooser.APPROVE_OPTION) { try { filepath = FileChoser.getSelectedFile().getCanonicalPath(); List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } } }//GEN-LAST:event_BatchLoadMenuItemActionPerformed private void BatchSaveMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BatchSaveMenuItemActionPerformed FileChoser = new JFileChooser(filepath); int choice = FileChoser.showSaveDialog(JGAAP_UI_MainForm.this); if (choice == JFileChooser.APPROVE_OPTION) { try { JGAAP_API.loadDocuments(); DocumentList = JGAAP_API.getDocuments(); Utils.saveDocumentsToCSV(DocumentList, FileChoser.getSelectedFile()); } catch (Exception e) { } } }//GEN-LAST:event_BatchSaveMenuItemActionPerformed private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed dispose(); System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void helpCloseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpCloseButtonActionPerformed toggleHelpDialog(); }//GEN-LAST:event_helpCloseButtonActionPerformed private void jLabel23MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel23MouseClicked browseToURL("http://evllabs.com"); }//GEN-LAST:event_jLabel23MouseClicked private void jLabel25MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel25MouseClicked if(!browseToURL("http://jgaap.com")){ browseToURL("http://server8.mathcomp.duq.edu/jgaap/w"); } }//GEN-LAST:event_jLabel25MouseClicked private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed toggleHelpDialog(); }//GEN-LAST:event_aboutMenuItemActionPerformed private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = AnalysisDriverMasterList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved private void AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedIndex()).longDescription()); if (evt.getClickCount() == 2) { AddAnalysisMethodSelection(); } }//GEN-LAST:event_AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked private void AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed JGAAP_API.removeAllAnalysisDrivers(); UpdateSelectedAnalysisMethodListBox(); }//GEN-LAST:event_AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed private void AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed try{ for (int i = 0; i < AnalysisDriverMasterList.size(); i++) { JGAAP_API.addAnalysisDriver(AnalysisDriverMasterList.get(i).displayName()); } UpdateSelectedAnalysisMethodListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } }//GEN-LAST:event_AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed private void AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed RemoveAnalysisMethodSelection(); }//GEN-LAST:event_AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed private void RemoveAnalysisMethodSelection() { SelectedAnalysisDriverList = JGAAP_API.getAnalysisDrivers(); JGAAP_API.removeAnalysisDriver(SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex())); UpdateSelectedAnalysisMethodListBox(); } private void AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed AddAnalysisMethodSelection(); }//GEN-LAST:event_AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed private void CheckMinimumRequirements() { boolean OK = true; if (DocumentList.isEmpty()) { OK = false; ReviewPanel_DocumentsLabel.setForeground(Color.RED); } else { ReviewPanel_DocumentsLabel.setForeground(Color.GREEN.darker()); } if (SelectedEventDriverList.isEmpty()) { OK = false; ReviewPanel_SelectedEventSetLabel.setForeground(Color.RED); } else { ReviewPanel_SelectedEventSetLabel.setForeground(Color.GREEN.darker()); } ReviewPanel_SelectedEventCullingLabel.setForeground(Color.GREEN.darker()); if (SelectedAnalysisDriverList.isEmpty()) { OK = false; ReviewPanel_SelectedAnalysisMethodsLabel.setForeground(Color.RED); } else { ReviewPanel_SelectedAnalysisMethodsLabel.setForeground(Color.GREEN.darker()); } ReviewPanel_ProcessButton.setEnabled(OK); } private void AddAnalysisMethodSelection() { try{ AnalysisDriver temp = JGAAP_API.addAnalysisDriver(AnalysisMethodPanel_AnalysisMethodsListBox.getSelectedValue().toString()); if (temp instanceof NeighborAnalysisDriver) { JGAAP_API.addDistanceFunction(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedValue().toString(), temp); } UpdateSelectedAnalysisMethodListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } } private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = SelectedAnalysisDriverList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved private void AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked AnalysisDriver temp = SelectedAnalysisDriverList.get(AnalysisMethodPanel_SelectedAnalysisMethodsListBox.getSelectedIndex()); AnalysisMethodPanel_AMParametersPanel.removeAll(); AnalysisMethodPanel_DFParametersPanel.removeAll(); AnalysisMethodPanel_AMParametersPanel.setLayout(temp.getGUILayout(AnalysisMethodPanel_AMParametersPanel)); if (temp instanceof NeighborAnalysisDriver) { AnalysisMethodPanel_DFParametersPanel.setLayout(((NeighborAnalysisDriver)temp).getDistanceFunction().getGUILayout(AnalysisMethodPanel_DFParametersPanel)); } AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(temp.longDescription()); if (temp instanceof NeighborAnalysisDriver) { AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(((NeighborAnalysisDriver)temp).getDistanceFunction().longDescription()); } if (evt!=null && evt.getClickCount() == 2) { RemoveAnalysisMethodSelection(); } }//GEN-LAST:event_AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked private void EventCullingPanel_EventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = EventCullersMasterList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_EventCullingPanel_EventCullingListBoxMouseMoved private void EventCullingPanel_EventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_EventCullingListBoxMouseClicked EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(EventCullingPanel_EventCullingListBox.getSelectedIndex()).longDescription()); if (evt.getClickCount() == 2) { AddEventCullerSelection(); } }//GEN-LAST:event_EventCullingPanel_EventCullingListBoxMouseClicked private void EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveAllEventCullingButtonActionPerformed JGAAP_API.removeAllEventCullers(); UpdateSelectedEventCullingListBox(); }//GEN-LAST:event_EventCullingPanel_RemoveAllEventCullingButtonActionPerformed private void EventCullingPanel_AddAllEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_AddAllEventCullingButtonActionPerformed try{ for (int i = 0; i < EventCullersMasterList.size(); i++) { JGAAP_API.addEventCuller(EventCullersMasterList.get(i).displayName()); } UpdateSelectedEventCullingListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } // TODO add your handling code here: }//GEN-LAST:event_EventCullingPanel_AddAllEventCullingButtonActionPerformed private void EventCullingPanel_RemoveEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed RemoveEventCullerSelection(); }//GEN-LAST:event_EventCullingPanel_RemoveEventCullingButtonActionPerformed private void RemoveEventCullerSelection() { SelectedEventCullersList = JGAAP_API.getEventCullers(); JGAAP_API.removeEventCuller(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex())); UpdateSelectedEventCullingListBox(); } private void EventCullingPanel_AddEventCullingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_AddEventCullingButtonActionPerformed AddEventCullerSelection(); }//GEN-LAST:event_EventCullingPanel_AddEventCullingButtonActionPerformed private void AddEventCullerSelection() { try{ JGAAP_API.addEventCuller(EventCullingPanel_EventCullingListBox.getSelectedValue().toString()); UpdateSelectedEventCullingListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } } private void EventCullingPanel_SelectedEventCullingListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = SelectedEventCullersList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_EventCullingPanel_SelectedEventCullingListBoxMouseMoved private void EventCullingPanel_SelectedEventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked EventCullingPanel_ParametersPanel.removeAll(); EventCullingPanel_ParametersPanel.setLayout(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()).getGUILayout(EventCullingPanel_ParametersPanel)); EventCullingPanel_EventCullingDescriptionTextbox.setText(SelectedEventCullersList.get(EventCullingPanel_SelectedEventCullingListBox.getSelectedIndex()).longDescription()); if (evt!=null && evt.getClickCount() == 2) { RemoveEventCullerSelection(); } }//GEN-LAST:event_EventCullingPanel_SelectedEventCullingListBoxMouseClicked private void EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveAllEventSetsButtonActionPerformed JGAAP_API.removeAllEventDrivers(); UpdateSelectedEventSetListBox(); }//GEN-LAST:event_EventSetsPanel_RemoveAllEventSetsButtonActionPerformed private void EventSetsPanel_AddAllEventSetsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_AddAllEventSetsButtonActionPerformed try{ for (int i = 0; i < EventDriverMasterList.size(); i++) { JGAAP_API.addEventDriver(EventDriverMasterList.get(i).displayName()); } UpdateSelectedEventSetListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } }//GEN-LAST:event_EventSetsPanel_AddAllEventSetsButtonActionPerformed private void EventSetsPanel_RemoveEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed RemoveEventSetSelection(); }//GEN-LAST:event_EventSetsPanel_RemoveEventSetButtonActionPerformed private void RemoveEventSetSelection() { SelectedEventDriverList = JGAAP_API.getEventDrivers(); JGAAP_API.removeEventDriver(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex())); UpdateSelectedEventSetListBox(); } private void EventSetsPanel_AddEventSetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_AddEventSetButtonActionPerformed AddEventSetSelection(); }//GEN-LAST:event_EventSetsPanel_AddEventSetButtonActionPerformed private void AddEventSetSelection() { try{ JGAAP_API.addEventDriver(EventSetsPanel_EventSetListBox.getSelectedValue().toString()); UpdateSelectedEventSetListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } } private void EventSetsPanel_SelectedEventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_SelectedEventSetListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = SelectedEventDriverList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_EventSetsPanel_SelectedEventSetListBoxMouseMoved private void EventSetsPanel_SelectedEventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_SelectedEventSetListBoxMouseClicked EventSetsPanel_ParametersPanel.removeAll(); EventSetsPanel_ParametersPanel.setLayout(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).getGUILayout(EventSetsPanel_ParametersPanel)); EventSetsPanel_EventSetDescriptionTextBox.setText(SelectedEventDriverList.get(EventSetsPanel_SelectedEventSetListBox.getSelectedIndex()).longDescription()); if (evt != null && evt.getClickCount() == 2) { RemoveEventSetSelection(); } }//GEN-LAST:event_EventSetsPanel_SelectedEventSetListBoxMouseClicked private void EventSetsPanel_EventSetListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = EventDriverMasterList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_EventSetsPanel_EventSetListBoxMouseMoved private void EventSetsPanel_EventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EventSetsPanel_EventSetListBoxMouseClicked EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(EventSetsPanel_EventSetListBox.getSelectedIndex()).longDescription()); if (evt.getClickCount() == 2) { AddEventSetSelection(); } }//GEN-LAST:event_EventSetsPanel_EventSetListBoxMouseClicked private void CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed SelectedCanonicizerList.clear(); UpdateSelectedCanonicizerListBox(); }//GEN-LAST:event_CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed private void CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_AddAllCanonicizersButtonActionPerformed try{ for (int i = 0; i < CanonicizerMasterList.size(); i++){ Canonicizer temp = CanonicizerMasterList.get(i).getClass().newInstance(); SelectedCanonicizerList.add(temp); } UpdateSelectedCanonicizerListBox(); } catch (Exception e){ System.out.println(e.getMessage()); } }//GEN-LAST:event_CanonicizersPanel_AddAllCanonicizersButtonActionPerformed private void CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed RemoveCanonicizerSelection(); }//GEN-LAST:event_CanonicizersPanel_RemoveCanonicizerButtonActionPerformed private void RemoveCanonicizerSelection() { SelectedCanonicizerList.remove(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex()); UpdateSelectedCanonicizerListBox(); } private void CanonicizersPanel_AddCanonicizerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed AddCanonicizerSelection(); }//GEN-LAST:event_CanonicizersPanel_AddCanonicizerButtonActionPerformed private void AddCanonicizerSelection() { try{ for (int i = 0; i < CanonicizerMasterList.size(); i++){ if (CanonicizerMasterList.get(i).displayName().equals(CanonicizersPanel_CanonicizerListBox.getSelectedValue().toString())){ Canonicizer temp = CanonicizerMasterList.get(i).getClass().newInstance(); SelectedCanonicizerList.add(temp); UpdateSelectedCanonicizerListBox(); } } } catch (Exception e){ System.out.println(e.getMessage()); } } private void CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = SelectedCanonicizerList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved private void CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(SelectedCanonicizerList.get(CanonicizersPanel_SelectedCanonicizerListBox.getSelectedIndex()).longDescription()); if (evt != null && evt.getClickCount() == 2) { RemoveCanonicizerSelection(); } }//GEN-LAST:event_CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked private void CanonicizersPanel_CanonicizerListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = CanonicizerMasterList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_CanonicizersPanel_CanonicizerListBoxMouseMoved private void CanonicizersPanel_CanonicizerListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setText(CanonicizerMasterList.get(CanonicizersPanel_CanonicizerListBox.getSelectedIndex()).longDescription()); if (evt.getClickCount() == 2) { AddCanonicizerSelection(); } }//GEN-LAST:event_CanonicizersPanel_CanonicizerListBoxMouseClicked private void DocumentsPanel_LanguageComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_LanguageComboBoxActionPerformed try { JGAAP_API.setLanguage(DocumentsPanel_LanguageComboBox.getSelectedItem().toString()); } catch (Exception e) { } }//GEN-LAST:event_DocumentsPanel_LanguageComboBoxActionPerformed private void DocumentsPanel_RemoveAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_RemoveAuthorButtonActionPerformed TreePath Path = DocumentsPanel_KnownAuthorsTree.getSelectionPath(); String AuthorName; if(Path.getPathCount() != 1) { AuthorName = Path.getPathComponent(1).toString(); KnownDocumentList = JGAAP_API.getDocumentsByAuthor(AuthorName); for (int i = KnownDocumentList.size() - 1; i >= 0; i--) { JGAAP_API.removeDocument(KnownDocumentList.get(i)); } UpdateKnownDocumentsTree(); } else { } }//GEN-LAST:event_DocumentsPanel_RemoveAuthorButtonActionPerformed private void DocumentsPanel_EditAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_EditAuthorButtonActionPerformed TreePath Path = DocumentsPanel_KnownAuthorsTree.getSelectionPath(); String AuthorName; if(Path.getPathCount() != 1) { AuthorName = Path.getPathComponent(1).toString(); JGAAP_UI_AddAuthorDialog AddAuthorDialog= new JGAAP_UI_AddAuthorDialog(JGAAP_UI_MainForm.this, true, JGAAP_API, AuthorName, filepath); AddAuthorDialog.setVisible(true); UpdateKnownDocumentsTree(); } else { } }//GEN-LAST:event_DocumentsPanel_EditAuthorButtonActionPerformed private void DocumentsPanel_AddAuthorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_AddAuthorButtonActionPerformed JGAAP_UI_AddAuthorDialog AddAuthorDialog= new JGAAP_UI_AddAuthorDialog(JGAAP_UI_MainForm.this, true, JGAAP_API,"",filepath); AddAuthorDialog.setVisible(true); filepath = AddAuthorDialog.getFilePath(); UpdateKnownDocumentsTree(); }//GEN-LAST:event_DocumentsPanel_AddAuthorButtonActionPerformed private void DocumentsPanel_RemoveDocumentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_RemoveDocumentsButtonActionPerformed UnknownDocumentList = JGAAP_API.getUnknownDocuments(); JGAAP_API.removeDocument(UnknownDocumentList.get(DocumentsPanel_UnknownAuthorsTable.getSelectedRow())); UpdateUnknownDocumentsTable(); }//GEN-LAST:event_DocumentsPanel_RemoveDocumentsButtonActionPerformed private void DocumentsPanel_AddDocumentsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_AddDocumentsButtonActionPerformed FileChoser = new JFileChooser(filepath); FileChoser.setMultiSelectionEnabled(true); int choice = FileChoser.showOpenDialog(JGAAP_UI_MainForm.this); if (choice == JFileChooser.APPROVE_OPTION) { for(File file : FileChoser.getSelectedFiles()){ try { JGAAP_API.addDocument(file.getCanonicalPath(), "",""); filepath = file.getCanonicalPath(); } catch (Exception e) { //TODO: add error dialog here } UpdateUnknownDocumentsTable(); } } }//GEN-LAST:event_DocumentsPanel_AddDocumentsButtonActionPerformed private void CanonicizersPanel_SetToDocumentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToDocumentButtonActionPerformed int row = CanonicizersPanel_DocumentsTable.getSelectedRow(); if (row >= 0) { DocumentList = JGAAP_API.getDocuments(); Document temp = DocumentList.get(row); temp.clearCanonicizers(); for (int i = 0; i < SelectedCanonicizerList.size(); i++) { try { JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName(),temp); } catch (Exception e) { } } UpdateCurrentCanonicizerBox(); UpdateDocumentsTable(); } }//GEN-LAST:event_CanonicizersPanel_SetToDocumentButtonActionPerformed private void CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToDocumentTypeButtonActionPerformed int row = CanonicizersPanel_DocumentsTable.getSelectedRow(); if (row >= 0) { DocumentList = JGAAP_API.getDocuments(); Document temp = DocumentList.get(row); temp.clearCanonicizers(); for (int i = 0; i < SelectedCanonicizerList.size(); i++) { try { JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName(),temp); } catch (Exception e) { } } UpdateCurrentCanonicizerBox(); UpdateDocumentsTable(); } }//GEN-LAST:event_CanonicizersPanel_SetToDocumentTypeButtonActionPerformed private void CanonicizersPanel_SetToAllDocumentsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_SetToAllDocumentsActionPerformed JGAAP_API.removeAllCanonicizers(); for (int i = 0; i < SelectedCanonicizerList.size(); i++) { try { JGAAP_API.addCanonicizer(SelectedCanonicizerList.get(i).displayName()); } catch (Exception e) { } } UpdateCurrentCanonicizerBox(); UpdateDocumentsTable(); }//GEN-LAST:event_CanonicizersPanel_SetToAllDocumentsActionPerformed private void DocumentsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DocumentsPanel_NotesButtonActionPerformed try { NotesPage.DisplayNote(Notes[0]); NotesPage.setVisible(true); if (NotesPage.SavedNote != null) { Notes[0] = NotesPage.SavedNote; } } catch (Exception e){ } }//GEN-LAST:event_DocumentsPanel_NotesButtonActionPerformed private void CanonicizersPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CanonicizersPanel_NotesButtonActionPerformed try { NotesPage.DisplayNote(Notes[1]); NotesPage.setVisible(true); if (NotesPage.SavedNote != null) { Notes[1] = NotesPage.SavedNote; } } catch (Exception e){ } }//GEN-LAST:event_CanonicizersPanel_NotesButtonActionPerformed private void EventSetsPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventSetsPanel_NotesButtonActionPerformed try { NotesPage.DisplayNote(Notes[2]); NotesPage.setVisible(true); if (NotesPage.SavedNote != null) { Notes[2] = NotesPage.SavedNote; } } catch (Exception e){ } }//GEN-LAST:event_EventSetsPanel_NotesButtonActionPerformed private void EventCullingPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCullingPanel_NotesButtonActionPerformed try { NotesPage.DisplayNote(Notes[3]); NotesPage.setVisible(true); if (NotesPage.SavedNote != null) { Notes[3] = NotesPage.SavedNote; } } catch (Exception e){ } }//GEN-LAST:event_EventCullingPanel_NotesButtonActionPerformed private void AnalysisMethodPanel_NotesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_NotesButtonActionPerformed try { NotesPage.DisplayNote(Notes[4]); NotesPage.setVisible(true); if (NotesPage.SavedNote != null) { Notes[4] = NotesPage.SavedNote; } } catch (Exception e){ } }//GEN-LAST:event_AnalysisMethodPanel_NotesButtonActionPerformed private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(AnalysisMethodPanel_DistanceFunctionsListBox.getSelectedIndex()).longDescription()); if (evt.getClickCount() == 2) { AddAnalysisMethodSelection(); } }//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked private void AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved JList theList = (JList) evt.getSource(); int index = theList.locationToIndex(evt.getPoint()); if (index > -1) { String text = DistanceFunctionsMasterList.get(index).tooltipText(); theList.setToolTipText(text); } }//GEN-LAST:event_AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved private void Next_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Next_ButtonActionPerformed int count = JGAAP_TabbedPane.getSelectedIndex(); if (count < 5) { JGAAP_TabbedPane.setSelectedIndex(count + 1); } }//GEN-LAST:event_Next_ButtonActionPerformed private void Review_ButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Review_ButtonActionPerformed JGAAP_TabbedPane.setSelectedIndex(5); }//GEN-LAST:event_Review_ButtonActionPerformed private void ProblemAMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemAMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadA.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemAMenuItemActionPerformed private void ProblemBMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemBMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadB.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemBMenuItemActionPerformed private void ProblemCMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemCMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadC.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemCMenuItemActionPerformed private void ProblemDMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemDMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadD.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemDMenuItemActionPerformed private void ProblemEMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemEMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadE.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemEMenuItemActionPerformed private void ProblemFMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemFMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadF.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemFMenuItemActionPerformed private void ProblemGMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemGMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadG.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemGMenuItemActionPerformed private void ProblemHMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemHMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadH.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemHMenuItemActionPerformed private void ProblemIMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemIMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadI.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemIMenuItemActionPerformed private void ProblemJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemJMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadJ.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemJMenuItemActionPerformed private void ProblemKMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemKMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadK.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemKMenuItemActionPerformed private void ProblemLMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemLMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadL.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemLMenuItemActionPerformed private void ProblemMMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ProblemMMenuItemActionPerformed try { filepath = jgaapConstants.docsDir()+"aaac/Demos/loadM.csv"; List<List<String>> DocumentCSVs = CSVIO.readCSV(filepath); for (int i = 0; i < DocumentCSVs.size(); i++) { JGAAP_API.addDocument(DocumentCSVs.get(i).get(1),DocumentCSVs.get(i).get(0),(DocumentCSVs.get(i).size()>2?DocumentCSVs.get(i).get(2):null)); } UpdateKnownDocumentsTree(); UpdateUnknownDocumentsTable(); } catch (Exception e) { } }//GEN-LAST:event_ProblemMMenuItemActionPerformed private void ReviewPanel_DocumentsLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_DocumentsLabelMouseClicked JGAAP_TabbedPane.setSelectedIndex(0); }//GEN-LAST:event_ReviewPanel_DocumentsLabelMouseClicked private void ReviewPanel_DocumentsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_DocumentsTableMouseClicked JGAAP_TabbedPane.setSelectedIndex(0); }//GEN-LAST:event_ReviewPanel_DocumentsTableMouseClicked private void ReviewPanel_SelectedEventSetLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventSetLabelMouseClicked JGAAP_TabbedPane.setSelectedIndex(2); }//GEN-LAST:event_ReviewPanel_SelectedEventSetLabelMouseClicked private void ReviewPanel_SelectedEventSetListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventSetListBoxMouseClicked JGAAP_TabbedPane.setSelectedIndex(2); }//GEN-LAST:event_ReviewPanel_SelectedEventSetListBoxMouseClicked private void ReviewPanel_SelectedEventCullingLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventCullingLabelMouseClicked JGAAP_TabbedPane.setSelectedIndex(3); }//GEN-LAST:event_ReviewPanel_SelectedEventCullingLabelMouseClicked private void ReviewPanel_SelectedEventCullingListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedEventCullingListBoxMouseClicked JGAAP_TabbedPane.setSelectedIndex(3); }//GEN-LAST:event_ReviewPanel_SelectedEventCullingListBoxMouseClicked private void ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked JGAAP_TabbedPane.setSelectedIndex(4); }//GEN-LAST:event_ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked private void ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked JGAAP_TabbedPane.setSelectedIndex(4); }//GEN-LAST:event_ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked private void toggleHelpDialog(){ helpDialog.setVisible(!helpDialog.isVisible()); } public boolean browseToURL(String url){ boolean succees = false; try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); succees = true; } catch (IOException ex) { ex.printStackTrace(); } return succees; } private void UpdateSelectedAnalysisMethodListBox() { SelectedAnalysisMethodListBox_Model.clear(); SelectedAnalysisDriverList = JGAAP_API.getAnalysisDrivers(); for (int i = 0; i < SelectedAnalysisDriverList.size(); i++) { SelectedAnalysisMethodListBox_Model.addElement(SelectedAnalysisDriverList.get(i).displayName()); } CheckMinimumRequirements(); if(!SelectedAnalysisDriverList.isEmpty()){ AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectedIndex(SelectedAnalysisDriverList.size()-1); AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(null); } } private void UpdateSelectedEventSetListBox() { SelectedEventSetsListBox_Model.clear(); SelectedEventDriverList = JGAAP_API.getEventDrivers(); for (int i = 0; i < SelectedEventDriverList.size(); i++) { SelectedEventSetsListBox_Model.addElement(SelectedEventDriverList.get(i).displayName()); } CheckMinimumRequirements(); if(!SelectedEventDriverList.isEmpty()){ EventSetsPanel_SelectedEventSetListBox.setSelectedIndex(SelectedEventDriverList.size()-1); EventSetsPanel_SelectedEventSetListBoxMouseClicked(null); } } private void UpdateSelectedEventCullingListBox() { SelectedEventCullingListBox_Model.clear(); SelectedEventCullersList = JGAAP_API.getEventCullers(); for (int i = 0; i < SelectedEventCullersList.size(); i++) { SelectedEventCullingListBox_Model.addElement(SelectedEventCullersList.get(i).displayName()); } if(!SelectedEventCullersList.isEmpty()){ EventCullingPanel_SelectedEventCullingListBox.setSelectedIndex(SelectedEventCullersList.size()-1); EventCullingPanel_SelectedEventCullingListBoxMouseClicked(null); } } private void UpdateSelectedCanonicizerListBox() { SelectedCanonicizerListBox_Model.clear(); for (int i = 0; i < SelectedCanonicizerList.size(); i++) { SelectedCanonicizerListBox_Model.addElement(SelectedCanonicizerList.get(i).displayName()); } if(!SelectedCanonicizerList.isEmpty()){ CanonicizersPanel_SelectedCanonicizerListBox.setSelectedIndex(SelectedCanonicizerList.size()-1); CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(null); } } private void UpdateUnknownDocumentsTable() { UnknownAuthorDocumentsTable_Model.setRowCount(0); UnknownDocumentList = JGAAP_API.getUnknownDocuments(); for (int i = 0; i < UnknownDocumentList.size(); i++) { Object RowData[] = {UnknownDocumentList.get(i).getTitle(), UnknownDocumentList.get(i).getFilePath()}; UnknownAuthorDocumentsTable_Model.addRow(RowData); } UpdateDocumentsTable(); } private void UpdateKnownDocumentsTree() { DefaultMutableTreeNode root = (DefaultMutableTreeNode) KnownAuthorsTree_Model.getRoot(); for (int i = root.getChildCount() - 1; i >= 0; i--) { KnownAuthorsTree_Model.removeNodeFromParent((DefaultMutableTreeNode)root.getChildAt(i)); } AuthorList = JGAAP_API.getAuthors(); for (int i = 0; i < AuthorList.size(); i++) { String AuthorName = AuthorList.get(i); DefaultMutableTreeNode author = new DefaultMutableTreeNode(AuthorName); KnownAuthorsTree_Model.insertNodeInto(author, root, i); //root.add(author); KnownDocumentList = JGAAP_API.getDocumentsByAuthor(AuthorName); for (int j = 0; j < KnownDocumentList.size(); j++) { //author.add(new DefaultMutableTreeNode(KnownDocumentList.get(j).getTitle() + " - " + KnownDocumentList.get(j).getFilePath())); DefaultMutableTreeNode temp = new DefaultMutableTreeNode(KnownDocumentList.get(j).getTitle() + " - " + KnownDocumentList.get(j).getFilePath()); KnownAuthorsTree_Model.insertNodeInto(temp, author, j); } } UpdateDocumentsTable(); } private void UpdateDocumentsTable() { String CanonPresent = "No"; DocumentsTable_Model.setRowCount(0); DocumentList = JGAAP_API.getDocuments(); for (int i = 0; i < DocumentList.size(); i++) { if (DocumentList.get(i).getCanonicizers().isEmpty()) { CanonPresent = "No"; } else { CanonPresent = "Yes"; } Object RowData[] = {DocumentList.get(i).getTitle(), DocumentList.get(i).isAuthorKnown(), DocumentList.get(i).getAuthor(), DocumentList.get(i).getDocType(), CanonPresent}; DocumentsTable_Model.addRow(RowData); } CheckMinimumRequirements(); } private void UpdateCurrentCanonicizerBox() { int row = CanonicizersPanel_DocumentsTable.getSelectedRow(); if (row >= 0) { DocumentList = JGAAP_API.getDocuments(); List<Canonicizer> tempList = DocumentList.get(row).getCanonicizers(); String tempString = ""; for (int i = 0; i < tempList.size(); i++) { tempString = tempString + tempList.get(i).displayName() + "\r\n"; } CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setText(tempString); } } private void SanatizeMasterLists() { for (int i = AnalysisDriverMasterList.size() - 1; i >= 0; i--) { if (!AnalysisDriverMasterList.get(i).showInGUI()) { AnalysisDriverMasterList.remove(i); } } for (int i = CanonicizerMasterList.size() - 1; i >= 0; i--) { if (!CanonicizerMasterList.get(i).showInGUI()) { CanonicizerMasterList.remove(i); } } for (int i = EventDriverMasterList.size() - 1; i >= 0; i--) { if (!EventDriverMasterList.get(i).showInGUI()) { EventDriverMasterList.remove(i); } } for (int i = EventCullersMasterList.size() - 1; i >= 0; i--) { if (!EventCullersMasterList.get(i).showInGUI()) { EventCullersMasterList.remove(i); } } for (int i = DistanceFunctionsMasterList.size() - 1; i >= 0; i--) { if (!DistanceFunctionsMasterList.get(i).showInGUI()) { DistanceFunctionsMasterList.remove(i); } } for (int i = LanguagesMasterList.size() - 1; i >= 0; i--) { if (!LanguagesMasterList.get(i).showInGUI()) { LanguagesMasterList.remove(i); } } } private void SetAnalysisMethodList() { for (int i = 0; i < AnalysisDriverMasterList.size(); i++) { AnalysisMethodListBox_Model.addElement(AnalysisDriverMasterList.get(i).displayName()); } if (!AnalysisDriverMasterList.isEmpty()) { AnalysisMethodPanel_AnalysisMethodsListBox.setSelectedIndex(0); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setText(AnalysisDriverMasterList.get(0).longDescription()); } } private void SetDistanceFunctionList() { for (int i = 0; i < DistanceFunctionsMasterList.size(); i++) { DistanceFunctionsListBox_Model.addElement(DistanceFunctionsMasterList.get(i).displayName()); } if (!DistanceFunctionsMasterList.isEmpty()) { AnalysisMethodPanel_DistanceFunctionsListBox.setSelectedIndex(0); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setText(DistanceFunctionsMasterList.get(0).longDescription()); } } private void SetCanonicizerList() { for (int i = 0; i < CanonicizerMasterList.size(); i++) { CanonicizerListBox_Model.addElement(CanonicizerMasterList.get(i).displayName()); } if (!CanonicizerMasterList.isEmpty()) { CanonicizersPanel_CanonicizerListBox.setSelectedIndex(0); //CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setText(CanonicizerMasterList.get(0).longDescription()); } } private void SetEventCullingList() { for (int i = 0; i < EventCullersMasterList.size(); i++) { EventCullingListBox_Model.addElement(EventCullersMasterList.get(i).displayName()); } if (!EventCullersMasterList.isEmpty()) { EventCullingPanel_EventCullingListBox.setSelectedIndex(0); EventCullingPanel_EventCullingDescriptionTextbox.setText(EventCullersMasterList.get(0).longDescription()); } } private void SetLanguagesList() { int englishIndex = -1; for (int i = 0; i < LanguagesMasterList.size(); i++) { LanguageComboBox_Model.addElement(LanguagesMasterList.get(i).displayName()); if (LanguagesMasterList.get(i).displayName().equalsIgnoreCase("English")) { englishIndex = i; } } if (englishIndex > -1) { DocumentsPanel_LanguageComboBox.setSelectedIndex(englishIndex); } } private void SetEventSetList() { for (int i = 0; i < EventDriverMasterList.size(); i++) { EventSetsListBox_Model.addElement(EventDriverMasterList.get(i).displayName()); } if (!EventDriverMasterList.isEmpty()) { EventSetsPanel_EventSetListBox.setSelectedIndex(0); EventSetsPanel_EventSetDescriptionTextBox.setText(EventDriverMasterList.get(0).longDescription()); } } private void SetUnknownDocumentColumns() { UnknownAuthorDocumentsTable_Model.addColumn("Title"); UnknownAuthorDocumentsTable_Model.addColumn("Filepath"); DocumentsPanel_UnknownAuthorsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(false); DocumentsPanel_UnknownAuthorsTable.setRowSelectionAllowed(true); DocumentsPanel_UnknownAuthorsTable.getModel().addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent e) { System.out.println("Unknown Documents Table Row: " + e.getFirstRow() + ", Column: " + e.getColumn()); if ((e.getColumn() >= 0) && (e.getFirstRow() >= 0)) { UnknownDocumentList = JGAAP_API.getUnknownDocuments(); if (e.getColumn() == 0) { UnknownDocumentList.get(e.getFirstRow()).setTitle((String)DocumentsPanel_UnknownAuthorsTable.getValueAt(e.getFirstRow(), 0)); } UpdateDocumentsTable(); } } }); } private void SetKnownDocumentTree() { DocumentsPanel_KnownAuthorsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true); } private void SetDocumentColumns() { DocumentsTable_Model.addColumn("Title"); DocumentsTable_Model.addColumn("Known"); DocumentsTable_Model.addColumn("Author"); DocumentsTable_Model.addColumn("Doc Type"); DocumentsTable_Model.addColumn("Canonicizers?"); CanonicizersPanel_DocumentsTable.setColumnSelectionAllowed(false); CanonicizersPanel_DocumentsTable.setRowSelectionAllowed(true); CanonicizersPanel_DocumentsTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { UpdateCurrentCanonicizerBox(); } }); } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JGAAP_UI_MainForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel AnalysisMethodPanel_AMParametersPanel; private javax.swing.JButton AnalysisMethodPanel_AddAllAnalysisMethodsButton; private javax.swing.JButton AnalysisMethodPanel_AddAnalysisMethodButton; private javax.swing.JTextArea AnalysisMethodPanel_AnalysisMethodDescriptionTextBox; private javax.swing.JList AnalysisMethodPanel_AnalysisMethodsListBox; private javax.swing.JPanel AnalysisMethodPanel_DFParametersPanel; private javax.swing.JTextArea AnalysisMethodPanel_DistanceFunctionDescriptionTextBox; private javax.swing.JList AnalysisMethodPanel_DistanceFunctionsListBox; private javax.swing.JButton AnalysisMethodPanel_NotesButton; private javax.swing.JButton AnalysisMethodPanel_RemoveAllAnalysisMethodsButton; private javax.swing.JButton AnalysisMethodPanel_RemoveAnalysisMethodsButton; private javax.swing.JList AnalysisMethodPanel_SelectedAnalysisMethodsListBox; private javax.swing.JMenuItem BatchLoadMenuItem; private javax.swing.JMenuItem BatchSaveMenuItem; private javax.swing.JButton CanonicizersPanel_AddAllCanonicizersButton; private javax.swing.JButton CanonicizersPanel_AddCanonicizerButton; private javax.swing.JList CanonicizersPanel_CanonicizerListBox; private javax.swing.JTextArea CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox; private javax.swing.JTextArea CanonicizersPanel_DocumentsCurrentCanonicizersTextBox; private javax.swing.JTable CanonicizersPanel_DocumentsTable; private javax.swing.JButton CanonicizersPanel_NotesButton; private javax.swing.JButton CanonicizersPanel_RemoveAllCanonicizersButton; private javax.swing.JButton CanonicizersPanel_RemoveCanonicizerButton; private javax.swing.JList CanonicizersPanel_SelectedCanonicizerListBox; private javax.swing.JButton CanonicizersPanel_SetToAllDocuments; private javax.swing.JButton CanonicizersPanel_SetToDocumentButton; private javax.swing.JButton CanonicizersPanel_SetToDocumentTypeButton; private javax.swing.JButton DocumentsPanel_AddAuthorButton; private javax.swing.JButton DocumentsPanel_AddDocumentsButton; private javax.swing.JButton DocumentsPanel_EditAuthorButton; private javax.swing.JTree DocumentsPanel_KnownAuthorsTree; private javax.swing.JComboBox DocumentsPanel_LanguageComboBox; private javax.swing.JButton DocumentsPanel_NotesButton; private javax.swing.JButton DocumentsPanel_RemoveAuthorButton; private javax.swing.JButton DocumentsPanel_RemoveDocumentsButton; private javax.swing.JTable DocumentsPanel_UnknownAuthorsTable; private javax.swing.JButton EventCullingPanel_AddAllEventCullingButton; private javax.swing.JButton EventCullingPanel_AddEventCullingButton; private javax.swing.JTextArea EventCullingPanel_EventCullingDescriptionTextbox; private javax.swing.JList EventCullingPanel_EventCullingListBox; private javax.swing.JButton EventCullingPanel_NotesButton; private javax.swing.JPanel EventCullingPanel_ParametersPanel; private javax.swing.JButton EventCullingPanel_RemoveAllEventCullingButton; private javax.swing.JButton EventCullingPanel_RemoveEventCullingButton; private javax.swing.JList EventCullingPanel_SelectedEventCullingListBox; private javax.swing.JButton EventSetsPanel_AddAllEventSetsButton; private javax.swing.JButton EventSetsPanel_AddEventSetButton; private javax.swing.JTextArea EventSetsPanel_EventSetDescriptionTextBox; private javax.swing.JList EventSetsPanel_EventSetListBox; private javax.swing.JButton EventSetsPanel_NotesButton; private javax.swing.JPanel EventSetsPanel_ParametersPanel; private javax.swing.JButton EventSetsPanel_RemoveAllEventSetsButton; private javax.swing.JButton EventSetsPanel_RemoveEventSetButton; private javax.swing.JList EventSetsPanel_SelectedEventSetListBox; private javax.swing.JPanel JGAAP_AnalysisMethodPanel; private javax.swing.JPanel JGAAP_CanonicizerPanel; private javax.swing.JPanel JGAAP_DocumentsPanel; private javax.swing.JPanel JGAAP_EventCullingPanel; private javax.swing.JPanel JGAAP_EventSetsPanel; private javax.swing.JMenuBar JGAAP_MenuBar; private javax.swing.JPanel JGAAP_ReviewPanel; private javax.swing.JTabbedPane JGAAP_TabbedPane; private javax.swing.JButton Next_Button; private javax.swing.JMenuItem ProblemAMenuItem; private javax.swing.JMenuItem ProblemBMenuItem; private javax.swing.JMenuItem ProblemCMenuItem; private javax.swing.JMenuItem ProblemDMenuItem; private javax.swing.JMenuItem ProblemEMenuItem; private javax.swing.JMenuItem ProblemFMenuItem; private javax.swing.JMenuItem ProblemGMenuItem; private javax.swing.JMenuItem ProblemHMenuItem; private javax.swing.JMenuItem ProblemIMenuItem; private javax.swing.JMenuItem ProblemJMenuItem; private javax.swing.JMenuItem ProblemKMenuItem; private javax.swing.JMenuItem ProblemLMenuItem; private javax.swing.JMenuItem ProblemMMenuItem; private javax.swing.JLabel ReviewPanel_DocumentsLabel; private javax.swing.JTable ReviewPanel_DocumentsTable; private javax.swing.JButton ReviewPanel_ProcessButton; private javax.swing.JLabel ReviewPanel_SelectedAnalysisMethodsLabel; private javax.swing.JList ReviewPanel_SelectedAnalysisMethodsListBox; private javax.swing.JLabel ReviewPanel_SelectedEventCullingLabel; private javax.swing.JList ReviewPanel_SelectedEventCullingListBox; private javax.swing.JLabel ReviewPanel_SelectedEventSetLabel; private javax.swing.JList ReviewPanel_SelectedEventSetListBox; private javax.swing.JButton Review_Button; private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JButton helpCloseButton; private javax.swing.JDialog helpDialog; private javax.swing.JMenu helpMenu; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenu jMenu4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane10; private javax.swing.JScrollPane jScrollPane11; private javax.swing.JScrollPane jScrollPane12; private javax.swing.JScrollPane jScrollPane13; private javax.swing.JScrollPane jScrollPane14; private javax.swing.JScrollPane jScrollPane15; private javax.swing.JScrollPane jScrollPane16; private javax.swing.JScrollPane jScrollPane17; private javax.swing.JScrollPane jScrollPane18; private javax.swing.JScrollPane jScrollPane19; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane20; private javax.swing.JScrollPane jScrollPane21; private javax.swing.JScrollPane jScrollPane22; private javax.swing.JScrollPane jScrollPane23; private javax.swing.JScrollPane jScrollPane24; private javax.swing.JScrollPane jScrollPane25; private javax.swing.JScrollPane jScrollPane26; private javax.swing.JScrollPane jScrollPane27; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane9; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { helpDialog = new javax.swing.JDialog(); helpCloseButton = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); JGAAP_TabbedPane = new javax.swing.JTabbedPane(); JGAAP_DocumentsPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree(); DocumentsPanel_AddDocumentsButton = new javax.swing.JButton(); DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton(); DocumentsPanel_AddAuthorButton = new javax.swing.JButton(); DocumentsPanel_EditAuthorButton = new javax.swing.JButton(); DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton(); DocumentsPanel_NotesButton = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox(); JGAAP_CanonicizerPanel = new javax.swing.JPanel(); CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton(); jLabel27 = new javax.swing.JLabel(); CanonicizersPanel_NotesButton = new javax.swing.JButton(); jScrollPane11 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea(); CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton(); CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton(); jScrollPane12 = new javax.swing.JScrollPane(); CanonicizersPanel_CanonicizerListBox = new javax.swing.JList(); jScrollPane13 = new javax.swing.JScrollPane(); CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList(); CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton(); jLabel31 = new javax.swing.JLabel(); jScrollPane20 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsTable = new javax.swing.JTable(); jScrollPane21 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea(); CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton(); CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton(); CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); JGAAP_EventSetsPanel = new javax.swing.JPanel(); EventSetsPanel_NotesButton = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jScrollPane9 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetListBox = new javax.swing.JList(); jScrollPane10 = new javax.swing.JScrollPane(); EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList(); EventSetsPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane6 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea(); EventSetsPanel_AddEventSetButton = new javax.swing.JButton(); EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton(); EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton(); EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton(); JGAAP_EventCullingPanel = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); EventCullingPanel_NotesButton = new javax.swing.JButton(); jScrollPane14 = new javax.swing.JScrollPane(); EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList(); EventCullingPanel_AddEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton(); EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane15 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingListBox = new javax.swing.JList(); jScrollPane16 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea(); jLabel18 = new javax.swing.JLabel(); JGAAP_AnalysisMethodPanel = new javax.swing.JPanel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); AnalysisMethodPanel_NotesButton = new javax.swing.JButton(); jScrollPane17 = new javax.swing.JScrollPane(); AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel(); jScrollPane18 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList(); jLabel28 = new javax.swing.JLabel(); jScrollPane19 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea(); jScrollPane22 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList(); jLabel35 = new javax.swing.JLabel(); jScrollPane23 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea(); jLabel36 = new javax.swing.JLabel(); AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel(); jLabel37 = new javax.swing.JLabel(); JGAAP_ReviewPanel = new javax.swing.JPanel(); ReviewPanel_ProcessButton = new javax.swing.JButton(); ReviewPanel_DocumentsLabel = new javax.swing.JLabel(); jScrollPane24 = new javax.swing.JScrollPane(); ReviewPanel_DocumentsTable = new javax.swing.JTable(); ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel(); ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel(); ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel(); jScrollPane25 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventSetListBox = new javax.swing.JList(); jScrollPane26 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList(); jScrollPane27 = new javax.swing.JScrollPane(); ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); Next_Button = new javax.swing.JButton(); Review_Button = new javax.swing.JButton(); JGAAP_MenuBar = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); BatchSaveMenuItem = new javax.swing.JMenuItem(); BatchLoadMenuItem = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); ProblemAMenuItem = new javax.swing.JMenuItem(); ProblemBMenuItem = new javax.swing.JMenuItem(); ProblemCMenuItem = new javax.swing.JMenuItem(); ProblemDMenuItem = new javax.swing.JMenuItem(); ProblemEMenuItem = new javax.swing.JMenuItem(); ProblemFMenuItem = new javax.swing.JMenuItem(); ProblemGMenuItem = new javax.swing.JMenuItem(); ProblemHMenuItem = new javax.swing.JMenuItem(); ProblemIMenuItem = new javax.swing.JMenuItem(); ProblemJMenuItem = new javax.swing.JMenuItem(); ProblemKMenuItem = new javax.swing.JMenuItem(); ProblemLMenuItem = new javax.swing.JMenuItem(); ProblemMMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); helpDialog.setTitle("About"); helpDialog.setMinimumSize(new java.awt.Dimension(520, 300)); helpDialog.setResizable(false); helpCloseButton.setText("close"); helpCloseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpCloseButtonActionPerformed(evt); } }); jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24)); jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel11.setText("JGAAP 5.0"); jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0"); jLabel13.setText("©2011 EVL lab"); jLabel23.setForeground(new java.awt.Color(0, 0, 255)); jLabel23.setText("http://evllabs.com"); jLabel23.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel23MouseClicked(evt); } }); jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N jLabel25.setForeground(new java.awt.Color(0, 0, 255)); jLabel25.setText("http://jgaap.com"); jLabel25.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel25MouseClicked(evt); } }); jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane()); helpDialog.getContentPane().setLayout(helpDialogLayout); helpDialogLayout.setHorizontalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addComponent(jLabel24) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel26)) .addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(199, 199, 199) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel23) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel13) .addComponent(jLabel25)))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); helpDialogLayout.setVerticalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel24) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11) .addGap(44, 44, 44))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel23) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel25) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(helpCloseButton) .addComponent(jLabel13)) .addContainerGap()) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("JGAAP"); JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel1.setText("Unknown Authors"); jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel2.setText("Known Authors"); DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model); DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN); DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true); DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable); DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model); DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true); jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree); DocumentsPanel_AddDocumentsButton.setText("Add Document"); DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_RemoveDocumentsButton.setText("Remove Document"); DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_AddAuthorButton.setLabel("Add Author"); DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddAuthorButtonActionPerformed(evt); } }); DocumentsPanel_EditAuthorButton.setLabel("Edit Author"); DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_EditAuthorButtonActionPerformed(evt); } }); DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author"); DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveAuthorButtonActionPerformed(evt); } }); DocumentsPanel_NotesButton.setLabel("Notes"); DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_NotesButtonActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel10.setText("Language"); DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model); DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_LanguageComboBoxActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel); JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout); JGAAP_DocumentsPanelLayout.setHorizontalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE) .addComponent(DocumentsPanel_NotesButton)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddDocumentsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveDocumentsButton)) .addComponent(jLabel2)) .addGap(512, 512, 512)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_EditAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveAuthorButton))) .addContainerGap()) ); JGAAP_DocumentsPanelLayout.setVerticalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(DocumentsPanel_NotesButton) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveDocumentsButton) .addComponent(DocumentsPanel_AddDocumentsButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveAuthorButton) .addComponent(DocumentsPanel_EditAuthorButton) .addComponent(DocumentsPanel_AddAuthorButton)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel); CanonicizersPanel_RemoveCanonicizerButton.setText("←"); CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt); } }); jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel27.setText("Documents"); CanonicizersPanel_NotesButton.setLabel("Notes"); CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_NotesButtonActionPerformed(evt); } }); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true); jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox); CanonicizersPanel_AddCanonicizerButton.setText("→"); CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt); } }); CanonicizersPanel_AddAllCanonicizersButton.setText("All"); CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt); } }); CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model); CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseMoved(evt); } }); jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox); CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model); CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt); } }); jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox); CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear"); CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt); } }); jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel31.setText("Document's Current Canonicizers"); CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model); jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true); jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox); CanonicizersPanel_SetToDocumentButton.setText("Set to Doc"); CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentButtonActionPerformed(evt); } }); CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type"); CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt); } }); CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs"); CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToAllDocumentsActionPerformed(evt); } }); jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel29.setText("Selected"); jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel30.setText("Canonicizers"); jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel32.setText("Canonicizer Description"); jLabel33.setText("Note: These buttons are used to add"); jLabel34.setText("selected canonicizers to documents."); javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel); JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout); JGAAP_CanonicizerPanelLayout.setHorizontalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel30) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addComponent(jLabel33) .addComponent(jLabel34)) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jLabel29) .addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel27) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE) .addComponent(CanonicizersPanel_NotesButton)))) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel32) .addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_CanonicizerPanelLayout.setVerticalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel27) .addComponent(jLabel30) .addComponent(jLabel29)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(CanonicizersPanel_NotesButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_AddCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_AddAllCanonicizersButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_SetToDocumentButton))) .addGap(6, 6, 6) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel33) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel34) .addGap(18, 18, 18)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_SetToDocumentTypeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel31) .addComponent(jLabel32)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel); EventSetsPanel_NotesButton.setLabel("Notes"); EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_NotesButtonActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel6.setText("Event Drivers"); jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel7.setText("Parameters"); jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel8.setText("Event Driver Description"); jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel9.setText("Selected"); EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model); EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseClicked(evt); } }); EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseMoved(evt); } }); jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox); EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt); } }); EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt); } }); jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox); EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel); EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout); EventSetsPanel_ParametersPanelLayout.setHorizontalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 344, Short.MAX_VALUE) ); EventSetsPanel_ParametersPanelLayout.setVerticalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventSetsPanel_EventSetDescriptionTextBox.setColumns(20); EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true); EventSetsPanel_EventSetDescriptionTextBox.setRows(5); EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true); jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox); EventSetsPanel_AddEventSetButton.setText("→"); EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddEventSetButtonActionPerformed(evt); } }); EventSetsPanel_RemoveEventSetButton.setText("←"); EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveEventSetButtonActionPerformed(evt); } }); EventSetsPanel_AddAllEventSetsButton.setText("All"); EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt); } }); EventSetsPanel_RemoveAllEventSetsButton.setText("Clear"); EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel); JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout); JGAAP_EventSetsPanelLayout.setHorizontalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE) .addComponent(EventSetsPanel_NotesButton)) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventSetsPanelLayout.setVerticalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jLabel9)) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(EventSetsPanel_NotesButton) .addComponent(jLabel7))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(EventSetsPanel_AddEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_AddAllEventSetsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveAllEventSetsButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel); jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel15.setText("Event Culling"); jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel16.setText("Parameters"); jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel17.setText("Selected"); EventCullingPanel_NotesButton.setLabel("Notes"); EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_NotesButtonActionPerformed(evt); } }); EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt); } }); jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox); EventCullingPanel_AddEventCullingButton.setText("→"); EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveEventCullingButton.setText("←"); EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_AddAllEventCullingButton.setText("All"); EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveAllEventCullingButton.setText("Clear"); EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel); EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout); EventCullingPanel_ParametersPanelLayout.setHorizontalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 343, Short.MAX_VALUE) ); EventCullingPanel_ParametersPanelLayout.setVerticalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model); EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseMoved(evt); } }); jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox); EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20); EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true); EventCullingPanel_EventCullingDescriptionTextbox.setRows(5); EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true); jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox); jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel18.setText("Event Culling Description"); javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel); JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout); JGAAP_EventCullingPanelLayout.setHorizontalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE) .addComponent(EventCullingPanel_NotesButton)) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventCullingPanelLayout.setVerticalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel17) .addComponent(jLabel16)) .addComponent(EventCullingPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(EventCullingPanel_AddEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_AddAllEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveAllEventCullingButton) .addGap(107, 107, 107))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel); jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel20.setText("Analysis Methods"); jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel21.setText("AM Parameters"); jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel22.setText("Selected"); AnalysisMethodPanel_NotesButton.setLabel("Notes"); AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_NotesButtonActionPerformed(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox); AnalysisMethodPanel_AddAnalysisMethodButton.setText("→"); AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("←"); AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All"); AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear"); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel); AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout); AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 125, Short.MAX_VALUE) ); AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model); AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox); jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel28.setText("Distance Function Description"); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true); jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox); AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model); AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt); } }); jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox); jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel35.setText("Distance Functions"); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true); jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox); jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel36.setText("Analysis Method Description"); AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel); AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout); AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 128, Short.MAX_VALUE) ); jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel37.setText("DF Parameters"); javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel); JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout); JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE) .addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE) .addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel22) .addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_NotesButton)) .addComponent(jLabel37))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel28) .addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_AnalysisMethodPanelLayout.setVerticalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22) .addComponent(AnalysisMethodPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel37) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton)) .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel35) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel28) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel); ReviewPanel_ProcessButton.setLabel("Process"); ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReviewPanel_ProcessButtonActionPerformed(evt); } }); ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_DocumentsLabel.setText("Documents"); ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsLabelMouseClicked(evt); } }); ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model); ReviewPanel_DocumentsTable.setEnabled(false); ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsTableMouseClicked(evt); } }); jScrollPane24.setViewportView(ReviewPanel_DocumentsTable); ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventSetLabel.setText("Event Driver"); ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventCullingLabel.setText("Event Culling"); ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingLabelMouseClicked(evt); } }); ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods"); ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventSetListBox.setEnabled(false); ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetListBoxMouseClicked(evt); } }); jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox); ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventCullingListBox.setEnabled(false); ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox); ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false); ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox); javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel); JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout); JGAAP_ReviewPanelLayout.setHorizontalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_ProcessButton) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ReviewPanel_SelectedEventSetLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_ReviewPanelLayout.setVerticalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(ReviewPanel_DocumentsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ReviewPanel_SelectedEventSetLabel) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ReviewPanel_ProcessButton) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel); Next_Button.setText("Next →"); Next_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Next_ButtonActionPerformed(evt); } }); Review_Button.setText("Finish & Review"); Review_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Review_ButtonActionPerformed(evt); } }); jMenu1.setText("File"); jMenu4.setText("Batch Documents"); BatchSaveMenuItem.setText("Save Documents"); BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchSaveMenuItemActionPerformed(evt); } }); jMenu4.add(BatchSaveMenuItem); BatchLoadMenuItem.setText("Load Documents"); BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchLoadMenuItemActionPerformed(evt); } }); jMenu4.add(BatchLoadMenuItem); jMenu1.add(jMenu4); jMenu2.setText("AAAC Problems"); ProblemAMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemBMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemCMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemDMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemEMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(KeyEvent.VK_E, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemFMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemGMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemHMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemIMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemJMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemKMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemLMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemMMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemAMenuItem.setText("Problem A"); ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemAMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemAMenuItem); ProblemBMenuItem.setText("Problem B"); ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemBMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemBMenuItem); ProblemCMenuItem.setText("Problem C"); ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemCMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemCMenuItem); ProblemDMenuItem.setText("Problem D"); ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemDMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemDMenuItem); ProblemEMenuItem.setText("Problem E"); ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemEMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemEMenuItem); ProblemFMenuItem.setText("Problem F"); ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemFMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemFMenuItem); ProblemGMenuItem.setText("Problem G"); ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemGMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemGMenuItem); ProblemHMenuItem.setText("Problem H"); ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemHMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemHMenuItem); ProblemIMenuItem.setText("Problem I"); ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemIMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemIMenuItem); ProblemJMenuItem.setText("Problem J"); ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemJMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemJMenuItem); ProblemKMenuItem.setText("Problem K"); ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemKMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemKMenuItem); ProblemLMenuItem.setText("Problem L"); ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemLMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemLMenuItem); ProblemMMenuItem.setText("Problem M"); ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemMMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemMMenuItem); jMenu1.add(jMenu2); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); jMenu1.add(exitMenuItem); JGAAP_MenuBar.add(jMenu1); helpMenu.setText("Help"); aboutMenuItem.setText("About.."); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); JGAAP_MenuBar.add(helpMenu); setJMenuBar(JGAAP_MenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(Review_Button) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Next_Button))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Next_Button) .addComponent(Review_Button)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { helpDialog = new javax.swing.JDialog(); helpCloseButton = new javax.swing.JButton(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel23 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel26 = new javax.swing.JLabel(); JGAAP_TabbedPane = new javax.swing.JTabbedPane(); JGAAP_DocumentsPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); DocumentsPanel_UnknownAuthorsTable = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); DocumentsPanel_KnownAuthorsTree = new javax.swing.JTree(); DocumentsPanel_AddDocumentsButton = new javax.swing.JButton(); DocumentsPanel_RemoveDocumentsButton = new javax.swing.JButton(); DocumentsPanel_AddAuthorButton = new javax.swing.JButton(); DocumentsPanel_EditAuthorButton = new javax.swing.JButton(); DocumentsPanel_RemoveAuthorButton = new javax.swing.JButton(); DocumentsPanel_NotesButton = new javax.swing.JButton(); jLabel10 = new javax.swing.JLabel(); DocumentsPanel_LanguageComboBox = new javax.swing.JComboBox(); JGAAP_CanonicizerPanel = new javax.swing.JPanel(); CanonicizersPanel_RemoveCanonicizerButton = new javax.swing.JButton(); jLabel27 = new javax.swing.JLabel(); CanonicizersPanel_NotesButton = new javax.swing.JButton(); jScrollPane11 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox = new javax.swing.JTextArea(); CanonicizersPanel_AddCanonicizerButton = new javax.swing.JButton(); CanonicizersPanel_AddAllCanonicizersButton = new javax.swing.JButton(); jScrollPane12 = new javax.swing.JScrollPane(); CanonicizersPanel_CanonicizerListBox = new javax.swing.JList(); jScrollPane13 = new javax.swing.JScrollPane(); CanonicizersPanel_SelectedCanonicizerListBox = new javax.swing.JList(); CanonicizersPanel_RemoveAllCanonicizersButton = new javax.swing.JButton(); jLabel31 = new javax.swing.JLabel(); jScrollPane20 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsTable = new javax.swing.JTable(); jScrollPane21 = new javax.swing.JScrollPane(); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox = new javax.swing.JTextArea(); CanonicizersPanel_SetToDocumentButton = new javax.swing.JButton(); CanonicizersPanel_SetToDocumentTypeButton = new javax.swing.JButton(); CanonicizersPanel_SetToAllDocuments = new javax.swing.JButton(); jLabel29 = new javax.swing.JLabel(); jLabel30 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); jLabel34 = new javax.swing.JLabel(); JGAAP_EventSetsPanel = new javax.swing.JPanel(); EventSetsPanel_NotesButton = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jScrollPane9 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetListBox = new javax.swing.JList(); jScrollPane10 = new javax.swing.JScrollPane(); EventSetsPanel_SelectedEventSetListBox = new javax.swing.JList(); EventSetsPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane6 = new javax.swing.JScrollPane(); EventSetsPanel_EventSetDescriptionTextBox = new javax.swing.JTextArea(); EventSetsPanel_AddEventSetButton = new javax.swing.JButton(); EventSetsPanel_RemoveEventSetButton = new javax.swing.JButton(); EventSetsPanel_AddAllEventSetsButton = new javax.swing.JButton(); EventSetsPanel_RemoveAllEventSetsButton = new javax.swing.JButton(); JGAAP_EventCullingPanel = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); EventCullingPanel_NotesButton = new javax.swing.JButton(); jScrollPane14 = new javax.swing.JScrollPane(); EventCullingPanel_SelectedEventCullingListBox = new javax.swing.JList(); EventCullingPanel_AddEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveEventCullingButton = new javax.swing.JButton(); EventCullingPanel_AddAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_RemoveAllEventCullingButton = new javax.swing.JButton(); EventCullingPanel_ParametersPanel = new javax.swing.JPanel(); jScrollPane15 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingListBox = new javax.swing.JList(); jScrollPane16 = new javax.swing.JScrollPane(); EventCullingPanel_EventCullingDescriptionTextbox = new javax.swing.JTextArea(); jLabel18 = new javax.swing.JLabel(); JGAAP_AnalysisMethodPanel = new javax.swing.JPanel(); jLabel20 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); AnalysisMethodPanel_NotesButton = new javax.swing.JButton(); jScrollPane17 = new javax.swing.JScrollPane(); AnalysisMethodPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); AnalysisMethodPanel_AddAnalysisMethodButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AddAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton = new javax.swing.JButton(); AnalysisMethodPanel_AMParametersPanel = new javax.swing.JPanel(); jScrollPane18 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodsListBox = new javax.swing.JList(); jLabel28 = new javax.swing.JLabel(); jScrollPane19 = new javax.swing.JScrollPane(); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox = new javax.swing.JTextArea(); jScrollPane22 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionsListBox = new javax.swing.JList(); jLabel35 = new javax.swing.JLabel(); jScrollPane23 = new javax.swing.JScrollPane(); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox = new javax.swing.JTextArea(); jLabel36 = new javax.swing.JLabel(); AnalysisMethodPanel_DFParametersPanel = new javax.swing.JPanel(); jLabel37 = new javax.swing.JLabel(); JGAAP_ReviewPanel = new javax.swing.JPanel(); ReviewPanel_ProcessButton = new javax.swing.JButton(); ReviewPanel_DocumentsLabel = new javax.swing.JLabel(); jScrollPane24 = new javax.swing.JScrollPane(); ReviewPanel_DocumentsTable = new javax.swing.JTable(); ReviewPanel_SelectedEventSetLabel = new javax.swing.JLabel(); ReviewPanel_SelectedEventCullingLabel = new javax.swing.JLabel(); ReviewPanel_SelectedAnalysisMethodsLabel = new javax.swing.JLabel(); jScrollPane25 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventSetListBox = new javax.swing.JList(); jScrollPane26 = new javax.swing.JScrollPane(); ReviewPanel_SelectedEventCullingListBox = new javax.swing.JList(); jScrollPane27 = new javax.swing.JScrollPane(); ReviewPanel_SelectedAnalysisMethodsListBox = new javax.swing.JList(); Next_Button = new javax.swing.JButton(); Review_Button = new javax.swing.JButton(); JGAAP_MenuBar = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu4 = new javax.swing.JMenu(); BatchSaveMenuItem = new javax.swing.JMenuItem(); BatchLoadMenuItem = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); ProblemAMenuItem = new javax.swing.JMenuItem(); ProblemBMenuItem = new javax.swing.JMenuItem(); ProblemCMenuItem = new javax.swing.JMenuItem(); ProblemDMenuItem = new javax.swing.JMenuItem(); ProblemEMenuItem = new javax.swing.JMenuItem(); ProblemFMenuItem = new javax.swing.JMenuItem(); ProblemGMenuItem = new javax.swing.JMenuItem(); ProblemHMenuItem = new javax.swing.JMenuItem(); ProblemIMenuItem = new javax.swing.JMenuItem(); ProblemJMenuItem = new javax.swing.JMenuItem(); ProblemKMenuItem = new javax.swing.JMenuItem(); ProblemLMenuItem = new javax.swing.JMenuItem(); ProblemMMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); aboutMenuItem = new javax.swing.JMenuItem(); helpDialog.setTitle("About"); helpDialog.setMinimumSize(new java.awt.Dimension(520, 300)); helpDialog.setResizable(false); helpCloseButton.setText("close"); helpCloseButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpCloseButtonActionPerformed(evt); } }); jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 24)); jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel11.setText("JGAAP 5.0"); jLabel12.setText("<html> JGAAP, the Java Graphical Authorship Attribution Program, <br/>is an opensource author attribution / text classification tool <br/>Developed by the EVL lab (Evaluating Variation in Language Labratory) <br/> Released by Patrick Juola under the GPL v3.0"); jLabel13.setText("©2011 EVL lab"); jLabel23.setForeground(new java.awt.Color(0, 0, 255)); jLabel23.setText("http://evllabs.com"); jLabel23.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel23MouseClicked(evt); } }); jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/jgaap_icon.png"))); // NOI18N jLabel25.setForeground(new java.awt.Color(0, 0, 255)); jLabel25.setText("http://jgaap.com"); jLabel25.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel25MouseClicked(evt); } }); jLabel26.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jgaap/ui/resources/EVLlab_icon.png"))); // NOI18N javax.swing.GroupLayout helpDialogLayout = new javax.swing.GroupLayout(helpDialog.getContentPane()); helpDialog.getContentPane().setLayout(helpDialogLayout); helpDialogLayout.setHorizontalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addComponent(jLabel24) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel26)) .addComponent(helpCloseButton, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(199, 199, 199) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel23) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel13) .addComponent(jLabel25)))) .addGroup(helpDialogLayout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); helpDialogLayout.setVerticalGroup( helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(helpDialogLayout.createSequentialGroup() .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel24) .addGroup(helpDialogLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel26, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, helpDialogLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11) .addGap(44, 44, 44))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel23) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel25) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE) .addGroup(helpDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(helpCloseButton) .addComponent(jLabel13)) .addContainerGap()) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("JGAAP"); JGAAP_TabbedPane.setName("JGAAP_TabbedPane"); // NOI18N jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel1.setText("Unknown Authors"); jLabel2.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel2.setText("Known Authors"); DocumentsPanel_UnknownAuthorsTable.setModel(UnknownAuthorDocumentsTable_Model); DocumentsPanel_UnknownAuthorsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN); DocumentsPanel_UnknownAuthorsTable.setColumnSelectionAllowed(true); DocumentsPanel_UnknownAuthorsTable.getTableHeader().setReorderingAllowed(false); jScrollPane1.setViewportView(DocumentsPanel_UnknownAuthorsTable); DocumentsPanel_UnknownAuthorsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); DocumentsPanel_KnownAuthorsTree.setModel(KnownAuthorsTree_Model); DocumentsPanel_KnownAuthorsTree.setShowsRootHandles(true); jScrollPane2.setViewportView(DocumentsPanel_KnownAuthorsTree); DocumentsPanel_AddDocumentsButton.setText("Add Document"); DocumentsPanel_AddDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_RemoveDocumentsButton.setText("Remove Document"); DocumentsPanel_RemoveDocumentsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveDocumentsButtonActionPerformed(evt); } }); DocumentsPanel_AddAuthorButton.setLabel("Add Author"); DocumentsPanel_AddAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_AddAuthorButtonActionPerformed(evt); } }); DocumentsPanel_EditAuthorButton.setLabel("Edit Author"); DocumentsPanel_EditAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_EditAuthorButtonActionPerformed(evt); } }); DocumentsPanel_RemoveAuthorButton.setLabel("Remove Author"); DocumentsPanel_RemoveAuthorButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_RemoveAuthorButtonActionPerformed(evt); } }); DocumentsPanel_NotesButton.setLabel("Notes"); DocumentsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_NotesButtonActionPerformed(evt); } }); jLabel10.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel10.setText("Language"); DocumentsPanel_LanguageComboBox.setModel(LanguageComboBox_Model); DocumentsPanel_LanguageComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { DocumentsPanel_LanguageComboBoxActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_DocumentsPanelLayout = new javax.swing.GroupLayout(JGAAP_DocumentsPanel); JGAAP_DocumentsPanel.setLayout(JGAAP_DocumentsPanelLayout); JGAAP_DocumentsPanelLayout.setHorizontalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 656, Short.MAX_VALUE) .addComponent(DocumentsPanel_NotesButton)) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddDocumentsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveDocumentsButton)) .addComponent(jLabel2)) .addGap(512, 512, 512)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(DocumentsPanel_AddAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_EditAuthorButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_RemoveAuthorButton))) .addContainerGap()) ); JGAAP_DocumentsPanelLayout.setVerticalGroup( JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(DocumentsPanel_NotesButton) .addGroup(JGAAP_DocumentsPanelLayout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(DocumentsPanel_LanguageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveDocumentsButton) .addComponent(DocumentsPanel_AddDocumentsButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_DocumentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(DocumentsPanel_RemoveAuthorButton) .addComponent(DocumentsPanel_EditAuthorButton) .addComponent(DocumentsPanel_AddAuthorButton)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Documents", JGAAP_DocumentsPanel); CanonicizersPanel_RemoveCanonicizerButton.setText("←"); CanonicizersPanel_RemoveCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveCanonicizerButtonActionPerformed(evt); } }); jLabel27.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel27.setText("Documents"); CanonicizersPanel_NotesButton.setLabel("Notes"); CanonicizersPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_NotesButtonActionPerformed(evt); } }); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setColumns(20); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setRows(5); CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox.setWrapStyleWord(true); jScrollPane11.setViewportView(CanonicizersPanel_DocumentsCanonicizerDescriptionTextBox); CanonicizersPanel_AddCanonicizerButton.setText("→"); CanonicizersPanel_AddCanonicizerButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddCanonicizerButtonActionPerformed(evt); } }); CanonicizersPanel_AddAllCanonicizersButton.setText("All"); CanonicizersPanel_AddAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_AddAllCanonicizersButtonActionPerformed(evt); } }); CanonicizersPanel_CanonicizerListBox.setModel(CanonicizerListBox_Model); CanonicizersPanel_CanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_CanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_CanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_CanonicizerListBoxMouseMoved(evt); } }); jScrollPane12.setViewportView(CanonicizersPanel_CanonicizerListBox); CanonicizersPanel_SelectedCanonicizerListBox.setModel(SelectedCanonicizerListBox_Model); CanonicizersPanel_SelectedCanonicizerListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); CanonicizersPanel_SelectedCanonicizerListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseClicked(evt); } }); CanonicizersPanel_SelectedCanonicizerListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { CanonicizersPanel_SelectedCanonicizerListBoxMouseMoved(evt); } }); jScrollPane13.setViewportView(CanonicizersPanel_SelectedCanonicizerListBox); CanonicizersPanel_RemoveAllCanonicizersButton.setText("Clear"); CanonicizersPanel_RemoveAllCanonicizersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_RemoveAllCanonicizersButtonActionPerformed(evt); } }); jLabel31.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel31.setText("Document's Current Canonicizers"); CanonicizersPanel_DocumentsTable.setModel(DocumentsTable_Model); jScrollPane20.setViewportView(CanonicizersPanel_DocumentsTable); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setColumns(20); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setLineWrap(true); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setRows(5); CanonicizersPanel_DocumentsCurrentCanonicizersTextBox.setWrapStyleWord(true); jScrollPane21.setViewportView(CanonicizersPanel_DocumentsCurrentCanonicizersTextBox); CanonicizersPanel_SetToDocumentButton.setText("Set to Doc"); CanonicizersPanel_SetToDocumentButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentButtonActionPerformed(evt); } }); CanonicizersPanel_SetToDocumentTypeButton.setText("Set to Doc Type"); CanonicizersPanel_SetToDocumentTypeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToDocumentTypeButtonActionPerformed(evt); } }); CanonicizersPanel_SetToAllDocuments.setText("Set to All Docs"); CanonicizersPanel_SetToAllDocuments.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { CanonicizersPanel_SetToAllDocumentsActionPerformed(evt); } }); jLabel29.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel29.setText("Selected"); jLabel30.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel30.setText("Canonicizers"); jLabel32.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel32.setText("Canonicizer Description"); jLabel33.setText("Note: These buttons are used to add"); jLabel34.setText("selected canonicizers to documents."); javax.swing.GroupLayout JGAAP_CanonicizerPanelLayout = new javax.swing.GroupLayout(JGAAP_CanonicizerPanel); JGAAP_CanonicizerPanel.setLayout(JGAAP_CanonicizerPanelLayout); JGAAP_CanonicizerPanelLayout.setHorizontalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel30) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(CanonicizersPanel_AddCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveCanonicizerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_AddAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)) .addComponent(jLabel33) .addComponent(jLabel34)) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(CanonicizersPanel_SetToDocumentTypeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jLabel29) .addComponent(CanonicizersPanel_SetToDocumentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(jScrollPane13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel27) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 255, Short.MAX_VALUE) .addComponent(CanonicizersPanel_NotesButton)))) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane21, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel32) .addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_CanonicizerPanelLayout.setVerticalGroup( JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel27) .addComponent(jLabel30) .addComponent(jLabel29)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(CanonicizersPanel_NotesButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane20, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_AddCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveCanonicizerButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_AddAllCanonicizersButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_RemoveAllCanonicizersButton)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane13, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE) .addComponent(jScrollPane12, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(CanonicizersPanel_SetToDocumentButton))) .addGap(6, 6, 6) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(jLabel33) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel34) .addGap(18, 18, 18)) .addGroup(JGAAP_CanonicizerPanelLayout.createSequentialGroup() .addComponent(CanonicizersPanel_SetToDocumentTypeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(CanonicizersPanel_SetToAllDocuments))))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel31) .addComponent(jLabel32)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_CanonicizerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane21, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Canonicizers", JGAAP_CanonicizerPanel); EventSetsPanel_NotesButton.setLabel("Notes"); EventSetsPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_NotesButtonActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel6.setText("Event Drivers"); jLabel7.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel7.setText("Parameters"); jLabel8.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel8.setText("Event Driver Description"); jLabel9.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel9.setText("Selected"); EventSetsPanel_EventSetListBox.setModel(EventSetsListBox_Model); EventSetsPanel_EventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_EventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseClicked(evt); } }); EventSetsPanel_EventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_EventSetListBoxMouseMoved(evt); } }); jScrollPane9.setViewportView(EventSetsPanel_EventSetListBox); EventSetsPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); EventSetsPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventSetsPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseClicked(evt); } }); EventSetsPanel_SelectedEventSetListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventSetsPanel_SelectedEventSetListBoxMouseMoved(evt); } }); jScrollPane10.setViewportView(EventSetsPanel_SelectedEventSetListBox); EventSetsPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventSetsPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventSetsPanel_ParametersPanel); EventSetsPanel_ParametersPanel.setLayout(EventSetsPanel_ParametersPanelLayout); EventSetsPanel_ParametersPanelLayout.setHorizontalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 344, Short.MAX_VALUE) ); EventSetsPanel_ParametersPanelLayout.setVerticalGroup( EventSetsPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventSetsPanel_EventSetDescriptionTextBox.setColumns(20); EventSetsPanel_EventSetDescriptionTextBox.setLineWrap(true); EventSetsPanel_EventSetDescriptionTextBox.setRows(5); EventSetsPanel_EventSetDescriptionTextBox.setWrapStyleWord(true); jScrollPane6.setViewportView(EventSetsPanel_EventSetDescriptionTextBox); EventSetsPanel_AddEventSetButton.setText("→"); EventSetsPanel_AddEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddEventSetButtonActionPerformed(evt); } }); EventSetsPanel_RemoveEventSetButton.setText("←"); EventSetsPanel_RemoveEventSetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveEventSetButtonActionPerformed(evt); } }); EventSetsPanel_AddAllEventSetsButton.setText("All"); EventSetsPanel_AddAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_AddAllEventSetsButtonActionPerformed(evt); } }); EventSetsPanel_RemoveAllEventSetsButton.setText("Clear"); EventSetsPanel_RemoveAllEventSetsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventSetsPanel_RemoveAllEventSetsButtonActionPerformed(evt); } }); javax.swing.GroupLayout JGAAP_EventSetsPanelLayout = new javax.swing.GroupLayout(JGAAP_EventSetsPanel); JGAAP_EventSetsPanel.setLayout(JGAAP_EventSetsPanelLayout); JGAAP_EventSetsPanelLayout.setHorizontalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventSetsPanel_RemoveEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddAllEventSetsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_AddEventSetButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventSetsPanel_RemoveAllEventSetsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9) .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE) .addComponent(EventSetsPanel_NotesButton)) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventSetsPanelLayout.setVerticalGroup( JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jLabel9)) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(EventSetsPanel_NotesButton) .addComponent(jLabel7))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventSetsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EventSetsPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane10, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventSetsPanelLayout.createSequentialGroup() .addComponent(EventSetsPanel_AddEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveEventSetButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_AddAllEventSetsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventSetsPanel_RemoveAllEventSetsButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Drivers", JGAAP_EventSetsPanel); jLabel15.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel15.setText("Event Culling"); jLabel16.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel16.setText("Parameters"); jLabel17.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel17.setText("Selected"); EventCullingPanel_NotesButton.setLabel("Notes"); EventCullingPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_NotesButtonActionPerformed(evt); } }); EventCullingPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); EventCullingPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_SelectedEventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_SelectedEventCullingListBoxMouseMoved(evt); } }); jScrollPane14.setViewportView(EventCullingPanel_SelectedEventCullingListBox); EventCullingPanel_AddEventCullingButton.setText("→"); EventCullingPanel_AddEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveEventCullingButton.setText("←"); EventCullingPanel_RemoveEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_AddAllEventCullingButton.setText("All"); EventCullingPanel_AddAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_AddAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_RemoveAllEventCullingButton.setText("Clear"); EventCullingPanel_RemoveAllEventCullingButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EventCullingPanel_RemoveAllEventCullingButtonActionPerformed(evt); } }); EventCullingPanel_ParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout EventCullingPanel_ParametersPanelLayout = new javax.swing.GroupLayout(EventCullingPanel_ParametersPanel); EventCullingPanel_ParametersPanel.setLayout(EventCullingPanel_ParametersPanelLayout); EventCullingPanel_ParametersPanelLayout.setHorizontalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 343, Short.MAX_VALUE) ); EventCullingPanel_ParametersPanelLayout.setVerticalGroup( EventCullingPanel_ParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); EventCullingPanel_EventCullingListBox.setModel(EventCullingListBox_Model); EventCullingPanel_EventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); EventCullingPanel_EventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseClicked(evt); } }); EventCullingPanel_EventCullingListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { EventCullingPanel_EventCullingListBoxMouseMoved(evt); } }); jScrollPane15.setViewportView(EventCullingPanel_EventCullingListBox); EventCullingPanel_EventCullingDescriptionTextbox.setColumns(20); EventCullingPanel_EventCullingDescriptionTextbox.setLineWrap(true); EventCullingPanel_EventCullingDescriptionTextbox.setRows(5); EventCullingPanel_EventCullingDescriptionTextbox.setWrapStyleWord(true); jScrollPane16.setViewportView(EventCullingPanel_EventCullingDescriptionTextbox); jLabel18.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel18.setText("Event Culling Description"); javax.swing.GroupLayout JGAAP_EventCullingPanelLayout = new javax.swing.GroupLayout(JGAAP_EventCullingPanel); JGAAP_EventCullingPanel.setLayout(JGAAP_EventCullingPanelLayout); JGAAP_EventCullingPanelLayout.setHorizontalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane16, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(jLabel18, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane15, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(EventCullingPanel_RemoveEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddAllEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_AddEventCullingButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(EventCullingPanel_RemoveAllEventCullingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jScrollPane14, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE) .addComponent(EventCullingPanel_NotesButton)) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_EventCullingPanelLayout.setVerticalGroup( JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(jLabel17) .addComponent(jLabel16)) .addComponent(EventCullingPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_EventCullingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addComponent(EventCullingPanel_ParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane15, javax.swing.GroupLayout.DEFAULT_SIZE, 304, Short.MAX_VALUE) .addGroup(JGAAP_EventCullingPanelLayout.createSequentialGroup() .addComponent(EventCullingPanel_AddEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_AddAllEventCullingButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(EventCullingPanel_RemoveAllEventCullingButton) .addGap(107, 107, 107))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane16, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Event Culling", JGAAP_EventCullingPanel); jLabel20.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel20.setText("Analysis Methods"); jLabel21.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel21.setText("AM Parameters"); jLabel22.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel22.setText("Selected"); AnalysisMethodPanel_NotesButton.setLabel("Notes"); AnalysisMethodPanel_NotesButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_NotesButtonActionPerformed(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_SelectedAnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_SelectedAnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane17.setViewportView(AnalysisMethodPanel_SelectedAnalysisMethodsListBox); AnalysisMethodPanel_AddAnalysisMethodButton.setText("→"); AnalysisMethodPanel_AddAnalysisMethodButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAnalysisMethodButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAnalysisMethodsButton.setText("←"); AnalysisMethodPanel_RemoveAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AddAllAnalysisMethodsButton.setText("All"); AnalysisMethodPanel_AddAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_AddAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.setText("Clear"); AnalysisMethodPanel_RemoveAllAnalysisMethodsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnalysisMethodPanel_RemoveAllAnalysisMethodsButtonActionPerformed(evt); } }); AnalysisMethodPanel_AMParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_AMParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_AMParametersPanel); AnalysisMethodPanel_AMParametersPanel.setLayout(AnalysisMethodPanel_AMParametersPanelLayout); AnalysisMethodPanel_AMParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_AMParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_AMParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 125, Short.MAX_VALUE) ); AnalysisMethodPanel_AnalysisMethodsListBox.setModel(AnalysisMethodListBox_Model); AnalysisMethodPanel_AnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_AnalysisMethodsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_AnalysisMethodsListBoxMouseMoved(evt); } }); jScrollPane18.setViewportView(AnalysisMethodPanel_AnalysisMethodsListBox); jLabel28.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel28.setText("Distance Function Description"); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setColumns(20); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setRows(5); AnalysisMethodPanel_AnalysisMethodDescriptionTextBox.setWrapStyleWord(true); jScrollPane19.setViewportView(AnalysisMethodPanel_AnalysisMethodDescriptionTextBox); AnalysisMethodPanel_DistanceFunctionsListBox.setModel(DistanceFunctionsListBox_Model); AnalysisMethodPanel_DistanceFunctionsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseClicked(evt); } }); AnalysisMethodPanel_DistanceFunctionsListBox.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { AnalysisMethodPanel_DistanceFunctionsListBoxMouseMoved(evt); } }); jScrollPane22.setViewportView(AnalysisMethodPanel_DistanceFunctionsListBox); jLabel35.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel35.setText("Distance Functions"); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setColumns(20); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setLineWrap(true); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setRows(5); AnalysisMethodPanel_DistanceFunctionDescriptionTextBox.setWrapStyleWord(true); jScrollPane23.setViewportView(AnalysisMethodPanel_DistanceFunctionDescriptionTextBox); jLabel36.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N jLabel36.setText("Analysis Method Description"); AnalysisMethodPanel_DFParametersPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout AnalysisMethodPanel_DFParametersPanelLayout = new javax.swing.GroupLayout(AnalysisMethodPanel_DFParametersPanel); AnalysisMethodPanel_DFParametersPanel.setLayout(AnalysisMethodPanel_DFParametersPanelLayout); AnalysisMethodPanel_DFParametersPanelLayout.setHorizontalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 355, Short.MAX_VALUE) ); AnalysisMethodPanel_DFParametersPanelLayout.setVerticalGroup( AnalysisMethodPanel_DFParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 128, Short.MAX_VALUE) ); jLabel37.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); jLabel37.setText("DF Parameters"); javax.swing.GroupLayout JGAAP_AnalysisMethodPanelLayout = new javax.swing.GroupLayout(JGAAP_AnalysisMethodPanel); JGAAP_AnalysisMethodPanel.setLayout(JGAAP_AnalysisMethodPanelLayout); JGAAP_AnalysisMethodPanelLayout.setHorizontalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel35, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane22, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE) .addComponent(jScrollPane18, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE) .addComponent(jLabel20, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel22) .addComponent(jScrollPane17, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(jLabel21) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 133, Short.MAX_VALUE) .addComponent(AnalysisMethodPanel_NotesButton)) .addComponent(jLabel37))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel28) .addComponent(jScrollPane23, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_AnalysisMethodPanelLayout.setVerticalGroup( JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(jLabel21) .addComponent(jLabel22) .addComponent(AnalysisMethodPanel_NotesButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane17, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AMParametersPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel37) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_DFParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_AnalysisMethodPanelLayout.createSequentialGroup() .addComponent(AnalysisMethodPanel_AddAnalysisMethodButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_AddAllAnalysisMethodsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(AnalysisMethodPanel_RemoveAllAnalysisMethodsButton)) .addComponent(jScrollPane18, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel35) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane22, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel28) .addComponent(jLabel36)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_AnalysisMethodPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane19, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane23, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Analysis Methods", JGAAP_AnalysisMethodPanel); ReviewPanel_ProcessButton.setLabel("Process"); ReviewPanel_ProcessButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ReviewPanel_ProcessButtonActionPerformed(evt); } }); ReviewPanel_DocumentsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_DocumentsLabel.setText("Documents"); ReviewPanel_DocumentsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsLabelMouseClicked(evt); } }); ReviewPanel_DocumentsTable.setModel(DocumentsTable_Model); ReviewPanel_DocumentsTable.setEnabled(false); ReviewPanel_DocumentsTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_DocumentsTableMouseClicked(evt); } }); jScrollPane24.setViewportView(ReviewPanel_DocumentsTable); ReviewPanel_SelectedEventSetLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventSetLabel.setText("Event Driver"); ReviewPanel_SelectedEventSetLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventCullingLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedEventCullingLabel.setText("Event Culling"); ReviewPanel_SelectedEventCullingLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingLabelMouseClicked(evt); } }); ReviewPanel_SelectedAnalysisMethodsLabel.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 24)); // NOI18N ReviewPanel_SelectedAnalysisMethodsLabel.setText("Analysis Methods"); ReviewPanel_SelectedAnalysisMethodsLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsLabelMouseClicked(evt); } }); ReviewPanel_SelectedEventSetListBox.setModel(SelectedEventSetsListBox_Model); ReviewPanel_SelectedEventSetListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventSetListBox.setEnabled(false); ReviewPanel_SelectedEventSetListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventSetListBoxMouseClicked(evt); } }); jScrollPane25.setViewportView(ReviewPanel_SelectedEventSetListBox); ReviewPanel_SelectedEventCullingListBox.setModel(SelectedEventCullingListBox_Model); ReviewPanel_SelectedEventCullingListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedEventCullingListBox.setEnabled(false); ReviewPanel_SelectedEventCullingListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedEventCullingListBoxMouseClicked(evt); } }); jScrollPane26.setViewportView(ReviewPanel_SelectedEventCullingListBox); ReviewPanel_SelectedAnalysisMethodsListBox.setModel(SelectedAnalysisMethodListBox_Model); ReviewPanel_SelectedAnalysisMethodsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); ReviewPanel_SelectedAnalysisMethodsListBox.setEnabled(false); ReviewPanel_SelectedAnalysisMethodsListBox.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ReviewPanel_SelectedAnalysisMethodsListBoxMouseClicked(evt); } }); jScrollPane27.setViewportView(ReviewPanel_SelectedAnalysisMethodsListBox); javax.swing.GroupLayout JGAAP_ReviewPanelLayout = new javax.swing.GroupLayout(JGAAP_ReviewPanel); JGAAP_ReviewPanel.setLayout(JGAAP_ReviewPanelLayout); JGAAP_ReviewPanelLayout.setHorizontalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane24, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 824, Short.MAX_VALUE) .addComponent(ReviewPanel_DocumentsLabel, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_ProcessButton) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, JGAAP_ReviewPanelLayout.createSequentialGroup() .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane25, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ReviewPanel_SelectedEventSetLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(jScrollPane26, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)))) .addContainerGap()) ); JGAAP_ReviewPanelLayout.setVerticalGroup( JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(JGAAP_ReviewPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(ReviewPanel_DocumentsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane24, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ReviewPanel_SelectedEventSetLabel) .addComponent(ReviewPanel_SelectedEventCullingLabel) .addComponent(ReviewPanel_SelectedAnalysisMethodsLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(JGAAP_ReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane27, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane26, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE) .addComponent(jScrollPane25, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(ReviewPanel_ProcessButton) .addContainerGap()) ); JGAAP_TabbedPane.addTab("Review & Process", JGAAP_ReviewPanel); Next_Button.setText("Next →"); Next_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Next_ButtonActionPerformed(evt); } }); Review_Button.setText("Finish & Review"); Review_Button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Review_ButtonActionPerformed(evt); } }); jMenu1.setText("File"); jMenu4.setText("Batch Documents"); BatchSaveMenuItem.setText("Save Documents"); BatchSaveMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchSaveMenuItemActionPerformed(evt); } }); jMenu4.add(BatchSaveMenuItem); BatchLoadMenuItem.setText("Load Documents"); BatchLoadMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BatchLoadMenuItemActionPerformed(evt); } }); jMenu4.add(BatchLoadMenuItem); jMenu1.add(jMenu4); jMenu2.setText("AAAC Problems"); ProblemAMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemBMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemCMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemDMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_D, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemEMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(KeyEvent.VK_E, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemFMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemGMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemHMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemIMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemJMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemKMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemLMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemMMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, (java.awt.event.InputEvent.CTRL_MASK) | InputEvent.SHIFT_MASK)); ProblemAMenuItem.setText("Problem A"); ProblemAMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemAMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemAMenuItem); ProblemBMenuItem.setText("Problem B"); ProblemBMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemBMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemBMenuItem); ProblemCMenuItem.setText("Problem C"); ProblemCMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemCMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemCMenuItem); ProblemDMenuItem.setText("Problem D"); ProblemDMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemDMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemDMenuItem); ProblemEMenuItem.setText("Problem E"); ProblemEMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemEMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemEMenuItem); ProblemFMenuItem.setText("Problem F"); ProblemFMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemFMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemFMenuItem); ProblemGMenuItem.setText("Problem G"); ProblemGMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemGMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemGMenuItem); ProblemHMenuItem.setText("Problem H"); ProblemHMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemHMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemHMenuItem); ProblemIMenuItem.setText("Problem I"); ProblemIMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemIMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemIMenuItem); ProblemJMenuItem.setText("Problem J"); ProblemJMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemJMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemJMenuItem); ProblemKMenuItem.setText("Problem K"); ProblemKMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemKMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemKMenuItem); ProblemLMenuItem.setText("Problem L"); ProblemLMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemLMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemLMenuItem); ProblemMMenuItem.setText("Problem M"); ProblemMMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ProblemMMenuItemActionPerformed(evt); } }); jMenu2.add(ProblemMMenuItem); jMenu1.add(jMenu2); exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); jMenu1.add(exitMenuItem); JGAAP_MenuBar.add(jMenu1); helpMenu.setText("Help"); aboutMenuItem.setText("About.."); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aboutMenuItemActionPerformed(evt); } }); helpMenu.add(aboutMenuItem); JGAAP_MenuBar.add(helpMenu); setJMenuBar(JGAAP_MenuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 849, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(Review_Button) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Next_Button))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(JGAAP_TabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, 529, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Next_Button) .addComponent(Review_Button)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/GPS.java b/src/GPS.java index 8415a1b..a85f7a8 100644 --- a/src/GPS.java +++ b/src/GPS.java @@ -1,139 +1,139 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author jonathan */ public class GPS extends Mod { /** * * NOTE: The player's coordinate map like this: * X-value: Latitude (north-south) * Y-value: Altitude * Z-value: Longitude (east-west) * * @param player * @param command * @param isAdmin * @return boolean */ protected boolean parseCommand(Player player, String[] tokens) { String command = tokens[0].substring(1); if(command.equalsIgnoreCase("gps")) { Player target; if( tokens.length > 1 ) { target = Server.getPlayer(tokens[1]); } else { target = player; } this.getCoordinates(player, target); return true; } return false; } @Override public String toString() { return "!gps"; } @Override public boolean onPlayerCommand(Player player, String[] command) { return this.parseCommand(player, command); } @Override public boolean onPlayerChat(Player player, String command) { String[] tokens = command.split(" "); return this.parseCommand(player, tokens); } protected String generateOrientation(Float degrees) { degrees = (degrees+270)%360; String textDirection = ""; // Determine North/South facing. if( degrees <= 78.75 || degrees > 281.25 ) { textDirection = "N"; } else if( degrees > 101.25 && degrees <= 258.75 ) { textDirection = "S"; } // Determine East/West facing. if (degrees > 11.25 && degrees <= 168.75 ) { textDirection += "E"; } else if( degrees > 190.25 && degrees <= 348.75 ) { textDirection += "W"; } // Determine Additional north/east/south/west facing for 3-letter precision. if( (degrees > 326.25 || degrees <= 33.75) && !textDirection.equalsIgnoreCase("N") ) { textDirection = "N"+textDirection; } else if( (degrees > 56.25 && degrees <= 123.75) && !textDirection.equalsIgnoreCase("E") ) { textDirection = "E"+textDirection; } else if( (degrees > 146.25 && degrees <= 213.75) && !textDirection.equalsIgnoreCase("S") ) { textDirection = "S"+textDirection; } else if( (degrees > 236.25 && degrees <= 303.75) && !textDirection.equalsIgnoreCase("W") ) { textDirection = "W"+textDirection; } String directionPadding = ""; if( textDirection.length() < 2 ) directionPadding += '_'; if( textDirection.length() < 3 ) directionPadding += '_'; - return String.format("%s(%s\u00A7d%s\u00A77) %s\u00A7d%.1f\u00A7f", + return String.format("(%s\u00A7d%s\u00A77) %s\u00A7d%.1f\u00A7f", directionPadding, textDirection, this.getDegreesPadding((double)degrees), degrees ); } protected String generateLatitude(Double degrees) { return String.format("\u00A77%s\u00A7a%.1f %s\u00A7f", this.getDegreesPadding(Math.abs(degrees)), Math.abs(degrees), (degrees<0?"N":degrees>0?"S":"") ); } protected String generateLongitude(Double degrees) { return String.format("\u00A77%s\u00A7a%.1f %s\u00A7f", this.getDegreesPadding(Math.abs(degrees)), Math.abs(degrees), (degrees<0?"E":degrees>0?"W":"") ); } protected String generateAltitude(Double altitude) { return Color.LightGray + this.getDegreesPadding(altitude) + Color.DarkPurple + String.format("%.0f", altitude) + Color.LightGray + "m" + Color.White; } protected String getDegreesPadding(Double degrees) { String padding = ""; if( degrees < 100 ) padding += "0"; if( degrees < 10 ) padding += "0"; return padding; } protected void getCoordinates(Player player, Player target) { Location loc = target.getLocation(); Double altitude = loc.getY(); String playerLabel = ""; if( player.getUniqueId() != target.getUniqueId() ) { playerLabel = String.format("\u00A77%s:\u00A7f ", target.getName()); } player.sendChat(String.format( "%s\u00A77Loc:[ %s\u00A77, %s\u00A77 ] Facing:[ %s\u00A77 ] Alt:[ %s\u00A77 ]", playerLabel, this.generateLatitude(loc.getX()), this.generateLongitude(loc.getZ()), this.generateOrientation(target.getRotation()), this.generateAltitude(loc.getY()) )); } }
true
true
protected String generateOrientation(Float degrees) { degrees = (degrees+270)%360; String textDirection = ""; // Determine North/South facing. if( degrees <= 78.75 || degrees > 281.25 ) { textDirection = "N"; } else if( degrees > 101.25 && degrees <= 258.75 ) { textDirection = "S"; } // Determine East/West facing. if (degrees > 11.25 && degrees <= 168.75 ) { textDirection += "E"; } else if( degrees > 190.25 && degrees <= 348.75 ) { textDirection += "W"; } // Determine Additional north/east/south/west facing for 3-letter precision. if( (degrees > 326.25 || degrees <= 33.75) && !textDirection.equalsIgnoreCase("N") ) { textDirection = "N"+textDirection; } else if( (degrees > 56.25 && degrees <= 123.75) && !textDirection.equalsIgnoreCase("E") ) { textDirection = "E"+textDirection; } else if( (degrees > 146.25 && degrees <= 213.75) && !textDirection.equalsIgnoreCase("S") ) { textDirection = "S"+textDirection; } else if( (degrees > 236.25 && degrees <= 303.75) && !textDirection.equalsIgnoreCase("W") ) { textDirection = "W"+textDirection; } String directionPadding = ""; if( textDirection.length() < 2 ) directionPadding += '_'; if( textDirection.length() < 3 ) directionPadding += '_'; return String.format("%s(%s\u00A7d%s\u00A77) %s\u00A7d%.1f\u00A7f", directionPadding, textDirection, this.getDegreesPadding((double)degrees), degrees ); }
protected String generateOrientation(Float degrees) { degrees = (degrees+270)%360; String textDirection = ""; // Determine North/South facing. if( degrees <= 78.75 || degrees > 281.25 ) { textDirection = "N"; } else if( degrees > 101.25 && degrees <= 258.75 ) { textDirection = "S"; } // Determine East/West facing. if (degrees > 11.25 && degrees <= 168.75 ) { textDirection += "E"; } else if( degrees > 190.25 && degrees <= 348.75 ) { textDirection += "W"; } // Determine Additional north/east/south/west facing for 3-letter precision. if( (degrees > 326.25 || degrees <= 33.75) && !textDirection.equalsIgnoreCase("N") ) { textDirection = "N"+textDirection; } else if( (degrees > 56.25 && degrees <= 123.75) && !textDirection.equalsIgnoreCase("E") ) { textDirection = "E"+textDirection; } else if( (degrees > 146.25 && degrees <= 213.75) && !textDirection.equalsIgnoreCase("S") ) { textDirection = "S"+textDirection; } else if( (degrees > 236.25 && degrees <= 303.75) && !textDirection.equalsIgnoreCase("W") ) { textDirection = "W"+textDirection; } String directionPadding = ""; if( textDirection.length() < 2 ) directionPadding += '_'; if( textDirection.length() < 3 ) directionPadding += '_'; return String.format("(%s\u00A7d%s\u00A77) %s\u00A7d%.1f\u00A7f", directionPadding, textDirection, this.getDegreesPadding((double)degrees), degrees ); }
diff --git a/platform-core/plugins/org.eclipse.core.filesystem.ftp/src/org/eclipse/core/internal/filesystem/ftp/FTPUtil.java b/platform-core/plugins/org.eclipse.core.filesystem.ftp/src/org/eclipse/core/internal/filesystem/ftp/FTPUtil.java index e9439019..ecf5d851 100644 --- a/platform-core/plugins/org.eclipse.core.filesystem.ftp/src/org/eclipse/core/internal/filesystem/ftp/FTPUtil.java +++ b/platform-core/plugins/org.eclipse.core.filesystem.ftp/src/org/eclipse/core/internal/filesystem/ftp/FTPUtil.java @@ -1,77 +1,77 @@ /******************************************************************************* * Copyright (c) 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.core.internal.filesystem.ftp; import java.net.URL; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.provider.FileInfo; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.ftp.*; /** * */ public class FTPUtil { private static final ThreadLocal openClients = new ThreadLocal(); public static IClient createClient(URL url) throws FtpException { IClient client = Ftp.createClient(url); client.setDataTransferMode(IClient.PASSIVE_DATA_TRANSFER, true); client.setAuthentication(KeyRing.USER, KeyRing.PASS); client.setTimeout(5); return client; } public static IClient getClient() { return (IClient) openClients.get(); } /** * Use this method to ensure that the same connection is used for multiple commands * issued from the same thread. * @throws FtpException */ public static void run(URL url, IFtpRunnable runnable, IProgressMonitor monitor) throws FtpException { monitor = Policy.monitorFor(monitor); IClient openClient = (IClient) openClients.get(); - monitor.beginTask(null, 100); + monitor.beginTask("", 100); //if the wrong client is connected, disconnect before trying again if (openClient != null && !openClient.getUrl().equals(url)) { openClient.close(new SubProgressMonitor(monitor, 0)); openClient = null; } if (openClient == null) { openClient = createClient(url); openClient.open(new SubProgressMonitor(monitor, 5)); openClient.changeDirectory(url.getPath(), new SubProgressMonitor(monitor, 5)); openClients.set(openClient); } runnable.run(new SubProgressMonitor(monitor, 90)); //just leave the client open to reuse the connection } /** * Converts a directory entry to a file info * @param entry * @return The file information for a directory entry */ public static IFileInfo entryToFileInfo(IDirectoryEntry entry) { FileInfo info = new FileInfo(); info.setExists(true); info.setName(entry.getName()); info.setLastModified(entry.getModTime().getTime()); info.setLength(entry.getSize()); info.setDirectory(entry.hasDirectorySemantics()); return info; } }
true
true
public static void run(URL url, IFtpRunnable runnable, IProgressMonitor monitor) throws FtpException { monitor = Policy.monitorFor(monitor); IClient openClient = (IClient) openClients.get(); monitor.beginTask(null, 100); //if the wrong client is connected, disconnect before trying again if (openClient != null && !openClient.getUrl().equals(url)) { openClient.close(new SubProgressMonitor(monitor, 0)); openClient = null; } if (openClient == null) { openClient = createClient(url); openClient.open(new SubProgressMonitor(monitor, 5)); openClient.changeDirectory(url.getPath(), new SubProgressMonitor(monitor, 5)); openClients.set(openClient); } runnable.run(new SubProgressMonitor(monitor, 90)); //just leave the client open to reuse the connection }
public static void run(URL url, IFtpRunnable runnable, IProgressMonitor monitor) throws FtpException { monitor = Policy.monitorFor(monitor); IClient openClient = (IClient) openClients.get(); monitor.beginTask("", 100); //if the wrong client is connected, disconnect before trying again if (openClient != null && !openClient.getUrl().equals(url)) { openClient.close(new SubProgressMonitor(monitor, 0)); openClient = null; } if (openClient == null) { openClient = createClient(url); openClient.open(new SubProgressMonitor(monitor, 5)); openClient.changeDirectory(url.getPath(), new SubProgressMonitor(monitor, 5)); openClients.set(openClient); } runnable.run(new SubProgressMonitor(monitor, 90)); //just leave the client open to reuse the connection }
diff --git a/quaketables2/webapp/WEB-INF/classes/edu/usc/sirlab/kml/KMLMapGenerator.java b/quaketables2/webapp/WEB-INF/classes/edu/usc/sirlab/kml/KMLMapGenerator.java index 6ada126..8614ca3 100644 --- a/quaketables2/webapp/WEB-INF/classes/edu/usc/sirlab/kml/KMLMapGenerator.java +++ b/quaketables2/webapp/WEB-INF/classes/edu/usc/sirlab/kml/KMLMapGenerator.java @@ -1,184 +1,187 @@ package edu.usc.sirlab.kml; import java.io.IOException; import java.sql.SQLException; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import edu.usc.sirlab.*; import edu.usc.sirlab.db.*; public class KMLMapGenerator extends HttpServlet { private static final long serialVersionUID = 1L; private static final String KML_CONTENT_TYPE = "application/vnd.google-earth.kml+xml"; private static final String DEFAULT_FILENAME_PREFIX = "QuakeTables-Query"; private static final String DEFAULT_FILENAME_SUFFIX = ".kml"; //private static final String KML_CONTENT_TYPE = "application/vnd.google-earth.kmz"; //private static final String KML_CONTENT_TYPE = "text/plain"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DatabaseQuery dbQuery; HttpSession session = request.getSession(true); KMLDocument kml = new KMLDocument(); String fileName = DEFAULT_FILENAME_PREFIX + DEFAULT_FILENAME_SUFFIX; int countInSAR = 0, countFault = 0, datasetCount = 0; try { if(session.getAttribute("dbQuery") == null) { dbQuery = new DatabaseQuery(); session.setAttribute("dbQuery", dbQuery); } else dbQuery = (DatabaseQuery) session.getAttribute("dbQuery"); //Look for DataSet requests if(request.getParameterValues("ds") != null && request.getParameterValues("fid") == null) { String[] dss = request.getParameterValues("ds"); if(dss.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null) { datasetCount++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 3); else style = new LineStyle("lineStyle", 3); kml.addStyle(style); if(dataset.getDataType().equalsIgnoreCase("cgs_fault")) { List<CGSFault> faults = dbQuery.getCGSFaults(dataset.getId()); for(CGSFault f : faults) { if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(f); dataset.addFaultKML(qsf.getKMLPlacemark(style)); } + else { + dataset.addFaultKML(f.getKMLPlacemark(style)); + } } } kml.addFolder(dataset.getKMLFolder()); kml.setName(dataset.getTitle()); kml.setDescription(dataset.getDescription()); } } else { //multiple data sets } } //Look for InSAR interferograms if(request.getParameterValues("iid") != null) { String[] iids = request.getParameterValues("iid"); boolean placeOverlay = true; if(request.getParameter("ov") != null) placeOverlay = false; if(iids.length == 1) { if(iids[0].equalsIgnoreCase("all")) { List<Interferogram> insar = dbQuery.getInerferograms(); fileName = "QuakeSim_InSAR.kml"; for(Interferogram i : insar) { countInSAR++; //kml.addFolder(i.getKMLPlacemark()); kml.addFolder(i.getKMLFolder(placeOverlay)); kml.setName("QuakeSim InSAR Map View"); kml.setDescription("QuakeSim InSAR Interferogram Map from QuakeTables"); } } else { Interferogram insar = dbQuery.getInerferogram(iids[0]); if(insar != null) { countInSAR++; fileName = insar.getDataURL().substring(insar.getDataURL().lastIndexOf('/') + 1) + ".kml"; kml.addFolder(insar.getKMLFolder(placeOverlay)); kml.setName(insar.getTitle()); kml.setDescription(insar.getDescription()); } } } else { for(String iid : iids) { Interferogram insar = dbQuery.getInerferogram(iid); if(insar == null) continue; countInSAR++; kml.addFolder(insar.getKMLFolder(placeOverlay)); } } } //Look for Faults if(request.getParameterValues("ds") != null && request.getParameter("fid") != null) { String[] dss = request.getParameterValues("ds"); String[] fids = request.getParameterValues("fid"); if(dss.length == 1 && fids.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null && dataset.getDataType().equalsIgnoreCase("cgs_fault")) { CGSFault fault = dbQuery.getCGSFault(dataset.getId(), fids[0]); if(fault != null) { countFault++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + "_" + fault.getId() + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 4); else style = new LineStyle("lineStyle", 4); kml.addStyle(style); boolean placemark = false; if(request.getParameter("mark") != null && request.getParameter("mark").equalsIgnoreCase("true")) placemark = true; if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(fault); kml.addFolder(qsf.getKMLFolder(style, placemark)); } else kml.addFolder(fault.getKMLFolder(style, placemark)); kml.setName(fault.getName()); kml.setDescription("QuakeTables Fault Query on " + new Date()); } } } else { //do for multiple faults } } if(countInSAR != 0 || countFault != 0 || datasetCount != 0) { response.setContentType(KML_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); ServletOutputStream out = response.getOutputStream(); out.println(kml.getKMLDocument()); out.flush(); } else response.sendRedirect("index.jsp"); }catch (SQLException e) { }catch (ClassNotFoundException e) { }catch(InstantiationException e) { }catch(IllegalAccessException e) {} } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DatabaseQuery dbQuery; HttpSession session = request.getSession(true); KMLDocument kml = new KMLDocument(); String fileName = DEFAULT_FILENAME_PREFIX + DEFAULT_FILENAME_SUFFIX; int countInSAR = 0, countFault = 0, datasetCount = 0; try { if(session.getAttribute("dbQuery") == null) { dbQuery = new DatabaseQuery(); session.setAttribute("dbQuery", dbQuery); } else dbQuery = (DatabaseQuery) session.getAttribute("dbQuery"); //Look for DataSet requests if(request.getParameterValues("ds") != null && request.getParameterValues("fid") == null) { String[] dss = request.getParameterValues("ds"); if(dss.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null) { datasetCount++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 3); else style = new LineStyle("lineStyle", 3); kml.addStyle(style); if(dataset.getDataType().equalsIgnoreCase("cgs_fault")) { List<CGSFault> faults = dbQuery.getCGSFaults(dataset.getId()); for(CGSFault f : faults) { if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(f); dataset.addFaultKML(qsf.getKMLPlacemark(style)); } } } kml.addFolder(dataset.getKMLFolder()); kml.setName(dataset.getTitle()); kml.setDescription(dataset.getDescription()); } } else { //multiple data sets } } //Look for InSAR interferograms if(request.getParameterValues("iid") != null) { String[] iids = request.getParameterValues("iid"); boolean placeOverlay = true; if(request.getParameter("ov") != null) placeOverlay = false; if(iids.length == 1) { if(iids[0].equalsIgnoreCase("all")) { List<Interferogram> insar = dbQuery.getInerferograms(); fileName = "QuakeSim_InSAR.kml"; for(Interferogram i : insar) { countInSAR++; //kml.addFolder(i.getKMLPlacemark()); kml.addFolder(i.getKMLFolder(placeOverlay)); kml.setName("QuakeSim InSAR Map View"); kml.setDescription("QuakeSim InSAR Interferogram Map from QuakeTables"); } } else { Interferogram insar = dbQuery.getInerferogram(iids[0]); if(insar != null) { countInSAR++; fileName = insar.getDataURL().substring(insar.getDataURL().lastIndexOf('/') + 1) + ".kml"; kml.addFolder(insar.getKMLFolder(placeOverlay)); kml.setName(insar.getTitle()); kml.setDescription(insar.getDescription()); } } } else { for(String iid : iids) { Interferogram insar = dbQuery.getInerferogram(iid); if(insar == null) continue; countInSAR++; kml.addFolder(insar.getKMLFolder(placeOverlay)); } } } //Look for Faults if(request.getParameterValues("ds") != null && request.getParameter("fid") != null) { String[] dss = request.getParameterValues("ds"); String[] fids = request.getParameterValues("fid"); if(dss.length == 1 && fids.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null && dataset.getDataType().equalsIgnoreCase("cgs_fault")) { CGSFault fault = dbQuery.getCGSFault(dataset.getId(), fids[0]); if(fault != null) { countFault++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + "_" + fault.getId() + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 4); else style = new LineStyle("lineStyle", 4); kml.addStyle(style); boolean placemark = false; if(request.getParameter("mark") != null && request.getParameter("mark").equalsIgnoreCase("true")) placemark = true; if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(fault); kml.addFolder(qsf.getKMLFolder(style, placemark)); } else kml.addFolder(fault.getKMLFolder(style, placemark)); kml.setName(fault.getName()); kml.setDescription("QuakeTables Fault Query on " + new Date()); } } } else { //do for multiple faults } } if(countInSAR != 0 || countFault != 0 || datasetCount != 0) { response.setContentType(KML_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); ServletOutputStream out = response.getOutputStream(); out.println(kml.getKMLDocument()); out.flush(); } else response.sendRedirect("index.jsp"); }catch (SQLException e) { }catch (ClassNotFoundException e) { }catch(InstantiationException e) { }catch(IllegalAccessException e) {} }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DatabaseQuery dbQuery; HttpSession session = request.getSession(true); KMLDocument kml = new KMLDocument(); String fileName = DEFAULT_FILENAME_PREFIX + DEFAULT_FILENAME_SUFFIX; int countInSAR = 0, countFault = 0, datasetCount = 0; try { if(session.getAttribute("dbQuery") == null) { dbQuery = new DatabaseQuery(); session.setAttribute("dbQuery", dbQuery); } else dbQuery = (DatabaseQuery) session.getAttribute("dbQuery"); //Look for DataSet requests if(request.getParameterValues("ds") != null && request.getParameterValues("fid") == null) { String[] dss = request.getParameterValues("ds"); if(dss.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null) { datasetCount++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 3); else style = new LineStyle("lineStyle", 3); kml.addStyle(style); if(dataset.getDataType().equalsIgnoreCase("cgs_fault")) { List<CGSFault> faults = dbQuery.getCGSFaults(dataset.getId()); for(CGSFault f : faults) { if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(f); dataset.addFaultKML(qsf.getKMLPlacemark(style)); } else { dataset.addFaultKML(f.getKMLPlacemark(style)); } } } kml.addFolder(dataset.getKMLFolder()); kml.setName(dataset.getTitle()); kml.setDescription(dataset.getDescription()); } } else { //multiple data sets } } //Look for InSAR interferograms if(request.getParameterValues("iid") != null) { String[] iids = request.getParameterValues("iid"); boolean placeOverlay = true; if(request.getParameter("ov") != null) placeOverlay = false; if(iids.length == 1) { if(iids[0].equalsIgnoreCase("all")) { List<Interferogram> insar = dbQuery.getInerferograms(); fileName = "QuakeSim_InSAR.kml"; for(Interferogram i : insar) { countInSAR++; //kml.addFolder(i.getKMLPlacemark()); kml.addFolder(i.getKMLFolder(placeOverlay)); kml.setName("QuakeSim InSAR Map View"); kml.setDescription("QuakeSim InSAR Interferogram Map from QuakeTables"); } } else { Interferogram insar = dbQuery.getInerferogram(iids[0]); if(insar != null) { countInSAR++; fileName = insar.getDataURL().substring(insar.getDataURL().lastIndexOf('/') + 1) + ".kml"; kml.addFolder(insar.getKMLFolder(placeOverlay)); kml.setName(insar.getTitle()); kml.setDescription(insar.getDescription()); } } } else { for(String iid : iids) { Interferogram insar = dbQuery.getInerferogram(iid); if(insar == null) continue; countInSAR++; kml.addFolder(insar.getKMLFolder(placeOverlay)); } } } //Look for Faults if(request.getParameterValues("ds") != null && request.getParameter("fid") != null) { String[] dss = request.getParameterValues("ds"); String[] fids = request.getParameterValues("fid"); if(dss.length == 1 && fids.length == 1) { FaultDataSet dataset = dbQuery.getFaultDataSet(dss[0]); if(dataset != null && dataset.getDataType().equalsIgnoreCase("cgs_fault")) { CGSFault fault = dbQuery.getCGSFault(dataset.getId(), fids[0]); if(fault != null) { countFault++; fileName = "QuakeTables_" + dataset.getNickName().replace(' ', '_') + "_" + fault.getId() + ".kml"; LineStyle style; if(request.getParameter("color") != null && request.getParameter("color").length() == 8) style = new LineStyle("lineStyle", request.getParameter("color"), 4); else style = new LineStyle("lineStyle", 4); kml.addStyle(style); boolean placemark = false; if(request.getParameter("mark") != null && request.getParameter("mark").equalsIgnoreCase("true")) placemark = true; if(request.getParameter("f") != null && request.getParameter("f").equalsIgnoreCase("qt")) { QuakeSimFault qsf = new QuakeSimFault(fault); kml.addFolder(qsf.getKMLFolder(style, placemark)); } else kml.addFolder(fault.getKMLFolder(style, placemark)); kml.setName(fault.getName()); kml.setDescription("QuakeTables Fault Query on " + new Date()); } } } else { //do for multiple faults } } if(countInSAR != 0 || countFault != 0 || datasetCount != 0) { response.setContentType(KML_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); ServletOutputStream out = response.getOutputStream(); out.println(kml.getKMLDocument()); out.flush(); } else response.sendRedirect("index.jsp"); }catch (SQLException e) { }catch (ClassNotFoundException e) { }catch(InstantiationException e) { }catch(IllegalAccessException e) {} }
diff --git a/src/amidst/gui/VersionSelectWindow.java b/src/amidst/gui/VersionSelectWindow.java index cd29849..5f2d5c4 100644 --- a/src/amidst/gui/VersionSelectWindow.java +++ b/src/amidst/gui/VersionSelectWindow.java @@ -1,103 +1,102 @@ package amidst.gui; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import MoF.FinderWindow; import amidst.Amidst; import amidst.Util; import amidst.json.InstallInformation; import amidst.json.LauncherProfile; import amidst.logging.Log; import amidst.minecraft.Minecraft; import amidst.resources.ResourceLoader; import com.google.gson.Gson; public class VersionSelectWindow extends JFrame { public VersionSelectWindow() { setIconImage(Amidst.icon); File profileJsonFile = new File(Util.minecraftDirectory + "/launcher_profiles.json"); Object[] profileArray = null; try { LauncherProfile profile = Util.readObject(profileJsonFile, LauncherProfile.class); // TODO This should use latest, not a preset version. profile.profiles.put("(Default)", new InstallInformation("(Default) ", "1.7.4")); profileArray = profile.profiles.values().toArray(); } catch (Exception e) { // TODO This is a very broad exception to catch for e.printStackTrace(); dispose(); try { new Minecraft(); new FinderWindow(); - } catch (IOException e1) { - // TODO Figure out what to do with this exception - e1.printStackTrace(); + } catch (MalformedURLException e1) { + Log.crash(e1, "MalformedURLException when creating Minecraft object."); } return; // TODO Do stuff here } addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); final JComboBox profileBox = new JComboBox(profileArray); profileBox.selectWithKeyChar('('); JButton btnConfirm = new JButton("Okay"); this.setLayout(new GridLayout(3,1)); getContentPane().add(new JLabel(" Multiple profiles detected, please select one.")); getContentPane().add(profileBox); getContentPane().add(btnConfirm); final JFrame window = this; btnConfirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Amidst.installInformation = (InstallInformation)profileBox.getSelectedItem(); boolean isValid = Amidst.installInformation.validate(); if (!isValid) { Log.e("\"Latest\" profile option detected, but there was an issue loading the version list.\nUsing alternative jar."); } else { try { new Minecraft(); } catch (MalformedURLException e1) { Log.crash(e1, "MalformedURLException when creating Minecraft object."); } window.dispose(); new FinderWindow(); } } }); getRootPane().setDefaultButton(btnConfirm); btnConfirm.requestFocus(); setTitle("Temporary profile selector"); setSize(300, 100); setLocation(200, 200); setVisible(true); } }
true
true
public VersionSelectWindow() { setIconImage(Amidst.icon); File profileJsonFile = new File(Util.minecraftDirectory + "/launcher_profiles.json"); Object[] profileArray = null; try { LauncherProfile profile = Util.readObject(profileJsonFile, LauncherProfile.class); // TODO This should use latest, not a preset version. profile.profiles.put("(Default)", new InstallInformation("(Default) ", "1.7.4")); profileArray = profile.profiles.values().toArray(); } catch (Exception e) { // TODO This is a very broad exception to catch for e.printStackTrace(); dispose(); try { new Minecraft(); new FinderWindow(); } catch (IOException e1) { // TODO Figure out what to do with this exception e1.printStackTrace(); } return; // TODO Do stuff here } addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); final JComboBox profileBox = new JComboBox(profileArray); profileBox.selectWithKeyChar('('); JButton btnConfirm = new JButton("Okay"); this.setLayout(new GridLayout(3,1)); getContentPane().add(new JLabel(" Multiple profiles detected, please select one.")); getContentPane().add(profileBox); getContentPane().add(btnConfirm); final JFrame window = this; btnConfirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Amidst.installInformation = (InstallInformation)profileBox.getSelectedItem(); boolean isValid = Amidst.installInformation.validate(); if (!isValid) { Log.e("\"Latest\" profile option detected, but there was an issue loading the version list.\nUsing alternative jar."); } else { try { new Minecraft(); } catch (MalformedURLException e1) { Log.crash(e1, "MalformedURLException when creating Minecraft object."); } window.dispose(); new FinderWindow(); } } }); getRootPane().setDefaultButton(btnConfirm); btnConfirm.requestFocus(); setTitle("Temporary profile selector"); setSize(300, 100); setLocation(200, 200); setVisible(true); }
public VersionSelectWindow() { setIconImage(Amidst.icon); File profileJsonFile = new File(Util.minecraftDirectory + "/launcher_profiles.json"); Object[] profileArray = null; try { LauncherProfile profile = Util.readObject(profileJsonFile, LauncherProfile.class); // TODO This should use latest, not a preset version. profile.profiles.put("(Default)", new InstallInformation("(Default) ", "1.7.4")); profileArray = profile.profiles.values().toArray(); } catch (Exception e) { // TODO This is a very broad exception to catch for e.printStackTrace(); dispose(); try { new Minecraft(); new FinderWindow(); } catch (MalformedURLException e1) { Log.crash(e1, "MalformedURLException when creating Minecraft object."); } return; // TODO Do stuff here } addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); System.exit(0); } }); final JComboBox profileBox = new JComboBox(profileArray); profileBox.selectWithKeyChar('('); JButton btnConfirm = new JButton("Okay"); this.setLayout(new GridLayout(3,1)); getContentPane().add(new JLabel(" Multiple profiles detected, please select one.")); getContentPane().add(profileBox); getContentPane().add(btnConfirm); final JFrame window = this; btnConfirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Amidst.installInformation = (InstallInformation)profileBox.getSelectedItem(); boolean isValid = Amidst.installInformation.validate(); if (!isValid) { Log.e("\"Latest\" profile option detected, but there was an issue loading the version list.\nUsing alternative jar."); } else { try { new Minecraft(); } catch (MalformedURLException e1) { Log.crash(e1, "MalformedURLException when creating Minecraft object."); } window.dispose(); new FinderWindow(); } } }); getRootPane().setDefaultButton(btnConfirm); btnConfirm.requestFocus(); setTitle("Temporary profile selector"); setSize(300, 100); setLocation(200, 200); setVisible(true); }
diff --git a/web/src/test/java/org/mule/galaxy/atom/ArtifactCollectionTest.java b/web/src/test/java/org/mule/galaxy/atom/ArtifactCollectionTest.java index 8cc20bc2..19b236e9 100755 --- a/web/src/test/java/org/mule/galaxy/atom/ArtifactCollectionTest.java +++ b/web/src/test/java/org/mule/galaxy/atom/ArtifactCollectionTest.java @@ -1,153 +1,153 @@ package org.mule.galaxy.atom; import java.io.InputStream; import java.util.List; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.i18n.text.CharUtils.Profile; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Service; import org.apache.abdera.model.Workspace; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.protocol.client.RequestOptions; import org.apache.axiom.om.util.Base64; import org.mule.galaxy.test.AbstractAtomTest; public class ArtifactCollectionTest extends AbstractAtomTest { public void testAddWsdl() throws Exception { AbderaClient client = new AbderaClient(abdera); RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); String base = "http://localhost:9002/api/"; // Grab workspaces & collections ClientResponse res = client.get(base, defaultOpts); assertEquals(res.getStatusText(), 200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Service> svcDoc = res.getDocument(); Service root = svcDoc.getRoot(); List<Workspace> workspaces = root.getWorkspaces(); assertEquals(1, workspaces.size()); Workspace workspace = workspaces.get(0); assertEquals("Mule Galaxy Registry & Repository", workspace.getTitle()); List<Collection> collections = workspace.getCollections(); assertEquals(2, collections.size()); Collection collection = null; for (Collection c : collections) { if ("registry".equals(c.getHref().toString())) { collection = c; } } assertNotNull(collection); res.release(); // Check out the feed, yo IRI colUri = new IRI(base).resolve(collection.getHref()); System.out.println("Grabbing the Feed " + colUri.toString()); res = client.get(colUri.toString(), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Testing of entry creation System.out.println("Creating Entry from a WSDL"); RequestOptions opts = new RequestOptions(); opts.setContentType("application/xml; charset=utf-8"); opts.setSlug("hello_world.wsdl"); opts.setHeader("X-Artifact-Version", "0.1"); opts.setHeader("X-Workspace", "Default Workspace"); opts.setAuthorization(defaultOpts.getAuthorization()); res = client.post(colUri.toASCIIString(), getWsdl(), opts); assertEquals(201, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Check the new feed for our entry System.out.println("Grabbing the Feed Again"); res = client.get(UrlEncoding.encode(colUri.toString(), Profile.PATH.filter()), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Feed> feedDoc = res.getDocument(); Feed feed = feedDoc.getRoot(); List<Entry> entries = feed.getEntries(); - assertEquals(8, entries.size()); + assertEquals(7, entries.size()); Entry e = null; for (Entry e2 : entries) { if (e2.getTitle().equals("hello_world.wsdl")) { e = e2; } } assertNotNull(e); res.release(); // get the individual entry res = client.get(e.getEditLinkResolvedHref().toString(), defaultOpts); org.apache.abdera.model.Document<Entry> entryDoc = res.getDocument(); Entry entry = entryDoc.getRoot(); Collection versionCollection = null; List<Element> elements = entry.getElements(); for (Element el : elements) { if (el instanceof Collection) { versionCollection = (Collection) el; } } assertNotNull(versionCollection); res.release(); // try getting the version history res = client.get(e.getContentSrc().toString() + "?view=history", defaultOpts); prettyPrint(res.getDocument()); feedDoc = res.getDocument(); feed = feedDoc.getRoot(); entries = feed.getEntries(); assertEquals(1, entries.size()); Entry historyEntry = entries.get(0); assertEquals("http://localhost:9002/api/registry/Default%20Workspace/hello_world.wsdl?version=0.1", historyEntry.getContentSrc().toString()); res.release(); // Get the raw content res = client.get(e.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); InputStream is = res.getInputStream(); while (is.read() != -1); res.release(); // Try the history entry res = client.get(historyEntry.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); is = res.getInputStream(); while (is.read() != -1); res.release(); } private InputStream getWsdl() { return getClass().getResourceAsStream("/wsdl/hello.wsdl"); } }
true
true
public void testAddWsdl() throws Exception { AbderaClient client = new AbderaClient(abdera); RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); String base = "http://localhost:9002/api/"; // Grab workspaces & collections ClientResponse res = client.get(base, defaultOpts); assertEquals(res.getStatusText(), 200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Service> svcDoc = res.getDocument(); Service root = svcDoc.getRoot(); List<Workspace> workspaces = root.getWorkspaces(); assertEquals(1, workspaces.size()); Workspace workspace = workspaces.get(0); assertEquals("Mule Galaxy Registry & Repository", workspace.getTitle()); List<Collection> collections = workspace.getCollections(); assertEquals(2, collections.size()); Collection collection = null; for (Collection c : collections) { if ("registry".equals(c.getHref().toString())) { collection = c; } } assertNotNull(collection); res.release(); // Check out the feed, yo IRI colUri = new IRI(base).resolve(collection.getHref()); System.out.println("Grabbing the Feed " + colUri.toString()); res = client.get(colUri.toString(), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Testing of entry creation System.out.println("Creating Entry from a WSDL"); RequestOptions opts = new RequestOptions(); opts.setContentType("application/xml; charset=utf-8"); opts.setSlug("hello_world.wsdl"); opts.setHeader("X-Artifact-Version", "0.1"); opts.setHeader("X-Workspace", "Default Workspace"); opts.setAuthorization(defaultOpts.getAuthorization()); res = client.post(colUri.toASCIIString(), getWsdl(), opts); assertEquals(201, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Check the new feed for our entry System.out.println("Grabbing the Feed Again"); res = client.get(UrlEncoding.encode(colUri.toString(), Profile.PATH.filter()), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Feed> feedDoc = res.getDocument(); Feed feed = feedDoc.getRoot(); List<Entry> entries = feed.getEntries(); assertEquals(8, entries.size()); Entry e = null; for (Entry e2 : entries) { if (e2.getTitle().equals("hello_world.wsdl")) { e = e2; } } assertNotNull(e); res.release(); // get the individual entry res = client.get(e.getEditLinkResolvedHref().toString(), defaultOpts); org.apache.abdera.model.Document<Entry> entryDoc = res.getDocument(); Entry entry = entryDoc.getRoot(); Collection versionCollection = null; List<Element> elements = entry.getElements(); for (Element el : elements) { if (el instanceof Collection) { versionCollection = (Collection) el; } } assertNotNull(versionCollection); res.release(); // try getting the version history res = client.get(e.getContentSrc().toString() + "?view=history", defaultOpts); prettyPrint(res.getDocument()); feedDoc = res.getDocument(); feed = feedDoc.getRoot(); entries = feed.getEntries(); assertEquals(1, entries.size()); Entry historyEntry = entries.get(0); assertEquals("http://localhost:9002/api/registry/Default%20Workspace/hello_world.wsdl?version=0.1", historyEntry.getContentSrc().toString()); res.release(); // Get the raw content res = client.get(e.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); InputStream is = res.getInputStream(); while (is.read() != -1); res.release(); // Try the history entry res = client.get(historyEntry.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); is = res.getInputStream(); while (is.read() != -1); res.release(); }
public void testAddWsdl() throws Exception { AbderaClient client = new AbderaClient(abdera); RequestOptions defaultOpts = client.getDefaultRequestOptions(); defaultOpts.setAuthorization("Basic " + Base64.encode("admin:admin".getBytes())); String base = "http://localhost:9002/api/"; // Grab workspaces & collections ClientResponse res = client.get(base, defaultOpts); assertEquals(res.getStatusText(), 200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Service> svcDoc = res.getDocument(); Service root = svcDoc.getRoot(); List<Workspace> workspaces = root.getWorkspaces(); assertEquals(1, workspaces.size()); Workspace workspace = workspaces.get(0); assertEquals("Mule Galaxy Registry & Repository", workspace.getTitle()); List<Collection> collections = workspace.getCollections(); assertEquals(2, collections.size()); Collection collection = null; for (Collection c : collections) { if ("registry".equals(c.getHref().toString())) { collection = c; } } assertNotNull(collection); res.release(); // Check out the feed, yo IRI colUri = new IRI(base).resolve(collection.getHref()); System.out.println("Grabbing the Feed " + colUri.toString()); res = client.get(colUri.toString(), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Testing of entry creation System.out.println("Creating Entry from a WSDL"); RequestOptions opts = new RequestOptions(); opts.setContentType("application/xml; charset=utf-8"); opts.setSlug("hello_world.wsdl"); opts.setHeader("X-Artifact-Version", "0.1"); opts.setHeader("X-Workspace", "Default Workspace"); opts.setAuthorization(defaultOpts.getAuthorization()); res = client.post(colUri.toASCIIString(), getWsdl(), opts); assertEquals(201, res.getStatus()); prettyPrint(res.getDocument()); res.release(); // Check the new feed for our entry System.out.println("Grabbing the Feed Again"); res = client.get(UrlEncoding.encode(colUri.toString(), Profile.PATH.filter()), defaultOpts); assertEquals(200, res.getStatus()); prettyPrint(res.getDocument()); org.apache.abdera.model.Document<Feed> feedDoc = res.getDocument(); Feed feed = feedDoc.getRoot(); List<Entry> entries = feed.getEntries(); assertEquals(7, entries.size()); Entry e = null; for (Entry e2 : entries) { if (e2.getTitle().equals("hello_world.wsdl")) { e = e2; } } assertNotNull(e); res.release(); // get the individual entry res = client.get(e.getEditLinkResolvedHref().toString(), defaultOpts); org.apache.abdera.model.Document<Entry> entryDoc = res.getDocument(); Entry entry = entryDoc.getRoot(); Collection versionCollection = null; List<Element> elements = entry.getElements(); for (Element el : elements) { if (el instanceof Collection) { versionCollection = (Collection) el; } } assertNotNull(versionCollection); res.release(); // try getting the version history res = client.get(e.getContentSrc().toString() + "?view=history", defaultOpts); prettyPrint(res.getDocument()); feedDoc = res.getDocument(); feed = feedDoc.getRoot(); entries = feed.getEntries(); assertEquals(1, entries.size()); Entry historyEntry = entries.get(0); assertEquals("http://localhost:9002/api/registry/Default%20Workspace/hello_world.wsdl?version=0.1", historyEntry.getContentSrc().toString()); res.release(); // Get the raw content res = client.get(e.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); InputStream is = res.getInputStream(); while (is.read() != -1); res.release(); // Try the history entry res = client.get(historyEntry.getContentSrc().toString(), defaultOpts); assertEquals(200, res.getStatus()); is = res.getInputStream(); while (is.read() != -1); res.release(); }
diff --git a/server/src/main/java/com/metamx/druid/index/v1/IncrementalIndexStorageAdapter.java b/server/src/main/java/com/metamx/druid/index/v1/IncrementalIndexStorageAdapter.java index bf8e0ac965..8ec2cc10f5 100644 --- a/server/src/main/java/com/metamx/druid/index/v1/IncrementalIndexStorageAdapter.java +++ b/server/src/main/java/com/metamx/druid/index/v1/IncrementalIndexStorageAdapter.java @@ -1,563 +1,563 @@ /* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.index.v1; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.metamx.common.IAE; import com.metamx.common.guava.FunctionalIterable; import com.metamx.common.guava.FunctionalIterator; import com.metamx.druid.Capabilities; import com.metamx.druid.QueryGranularity; import com.metamx.druid.StorageAdapter; import com.metamx.druid.aggregation.Aggregator; import com.metamx.druid.index.brita.BooleanValueMatcher; import com.metamx.druid.index.brita.Filter; import com.metamx.druid.index.brita.ValueMatcher; import com.metamx.druid.index.brita.ValueMatcherFactory; import com.metamx.druid.index.v1.processing.Cursor; import com.metamx.druid.index.v1.processing.DimensionSelector; import com.metamx.druid.index.v1.serde.ComplexMetricSerde; import com.metamx.druid.index.v1.serde.ComplexMetrics; import com.metamx.druid.kv.IndexedInts; import com.metamx.druid.processing.ComplexMetricSelector; import com.metamx.druid.processing.FloatMetricSelector; import com.metamx.druid.query.search.SearchHit; import com.metamx.druid.query.search.SearchQuery; import com.metamx.druid.query.search.SearchQuerySpec; import org.joda.time.DateTime; import org.joda.time.Interval; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.ConcurrentNavigableMap; /** */ public class IncrementalIndexStorageAdapter implements StorageAdapter { private final IncrementalIndex index; public IncrementalIndexStorageAdapter( IncrementalIndex index ) { this.index = index; } @Override public String getSegmentIdentifier() { throw new UnsupportedOperationException(); } @Override public Interval getInterval() { return index.getInterval(); } @Override public int getDimensionCardinality(String dimension) { IncrementalIndex.DimDim dimDim = index.getDimension(dimension.toLowerCase()); if (dimDim == null) { return 0; } return dimDim.size(); } @Override public DateTime getMinTime() { return index.getMinTime(); } @Override public DateTime getMaxTime() { return index.getMaxTime(); } @Override public Capabilities getCapabilities() { return Capabilities.builder().dimensionValuesSorted(false).build(); } @Override public Iterable<Cursor> makeCursors(final Filter filter, final Interval interval, final QueryGranularity gran) { Interval actualIntervalTmp = interval; Interval dataInterval = getInterval(); if (!actualIntervalTmp.overlaps(dataInterval)) { return ImmutableList.of(); } if (actualIntervalTmp.getStart().isBefore(dataInterval.getStart())) { actualIntervalTmp = actualIntervalTmp.withStart(dataInterval.getStart()); } if (actualIntervalTmp.getEnd().isAfter(dataInterval.getEnd())) { actualIntervalTmp = actualIntervalTmp.withEnd(dataInterval.getEnd()); } final Interval actualInterval = actualIntervalTmp; return new Iterable<Cursor>() { @Override public Iterator<Cursor> iterator() { return FunctionalIterator .create(gran.iterable(actualInterval.getStartMillis(), actualInterval.getEndMillis()).iterator()) .transform( new Function<Long, Cursor>() { EntryHolder currEntry = new EntryHolder(); private final ValueMatcher filterMatcher; { filterMatcher = makeFilterMatcher(filter, currEntry); } @Override public Cursor apply(@Nullable final Long input) { final long timeStart = Math.max(input, actualInterval.getStartMillis()); return new Cursor() { private Iterator<Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]>> baseIter; private ConcurrentNavigableMap<IncrementalIndex.TimeAndDims, Aggregator[]> cursorMap; final DateTime time; int numAdvanced = -1; boolean done; { cursorMap = index.getSubMap( new IncrementalIndex.TimeAndDims( timeStart, new String[][]{} ), new IncrementalIndex.TimeAndDims( - Math.min(actualInterval.getEndMillis(), gran.next(timeStart)), new String[][]{} + Math.min(actualInterval.getEndMillis(), gran.next(input)), new String[][]{} ) ); time = gran.toDateTime(input); reset(); } @Override public DateTime getTime() { return time; } @Override public void advance() { if (!baseIter.hasNext()) { done = true; return; } while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } } if (!filterMatcher.matches()) { done = true; } } @Override public boolean isDone() { return done; } @Override public void reset() { baseIter = cursorMap.entrySet().iterator(); if (numAdvanced == -1) { numAdvanced = 0; while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } numAdvanced++; } } else { Iterators.skip(baseIter, numAdvanced); if (baseIter.hasNext()) { currEntry.set(baseIter.next()); } } done = cursorMap.size() == 0 || !baseIter.hasNext(); } @Override public DimensionSelector makeDimensionSelector(String dimension) { final String dimensionName = dimension.toLowerCase(); final IncrementalIndex.DimDim dimValLookup = index.getDimension(dimensionName); if (dimValLookup == null) { return null; } final int maxId = dimValLookup.size(); final int dimIndex = index.getDimensionIndex(dimensionName); return new DimensionSelector() { @Override public IndexedInts getRow() { final ArrayList<Integer> vals = Lists.newArrayList(); if (dimIndex < currEntry.getKey().getDims().length) { final String[] dimVals = currEntry.getKey().getDims()[dimIndex]; if (dimVals != null) { for (String dimVal : dimVals) { int id = dimValLookup.getId(dimVal); if (id < maxId) { vals.add(id); } } } } return new IndexedInts() { @Override public int size() { return vals.size(); } @Override public int get(int index) { return vals.get(index); } @Override public Iterator<Integer> iterator() { return vals.iterator(); } }; } @Override public int getValueCardinality() { return dimValLookup.size(); } @Override public String lookupName(int id) { return dimValLookup.getValue(id); } @Override public int lookupId(String name) { return dimValLookup.getId(name); } }; } @Override public FloatMetricSelector makeFloatMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return new FloatMetricSelector() { @Override public float get() { return 0.0f; } }; } final int metricIndex = metricIndexInt; return new FloatMetricSelector() { @Override public float get() { return currEntry.getValue()[metricIndex].getFloat(); } }; } @Override public ComplexMetricSelector makeComplexMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return null; } final int metricIndex = metricIndexInt; final ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(index.getMetricType(metricName)); return new ComplexMetricSelector() { @Override public Class classOfObject() { return serde.getObjectStrategy().getClazz(); } @Override public Object get() { return currEntry.getValue()[metricIndex].get(); } }; } }; } } ); } }; } @Override public Iterable<SearchHit> searchDimensions(final SearchQuery query, final Filter filter) { final List<String> dimensions = query.getDimensions(); final int[] dimensionIndexes; final String[] dimensionNames; final List<String> dimensionOrder = index.getDimensions(); if (dimensions == null || dimensions.isEmpty()) { dimensionIndexes = new int[dimensionOrder.size()]; dimensionNames = new String[dimensionIndexes.length]; Iterator<String> dimensionOrderIter = dimensionOrder.iterator(); for (int i = 0; i < dimensionIndexes.length; ++i) { dimensionNames[i] = dimensionOrderIter.next(); dimensionIndexes[i] = index.getDimensionIndex(dimensionNames[i]); } } else { int[] tmpDimensionIndexes = new int[dimensions.size()]; String[] tmpDimensionNames = new String[dimensions.size()]; int i = 0; for (String dimension : dimensions) { Integer dimIndex = index.getDimensionIndex(dimension.toLowerCase()); if (dimIndex != null) { tmpDimensionNames[i] = dimension; tmpDimensionIndexes[i] = dimIndex; ++i; } } if (i != tmpDimensionIndexes.length) { dimensionIndexes = new int[i]; dimensionNames = new String[i]; System.arraycopy(tmpDimensionIndexes, 0, dimensionIndexes, 0, i); System.arraycopy(tmpDimensionNames, 0, dimensionNames, 0, i); } else { dimensionIndexes = tmpDimensionIndexes; dimensionNames = tmpDimensionNames; } } final List<Interval> queryIntervals = query.getIntervals(); if (queryIntervals.size() != 1) { throw new IAE("Can only handle one interval, got query[%s]", query); } final Interval queryInterval = queryIntervals.get(0); final long intervalStart = queryInterval.getStartMillis(); final long intervalEnd = queryInterval.getEndMillis(); final EntryHolder holder = new EntryHolder(); final ValueMatcher theMatcher = makeFilterMatcher(filter, holder); final SearchQuerySpec searchQuerySpec = query.getQuery(); final TreeSet<SearchHit> retVal = Sets.newTreeSet(query.getSort().getComparator()); ConcurrentNavigableMap<IncrementalIndex.TimeAndDims, Aggregator[]> facts = index.getSubMap( new IncrementalIndex.TimeAndDims(intervalStart, new String[][]{}), new IncrementalIndex.TimeAndDims(intervalEnd, new String[][]{}) ); for (Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]> entry : facts.entrySet()) { holder.set(entry); final IncrementalIndex.TimeAndDims key = holder.getKey(); final long timestamp = key.getTimestamp(); if (timestamp >= intervalStart && timestamp < intervalEnd && theMatcher.matches()) { final String[][] dims = key.getDims(); for (int i = 0; i < dimensionIndexes.length; ++i) { if (dimensionIndexes[i] < dims.length) { final String[] dimVals = dims[dimensionIndexes[i]]; if (dimVals != null) { for (int j = 0; j < dimVals.length; ++j) { if (searchQuerySpec.accept(dimVals[j])) { retVal.add(new SearchHit(dimensionNames[i], dimVals[j])); } } } } } } } return new FunctionalIterable<SearchHit>(retVal).limit(query.getLimit()); } private ValueMatcher makeFilterMatcher(final Filter filter, final EntryHolder holder) { return filter == null ? new BooleanValueMatcher(true) : filter.makeMatcher(new EntryHolderValueMatcherFactory(holder)); } private static class EntryHolder { Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]> currEntry = null; public Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]> get() { return currEntry; } public void set(Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]> currEntry) { this.currEntry = currEntry; } public IncrementalIndex.TimeAndDims getKey() { return currEntry.getKey(); } public Aggregator[] getValue() { return currEntry.getValue(); } } private class EntryHolderValueMatcherFactory implements ValueMatcherFactory { private final EntryHolder holder; public EntryHolderValueMatcherFactory( EntryHolder holder ) { this.holder = holder; } @Override public ValueMatcher makeValueMatcher(String dimension, String value) { Integer dimIndexObject = index.getDimensionIndex(dimension.toLowerCase()); if (dimIndexObject == null) { return new BooleanValueMatcher(false); } String idObject = index.getDimension(dimension.toLowerCase()).get(value); if (idObject == null) { return new BooleanValueMatcher(false); } final int dimIndex = dimIndexObject; final String id = idObject; return new ValueMatcher() { @Override public boolean matches() { String[][] dims = holder.getKey().getDims(); if (dimIndex >= dims.length || dims[dimIndex] == null) { return false; } for (String dimVal : dims[dimIndex]) { if (id == dimVal) { return true; } } return false; } }; } @Override public ValueMatcher makeValueMatcher(String dimension, final Predicate<String> predicate) { Integer dimIndexObject = index.getDimensionIndex(dimension.toLowerCase()); if (dimIndexObject == null) { return new BooleanValueMatcher(false); } final int dimIndex = dimIndexObject; return new ValueMatcher() { @Override public boolean matches() { String[][] dims = holder.getKey().getDims(); if (dimIndex >= dims.length || dims[dimIndex] == null) { return false; } for (String dimVal : dims[dimIndex]) { if (predicate.apply(dimVal)) { return true; } } return false; } }; } } }
true
true
public Iterable<Cursor> makeCursors(final Filter filter, final Interval interval, final QueryGranularity gran) { Interval actualIntervalTmp = interval; Interval dataInterval = getInterval(); if (!actualIntervalTmp.overlaps(dataInterval)) { return ImmutableList.of(); } if (actualIntervalTmp.getStart().isBefore(dataInterval.getStart())) { actualIntervalTmp = actualIntervalTmp.withStart(dataInterval.getStart()); } if (actualIntervalTmp.getEnd().isAfter(dataInterval.getEnd())) { actualIntervalTmp = actualIntervalTmp.withEnd(dataInterval.getEnd()); } final Interval actualInterval = actualIntervalTmp; return new Iterable<Cursor>() { @Override public Iterator<Cursor> iterator() { return FunctionalIterator .create(gran.iterable(actualInterval.getStartMillis(), actualInterval.getEndMillis()).iterator()) .transform( new Function<Long, Cursor>() { EntryHolder currEntry = new EntryHolder(); private final ValueMatcher filterMatcher; { filterMatcher = makeFilterMatcher(filter, currEntry); } @Override public Cursor apply(@Nullable final Long input) { final long timeStart = Math.max(input, actualInterval.getStartMillis()); return new Cursor() { private Iterator<Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]>> baseIter; private ConcurrentNavigableMap<IncrementalIndex.TimeAndDims, Aggregator[]> cursorMap; final DateTime time; int numAdvanced = -1; boolean done; { cursorMap = index.getSubMap( new IncrementalIndex.TimeAndDims( timeStart, new String[][]{} ), new IncrementalIndex.TimeAndDims( Math.min(actualInterval.getEndMillis(), gran.next(timeStart)), new String[][]{} ) ); time = gran.toDateTime(input); reset(); } @Override public DateTime getTime() { return time; } @Override public void advance() { if (!baseIter.hasNext()) { done = true; return; } while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } } if (!filterMatcher.matches()) { done = true; } } @Override public boolean isDone() { return done; } @Override public void reset() { baseIter = cursorMap.entrySet().iterator(); if (numAdvanced == -1) { numAdvanced = 0; while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } numAdvanced++; } } else { Iterators.skip(baseIter, numAdvanced); if (baseIter.hasNext()) { currEntry.set(baseIter.next()); } } done = cursorMap.size() == 0 || !baseIter.hasNext(); } @Override public DimensionSelector makeDimensionSelector(String dimension) { final String dimensionName = dimension.toLowerCase(); final IncrementalIndex.DimDim dimValLookup = index.getDimension(dimensionName); if (dimValLookup == null) { return null; } final int maxId = dimValLookup.size(); final int dimIndex = index.getDimensionIndex(dimensionName); return new DimensionSelector() { @Override public IndexedInts getRow() { final ArrayList<Integer> vals = Lists.newArrayList(); if (dimIndex < currEntry.getKey().getDims().length) { final String[] dimVals = currEntry.getKey().getDims()[dimIndex]; if (dimVals != null) { for (String dimVal : dimVals) { int id = dimValLookup.getId(dimVal); if (id < maxId) { vals.add(id); } } } } return new IndexedInts() { @Override public int size() { return vals.size(); } @Override public int get(int index) { return vals.get(index); } @Override public Iterator<Integer> iterator() { return vals.iterator(); } }; } @Override public int getValueCardinality() { return dimValLookup.size(); } @Override public String lookupName(int id) { return dimValLookup.getValue(id); } @Override public int lookupId(String name) { return dimValLookup.getId(name); } }; } @Override public FloatMetricSelector makeFloatMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return new FloatMetricSelector() { @Override public float get() { return 0.0f; } }; } final int metricIndex = metricIndexInt; return new FloatMetricSelector() { @Override public float get() { return currEntry.getValue()[metricIndex].getFloat(); } }; } @Override public ComplexMetricSelector makeComplexMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return null; } final int metricIndex = metricIndexInt; final ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(index.getMetricType(metricName)); return new ComplexMetricSelector() { @Override public Class classOfObject() { return serde.getObjectStrategy().getClazz(); } @Override public Object get() { return currEntry.getValue()[metricIndex].get(); } }; } }; } } ); } }; }
public Iterable<Cursor> makeCursors(final Filter filter, final Interval interval, final QueryGranularity gran) { Interval actualIntervalTmp = interval; Interval dataInterval = getInterval(); if (!actualIntervalTmp.overlaps(dataInterval)) { return ImmutableList.of(); } if (actualIntervalTmp.getStart().isBefore(dataInterval.getStart())) { actualIntervalTmp = actualIntervalTmp.withStart(dataInterval.getStart()); } if (actualIntervalTmp.getEnd().isAfter(dataInterval.getEnd())) { actualIntervalTmp = actualIntervalTmp.withEnd(dataInterval.getEnd()); } final Interval actualInterval = actualIntervalTmp; return new Iterable<Cursor>() { @Override public Iterator<Cursor> iterator() { return FunctionalIterator .create(gran.iterable(actualInterval.getStartMillis(), actualInterval.getEndMillis()).iterator()) .transform( new Function<Long, Cursor>() { EntryHolder currEntry = new EntryHolder(); private final ValueMatcher filterMatcher; { filterMatcher = makeFilterMatcher(filter, currEntry); } @Override public Cursor apply(@Nullable final Long input) { final long timeStart = Math.max(input, actualInterval.getStartMillis()); return new Cursor() { private Iterator<Map.Entry<IncrementalIndex.TimeAndDims, Aggregator[]>> baseIter; private ConcurrentNavigableMap<IncrementalIndex.TimeAndDims, Aggregator[]> cursorMap; final DateTime time; int numAdvanced = -1; boolean done; { cursorMap = index.getSubMap( new IncrementalIndex.TimeAndDims( timeStart, new String[][]{} ), new IncrementalIndex.TimeAndDims( Math.min(actualInterval.getEndMillis(), gran.next(input)), new String[][]{} ) ); time = gran.toDateTime(input); reset(); } @Override public DateTime getTime() { return time; } @Override public void advance() { if (!baseIter.hasNext()) { done = true; return; } while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } } if (!filterMatcher.matches()) { done = true; } } @Override public boolean isDone() { return done; } @Override public void reset() { baseIter = cursorMap.entrySet().iterator(); if (numAdvanced == -1) { numAdvanced = 0; while (baseIter.hasNext()) { currEntry.set(baseIter.next()); if (filterMatcher.matches()) { return; } numAdvanced++; } } else { Iterators.skip(baseIter, numAdvanced); if (baseIter.hasNext()) { currEntry.set(baseIter.next()); } } done = cursorMap.size() == 0 || !baseIter.hasNext(); } @Override public DimensionSelector makeDimensionSelector(String dimension) { final String dimensionName = dimension.toLowerCase(); final IncrementalIndex.DimDim dimValLookup = index.getDimension(dimensionName); if (dimValLookup == null) { return null; } final int maxId = dimValLookup.size(); final int dimIndex = index.getDimensionIndex(dimensionName); return new DimensionSelector() { @Override public IndexedInts getRow() { final ArrayList<Integer> vals = Lists.newArrayList(); if (dimIndex < currEntry.getKey().getDims().length) { final String[] dimVals = currEntry.getKey().getDims()[dimIndex]; if (dimVals != null) { for (String dimVal : dimVals) { int id = dimValLookup.getId(dimVal); if (id < maxId) { vals.add(id); } } } } return new IndexedInts() { @Override public int size() { return vals.size(); } @Override public int get(int index) { return vals.get(index); } @Override public Iterator<Integer> iterator() { return vals.iterator(); } }; } @Override public int getValueCardinality() { return dimValLookup.size(); } @Override public String lookupName(int id) { return dimValLookup.getValue(id); } @Override public int lookupId(String name) { return dimValLookup.getId(name); } }; } @Override public FloatMetricSelector makeFloatMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return new FloatMetricSelector() { @Override public float get() { return 0.0f; } }; } final int metricIndex = metricIndexInt; return new FloatMetricSelector() { @Override public float get() { return currEntry.getValue()[metricIndex].getFloat(); } }; } @Override public ComplexMetricSelector makeComplexMetricSelector(String metric) { final String metricName = metric.toLowerCase(); final Integer metricIndexInt = index.getMetricIndex(metricName); if (metricIndexInt == null) { return null; } final int metricIndex = metricIndexInt; final ComplexMetricSerde serde = ComplexMetrics.getSerdeForType(index.getMetricType(metricName)); return new ComplexMetricSelector() { @Override public Class classOfObject() { return serde.getObjectStrategy().getClazz(); } @Override public Object get() { return currEntry.getValue()[metricIndex].get(); } }; } }; } } ); } }; }
diff --git a/src/main/java/org/cc/response/CloudInvalidArgsResponse.java b/src/main/java/org/cc/response/CloudInvalidArgsResponse.java index 6c77b46..4d26298 100644 --- a/src/main/java/org/cc/response/CloudInvalidArgsResponse.java +++ b/src/main/java/org/cc/response/CloudInvalidArgsResponse.java @@ -1,32 +1,36 @@ package org.cc.response; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Daneel Yaitskov */ public class CloudInvalidArgsResponse extends CloudErrorResponse { /** * invalid parameter => error details. */ @JsonProperty("errors") private List<InvalidField> errors; public CloudInvalidArgsResponse(BindException e) { super(e); + StringBuilder builder = new StringBuilder(); errors = new ArrayList<InvalidField>(e.getErrorCount()); for (FieldError error : e.getFieldErrors()) { errors.add(new InvalidField(error.getField(), error.getDefaultMessage())); + builder.append(error.getField()).append(": ") + .append(error.getDefaultMessage()).append(";\n"); } + setMessage(builder.toString()); } }
false
true
public CloudInvalidArgsResponse(BindException e) { super(e); errors = new ArrayList<InvalidField>(e.getErrorCount()); for (FieldError error : e.getFieldErrors()) { errors.add(new InvalidField(error.getField(), error.getDefaultMessage())); } }
public CloudInvalidArgsResponse(BindException e) { super(e); StringBuilder builder = new StringBuilder(); errors = new ArrayList<InvalidField>(e.getErrorCount()); for (FieldError error : e.getFieldErrors()) { errors.add(new InvalidField(error.getField(), error.getDefaultMessage())); builder.append(error.getField()).append(": ") .append(error.getDefaultMessage()).append(";\n"); } setMessage(builder.toString()); }
diff --git a/IndexWriter.java b/IndexWriter.java index 1dbe202..809fec6 100644 --- a/IndexWriter.java +++ b/IndexWriter.java @@ -1,469 +1,469 @@ /* 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.XMLSpider; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import plugins.XMLSpider.db.Config; import plugins.XMLSpider.db.Page; import plugins.XMLSpider.db.PerstRoot; import plugins.XMLSpider.db.Term; import plugins.XMLSpider.db.TermPosition; import plugins.XMLSpider.org.garret.perst.IterableIterator; import plugins.XMLSpider.org.garret.perst.Storage; import plugins.XMLSpider.org.garret.perst.StorageFactory; import freenet.support.Logger; import freenet.support.io.Closer; /** * Write index to disk file */ public class IndexWriter { private static final String[] HEX = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; //- Writing Index public long tProducedIndex; private Vector<String> indices; private int match; private long time_taken; private boolean logMINOR = Logger.shouldLog(Logger.MINOR, this); IndexWriter() { } public synchronized void makeIndex(PerstRoot perstRoot) throws Exception { logMINOR = Logger.shouldLog(Logger.MINOR, this); try { time_taken = System.currentTimeMillis(); Config config = perstRoot.getConfig(); File indexDir = new File(config.getIndexDir()); if(((!indexDir.exists()) && !indexDir.mkdirs()) || (indexDir.exists() && !indexDir.isDirectory())) { Logger.error(this, "Cannot create index directory: " + indexDir); return; } makeSubIndices(perstRoot); makeMainIndex(config); time_taken = System.currentTimeMillis() - time_taken; if (logMINOR) Logger.minor(this, "Spider: indexes regenerated - tProducedIndex=" + (System.currentTimeMillis() - tProducedIndex) + "ms ago time taken=" + time_taken + "ms"); tProducedIndex = System.currentTimeMillis(); } finally { } } /** * generates the main index file that can be used by librarian for searching in the list of * subindices * * @param void * @author swati * @throws IOException * @throws NoSuchAlgorithmException */ private void makeMainIndex(Config config) throws IOException, NoSuchAlgorithmException { // Produce the main index file. if (logMINOR) Logger.minor(this, "Producing top index..."); //the main index file File outputFile = new File(config.getIndexDir() + "index.xml"); // Use a stream so we can explicitly close - minimise number of filehandles used. BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream; resultStream = new StreamResult(fos); try { /* Initialize xml builder */ Document xmlDoc = null; DocumentBuilderFactory xmlFactory = null; DocumentBuilder xmlBuilder = null; DOMImplementation impl = null; Element rootElement = null; xmlFactory = DocumentBuilderFactory.newInstance(); try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { Logger.error(this, "Spider: Error while initializing XML generator: " + e.toString(), e); return; } impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ xmlDoc = impl.createDocument(null, "main_index", null); rootElement = xmlDoc.getDocumentElement(); /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner */ subHeaderElement = xmlDoc.createElement("owner"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwner()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* -> owner email */ if (config.getIndexOwnerEmail() != null) { subHeaderElement = xmlDoc.createElement("email"); subHeaderText = xmlDoc.createTextNode(config.getIndexOwnerEmail()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); } /* * the max number of digits in md5 to be used for matching with the search query is * stored in the xml */ Element prefixElement = xmlDoc.createElement("prefix"); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); for (int i = 0; i < indices.size(); i++) { Element subIndexElement = xmlDoc.createElement("subIndex"); subIndexElement.setAttribute("key", indices.elementAt(i)); //the subindex element key will contain the bits used for matching in that subindex keywordsElement.appendChild(subIndexElement); } prefixElement.setAttribute("value", match + ""); rootElement.appendChild(prefixElement); rootElement.appendChild(headerElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { Logger.error(this, "Spider: Error while serializing XML (transformFactory.newTransformer()): " + e.toString(), e); return; } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { Logger.error(this, "Spider: Error while serializing XML (transform()): " + e.toString(), e); return; } } finally { fos.close(); } //The main xml file is generated //As each word is generated enter it into the respective subindex //The parsing will start and nodes will be added as needed } /** * Generates the subindices. Each index has less than {@code MAX_ENTRIES} words. The original * treemap is split into several sublists indexed by the common substring of the hash code of * the words * * @throws Exception */ private void makeSubIndices(PerstRoot perstRoot) throws Exception { Logger.normal(this, "Generating index..."); indices = new Vector<String>(); match = 1; for (String hex : HEX) generateSubIndex(perstRoot, hex); } private void generateSubIndex(PerstRoot perstRoot, String prefix) throws Exception { if (logMINOR) Logger.minor(this, "Generating subindex for (" + prefix + ")"); if (prefix.length() > match) match = prefix.length(); if (generateXML(perstRoot, prefix)) return; if (logMINOR) Logger.minor(this, "Too big subindex for (" + prefix + ")"); for (String hex : HEX) generateSubIndex(perstRoot, prefix + hex); } /** * generates the xml index with the given list of words with prefix number of matching bits in * md5 * * @param prefix * prefix string * @return successful * @throws IOException */ private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) { wordElement.setAttributeNS("urn:freenet:xmlspider:debug", "debug:md5", term.getMD5()); } count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { - if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix + if (prefix.length() < 2 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; } public static void main(String[] arg) throws Exception { Storage db = StorageFactory.getInstance().createStorage(); db.setProperty("perst.object.cache.kind", "pinned"); db.setProperty("perst.object.cache.init.size", 8192); db.setProperty("perst.alternative.btree", true); db.setProperty("perst.string.encoding", "UTF-8"); db.setProperty("perst.concurrent.iterator", true); db.setProperty("perst.file.readonly", true); db.open(arg[0]); PerstRoot root = (PerstRoot) db.getRoot(); IndexWriter writer = new IndexWriter(); int benchmark = 0; long[] timeTaken = null; if (arg[1] != null) { benchmark = Integer.parseInt(arg[1]); timeTaken = new long[benchmark]; } for (int i = 0; i < benchmark; i++) { long startTime = System.currentTimeMillis(); writer.makeIndex(root); long endTime = System.currentTimeMillis(); long memFree = Runtime.getRuntime().freeMemory(); long memTotal = Runtime.getRuntime().totalMemory(); System.out.println("Index generated in " + (endTime - startTime) // + "ms. Used memory=" + (memTotal - memFree)); if (benchmark > 0) { timeTaken[i] = (endTime - startTime); System.out.println("Cooling down."); for (int j = 0; j < 3; j++) { System.gc(); System.runFinalization(); Thread.sleep(3000); } } } if (benchmark > 0) { long totalTime = 0; long totalSqTime = 0; for (long t : timeTaken) { totalTime += t; totalSqTime += t * t; } double meanTime = (totalTime / benchmark); double meanSqTime = (totalSqTime / benchmark); System.out.println("Mean time = " + (long) meanTime + "ms"); System.out.println(" sd = " + (long) Math.sqrt(meanSqTime - meanTime * meanTime) + "ms"); } } }
true
true
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) { wordElement.setAttributeNS("urn:freenet:xmlspider:debug", "debug:md5", term.getMD5()); } count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 3 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
private boolean generateXML(PerstRoot perstRoot, String prefix) throws IOException { final Config config = perstRoot.getConfig(); final long MAX_SIZE = config.getIndexSubindexMaxSize(); final int MAX_ENTRIES = config.getIndexMaxEntries(); File outputFile = new File(config.getIndexDir() + "index_" + prefix + ".xml"); BufferedOutputStream fos = null; int count = 0; int estimateSize = 0; try { DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder xmlBuilder; try { xmlBuilder = xmlFactory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException("Spider: Error while initializing XML generator", e); } DOMImplementation impl = xmlBuilder.getDOMImplementation(); /* Starting to generate index */ Document xmlDoc = impl.createDocument(null, "sub_index", null); Element rootElement = xmlDoc.getDocumentElement(); if (config.isDebug()) { rootElement.appendChild(xmlDoc.createComment(new Date().toGMTString())); } /* Adding header to the index */ Element headerElement = xmlDoc.createElement("header"); /* -> title */ Element subHeaderElement = xmlDoc.createElement("title"); Text subHeaderText = xmlDoc.createTextNode(config.getIndexTitle()); subHeaderElement.appendChild(subHeaderText); headerElement.appendChild(subHeaderElement); /* List of files referenced in this subindex */ Element filesElement = xmlDoc.createElement("files"); /* filesElement != fileElement */ Set<Long> fileid = new HashSet<Long>(); /* Adding word index */ Element keywordsElement = xmlDoc.createElement("keywords"); IterableIterator<Term> termIterator = perstRoot.getTermIterator(prefix, prefix + "g"); for (Term term : termIterator) { Element wordElement = xmlDoc.createElement("word"); wordElement.setAttribute("v", term.getWord()); if (config.isDebug()) { wordElement.setAttributeNS("urn:freenet:xmlspider:debug", "debug:md5", term.getMD5()); } count++; estimateSize += 12; estimateSize += term.getWord().length(); Set<Page> pages = term.getPages(); if ((count > 1 && (estimateSize + pages.size() * 13) > MAX_SIZE) || // (count > MAX_ENTRIES)) { if (prefix.length() < 2 && indices.size() < 256) // FIXME this is a hack to limit number of files. remove after metadata fix return false; } for (Page page : pages) { TermPosition termPos = page.getTermPosition(term, false); if (termPos == null) continue; synchronized (termPos) { synchronized (page) { /* * adding file information uriElement - lists the id of the file * containing a particular word fileElement - lists the id,key,title of * the files mentioned in the entire subindex */ Element uriElement = xmlDoc.createElement("file"); uriElement.setAttribute("id", Long.toString(page.getId())); /* Position by position */ int[] positions = termPos.positions; StringBuilder positionList = new StringBuilder(); for (int k = 0; k < positions.length; k++) { if (k != 0) positionList.append(','); positionList.append(positions[k]); } uriElement.appendChild(xmlDoc.createTextNode(positionList.toString())); wordElement.appendChild(uriElement); estimateSize += 13; estimateSize += positionList.length(); if (!fileid.contains(page.getId())) { fileid.add(page.getId()); Element fileElement = xmlDoc.createElement("file"); fileElement.setAttribute("id", Long.toString(page.getId())); fileElement.setAttribute("key", page.getURI()); fileElement.setAttribute("title", page.getPageTitle() != null ? page.getPageTitle() : page.getURI()); filesElement.appendChild(fileElement); estimateSize += 15; estimateSize += filesElement.getAttribute("id").length(); estimateSize += filesElement.getAttribute("key").length(); estimateSize += filesElement.getAttribute("title").length(); } } } } keywordsElement.appendChild(wordElement); } Element entriesElement = xmlDoc.createElement("entries"); entriesElement.setAttribute("value", count + ""); rootElement.appendChild(entriesElement); rootElement.appendChild(headerElement); rootElement.appendChild(filesElement); rootElement.appendChild(keywordsElement); /* Serialization */ DOMSource domSource = new DOMSource(xmlDoc); TransformerFactory transformFactory = TransformerFactory.newInstance(); Transformer serializer; try { serializer = transformFactory.newTransformer(); } catch (javax.xml.transform.TransformerConfigurationException e) { throw new RuntimeException("Spider: Error while serializing XML (transformFactory.newTransformer())", e); } serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); fos = new BufferedOutputStream(new FileOutputStream(outputFile)); StreamResult resultStream = new StreamResult(fos); /* final step */ try { serializer.transform(domSource, resultStream); } catch (javax.xml.transform.TransformerException e) { throw new RuntimeException("Spider: Error while serializing XML (transform())", e); } } finally { Closer.close(fos); } if (outputFile.length() > MAX_SIZE && count > 1) { if (prefix.length() < 3 && indices.size() < 256) { // FIXME this is a hack to limit number of files. remove after metadata fix outputFile.delete(); return false; } } if (logMINOR) Logger.minor(this, "Spider: indexes regenerated."); indices.add(prefix); return true; }
diff --git a/modules/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java b/modules/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java index 54cb220b7..a398e3779 100644 --- a/modules/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java +++ b/modules/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java @@ -1,936 +1,936 @@ // ======================================================================== // 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. // ======================================================================== package org.mortbay.jetty.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.util.Enumeration; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mortbay.io.Buffer; import org.mortbay.io.ByteArrayBuffer; import org.mortbay.io.WriterOutputStream; import org.mortbay.io.nio.NIOBuffer; import org.mortbay.jetty.Connector; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.HttpContent; import org.mortbay.jetty.HttpFields; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.HttpMethods; import org.mortbay.jetty.InclusiveByteRange; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.ResourceCache; import org.mortbay.jetty.Response; import org.mortbay.jetty.handler.ContextHandler; import org.mortbay.jetty.nio.NIOConnector; import org.mortbay.log.Log; import org.mortbay.resource.Resource; import org.mortbay.resource.ResourceFactory; import org.mortbay.util.IO; import org.mortbay.util.MultiPartOutputStream; import org.mortbay.util.TypeUtil; import org.mortbay.util.URIUtil; /* ------------------------------------------------------------ */ /** The default servlet. * This servlet, normally mapped to /, provides the handling for static * content, OPTION and TRACE methods for the context. * The following initParameters are supported, these can be set either * on the servlet itself or as ServletContext initParameters with a prefix * of org.mortbay.jetty.servlet.Default. : * <PRE> * acceptRanges If true, range requests and responses are * supported * * dirAllowed If true, directory listings are returned if no * welcome file is found. Else 403 Forbidden. * * redirectWelcome If true, welcome files are redirected rather than * forwarded to. * * gzip If set to true, then static content will be served as * gzip content encoded if a matching resource is * found ending with ".gz" * * resourceBase Set to replace the context resource base * * relativeResourceBase * Set with a pathname relative to the base of the * servlet context root. Useful for only serving static content out * of only specific subdirectories. * * aliases If True, aliases of resources are allowed (eg. symbolic * links and caps variations). May bypass security constraints. * * maxCacheSize The maximum total size of the cache or 0 for no cache. * maxCachedFileSize The maximum size of a file to cache * maxCachedFiles The maximum number of files to cache * cacheType Set to "bio", "nio" or "both" to determine the type resource cache. * A bio cached buffer may be used by nio but is not as efficient as an * nio buffer. An nio cached buffer may not be used by bio. * * useFileMappedBuffer * If set to true, it will use mapped file buffer to serve static content * when using NIO connector. Setting this value to false means that * a direct buffer will be used instead of a mapped file buffer. * By default, this is set to true. * * cacheControl If set, all static content will have this value set as the cache-control * header. * * * </PRE> * * * @author Greg Wilkins (gregw) * @author Nigel Canonizado */ public class DefaultServlet extends HttpServlet implements ResourceFactory { private static ByteArrayBuffer BYTE_RANGES=new ByteArrayBuffer("bytes"); private ContextHandler.SContext _context; private boolean _acceptRanges=true; private boolean _dirAllowed=true; private boolean _redirectWelcome=false; private boolean _gzip=true; private Resource _resourceBase; private NIOResourceCache _nioCache; private ResourceCache _bioCache; private MimeTypes _mimeTypes; private String[] _welcomes; private boolean _aliases=false; private boolean _useFileMappedBuffer=false; ByteArrayBuffer _cacheControl; /* ------------------------------------------------------------ */ public void init() throws UnavailableException { ServletContext config=getServletContext(); _context = (ContextHandler.SContext)config; _mimeTypes = _context.getContextHandler().getMimeTypes(); _welcomes = _context.getContextHandler().getWelcomeFiles(); if (_welcomes==null) _welcomes=new String[] {"index.jsp","index.html"}; _acceptRanges=getInitBoolean("acceptRanges",_acceptRanges); _dirAllowed=getInitBoolean("dirAllowed",_dirAllowed); _redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome); _gzip=getInitBoolean("gzip",_gzip); _aliases=getInitBoolean("aliases",_aliases); _useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer); String rrb = getInitParameter("relativeResourceBase"); if (rrb!=null) { try { _resourceBase=Resource.newResource(_context.getResource(URIUtil.SLASH)).addPath(rrb); } catch (Exception e) { Log.warn(Log.EXCEPTION,e); throw new UnavailableException(e.toString()); } } String rb=getInitParameter("resourceBase"); if (rrb != null && rb != null) throw new UnavailableException("resourceBase & relativeResourceBase"); if (rb!=null) { try{_resourceBase=Resource.newResource(rb);} catch (Exception e) { Log.warn(Log.EXCEPTION,e); throw new UnavailableException(e.toString()); } } String t=getInitParameter("cacheControl"); if (t!=null) _cacheControl=new ByteArrayBuffer(t); try { if (_resourceBase==null) _resourceBase=Resource.newResource(_context.getResource(URIUtil.SLASH)); String cache_type =getInitParameter("cacheType"); int max_cache_size=getInitInt("maxCacheSize", -2); int max_cached_file_size=getInitInt("maxCachedFileSize", -2); int max_cached_files=getInitInt("maxCachedFiles", -2); if (cache_type==null || "nio".equals(cache_type)|| "both".equals(cache_type)) { if (max_cache_size==-2 || max_cache_size>0) { _nioCache=new NIOResourceCache(_mimeTypes); if (max_cache_size>0) _nioCache.setMaxCacheSize(max_cache_size); if (max_cached_file_size>=-1) _nioCache.setMaxCachedFileSize(max_cached_file_size); if (max_cached_files>=-1) _nioCache.setMaxCachedFiles(max_cached_files); _nioCache.start(); } } if ("bio".equals(cache_type)|| "both".equals(cache_type)) { if (max_cache_size==-2 || max_cache_size>0) { _bioCache=new ResourceCache(_mimeTypes); if (max_cache_size>0) _bioCache.setMaxCacheSize(max_cache_size); if (max_cached_file_size>=-1) _bioCache.setMaxCachedFileSize(max_cached_file_size); if (max_cached_files>=-1) _bioCache.setMaxCachedFiles(max_cached_files); _bioCache.start(); } } if (_nioCache==null) _bioCache=null; } catch (Exception e) { Log.warn(Log.EXCEPTION,e); throw new UnavailableException(e.toString()); } if (Log.isDebugEnabled()) Log.debug("resource base = "+_resourceBase); } /* ------------------------------------------------------------ */ public String getInitParameter(String name) { String value=getServletContext().getInitParameter("org.mortbay.jetty.servlet.Default."+name); if (value==null) value=super.getInitParameter(name); return value; } /* ------------------------------------------------------------ */ private boolean getInitBoolean(String name, boolean dft) { String value=getInitParameter(name); if (value==null || value.length()==0) return dft; return (value.startsWith("t")|| value.startsWith("T")|| value.startsWith("y")|| value.startsWith("Y")|| value.startsWith("1")); } /* ------------------------------------------------------------ */ private int getInitInt(String name, int dft) { String value=getInitParameter(name); if (value==null) value=getInitParameter(name); if (value!=null && value.length()>0) return Integer.parseInt(value); return dft; } /* ------------------------------------------------------------ */ /** get Resource to serve. * Map a path to a resource. The default implementation calls * HttpContext.getResource but derived servlets may provide * their own mapping. * @param pathInContext The path to find a resource for. * @return The resource to serve. */ public Resource getResource(String pathInContext) { if (_resourceBase==null) return null; Resource r=null; try { r = _resourceBase.addPath(pathInContext); if (!_aliases && r.getAlias()!=null) { if (r.exists()) Log.warn("Aliased resource: "+r+"=="+r.getAlias()); return null; } if (Log.isDebugEnabled()) Log.debug("RESOURCE="+r); } catch (IOException e) { Log.ignore(e); } return r; } /* ------------------------------------------------------------ */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletPath=null; String pathInfo=null; Enumeration reqRanges = null; Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY); if (included!=null && included.booleanValue()) { servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH); pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO); if (servletPath==null) { servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); } } else { included=Boolean.FALSE; servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); // Is this a range request? reqRanges = request.getHeaders(HttpHeaders.RANGE); if (reqRanges!=null && !reqRanges.hasMoreElements()) reqRanges=null; } String pathInContext=URIUtil.addPaths(servletPath,pathInfo); boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH); // Can we gzip this request? String pathInContextGz=null; boolean gzip=false; - if (_gzip && reqRanges==null && !endsWithSlash ) + if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash ) { String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING); if (accept!=null && accept.indexOf("gzip")>=0) gzip=true; } // Find the resource and content Resource resource=null; HttpContent content=null; Connector connector = HttpConnection.getCurrentConnection().getConnector(); ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache; try { // Try gzipped content first if (gzip) { pathInContextGz=pathInContext+".gz"; resource=getResource(pathInContextGz); if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } else if (cache!=null) { content=cache.lookup(pathInContextGz,resource); if (content!=null) resource=content.getResource(); } if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } } // find resource if (!gzip) { if (cache==null) resource=getResource(pathInContext); else { content=cache.lookup(pathInContext,this); if (content!=null) resource=content.getResource(); else resource=getResource(pathInContext); } } if (Log.isDebugEnabled()) Log.debug("resource="+resource+(content!=null?" content":"")); // Handle resource if (resource==null || !resource.exists()) response.sendError(HttpServletResponse.SC_NOT_FOUND); else if (!resource.isDirectory()) { // ensure we have content if (content==null) content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) { if (gzip) { response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip"); String mt=_context.getMimeType(pathInContext); if (mt!=null) response.setContentType(mt); } sendData(request,response,included.booleanValue(),resource,content,reqRanges); } } else { String welcome=null; if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null)) { StringBuffer buf=request.getRequestURL(); int param=buf.lastIndexOf(";"); if (param<0) buf.append('/'); else buf.insert(param,'/'); String q=request.getQueryString(); if (q!=null&&q.length()!=0) { buf.append('?'); buf.append(q); } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(buf.toString())); } // else look for a welcome file else if (null!=(welcome=getWelcomeFile(resource))) { String ipath=URIUtil.addPaths(pathInContext,welcome); if (_redirectWelcome) { // Redirect to the index response.setContentLength(0); String q=request.getQueryString(); if (q!=null&&q.length()!=0) response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q); else response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)); } else { // Forward to the index RequestDispatcher dispatcher=request.getRequestDispatcher(ipath); if (dispatcher!=null) { if (included.booleanValue()) dispatcher.include(request,response); else { request.setAttribute("org.mortbay.jetty.welcome",ipath); dispatcher.forward(request,response); } } } } else { content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) sendDirectory(request,response,resource,pathInContext.length()>1); } } } catch(IllegalArgumentException e) { Log.warn(Log.EXCEPTION,e); } finally { if (content!=null) content.release(); else if (resource!=null) resource.release(); } } /* ------------------------------------------------------------ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } /* ------------------------------------------------------------ */ /* (non-Javadoc) * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } /* ------------------------------------------------------------ */ /** * Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of * configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>. * If the resource is not a directory, or no matching file is found, then <code>null</code> is returned. * The list of welcome files is read from the {@link ContextHandler} for this servlet, or * <code>"index.jsp" , "index.html"</code> if that is <code>null</code>. * @param resource * @return The name of the matching welcome file. * @throws IOException * @throws MalformedURLException */ private String getWelcomeFile(Resource resource) throws MalformedURLException, IOException { if (!resource.isDirectory() || _welcomes==null) return null; for (int i=0;i<_welcomes.length;i++) { Resource welcome=resource.addPath(_welcomes[i]); if (welcome.exists()) return _welcomes[i]; } return null; } /* ------------------------------------------------------------ */ /* Check modification date headers. */ protected boolean passConditionalHeaders(HttpServletRequest request,HttpServletResponse response, Resource resource, HttpContent content) throws IOException { if (!request.getMethod().equals(HttpMethods.HEAD) ) { String ifms=request.getHeader(HttpHeaders.IF_MODIFIED_SINCE); if (ifms!=null) { if (content!=null) { Buffer mdlm=content.getLastModified(); if (mdlm!=null) { if (ifms.equals(mdlm.toString())) { response.reset(); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return false; } } } long ifmsl=request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); if (ifmsl!=-1) { if (resource.lastModified()/1000 <= ifmsl/1000) { response.reset(); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return false; } } } // Parse the if[un]modified dates and compare to resource long date=request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE); if (date!=-1) { if (resource.lastModified()/1000 > date/1000) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } return true; } /* ------------------------------------------------------------------- */ protected void sendDirectory(HttpServletRequest request, HttpServletResponse response, Resource resource, boolean parent) throws IOException { if (!_dirAllowed) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } byte[] data=null; String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH); String dir = resource.getListHTML(base,parent); if (dir==null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "No directory"); return; } data=dir.getBytes("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setContentLength(data.length); response.getOutputStream().write(data); } /* ------------------------------------------------------------ */ protected void sendData(HttpServletRequest request, HttpServletResponse response, boolean include, Resource resource, HttpContent content, Enumeration reqRanges) throws IOException { long content_length=resource.length(); // Get the output stream (or writer) OutputStream out =null; try{out = response.getOutputStream();} catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());} if ( reqRanges == null || !reqRanges.hasMoreElements()) { // if there were no ranges, send entire entity if (include) { resource.writeTo(out,0,content_length); } else { // See if a short direct method can be used? if (out instanceof HttpConnection.Output) { if (_cacheControl!=null) { if (response instanceof Response) ((Response)response).getHttpFields().put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl); else response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString()); } ((HttpConnection.Output)out).sendContent(content); } else { // Write content normally writeHeaders(response,content,content_length); resource.writeTo(out,0,content_length); } } } else { // Parse the satisfiable ranges List ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length); // if there are no satisfiable ranges, send 416 response if (ranges==null || ranges.size()==0) { writeHeaders(response, content, content_length); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); response.setHeader(HttpHeaders.CONTENT_RANGE, InclusiveByteRange.to416HeaderRangeString(content_length)); resource.writeTo(out,0,content_length); return; } // if there is only a single valid range (must be satisfiable // since were here now), send that range with a 216 response if ( ranges.size()== 1) { InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange)ranges.get(0); long singleLength = singleSatisfiableRange.getSize(content_length); writeHeaders(response,content,singleLength ); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setHeader(HttpHeaders.CONTENT_RANGE, singleSatisfiableRange.toHeaderRangeString(content_length)); resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response,content,-1); String mimetype=content.getContentType().toString(); MultiPartOutputStream multi = new MultiPartOutputStream(out); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // If the request has a "Request-Range" header then we need to // send an old style multipart/x-byteranges Content-Type. This // keeps Netscape and acrobat happy. This is what Apache does. String ctp; if (request.getHeader(HttpHeaders.REQUEST_RANGE)!=null) ctp = "multipart/x-byteranges; boundary="; else ctp = "multipart/byteranges; boundary="; response.setContentType(ctp+multi.getBoundary()); InputStream in=resource.getInputStream(); long pos=0; for (int i=0;i<ranges.size();i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); String header=HttpHeaders.CONTENT_RANGE+": "+ ibr.toHeaderRangeString(content_length); multi.startPart(mimetype,new String[]{header}); long start=ibr.getFirst(content_length); long size=ibr.getSize(content_length); if (in!=null) { // Handle non cached resource if (start<pos) { in.close(); in=resource.getInputStream(); pos=0; } if (pos<start) { in.skip(start-pos); pos=start; } IO.copy(in,multi,size); pos+=size; } else // Handle cached resource (resource).writeTo(multi,start,size); } if (in!=null) in.close(); multi.close(); } return; } /* ------------------------------------------------------------ */ protected void writeHeaders(HttpServletResponse response,HttpContent content,long count) throws IOException { if (content.getContentType()!=null) response.setContentType(content.getContentType().toString()); if (response instanceof Response) { Response r=(Response)response; HttpFields fields = r.getHttpFields(); if (content.getLastModified()!=null) fields.put(HttpHeaders.LAST_MODIFIED_BUFFER,content.getLastModified()); else if (content.getResource()!=null) { long lml=content.getResource().lastModified(); if (lml!=-1) fields.putDateField(HttpHeaders.LAST_MODIFIED_BUFFER,lml); } if (count != -1) r.setLongContentLength(count); if (_acceptRanges) fields.put(HttpHeaders.ACCEPT_RANGES_BUFFER,BYTE_RANGES); if (_cacheControl!=null) fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl); } else { if (content.getLastModified()!=null) response.setHeader(HttpHeaders.LAST_MODIFIED,content.getLastModified().toString()); else response.setDateHeader(HttpHeaders.LAST_MODIFIED,content.getResource().lastModified()); if (count != -1) { if (count<Integer.MAX_VALUE) response.setContentLength((int)count); else response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(count)); } if (_acceptRanges) response.setHeader(HttpHeaders.ACCEPT_RANGES,"bytes"); if (_cacheControl!=null) response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString()); } } /* ------------------------------------------------------------ */ /* * @see javax.servlet.Servlet#destroy() */ public void destroy() { try { if (_nioCache!=null) _nioCache.stop(); if (_bioCache!=null) _bioCache.stop(); } catch(Exception e) { Log.warn(Log.EXCEPTION,e); } finally { super.destroy(); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private class UnCachedContent implements HttpContent { Resource _resource; UnCachedContent(Resource resource) { _resource=resource; } /* ------------------------------------------------------------ */ public Buffer getContentType() { return _mimeTypes.getMimeByExtension(_resource.toString()); } /* ------------------------------------------------------------ */ public Buffer getLastModified() { return null; } /* ------------------------------------------------------------ */ public Buffer getBuffer() { return null; } /* ------------------------------------------------------------ */ public long getContentLength() { return _resource.length(); } /* ------------------------------------------------------------ */ public InputStream getInputStream() throws IOException { return _resource.getInputStream(); } /* ------------------------------------------------------------ */ public Resource getResource() { return _resource; } /* ------------------------------------------------------------ */ public void release() { _resource.release(); _resource=null; } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ class NIOResourceCache extends ResourceCache { /* ------------------------------------------------------------ */ public NIOResourceCache(MimeTypes mimeTypes) { super(mimeTypes); } /* ------------------------------------------------------------ */ protected void fill(Content content) throws IOException { Buffer buffer=null; Resource resource=content.getResource(); long length=resource.length(); if (_useFileMappedBuffer && resource.getFile()!=null) { File file = resource.getFile(); if (file != null) buffer = new NIOBuffer(file); } else { InputStream is = resource.getInputStream(); try { Connector connector = HttpConnection.getCurrentConnection().getConnector(); buffer = new NIOBuffer((int) length, ((NIOConnector)connector).getUseDirectBuffers()?NIOBuffer.DIRECT:NIOBuffer.INDIRECT); } catch(OutOfMemoryError e) { Log.warn(e.toString()); Log.debug(e); buffer = new NIOBuffer((int) length, NIOBuffer.INDIRECT); } buffer.readFrom(is,(int)length); is.close(); } content.setBuffer(buffer); } } }
true
true
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletPath=null; String pathInfo=null; Enumeration reqRanges = null; Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY); if (included!=null && included.booleanValue()) { servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH); pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO); if (servletPath==null) { servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); } } else { included=Boolean.FALSE; servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); // Is this a range request? reqRanges = request.getHeaders(HttpHeaders.RANGE); if (reqRanges!=null && !reqRanges.hasMoreElements()) reqRanges=null; } String pathInContext=URIUtil.addPaths(servletPath,pathInfo); boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH); // Can we gzip this request? String pathInContextGz=null; boolean gzip=false; if (_gzip && reqRanges==null && !endsWithSlash ) { String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING); if (accept!=null && accept.indexOf("gzip")>=0) gzip=true; } // Find the resource and content Resource resource=null; HttpContent content=null; Connector connector = HttpConnection.getCurrentConnection().getConnector(); ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache; try { // Try gzipped content first if (gzip) { pathInContextGz=pathInContext+".gz"; resource=getResource(pathInContextGz); if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } else if (cache!=null) { content=cache.lookup(pathInContextGz,resource); if (content!=null) resource=content.getResource(); } if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } } // find resource if (!gzip) { if (cache==null) resource=getResource(pathInContext); else { content=cache.lookup(pathInContext,this); if (content!=null) resource=content.getResource(); else resource=getResource(pathInContext); } } if (Log.isDebugEnabled()) Log.debug("resource="+resource+(content!=null?" content":"")); // Handle resource if (resource==null || !resource.exists()) response.sendError(HttpServletResponse.SC_NOT_FOUND); else if (!resource.isDirectory()) { // ensure we have content if (content==null) content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) { if (gzip) { response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip"); String mt=_context.getMimeType(pathInContext); if (mt!=null) response.setContentType(mt); } sendData(request,response,included.booleanValue(),resource,content,reqRanges); } } else { String welcome=null; if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null)) { StringBuffer buf=request.getRequestURL(); int param=buf.lastIndexOf(";"); if (param<0) buf.append('/'); else buf.insert(param,'/'); String q=request.getQueryString(); if (q!=null&&q.length()!=0) { buf.append('?'); buf.append(q); } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(buf.toString())); } // else look for a welcome file else if (null!=(welcome=getWelcomeFile(resource))) { String ipath=URIUtil.addPaths(pathInContext,welcome); if (_redirectWelcome) { // Redirect to the index response.setContentLength(0); String q=request.getQueryString(); if (q!=null&&q.length()!=0) response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q); else response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)); } else { // Forward to the index RequestDispatcher dispatcher=request.getRequestDispatcher(ipath); if (dispatcher!=null) { if (included.booleanValue()) dispatcher.include(request,response); else { request.setAttribute("org.mortbay.jetty.welcome",ipath); dispatcher.forward(request,response); } } } } else { content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) sendDirectory(request,response,resource,pathInContext.length()>1); } } } catch(IllegalArgumentException e) { Log.warn(Log.EXCEPTION,e); } finally { if (content!=null) content.release(); else if (resource!=null) resource.release(); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletPath=null; String pathInfo=null; Enumeration reqRanges = null; Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY); if (included!=null && included.booleanValue()) { servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH); pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO); if (servletPath==null) { servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); } } else { included=Boolean.FALSE; servletPath=request.getServletPath(); pathInfo=request.getPathInfo(); // Is this a range request? reqRanges = request.getHeaders(HttpHeaders.RANGE); if (reqRanges!=null && !reqRanges.hasMoreElements()) reqRanges=null; } String pathInContext=URIUtil.addPaths(servletPath,pathInfo); boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH); // Can we gzip this request? String pathInContextGz=null; boolean gzip=false; if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash ) { String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING); if (accept!=null && accept.indexOf("gzip")>=0) gzip=true; } // Find the resource and content Resource resource=null; HttpContent content=null; Connector connector = HttpConnection.getCurrentConnection().getConnector(); ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache; try { // Try gzipped content first if (gzip) { pathInContextGz=pathInContext+".gz"; resource=getResource(pathInContextGz); if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } else if (cache!=null) { content=cache.lookup(pathInContextGz,resource); if (content!=null) resource=content.getResource(); } if (resource==null || !resource.exists()|| resource.isDirectory()) { gzip=false; pathInContextGz=null; } } // find resource if (!gzip) { if (cache==null) resource=getResource(pathInContext); else { content=cache.lookup(pathInContext,this); if (content!=null) resource=content.getResource(); else resource=getResource(pathInContext); } } if (Log.isDebugEnabled()) Log.debug("resource="+resource+(content!=null?" content":"")); // Handle resource if (resource==null || !resource.exists()) response.sendError(HttpServletResponse.SC_NOT_FOUND); else if (!resource.isDirectory()) { // ensure we have content if (content==null) content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) { if (gzip) { response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip"); String mt=_context.getMimeType(pathInContext); if (mt!=null) response.setContentType(mt); } sendData(request,response,included.booleanValue(),resource,content,reqRanges); } } else { String welcome=null; if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null)) { StringBuffer buf=request.getRequestURL(); int param=buf.lastIndexOf(";"); if (param<0) buf.append('/'); else buf.insert(param,'/'); String q=request.getQueryString(); if (q!=null&&q.length()!=0) { buf.append('?'); buf.append(q); } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(buf.toString())); } // else look for a welcome file else if (null!=(welcome=getWelcomeFile(resource))) { String ipath=URIUtil.addPaths(pathInContext,welcome); if (_redirectWelcome) { // Redirect to the index response.setContentLength(0); String q=request.getQueryString(); if (q!=null&&q.length()!=0) response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q); else response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)); } else { // Forward to the index RequestDispatcher dispatcher=request.getRequestDispatcher(ipath); if (dispatcher!=null) { if (included.booleanValue()) dispatcher.include(request,response); else { request.setAttribute("org.mortbay.jetty.welcome",ipath); dispatcher.forward(request,response); } } } } else { content=new UnCachedContent(resource); if (included.booleanValue() || passConditionalHeaders(request,response, resource,content)) sendDirectory(request,response,resource,pathInContext.length()>1); } } } catch(IllegalArgumentException e) { Log.warn(Log.EXCEPTION,e); } finally { if (content!=null) content.release(); else if (resource!=null) resource.release(); } }
diff --git a/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java b/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java index 12794d55a..dd1b56d54 100755 --- a/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java +++ b/src/java/org/infoglue/cms/util/graphics/ThumbnailGenerator.java @@ -1,120 +1,120 @@ /* =============================================================================== * * 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.cms.util.graphics; import java.awt.*; import java.awt.image.*; import java.io.*; import org.apache.log4j.Logger; import org.infoglue.cms.util.CmsPropertyHandler; public class ThumbnailGenerator { private final static Logger logger = Logger.getLogger(ThumbnailGenerator.class.getName()); public ThumbnailGenerator() { } private void execCmd(String command) throws Exception { logger.error(command); String line; Process p = Runtime.getRuntime().exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { logger.error(line); } input.close(); } public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception { Image image = javax.imageio.ImageIO.read(new File(originalFile)); double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } if(imageWidth < thumbWidth && imageHeight < thumbHeight) { thumbWidth = imageWidth; thumbHeight = imageHeight; } else if(imageWidth < thumbWidth) thumbWidth = imageWidth; else if(imageHeight < thumbHeight) thumbHeight = imageHeight; if(thumbWidth < 1) thumbWidth = 1; if(thumbHeight < 1) thumbHeight = 1; - if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase("")) + if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && !CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase("")) { String[] args = new String[5]; args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration"); args[1] = "-resize"; args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight); args[3] = originalFile; args[4] = thumbnailFile; try { Process p = Runtime.getRuntime().exec(args); p.waitFor(); } catch(InterruptedException e) { new Exception("Error resizing image for thumbnail", e); } } else { BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile)); } } }
true
true
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception { Image image = javax.imageio.ImageIO.read(new File(originalFile)); double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } if(imageWidth < thumbWidth && imageHeight < thumbHeight) { thumbWidth = imageWidth; thumbHeight = imageHeight; } else if(imageWidth < thumbWidth) thumbWidth = imageWidth; else if(imageHeight < thumbHeight) thumbHeight = imageHeight; if(thumbWidth < 1) thumbWidth = 1; if(thumbHeight < 1) thumbHeight = 1; if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase("")) { String[] args = new String[5]; args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration"); args[1] = "-resize"; args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight); args[3] = originalFile; args[4] = thumbnailFile; try { Process p = Runtime.getRuntime().exec(args); p.waitFor(); } catch(InterruptedException e) { new Exception("Error resizing image for thumbnail", e); } } else { BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile)); } }
public void transform(String originalFile, String thumbnailFile, int thumbWidth, int thumbHeight, int quality) throws Exception { Image image = javax.imageio.ImageIO.read(new File(originalFile)); double thumbRatio = (double)thumbWidth / (double)thumbHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int)(thumbWidth / imageRatio); } else { thumbWidth = (int)(thumbHeight * imageRatio); } if(imageWidth < thumbWidth && imageHeight < thumbHeight) { thumbWidth = imageWidth; thumbHeight = imageHeight; } else if(imageWidth < thumbWidth) thumbWidth = imageWidth; else if(imageHeight < thumbHeight) thumbHeight = imageHeight; if(thumbWidth < 1) thumbWidth = 1; if(thumbHeight < 1) thumbHeight = 1; if(CmsPropertyHandler.getProperty("externalThumbnailGeneration") != null && !CmsPropertyHandler.getProperty("externalThumbnailGeneration").equalsIgnoreCase("")) { String[] args = new String[5]; args[0] = CmsPropertyHandler.getProperty("externalThumbnailGeneration"); args[1] = "-resize"; args[2] = String.valueOf(thumbWidth) + "x" + String.valueOf(thumbHeight); args[3] = originalFile; args[4] = thumbnailFile; try { Process p = Runtime.getRuntime().exec(args); p.waitFor(); } catch(InterruptedException e) { new Exception("Error resizing image for thumbnail", e); } } else { BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, thumbWidth, thumbHeight); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); javax.imageio.ImageIO.write(thumbImage, "JPG", new File(thumbnailFile)); } }
diff --git a/src/java/main/ca/nengo/ui/actions/PasteAction.java b/src/java/main/ca/nengo/ui/actions/PasteAction.java index 16742c76..0bc32a9f 100644 --- a/src/java/main/ca/nengo/ui/actions/PasteAction.java +++ b/src/java/main/ca/nengo/ui/actions/PasteAction.java @@ -1,86 +1,90 @@ /* 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. The Original Code is "PasteAction.java". Description: "" The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU Public License license (the GPL License), in which case the provisions of GPL License are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL License. */ package ca.nengo.ui.actions; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import ca.nengo.model.Node; import ca.nengo.ui.NengoGraphics; import ca.nengo.ui.lib.actions.ActionException; import ca.nengo.ui.lib.actions.StandardAction; import ca.nengo.ui.models.NodeContainer; import ca.nengo.ui.models.NodeContainer.ContainerException; /** * TODO * * @author TODO */ public class PasteAction extends StandardAction { private static final long serialVersionUID = 1L; private NodeContainer nodeContainer; private Double posX = null; private Double posY = null; /** * @param description TODO * @param nodeContainer TODO */ public PasteAction(String description, NodeContainer nodeContainer) { super(description); this.nodeContainer = nodeContainer; } @Override protected void action() throws ActionException { ArrayList<Node> nodes = NengoGraphics.getInstance().getClipboard().getContents(); ArrayList<Point2D> offsets = NengoGraphics.getInstance().getClipboard().getOffsets(); if (nodes != null && nodes.size() > 0) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); try { CreateModelAction.ensureNonConflictingName(node, nodeContainer); - nodeContainer.addNodeModel(node, posX + offsets.get(i).getX(), posY + offsets.get(i).getY()); + if (posX == null || posY == null) { + nodeContainer.addNodeModel(node, posX, posY); + } else { + nodeContainer.addNodeModel(node, posX + offsets.get(i).getX(), posY + offsets.get(i).getY()); + } } catch (ContainerException e) { throw new ActionException(e); } } } else { throw new ActionException("Clipboard is empty"); } } public void setPosition(Double x, Double y) { posX = x; posY = y; } }
true
true
protected void action() throws ActionException { ArrayList<Node> nodes = NengoGraphics.getInstance().getClipboard().getContents(); ArrayList<Point2D> offsets = NengoGraphics.getInstance().getClipboard().getOffsets(); if (nodes != null && nodes.size() > 0) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); try { CreateModelAction.ensureNonConflictingName(node, nodeContainer); nodeContainer.addNodeModel(node, posX + offsets.get(i).getX(), posY + offsets.get(i).getY()); } catch (ContainerException e) { throw new ActionException(e); } } } else { throw new ActionException("Clipboard is empty"); } }
protected void action() throws ActionException { ArrayList<Node> nodes = NengoGraphics.getInstance().getClipboard().getContents(); ArrayList<Point2D> offsets = NengoGraphics.getInstance().getClipboard().getOffsets(); if (nodes != null && nodes.size() > 0) { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); try { CreateModelAction.ensureNonConflictingName(node, nodeContainer); if (posX == null || posY == null) { nodeContainer.addNodeModel(node, posX, posY); } else { nodeContainer.addNodeModel(node, posX + offsets.get(i).getX(), posY + offsets.get(i).getY()); } } catch (ContainerException e) { throw new ActionException(e); } } } else { throw new ActionException("Clipboard is empty"); } }
diff --git a/src/com/google/ruvolof/randomsequencegenerator/Rsg_main.java b/src/com/google/ruvolof/randomsequencegenerator/Rsg_main.java index 13fcc74..5608151 100644 --- a/src/com/google/ruvolof/randomsequencegenerator/Rsg_main.java +++ b/src/com/google/ruvolof/randomsequencegenerator/Rsg_main.java @@ -1,118 +1,118 @@ package com.google.ruvolof.randomsequencegenerator; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import android.app.Activity; public class Rsg_main extends Activity implements OnClickListener, OnCheckedChangeListener { View range_layout_1; View range_layout_2; View manual_layout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rsg_main); this.range_layout_1 = (View)findViewById(R.id.dlu_range); this.range_layout_2 = (View)findViewById(R.id.s_range); this.manual_layout = (View)findViewById(R.id.manual_layout); Button create = (Button)findViewById(R.id.button_create); create.setOnClickListener(this); RadioGroup rg = (RadioGroup)findViewById(R.id.radio_group); rg.setOnCheckedChangeListener(this); } public void onCheckedChanged (RadioGroup rg, int newchecked) { switch (newchecked) { case R.id.class_radio: this.range_layout_1.setVisibility(View.VISIBLE); this.range_layout_2.setVisibility(View.VISIBLE); this.manual_layout.setVisibility(View.GONE); break; case R.id.manual_radio: this.manual_layout.setVisibility(View.VISIBLE); this.range_layout_1.setVisibility(View.GONE); this.range_layout_2.setVisibility(View.GONE); break; default: this.manual_layout.setVisibility(View.GONE); this.range_layout_1.setVisibility(View.GONE); this.range_layout_2.setVisibility(View.GONE); } } public void onClick (View v) { int clicked = v.getId(); switch (clicked) { case R.id.button_create: - String chars = "0"; + String chars = ""; String result = ""; RadioGroup rg = (RadioGroup)findViewById(R.id.radio_group); int selected = rg.getCheckedRadioButtonId(); switch (selected) { case R.id.binary_radio: chars = chars.concat("01"); break; case R.id.hex_radio: chars = chars.concat("0123456789ABCDEF"); break; case R.id.class_radio: CheckBox digit = (CheckBox)findViewById(R.id.range_digit); CheckBox lowercase = (CheckBox)findViewById(R.id.range_lowercase); CheckBox uppercase = (CheckBox)findViewById(R.id.range_uppercase); CheckBox special = (CheckBox)findViewById(R.id.range_special); if (digit.isChecked()) { chars = chars.concat("0123456789"); } if (lowercase.isChecked()) { chars = chars.concat("qwertyuiopasdfghjklzxcvbnm"); } if (uppercase.isChecked()) { chars = chars.concat("QWERTYUIOPASDFGHJKLZXCVBNM"); } if (special.isChecked()) { chars = chars.concat("$%&/()=?@#<>_-£[]*"); } break; case R.id.manual_radio: TextView manual = (TextView)findViewById(R.id.manual); String chars_to_add = manual.getText().toString(); chars = chars.concat(chars_to_add); break; default: break; } int chars_last_index = chars.length() - 1; TextView length_textview = (TextView)findViewById(R.id.string_length); String length_as_string = length_textview.getText().toString(); int selected_length = Integer.parseInt(length_as_string, 10); for (int i = selected_length; i > 0; i--) { long random = Math.round(Math.random()*chars_last_index); int index = (int) random; String to_concat = String.valueOf(chars.charAt(index)); result = result.concat(to_concat); } TextView output = (TextView)findViewById(R.id.output_textview); output.setText(chars); break; default: break; } } }
true
true
public void onClick (View v) { int clicked = v.getId(); switch (clicked) { case R.id.button_create: String chars = "0"; String result = ""; RadioGroup rg = (RadioGroup)findViewById(R.id.radio_group); int selected = rg.getCheckedRadioButtonId(); switch (selected) { case R.id.binary_radio: chars = chars.concat("01"); break; case R.id.hex_radio: chars = chars.concat("0123456789ABCDEF"); break; case R.id.class_radio: CheckBox digit = (CheckBox)findViewById(R.id.range_digit); CheckBox lowercase = (CheckBox)findViewById(R.id.range_lowercase); CheckBox uppercase = (CheckBox)findViewById(R.id.range_uppercase); CheckBox special = (CheckBox)findViewById(R.id.range_special); if (digit.isChecked()) { chars = chars.concat("0123456789"); } if (lowercase.isChecked()) { chars = chars.concat("qwertyuiopasdfghjklzxcvbnm"); } if (uppercase.isChecked()) { chars = chars.concat("QWERTYUIOPASDFGHJKLZXCVBNM"); } if (special.isChecked()) { chars = chars.concat("$%&/()=?@#<>_-£[]*"); } break; case R.id.manual_radio: TextView manual = (TextView)findViewById(R.id.manual); String chars_to_add = manual.getText().toString(); chars = chars.concat(chars_to_add); break; default: break; } int chars_last_index = chars.length() - 1; TextView length_textview = (TextView)findViewById(R.id.string_length); String length_as_string = length_textview.getText().toString(); int selected_length = Integer.parseInt(length_as_string, 10); for (int i = selected_length; i > 0; i--) { long random = Math.round(Math.random()*chars_last_index); int index = (int) random; String to_concat = String.valueOf(chars.charAt(index)); result = result.concat(to_concat); } TextView output = (TextView)findViewById(R.id.output_textview); output.setText(chars); break; default: break; } }
public void onClick (View v) { int clicked = v.getId(); switch (clicked) { case R.id.button_create: String chars = ""; String result = ""; RadioGroup rg = (RadioGroup)findViewById(R.id.radio_group); int selected = rg.getCheckedRadioButtonId(); switch (selected) { case R.id.binary_radio: chars = chars.concat("01"); break; case R.id.hex_radio: chars = chars.concat("0123456789ABCDEF"); break; case R.id.class_radio: CheckBox digit = (CheckBox)findViewById(R.id.range_digit); CheckBox lowercase = (CheckBox)findViewById(R.id.range_lowercase); CheckBox uppercase = (CheckBox)findViewById(R.id.range_uppercase); CheckBox special = (CheckBox)findViewById(R.id.range_special); if (digit.isChecked()) { chars = chars.concat("0123456789"); } if (lowercase.isChecked()) { chars = chars.concat("qwertyuiopasdfghjklzxcvbnm"); } if (uppercase.isChecked()) { chars = chars.concat("QWERTYUIOPASDFGHJKLZXCVBNM"); } if (special.isChecked()) { chars = chars.concat("$%&/()=?@#<>_-£[]*"); } break; case R.id.manual_radio: TextView manual = (TextView)findViewById(R.id.manual); String chars_to_add = manual.getText().toString(); chars = chars.concat(chars_to_add); break; default: break; } int chars_last_index = chars.length() - 1; TextView length_textview = (TextView)findViewById(R.id.string_length); String length_as_string = length_textview.getText().toString(); int selected_length = Integer.parseInt(length_as_string, 10); for (int i = selected_length; i > 0; i--) { long random = Math.round(Math.random()*chars_last_index); int index = (int) random; String to_concat = String.valueOf(chars.charAt(index)); result = result.concat(to_concat); } TextView output = (TextView)findViewById(R.id.output_textview); output.setText(chars); break; default: break; } }
diff --git a/src/me/cyberpew/moovr/MoovrBlock.java b/src/me/cyberpew/moovr/MoovrBlock.java index cc830b3..d9a1555 100644 --- a/src/me/cyberpew/moovr/MoovrBlock.java +++ b/src/me/cyberpew/moovr/MoovrBlock.java @@ -1,47 +1,44 @@ package me.cyberpew.moovr; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; public class MoovrBlock implements Listener { private Moovr plugin; public MoovrBlock(Moovr p) { plugin = p; } @EventHandler public void onPlayerMoveEvent(PlayerMoveEvent event) { - event.getFrom().getBlock().getLocation() - .equals(event.getTo().getBlock().getLocation()); + event.getFrom().getBlock().getLocation().equals(event.getTo().getBlock().getLocation()); Player player = event.getPlayer(); Block block = player.getLocation().getBlock(); Block blockAbove = block.getRelative(BlockFace.UP); - Block blockJump = block.getRelative(BlockFace.UP, 1); + Block blockJump = block.getRelative(BlockFace.UP, 2); if (player.hasPermission("moovr.use") || player.getPlayer().isOp()) { - if (blockAbove.getType() == Material.AIR - || blockJump.getType() == Material.AIR) { + if (blockAbove.getType() == Material.AIR || blockJump.getType() == Material.AIR) { if (block.getType() == Material.POWERED_RAIL) { Block blockUnder = block.getRelative(BlockFace.DOWN); if (blockUnder.getType() == Material.GOLD_BLOCK) { if (player.hasPermission("moovr.use")) { - float walkspeed = (float) plugin.getConfig() - .getDouble("moovr.walkspeed"); + float walkspeed = (float) plugin.getConfig().getDouble("moovr.walkspeed"); player.setWalkSpeed(walkspeed); } } } else { float defaultwalkspeed = 0.2F; player.setWalkSpeed(defaultwalkspeed); } } } } }
false
true
public void onPlayerMoveEvent(PlayerMoveEvent event) { event.getFrom().getBlock().getLocation() .equals(event.getTo().getBlock().getLocation()); Player player = event.getPlayer(); Block block = player.getLocation().getBlock(); Block blockAbove = block.getRelative(BlockFace.UP); Block blockJump = block.getRelative(BlockFace.UP, 1); if (player.hasPermission("moovr.use") || player.getPlayer().isOp()) { if (blockAbove.getType() == Material.AIR || blockJump.getType() == Material.AIR) { if (block.getType() == Material.POWERED_RAIL) { Block blockUnder = block.getRelative(BlockFace.DOWN); if (blockUnder.getType() == Material.GOLD_BLOCK) { if (player.hasPermission("moovr.use")) { float walkspeed = (float) plugin.getConfig() .getDouble("moovr.walkspeed"); player.setWalkSpeed(walkspeed); } } } else { float defaultwalkspeed = 0.2F; player.setWalkSpeed(defaultwalkspeed); } } } }
public void onPlayerMoveEvent(PlayerMoveEvent event) { event.getFrom().getBlock().getLocation().equals(event.getTo().getBlock().getLocation()); Player player = event.getPlayer(); Block block = player.getLocation().getBlock(); Block blockAbove = block.getRelative(BlockFace.UP); Block blockJump = block.getRelative(BlockFace.UP, 2); if (player.hasPermission("moovr.use") || player.getPlayer().isOp()) { if (blockAbove.getType() == Material.AIR || blockJump.getType() == Material.AIR) { if (block.getType() == Material.POWERED_RAIL) { Block blockUnder = block.getRelative(BlockFace.DOWN); if (blockUnder.getType() == Material.GOLD_BLOCK) { if (player.hasPermission("moovr.use")) { float walkspeed = (float) plugin.getConfig().getDouble("moovr.walkspeed"); player.setWalkSpeed(walkspeed); } } } else { float defaultwalkspeed = 0.2F; player.setWalkSpeed(defaultwalkspeed); } } } }
diff --git a/src/main/java/stormpot/benchmark/SingleThreadedBenchmark.java b/src/main/java/stormpot/benchmark/SingleThreadedBenchmark.java index 82b83e8..b87997e 100644 --- a/src/main/java/stormpot/benchmark/SingleThreadedBenchmark.java +++ b/src/main/java/stormpot/benchmark/SingleThreadedBenchmark.java @@ -1,38 +1,38 @@ package stormpot.benchmark; import org.benchkit.Benchmark; import org.benchkit.BenchmarkRunner; import org.benchkit.Recorder; public class SingleThreadedBenchmark implements Benchmark { private final PoolFactory factory; private PoolFacade pool; public SingleThreadedBenchmark(PoolFactory factory) { this.factory = factory; } @Override public void setUp() { pool = factory.create(10, 10000); } @Override - public void runSession(Recorder mainRecorder) throws Exception { + public void runSession(Recorder recorder) throws Exception { for (int i = 0; i < 1000 * 1000; i++) { - long begin = mainRecorder.begin(); + long begin = recorder.begin(); Object obj = pool.claim(); pool.release(obj); - mainRecorder.record(begin); + recorder.record(begin); } } @Override public void tearDown() throws Exception { factory.shutdown(pool); } public static void main(String[] args) throws Exception { BenchmarkRunner.run(new SingleThreadedBenchmark(PoolFactory.blaze)); } }
false
true
public void runSession(Recorder mainRecorder) throws Exception { for (int i = 0; i < 1000 * 1000; i++) { long begin = mainRecorder.begin(); Object obj = pool.claim(); pool.release(obj); mainRecorder.record(begin); } }
public void runSession(Recorder recorder) throws Exception { for (int i = 0; i < 1000 * 1000; i++) { long begin = recorder.begin(); Object obj = pool.claim(); pool.release(obj); recorder.record(begin); } }
diff --git a/src/powercrystals/minefactoryreloaded/block/BlockRubberWood.java b/src/powercrystals/minefactoryreloaded/block/BlockRubberWood.java index c70b7cf4..e7b7c5c5 100644 --- a/src/powercrystals/minefactoryreloaded/block/BlockRubberWood.java +++ b/src/powercrystals/minefactoryreloaded/block/BlockRubberWood.java @@ -1,99 +1,99 @@ package powercrystals.minefactoryreloaded.block; import java.util.ArrayList; import java.util.List; import net.minecraft.block.BlockLog; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import powercrystals.minefactoryreloaded.MineFactoryReloadedCore; import powercrystals.minefactoryreloaded.api.rednet.IConnectableRedNet; import powercrystals.minefactoryreloaded.api.rednet.RedNetConnectionType; import powercrystals.minefactoryreloaded.gui.MFRCreativeTab; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class BlockRubberWood extends BlockLog implements IConnectableRedNet { private Icon _iconLogTop; private Icon _iconLogSide; public BlockRubberWood(int id) { super(id); setHardness(2.0F); setStepSound(soundWoodFootstep); setUnlocalizedName("mfr.rubberwood.log"); setCreativeTab(MFRCreativeTab.tab); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister ir) { _iconLogSide = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName() + ".side"); _iconLogTop = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName() + ".top"); } @Override @SideOnly(Side.CLIENT) public Icon getIcon(int side, int meta) { int logDirection = meta & 12; return logDirection == 0 && (side == 1 || side == 0) ? _iconLogTop : (logDirection == 4 && (side == 5 || side == 4) ? _iconLogTop : (logDirection == 8 && (side == 2 || side == 3) ? _iconLogTop : _iconLogSide)); } @Override public ArrayList<ItemStack> getBlockDropped(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> drops = new ArrayList<ItemStack>(); drops.add(new ItemStack(blockID, 1, 0)); if((metadata & 3) > 0) { - drops.add(new ItemStack(MineFactoryReloadedCore.rawRubberItem, 1 + world.rand.nextInt(fortune))); + drops.add(new ItemStack(MineFactoryReloadedCore.rawRubberItem, fortune <= 0 ? 1 : 1 + world.rand.nextInt(fortune))); } return drops; } @SuppressWarnings({ "unchecked", "rawtypes" }) @SideOnly(Side.CLIENT) @Override public void getSubBlocks(int blockId, CreativeTabs tab, List subBlocks) { subBlocks.add(new ItemStack(blockId, 1, 0)); } @Override public RedNetConnectionType getConnectionType(World world, int x, int y, int z, ForgeDirection side) { return RedNetConnectionType.None; } @Override public int[] getOutputValues(World world, int x, int y, int z, ForgeDirection side) { return null; } @Override public int getOutputValue(World world, int x, int y, int z, ForgeDirection side, int subnet) { return 0; } @Override public void onInputsChanged(World world, int x, int y, int z, ForgeDirection side, int[] inputValues) { } @Override public void onInputChanged(World world, int x, int y, int z, ForgeDirection side, int inputValue) { } }
true
true
public ArrayList<ItemStack> getBlockDropped(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> drops = new ArrayList<ItemStack>(); drops.add(new ItemStack(blockID, 1, 0)); if((metadata & 3) > 0) { drops.add(new ItemStack(MineFactoryReloadedCore.rawRubberItem, 1 + world.rand.nextInt(fortune))); } return drops; }
public ArrayList<ItemStack> getBlockDropped(World world, int x, int y, int z, int metadata, int fortune) { ArrayList<ItemStack> drops = new ArrayList<ItemStack>(); drops.add(new ItemStack(blockID, 1, 0)); if((metadata & 3) > 0) { drops.add(new ItemStack(MineFactoryReloadedCore.rawRubberItem, fortune <= 0 ? 1 : 1 + world.rand.nextInt(fortune))); } return drops; }
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java index 967fac51b..0fdd433fd 100644 --- a/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java +++ b/grails/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java @@ -1,285 +1,288 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.metaclass; import grails.util.JSonBuilder; import grails.util.OpenRicoBuilder; import groovy.lang.*; import groovy.text.Template; import groovy.xml.StreamingMarkupBuilder; import org.apache.commons.collections.BeanMap; import org.apache.commons.lang.StringUtils; import org.codehaus.groovy.grails.commons.GrailsControllerClass; import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine; import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes; import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletResponse; import org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Pattern; /** * Allows rendering of text, views, and templates to the response * * @author Graeme Rocher * @since Oct 27, 2005 */ public class RenderDynamicMethod extends AbstractDynamicControllerMethod { public static final String METHOD_SIGNATURE = "render"; public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$'); public static final String ARGUMENT_TEXT = "text"; public static final String ARGUMENT_CONTENT_TYPE = "contentType"; public static final String ARGUMENT_ENCODING = "encoding"; public static final String ARGUMENT_VIEW = "view"; public static final String ARGUMENT_MODEL = "model"; public static final String ARGUMENT_TEMPLATE = "template"; public static final String ARGUMENT_BEAN = "bean"; public static final String ARGUMENT_COLLECTION = "collection"; public static final String ARGUMENT_BUILDER = "builder"; public static final String ARGUMENT_VAR = "var"; private static final String DEFAULT_ARGUMENT = "it"; private static final String BUILDER_TYPE_RICO = "rico"; private static final String BUILDER_TYPE_JSON = "json"; private GrailsControllerHelper helper; protected GrailsHttpServletResponse response; private static final String ARGUMENT_TO = "to"; public RenderDynamicMethod(GrailsControllerHelper helper, HttpServletRequest request, HttpServletResponse response) { super(METHOD_PATTERN, request, response); this.helper = helper; if(response instanceof GrailsHttpServletResponse) this.response = (GrailsHttpServletResponse)response; else this.response = new GrailsHttpServletResponse(response); } public Object invoke(Object target, Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); boolean renderView = true; GroovyObject controller = (GroovyObject)target; if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) { try { response.getWriter().write(arguments[0].toString()); renderView = false; } catch (IOException e) { throw new ControllerExecutionException(e.getMessage(),e); } } else if(arguments[0] instanceof Closure) { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(response.getWriter()); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e); } renderView = false; } else if(arguments[0] instanceof Map) { Map argMap = (Map)arguments[0]; Writer out; try { if(argMap.containsKey(ARGUMENT_TO)) { out = (Writer)argMap.get(ARGUMENT_TO); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(), argMap.get(ARGUMENT_ENCODING).toString()); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString()); } else { out = response.getWriter(); } } catch(IOException ioe) { throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe); } if(arguments[arguments.length - 1] instanceof Closure) { if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) { OpenRicoBuilder orb; try { orb = new OpenRicoBuilder(response); renderView = false; } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] }); } else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){ JSonBuilder jsonBuilder; try{ jsonBuilder = new JSonBuilder(response); renderView = false; }catch(IOException e){ throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] }); } else { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(out); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } } else if(arguments[arguments.length - 1] instanceof String) { try { out.write((String)arguments[arguments.length - 1]); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_TEXT)) { String text = argMap.get(ARGUMENT_TEXT).toString(); try { out.write(text); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_VIEW)) { String viewName = argMap.get(ARGUMENT_VIEW).toString(); String viewUri; if(viewName.indexOf('/') > -1) { if(!viewName.startsWith("/")) viewName = '/' + viewName; viewUri = viewName; } else { GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName()); viewUri = controllerClass.getViewByName(viewName); } Map model; Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { model = (Map)modelObject; } else { model = new BeanMap(target); } controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) ); } else if(argMap.containsKey(ARGUMENT_TEMPLATE)) { String templateName = argMap.get(ARGUMENT_TEMPLATE).toString(); String var = (String)argMap.get(ARGUMENT_VAR); // get the template uri GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES); String templateUri = attrs.getTemplateUri(templateName,request); // retrieve gsp engine GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine(); try { Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response); if(t == null) { throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found."); } Map binding = new HashMap(); if(argMap.containsKey(ARGUMENT_BEAN)) { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, argMap.get(ARGUMENT_BEAN)); Writable w = t.make(binding); w.writeTo(out); } else if(argMap.containsKey(ARGUMENT_COLLECTION)) { Object colObject = argMap.get(ARGUMENT_COLLECTION); if(colObject instanceof Collection) { Collection c = (Collection) colObject; for (Iterator i = c.iterator(); i.hasNext();) { Object o = i.next(); if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, o); else binding.put(var, o); Writable w = t.make(binding); w.writeTo(out); } } else { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, colObject); Writable w = t.make(binding); w.writeTo(out); } } else if(argMap.containsKey(ARGUMENT_MODEL)) { Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL)); w.writeTo(out); } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } renderView = false; } + catch(GroovyRuntimeException gre) { + throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre); + } catch(IOException ioex) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex); } catch (ServletException e) { throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } if(controller!=null) controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView)); return null; } }
true
true
public Object invoke(Object target, Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); boolean renderView = true; GroovyObject controller = (GroovyObject)target; if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) { try { response.getWriter().write(arguments[0].toString()); renderView = false; } catch (IOException e) { throw new ControllerExecutionException(e.getMessage(),e); } } else if(arguments[0] instanceof Closure) { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(response.getWriter()); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e); } renderView = false; } else if(arguments[0] instanceof Map) { Map argMap = (Map)arguments[0]; Writer out; try { if(argMap.containsKey(ARGUMENT_TO)) { out = (Writer)argMap.get(ARGUMENT_TO); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(), argMap.get(ARGUMENT_ENCODING).toString()); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString()); } else { out = response.getWriter(); } } catch(IOException ioe) { throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe); } if(arguments[arguments.length - 1] instanceof Closure) { if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) { OpenRicoBuilder orb; try { orb = new OpenRicoBuilder(response); renderView = false; } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] }); } else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){ JSonBuilder jsonBuilder; try{ jsonBuilder = new JSonBuilder(response); renderView = false; }catch(IOException e){ throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] }); } else { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(out); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } } else if(arguments[arguments.length - 1] instanceof String) { try { out.write((String)arguments[arguments.length - 1]); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_TEXT)) { String text = argMap.get(ARGUMENT_TEXT).toString(); try { out.write(text); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_VIEW)) { String viewName = argMap.get(ARGUMENT_VIEW).toString(); String viewUri; if(viewName.indexOf('/') > -1) { if(!viewName.startsWith("/")) viewName = '/' + viewName; viewUri = viewName; } else { GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName()); viewUri = controllerClass.getViewByName(viewName); } Map model; Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { model = (Map)modelObject; } else { model = new BeanMap(target); } controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) ); } else if(argMap.containsKey(ARGUMENT_TEMPLATE)) { String templateName = argMap.get(ARGUMENT_TEMPLATE).toString(); String var = (String)argMap.get(ARGUMENT_VAR); // get the template uri GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES); String templateUri = attrs.getTemplateUri(templateName,request); // retrieve gsp engine GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine(); try { Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response); if(t == null) { throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found."); } Map binding = new HashMap(); if(argMap.containsKey(ARGUMENT_BEAN)) { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, argMap.get(ARGUMENT_BEAN)); Writable w = t.make(binding); w.writeTo(out); } else if(argMap.containsKey(ARGUMENT_COLLECTION)) { Object colObject = argMap.get(ARGUMENT_COLLECTION); if(colObject instanceof Collection) { Collection c = (Collection) colObject; for (Iterator i = c.iterator(); i.hasNext();) { Object o = i.next(); if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, o); else binding.put(var, o); Writable w = t.make(binding); w.writeTo(out); } } else { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, colObject); Writable w = t.make(binding); w.writeTo(out); } } else if(argMap.containsKey(ARGUMENT_MODEL)) { Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL)); w.writeTo(out); } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } renderView = false; } catch(IOException ioex) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex); } catch (ServletException e) { throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } if(controller!=null) controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView)); return null; }
public Object invoke(Object target, Object[] arguments) { if(arguments.length == 0) throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); boolean renderView = true; GroovyObject controller = (GroovyObject)target; if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) { try { response.getWriter().write(arguments[0].toString()); renderView = false; } catch (IOException e) { throw new ControllerExecutionException(e.getMessage(),e); } } else if(arguments[0] instanceof Closure) { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(response.getWriter()); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e); } renderView = false; } else if(arguments[0] instanceof Map) { Map argMap = (Map)arguments[0]; Writer out; try { if(argMap.containsKey(ARGUMENT_TO)) { out = (Writer)argMap.get(ARGUMENT_TO); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(), argMap.get(ARGUMENT_ENCODING).toString()); } else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) { out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString()); } else { out = response.getWriter(); } } catch(IOException ioe) { throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe); } if(arguments[arguments.length - 1] instanceof Closure) { if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) { OpenRicoBuilder orb; try { orb = new OpenRicoBuilder(response); renderView = false; } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] }); } else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){ JSonBuilder jsonBuilder; try{ jsonBuilder = new JSonBuilder(response); renderView = false; }catch(IOException e){ throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] }); } else { StreamingMarkupBuilder b = new StreamingMarkupBuilder(); Writable markup = (Writable)b.bind(arguments[arguments.length - 1]); try { markup.writeTo(out); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } } else if(arguments[arguments.length - 1] instanceof String) { try { out.write((String)arguments[arguments.length - 1]); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_TEXT)) { String text = argMap.get(ARGUMENT_TEXT).toString(); try { out.write(text); } catch (IOException e) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } renderView = false; } else if(argMap.containsKey(ARGUMENT_VIEW)) { String viewName = argMap.get(ARGUMENT_VIEW).toString(); String viewUri; if(viewName.indexOf('/') > -1) { if(!viewName.startsWith("/")) viewName = '/' + viewName; viewUri = viewName; } else { GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName()); viewUri = controllerClass.getViewByName(viewName); } Map model; Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { model = (Map)modelObject; } else { model = new BeanMap(target); } controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) ); } else if(argMap.containsKey(ARGUMENT_TEMPLATE)) { String templateName = argMap.get(ARGUMENT_TEMPLATE).toString(); String var = (String)argMap.get(ARGUMENT_VAR); // get the template uri GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES); String templateUri = attrs.getTemplateUri(templateName,request); // retrieve gsp engine GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine(); try { Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response); if(t == null) { throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found."); } Map binding = new HashMap(); if(argMap.containsKey(ARGUMENT_BEAN)) { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, argMap.get(ARGUMENT_BEAN)); Writable w = t.make(binding); w.writeTo(out); } else if(argMap.containsKey(ARGUMENT_COLLECTION)) { Object colObject = argMap.get(ARGUMENT_COLLECTION); if(colObject instanceof Collection) { Collection c = (Collection) colObject; for (Iterator i = c.iterator(); i.hasNext();) { Object o = i.next(); if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, o); else binding.put(var, o); Writable w = t.make(binding); w.writeTo(out); } } else { if(StringUtils.isBlank(var)) binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN)); else binding.put(var, colObject); Writable w = t.make(binding); w.writeTo(out); } } else if(argMap.containsKey(ARGUMENT_MODEL)) { Object modelObject = argMap.get(ARGUMENT_MODEL); if(modelObject instanceof Map) { Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL)); w.writeTo(out); } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } } else { Writable w = t.make(new BeanMap(target)); w.writeTo(out); } renderView = false; } catch(GroovyRuntimeException gre) { throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre); } catch(IOException ioex) { throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex); } catch (ServletException e) { throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } } else { throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments); } if(controller!=null) controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView)); return null; }
diff --git a/src/app/navigps/gui/ToolBar/NaviToolBar.java b/src/app/navigps/gui/ToolBar/NaviToolBar.java index 91116af..cd7f9ad 100644 --- a/src/app/navigps/gui/ToolBar/NaviToolBar.java +++ b/src/app/navigps/gui/ToolBar/NaviToolBar.java @@ -1,117 +1,118 @@ /* * NaviToolbar.java * * Created on 2009-04-15, 20:45:36 */ package app.navigps.gui.ToolBar; import app.navigps.gui.ToolBar.UI.NaviToolBarUI; import app.navigps.gui.borders.OvalBorder; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.RoundRectangle2D; import javax.swing.JToolBar; import javax.swing.border.Border; import org.jdesktop.animation.timing.Animator; import org.jdesktop.animation.timing.TimingTargetAdapter; import org.jdesktop.animation.timing.interpolation.PropertySetter; /** * * @author Grzegorz (wara) Warywoda */ public class NaviToolBar extends JToolBar{ private Animator animator; public NaviToolBar(String name){ super(name); init(); } private void init() { setBorder(new OvalBorder(3,3,3,3,10,10,new Color(166,166,166))); addSeparator(); setUI(new NaviToolBarUI()); } @Override protected void paintComponent(Graphics g) { Border bord = getBorder(); if(bord instanceof OvalBorder){ OvalBorder ovb= (OvalBorder)bord; RoundRectangle2D clip = new RoundRectangle2D.Double(-1,-1, getWidth()+1,getHeight()+1, ovb.getRecW(), ovb.getRecH()); Area newClip = new Area(g.getClip()); Area visbClip = new Area(clip); newClip.intersect(visbClip); GeneralPath gpClip = new GeneralPath(newClip); g.setClip(gpClip); } super.paintComponent(g); } @Override public void setVisible(boolean aFlag) { if(isVisible() != aFlag){ super.setVisible(aFlag); } } @Override public void setLocation(Point p) { super.setLocation(p); } @Override public void setBounds(Rectangle r) { animationBounds(this, r); } private void animationBounds(Component comp,Rectangle newrec){ Rectangle oldrec = comp.getBounds();//current position if(newrec.equals(oldrec)){ //System.out.println("the same rect, return"); return; } comp.setLocation(newrec.x, newrec.y); Dimension oldDim = new Dimension(oldrec.width, oldrec.height); Dimension newDim = new Dimension(newrec.width, newrec.height); if(animator != null && animator.isRunning()){ animator.stop(); } animator = PropertySetter.createAnimator(500,comp,"size",oldDim,newDim); animator.setDeceleration(.7f); animator.addTarget(new TimingTargetAdapter(){ @Override public void timingEvent(float fraction) { //System.out.println("timing event "+fraction); - //repaint(); + //repaint(); } @Override public void end() { //animatorCount--; //repaint(); + validate(); } @Override public void begin() { //animatorCount++; } }); animator.start(); } }
false
true
private void animationBounds(Component comp,Rectangle newrec){ Rectangle oldrec = comp.getBounds();//current position if(newrec.equals(oldrec)){ //System.out.println("the same rect, return"); return; } comp.setLocation(newrec.x, newrec.y); Dimension oldDim = new Dimension(oldrec.width, oldrec.height); Dimension newDim = new Dimension(newrec.width, newrec.height); if(animator != null && animator.isRunning()){ animator.stop(); } animator = PropertySetter.createAnimator(500,comp,"size",oldDim,newDim); animator.setDeceleration(.7f); animator.addTarget(new TimingTargetAdapter(){ @Override public void timingEvent(float fraction) { //System.out.println("timing event "+fraction); //repaint(); } @Override public void end() { //animatorCount--; //repaint(); } @Override public void begin() { //animatorCount++; } }); animator.start(); }
private void animationBounds(Component comp,Rectangle newrec){ Rectangle oldrec = comp.getBounds();//current position if(newrec.equals(oldrec)){ //System.out.println("the same rect, return"); return; } comp.setLocation(newrec.x, newrec.y); Dimension oldDim = new Dimension(oldrec.width, oldrec.height); Dimension newDim = new Dimension(newrec.width, newrec.height); if(animator != null && animator.isRunning()){ animator.stop(); } animator = PropertySetter.createAnimator(500,comp,"size",oldDim,newDim); animator.setDeceleration(.7f); animator.addTarget(new TimingTargetAdapter(){ @Override public void timingEvent(float fraction) { //System.out.println("timing event "+fraction); //repaint(); } @Override public void end() { //animatorCount--; //repaint(); validate(); } @Override public void begin() { //animatorCount++; } }); animator.start(); }
diff --git a/src/jclustering/metrics/Mahalanobis.java b/src/jclustering/metrics/Mahalanobis.java index 7409c23..7001bc3 100755 --- a/src/jclustering/metrics/Mahalanobis.java +++ b/src/jclustering/metrics/Mahalanobis.java @@ -1,84 +1,84 @@ package jclustering.metrics; import java.util.Arrays; import org.apache.commons.math3.linear.LUDecomposition; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.stat.correlation.StorelessCovariance; /** * Implements a Mahanalnobis distance. See * <a href="http://en.wikipedia.org/wiki/Mahalanobis_distance">the * Mahalanobis distance</a> page on Wikipedia for more information. * * @author <a href="mailto:[email protected]">Jos� Mar�a Mateos</a>. * */ public class Mahalanobis extends ClusteringMetric { private boolean init = false; private RealMatrix cov = null; @Override public double distance(double[] centroid, double[] data) { // Need some data before starting if (!init) { _init(); } // If the arrays are the same, the distance is 0.0 if (Arrays.equals(centroid, data)) { return 0.0; } // Create a new array with the difference between the two arrays double [] diff = new double[centroid.length]; for (int i = 0; i < centroid.length; i++) { diff[i] = centroid[i] - data[i]; } // Left-hand side of the equation: vector * cov^-1 double [] left = cov.preMultiply(diff); // Compute the dot product of both vectors double res = 0.0; for (int i = 0; i < diff.length; i++) { res += left[i] * diff[i]; } - return res; + return Math.sqrt(res); } /* * Initializes the covariance matrix */ private void _init() { int dim[] = ip.getDimensions(); StorelessCovariance sc = new StorelessCovariance(dim[4]); // Feed the StorelessCovariance for (int slice = 1; slice < dim[3]; slice++) { for (int x = 0; x < dim[0]; x++) { for (int y = 0; y < dim[1]; y++) { double [] tac = ip.getTAC(x, y, slice); sc.increment(tac); } } } // Set the covariance value RealMatrix temp = sc.getCovarianceMatrix(); // But this matrix is always used inverted. Do it now. cov = new LUDecomposition(temp).getSolver().getInverse(); // Don't init again init = true; } }
true
true
public double distance(double[] centroid, double[] data) { // Need some data before starting if (!init) { _init(); } // If the arrays are the same, the distance is 0.0 if (Arrays.equals(centroid, data)) { return 0.0; } // Create a new array with the difference between the two arrays double [] diff = new double[centroid.length]; for (int i = 0; i < centroid.length; i++) { diff[i] = centroid[i] - data[i]; } // Left-hand side of the equation: vector * cov^-1 double [] left = cov.preMultiply(diff); // Compute the dot product of both vectors double res = 0.0; for (int i = 0; i < diff.length; i++) { res += left[i] * diff[i]; } return res; }
public double distance(double[] centroid, double[] data) { // Need some data before starting if (!init) { _init(); } // If the arrays are the same, the distance is 0.0 if (Arrays.equals(centroid, data)) { return 0.0; } // Create a new array with the difference between the two arrays double [] diff = new double[centroid.length]; for (int i = 0; i < centroid.length; i++) { diff[i] = centroid[i] - data[i]; } // Left-hand side of the equation: vector * cov^-1 double [] left = cov.preMultiply(diff); // Compute the dot product of both vectors double res = 0.0; for (int i = 0; i < diff.length; i++) { res += left[i] * diff[i]; } return Math.sqrt(res); }
diff --git a/src/gov/nist/javax/sip/stack/IOHandler.java b/src/gov/nist/javax/sip/stack/IOHandler.java index c5795733..072ec1d9 100755 --- a/src/gov/nist/javax/sip/stack/IOHandler.java +++ b/src/gov/nist/javax/sip/stack/IOHandler.java @@ -1,715 +1,715 @@ /* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 United States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ /******************************************************************************* * Product of NIST/ITL Advanced Networking Technologies Division (ANTD). * *******************************************************************************/ package gov.nist.javax.sip.stack; import gov.nist.core.CommonLogger; import gov.nist.core.LogLevels; import gov.nist.core.LogWriter; import gov.nist.core.StackLogger; import gov.nist.javax.sip.SipStackImpl; import java.io.IOException; import java.io.OutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.util.Enumeration; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; /* * TLS support Added by Daniel J.Martinez Manzano <[email protected]> * */ /** * Low level Input output to a socket. Caches TCP connections and takes care of * re-connecting to the remote party if the other end drops the connection * * @version 1.2 * * @author M. Ranganathan <br/> * * */ public class IOHandler { private static StackLogger logger = CommonLogger.getLogger(IOHandler.class); private SipStackImpl sipStack; private static final String TCP = "tcp"; // Added by Daniel J. Martinez Manzano <[email protected]> private static final String TLS = "tls"; // A cache of client sockets that can be re-used for // sending tcp messages. private final ConcurrentHashMap<String, Socket> socketTable = new ConcurrentHashMap<String, Socket>(); private final ConcurrentHashMap<String, Semaphore> socketCreationMap = new ConcurrentHashMap<String, Semaphore>(); // private Semaphore ioSemaphore = new Semaphore(1); protected static String makeKey(InetAddress addr, int port) { return addr.getHostAddress() + ":" + port; } protected static String makeKey(String addr, int port) { return addr + ":" + port; } protected IOHandler(SIPTransactionStack sipStack) { this.sipStack = (SipStackImpl) sipStack; } protected void putSocket(String key, Socket sock) { if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { logger.logDebug("adding socket for key " + key); } socketTable.put(key, sock); } protected Socket getSocket(String key) { return (Socket) socketTable.get(key); } protected void removeSocket(String key) { socketTable.remove(key); socketCreationMap.remove(key); if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { logger.logDebug("removed Socket and Semaphore for key " + key); } } /** * A private function to write things out. This needs to be synchronized as * writes can occur from multiple threads. We write in chunks to allow the * other side to synchronize for large sized writes. */ private void writeChunks(OutputStream outputStream, byte[] bytes, int length) throws IOException { // Chunk size is 16K - this hack is for large // writes over slow connections. synchronized (outputStream) { // outputStream.write(bytes,0,length); int chunksize = 8 * 1024; for (int p = 0; p < length; p += chunksize) { int chunk = p + chunksize < length ? chunksize : length - p; outputStream.write(bytes, p, chunk); } } outputStream.flush(); } /** * Creates and binds, if necessary, a socket connected to the specified * destination address and port and then returns its local address. * * @param dst * the destination address that the socket would need to connect * to. * @param dstPort * the port number that the connection would be established with. * @param localAddress * the address that we would like to bind on (null for the "any" * address). * @param localPort * the port that we'd like our socket to bind to (0 for a random * port). * * @return the SocketAddress that this handler would use when connecting to * the specified destination address and port. * * @throws IOException if we fail binding the socket */ public SocketAddress getLocalAddressForTcpDst(InetAddress dst, int dstPort, InetAddress localAddress, int localPort) throws IOException { String key = makeKey(dst, dstPort); Socket clientSock = getSocket(key); if (clientSock == null) { clientSock = sipStack.getNetworkLayer().createSocket(dst, dstPort, localAddress, localPort); putSocket(key, clientSock); } return clientSock.getLocalSocketAddress(); } /** * Creates and binds, if necessary, a socket connected to the specified * destination address and port and then returns its local address. * * @param dst the destination address that the socket would need to connect * to. * @param dstPort the port number that the connection would be established * with. * @param localAddress the address that we would like to bind on (null for * the "any" address). * * @param channel the message channel that will be servicing the socket * * @return the SocketAddress that this handler would use when connecting to * the specified destination address and port. * * @throws IOException if we fail binding the socket */ public SocketAddress getLocalAddressForTlsDst(InetAddress dst, int dstPort, InetAddress localAddress, TLSMessageChannel channel) throws IOException { String key = makeKey(dst, dstPort); Socket clientSock = getSocket(key); if (clientSock == null) { clientSock = sipStack.getNetworkLayer() .createSSLSocket(dst, dstPort, localAddress); SSLSocket sslsock = (SSLSocket) clientSock; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + dst); logger.logDebug( "port = " + dstPort); } HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl(channel); channel.setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack.getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } // allow application to enforce policy by validating the // certificate try { sipStack.getTlsSecurityPolicy().enforceTlsPolicy( channel.getEncapsulatedClientTransaction()); } catch (SecurityException ex) { throw new IOException(ex.getMessage()); } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "TLS Security policy passed"); } putSocket(key, clientSock); } return clientSock.getLocalSocketAddress(); } /** * Send an array of bytes. * * @param receiverAddress * -- inet address * @param contactPort * -- port to connect to. * @param transport * -- tcp or udp. * @param isClient * -- retry to connect if the other end closed connection * @throws IOException * -- if there is an IO exception sending message. */ public Socket sendBytes(InetAddress senderAddress, InetAddress receiverAddress, int contactPort, String transport, byte[] bytes, boolean isClient, MessageChannel messageChannel) throws IOException { int retry_count = 0; int max_retry = isClient ? 2 : 1; // Server uses TCP transport. TCP client sockets are cached int length = bytes.length; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " length = " + length + " isClient " + isClient ); } if (logger.isLoggingEnabled(LogLevels.TRACE_INFO) && sipStack.isLogStackTraceOnMessageSend()) { logger.logStackTrace(StackLogger.TRACE_INFO); } if (transport.compareToIgnoreCase(TCP) == 0) { String key = makeKey(receiverAddress, contactPort); // This should be in a synchronized block ( reported by // Jayashenkhar ( lucent ). Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } // note that the IP Address for stack may not be // assigned. // sender address is the address of the listening point. // in version 1.1 all listening points have the same IP // address (i.e. that of the stack). In version 1.2 // the IP address is on a per listening point basis. try { clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException logger.logError("Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); // new connection is bad. // remove from our table the socket and its semaphore removeSocket(key); throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger .isLoggingEnabled(LogWriter.TRACE_WARN)) logger.logWarning( "IOException occured retryCount " + retry_count); try { clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; // This is a server tx trying to send a response. if ( !isClient ) { removeSocket(key); throw ex; } if(retry_count >= max_retry) { // old connection is bad. // remove from our table the socket and its semaphore removeSocket(key); } else { // don't remove the semaphore on retry socketTable.remove(key); } } } } } catch (IOException ex) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( "Problem sending: sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " remoteHost " + messageChannel.getPeerAddress() + " remotePort " + messageChannel.getPeerPort() + " peerPacketPort " + messageChannel.getPeerPacketSourcePort() + " isClient " + isClient); } removeSocket(key); /* * For TCP responses, the transmission of responses is * controlled by RFC 3261, section 18.2.2 : * * o If the "sent-protocol" is a reliable transport protocol * such as TCP or SCTP, or TLS over those, the response MUST be * sent using the existing connection to the source of the * original request that created the transaction, if that * connection is still open. This requires the server transport * to maintain an association between server transactions and * transport connections. If that connection is no longer open, * the server SHOULD open a connection to the IP address in the * "received" parameter, if present, using the port in the * "sent-by" value, or the default port for that transport, if * no port is specified. If that connection attempt fails, the * server SHOULD use the procedures in [4] for servers in order * to determine the IP address and port to open the connection * and send the response to. */ if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); return clientSock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { logger.logError("IOException occured at " , ex); throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( this.socketTable.toString()); logger.logError( "Could not connect to " + receiverAddress + ":" + contactPort); } throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else { return clientSock; } // Added by Daniel J. Martinez Manzano <[email protected]> // Copied and modified from the former section for TCP } else if (transport.compareToIgnoreCase(TLS) == 0) { String key = makeKey(receiverAddress, contactPort); Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { clientSock = sipStack.getNetworkLayer() .createSSLSocket(receiverAddress, contactPort, senderAddress); SSLSocket sslsock = (SSLSocket) clientSock; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } // allow application to enforce policy by validating the // certificate try { sipStack .getTlsSecurityPolicy() .enforceTlsPolicy( messageChannel .getEncapsulatedClientTransaction()); } catch (SecurityException ex) { throw new IOException(ex.getMessage()); } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "TLS Security policy passed"); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger.isLoggingEnabled()) logger.logException(ex); // old connection is bad. // remove from our table. removeSocket(key); try { logger.logDebug( "Closing socket"); clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; } } } } catch (SSLHandshakeException ex) { removeSocket(key); throw ex; } catch (IOException ex) { removeSocket(key); if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } SSLSocket sslsock = sipStack.getNetworkLayer().createSSLSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = sslsock .getOutputStream(); HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } writeChunks(outputStream, bytes, length); - putSocket(key, clientSock); + putSocket(key, sslsock); return sslsock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else return clientSock; } else { // This is a UDP transport... DatagramSocket datagramSock = sipStack.getNetworkLayer() .createDatagramSocket(); datagramSock.connect(receiverAddress, contactPort); DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length, receiverAddress, contactPort); datagramSock.send(dgPacket); datagramSock.close(); return null; } } /* * private void enterIOCriticalSection(String key) throws IOException { try * { if ( ! this.ioSemaphore.tryAcquire(10,TimeUnit.SECONDS) ) { throw new * IOException("Could not acquire semaphore"); } } catch * (InterruptedException e) { throw new * IOException("exception in acquiring sem"); } } * * * private void leaveIOCriticalSection(String key) { * this.ioSemaphore.release(); } */ private void leaveIOCriticalSection(String key) { Semaphore creationSemaphore = socketCreationMap.get(key); if (creationSemaphore != null) { creationSemaphore.release(); } } private void enterIOCriticalSection(String key) throws IOException { // http://dmy999.com/article/34/correct-use-of-concurrenthashmap Semaphore creationSemaphore = socketCreationMap.get(key); if(creationSemaphore == null) { Semaphore newCreationSemaphore = new Semaphore(1, true); creationSemaphore = socketCreationMap.putIfAbsent(key, newCreationSemaphore); if(creationSemaphore == null) { creationSemaphore = newCreationSemaphore; if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { logger.logDebug("new Semaphore added for key " + key); } } } try { boolean retval = creationSemaphore.tryAcquire(10, TimeUnit.SECONDS); if (!retval) { throw new IOException("Could not acquire IO Semaphore'" + key + "' after 10 seconds -- giving up "); } } catch (InterruptedException e) { throw new IOException("exception in acquiring sem"); } } /** * Close all the cached connections. */ public void closeAll() { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger .logDebug( "Closing " + socketTable.size() + " sockets from IOHandler"); for (Enumeration<Socket> values = socketTable.elements(); values .hasMoreElements();) { Socket s = (Socket) values.nextElement(); try { s.close(); } catch (IOException ex) { } } } }
true
true
public Socket sendBytes(InetAddress senderAddress, InetAddress receiverAddress, int contactPort, String transport, byte[] bytes, boolean isClient, MessageChannel messageChannel) throws IOException { int retry_count = 0; int max_retry = isClient ? 2 : 1; // Server uses TCP transport. TCP client sockets are cached int length = bytes.length; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " length = " + length + " isClient " + isClient ); } if (logger.isLoggingEnabled(LogLevels.TRACE_INFO) && sipStack.isLogStackTraceOnMessageSend()) { logger.logStackTrace(StackLogger.TRACE_INFO); } if (transport.compareToIgnoreCase(TCP) == 0) { String key = makeKey(receiverAddress, contactPort); // This should be in a synchronized block ( reported by // Jayashenkhar ( lucent ). Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } // note that the IP Address for stack may not be // assigned. // sender address is the address of the listening point. // in version 1.1 all listening points have the same IP // address (i.e. that of the stack). In version 1.2 // the IP address is on a per listening point basis. try { clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException logger.logError("Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); // new connection is bad. // remove from our table the socket and its semaphore removeSocket(key); throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger .isLoggingEnabled(LogWriter.TRACE_WARN)) logger.logWarning( "IOException occured retryCount " + retry_count); try { clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; // This is a server tx trying to send a response. if ( !isClient ) { removeSocket(key); throw ex; } if(retry_count >= max_retry) { // old connection is bad. // remove from our table the socket and its semaphore removeSocket(key); } else { // don't remove the semaphore on retry socketTable.remove(key); } } } } } catch (IOException ex) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( "Problem sending: sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " remoteHost " + messageChannel.getPeerAddress() + " remotePort " + messageChannel.getPeerPort() + " peerPacketPort " + messageChannel.getPeerPacketSourcePort() + " isClient " + isClient); } removeSocket(key); /* * For TCP responses, the transmission of responses is * controlled by RFC 3261, section 18.2.2 : * * o If the "sent-protocol" is a reliable transport protocol * such as TCP or SCTP, or TLS over those, the response MUST be * sent using the existing connection to the source of the * original request that created the transaction, if that * connection is still open. This requires the server transport * to maintain an association between server transactions and * transport connections. If that connection is no longer open, * the server SHOULD open a connection to the IP address in the * "received" parameter, if present, using the port in the * "sent-by" value, or the default port for that transport, if * no port is specified. If that connection attempt fails, the * server SHOULD use the procedures in [4] for servers in order * to determine the IP address and port to open the connection * and send the response to. */ if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); return clientSock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { logger.logError("IOException occured at " , ex); throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( this.socketTable.toString()); logger.logError( "Could not connect to " + receiverAddress + ":" + contactPort); } throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else { return clientSock; } // Added by Daniel J. Martinez Manzano <[email protected]> // Copied and modified from the former section for TCP } else if (transport.compareToIgnoreCase(TLS) == 0) { String key = makeKey(receiverAddress, contactPort); Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { clientSock = sipStack.getNetworkLayer() .createSSLSocket(receiverAddress, contactPort, senderAddress); SSLSocket sslsock = (SSLSocket) clientSock; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } // allow application to enforce policy by validating the // certificate try { sipStack .getTlsSecurityPolicy() .enforceTlsPolicy( messageChannel .getEncapsulatedClientTransaction()); } catch (SecurityException ex) { throw new IOException(ex.getMessage()); } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "TLS Security policy passed"); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger.isLoggingEnabled()) logger.logException(ex); // old connection is bad. // remove from our table. removeSocket(key); try { logger.logDebug( "Closing socket"); clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; } } } } catch (SSLHandshakeException ex) { removeSocket(key); throw ex; } catch (IOException ex) { removeSocket(key); if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } SSLSocket sslsock = sipStack.getNetworkLayer().createSSLSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = sslsock .getOutputStream(); HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } writeChunks(outputStream, bytes, length); putSocket(key, clientSock); return sslsock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else return clientSock; } else { // This is a UDP transport... DatagramSocket datagramSock = sipStack.getNetworkLayer() .createDatagramSocket(); datagramSock.connect(receiverAddress, contactPort); DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length, receiverAddress, contactPort); datagramSock.send(dgPacket); datagramSock.close(); return null; } }
public Socket sendBytes(InetAddress senderAddress, InetAddress receiverAddress, int contactPort, String transport, byte[] bytes, boolean isClient, MessageChannel messageChannel) throws IOException { int retry_count = 0; int max_retry = isClient ? 2 : 1; // Server uses TCP transport. TCP client sockets are cached int length = bytes.length; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " length = " + length + " isClient " + isClient ); } if (logger.isLoggingEnabled(LogLevels.TRACE_INFO) && sipStack.isLogStackTraceOnMessageSend()) { logger.logStackTrace(StackLogger.TRACE_INFO); } if (transport.compareToIgnoreCase(TCP) == 0) { String key = makeKey(receiverAddress, contactPort); // This should be in a synchronized block ( reported by // Jayashenkhar ( lucent ). Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } // note that the IP Address for stack may not be // assigned. // sender address is the address of the listening point. // in version 1.1 all listening points have the same IP // address (i.e. that of the stack). In version 1.2 // the IP address is on a per listening point basis. try { clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); } catch (SocketException e) { // We must catch the socket timeout exceptions here, any SocketException not just ConnectException logger.logError("Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); // new connection is bad. // remove from our table the socket and its semaphore removeSocket(key); throw new SocketException(e.getClass() + " " + e.getMessage() + " " + e.getCause() + " Problem connecting " + receiverAddress + " " + contactPort + " " + senderAddress + " for message " + new String(bytes, "UTF-8")); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger .isLoggingEnabled(LogWriter.TRACE_WARN)) logger.logWarning( "IOException occured retryCount " + retry_count); try { clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; // This is a server tx trying to send a response. if ( !isClient ) { removeSocket(key); throw ex; } if(retry_count >= max_retry) { // old connection is bad. // remove from our table the socket and its semaphore removeSocket(key); } else { // don't remove the semaphore on retry socketTable.remove(key); } } } } } catch (IOException ex) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( "Problem sending: sendBytes " + transport + " inAddr " + receiverAddress.getHostAddress() + " port = " + contactPort + " remoteHost " + messageChannel.getPeerAddress() + " remotePort " + messageChannel.getPeerPort() + " peerPacketPort " + messageChannel.getPeerPacketSourcePort() + " isClient " + isClient); } removeSocket(key); /* * For TCP responses, the transmission of responses is * controlled by RFC 3261, section 18.2.2 : * * o If the "sent-protocol" is a reliable transport protocol * such as TCP or SCTP, or TLS over those, the response MUST be * sent using the existing connection to the source of the * original request that created the transaction, if that * connection is still open. This requires the server transport * to maintain an association between server transactions and * transport connections. If that connection is no longer open, * the server SHOULD open a connection to the IP address in the * "received" parameter, if present, using the port in the * "sent-by" value, or the default port for that transport, if * no port is specified. If that connection attempt fails, the * server SHOULD use the procedures in [4] for servers in order * to determine the IP address and port to open the connection * and send the response to. */ if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } clientSock = sipStack.getNetworkLayer().createSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); return clientSock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { logger.logError("IOException occured at " , ex); throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) { logger.logError( this.socketTable.toString()); logger.logError( "Could not connect to " + receiverAddress + ":" + contactPort); } throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else { return clientSock; } // Added by Daniel J. Martinez Manzano <[email protected]> // Copied and modified from the former section for TCP } else if (transport.compareToIgnoreCase(TLS) == 0) { String key = makeKey(receiverAddress, contactPort); Socket clientSock = null; enterIOCriticalSection(key); try { clientSock = getSocket(key); while (retry_count < max_retry) { if (clientSock == null) { clientSock = sipStack.getNetworkLayer() .createSSLSocket(receiverAddress, contactPort, senderAddress); SSLSocket sslsock = (SSLSocket) clientSock; if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress); logger.logDebug( "port = " + contactPort); } HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } // allow application to enforce policy by validating the // certificate try { sipStack .getTlsSecurityPolicy() .enforceTlsPolicy( messageChannel .getEncapsulatedClientTransaction()); } catch (SecurityException ex) { throw new IOException(ex.getMessage()); } if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "TLS Security policy passed"); } OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); putSocket(key, clientSock); break; } else { try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); break; } catch (IOException ex) { if (logger.isLoggingEnabled()) logger.logException(ex); // old connection is bad. // remove from our table. removeSocket(key); try { logger.logDebug( "Closing socket"); clientSock.close(); } catch (Exception e) { } clientSock = null; retry_count++; } } } } catch (SSLHandshakeException ex) { removeSocket(key); throw ex; } catch (IOException ex) { removeSocket(key); if (!isClient) { receiverAddress = InetAddress.getByName(messageChannel .getViaHost()); contactPort = messageChannel.getViaPort(); if (contactPort == -1) contactPort = 5060; key = makeKey(receiverAddress, messageChannel .getViaPort()); clientSock = this.getSocket(key); if (clientSock == null) { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "inaddr = " + receiverAddress + " port = " + contactPort); } SSLSocket sslsock = sipStack.getNetworkLayer().createSSLSocket( receiverAddress, contactPort, senderAddress); OutputStream outputStream = sslsock .getOutputStream(); HandshakeCompletedListener listner = new HandshakeCompletedListenerImpl( (TLSMessageChannel) messageChannel); ((TLSMessageChannel) messageChannel) .setHandshakeCompletedListener(listner); sslsock.addHandshakeCompletedListener(listner); sslsock.setEnabledProtocols(sipStack .getEnabledProtocols()); sslsock.startHandshake(); if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { this.logger.logDebug( "Handshake passed"); } writeChunks(outputStream, bytes, length); putSocket(key, sslsock); return sslsock; } else { if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) { logger.logDebug( "sending to " + key ); } try { OutputStream outputStream = clientSock .getOutputStream(); writeChunks(outputStream, bytes, length); return clientSock; } catch (IOException ioe) { if (logger .isLoggingEnabled(LogWriter.TRACE_ERROR)) logger.logError( "IOException occured ", ioe); if (logger .isLoggingEnabled(LogWriter.TRACE_DEBUG)) logger.logDebug( "Removing and Closing socket"); // old connection is bad. // remove from our table. removeSocket(key); try { clientSock.close(); } catch (Exception e) { } clientSock = null; throw ioe; } } } else { throw ex; } } finally { leaveIOCriticalSection(key); } if (clientSock == null) { throw new IOException("Could not connect to " + receiverAddress + ":" + contactPort); } else return clientSock; } else { // This is a UDP transport... DatagramSocket datagramSock = sipStack.getNetworkLayer() .createDatagramSocket(); datagramSock.connect(receiverAddress, contactPort); DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length, receiverAddress, contactPort); datagramSock.send(dgPacket); datagramSock.close(); return null; } }
diff --git a/src/com/xabber/android/data/message/MessageManager.java b/src/com/xabber/android/data/message/MessageManager.java index 81d1d015..12a7ccfa 100644 --- a/src/com/xabber/android/data/message/MessageManager.java +++ b/src/com/xabber/android/data/message/MessageManager.java @@ -1,582 +1,584 @@ /** * Copyright (c) 2013, Redsolution LTD. All rights reserved. * * This file is part of Xabber project; you can redistribute it and/or * modify it under the terms of the GNU General Public License, Version 3. * * Xabber 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.xabber.android.data.message; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smackx.packet.MUCUser; import android.database.Cursor; import android.os.Environment; import com.xabber.android.data.Application; import com.xabber.android.data.NetworkException; import com.xabber.android.data.OnLoadListener; import com.xabber.android.data.SettingsManager; import com.xabber.android.data.SettingsManager.ChatsShowStatusChange; import com.xabber.android.data.account.AccountItem; import com.xabber.android.data.account.AccountManager; import com.xabber.android.data.account.ArchiveMode; import com.xabber.android.data.account.OnAccountArchiveModeChangedListener; import com.xabber.android.data.account.OnAccountRemovedListener; import com.xabber.android.data.connection.ConnectionItem; import com.xabber.android.data.connection.OnDisconnectListener; import com.xabber.android.data.connection.OnPacketListener; import com.xabber.android.data.entity.BaseEntity; import com.xabber.android.data.entity.NestedMap; import com.xabber.android.data.extension.archive.MessageArchiveManager; import com.xabber.android.data.extension.muc.RoomChat; import com.xabber.android.data.roster.OnRosterReceivedListener; import com.xabber.android.data.roster.RosterManager; import com.xabber.android.utils.StringUtils; import com.xabber.androiddev.R; import com.xabber.xmpp.address.Jid; import com.xabber.xmpp.delay.Delay; /** * Manage chats and its messages. * * Warning: message processing using chat instances should be changed. * * @author alexander.ivanov * */ public class MessageManager implements OnLoadListener, OnPacketListener, OnDisconnectListener, OnAccountRemovedListener, OnRosterReceivedListener, OnAccountArchiveModeChangedListener { /** * Registered chats for bareAddresses in accounts. */ private final NestedMap<AbstractChat> chats; /** * Visible chat. * * Will be <code>null</code> if there is no one. */ private AbstractChat visibleChat; private final static MessageManager instance; static { instance = new MessageManager(); Application.getInstance().addManager(instance); } public static MessageManager getInstance() { return instance; } private MessageManager() { chats = new NestedMap<AbstractChat>(); } @Override public void onLoad() { final Set<BaseEntity> loadChats = new HashSet<BaseEntity>(); Cursor cursor; cursor = MessageTable.getInstance().messagesToSend(); try { if (cursor.moveToFirst()) { do { loadChats.add(new BaseEntity(MessageTable .getAccount(cursor), MessageTable.getUser(cursor))); } while (cursor.moveToNext()); } } finally { cursor.close(); } Application.getInstance().runOnUiThread(new Runnable() { @Override public void run() { onLoaded(loadChats); } }); } private void onLoaded(Set<BaseEntity> loadChats) { for (BaseEntity baseEntity : loadChats) if (getChat(baseEntity.getAccount(), Jid.getBareAddress(baseEntity.getUser())) == null) createChat(baseEntity.getAccount(), baseEntity.getUser()); } /** * @param account * @param user * @return <code>null</code> if there is no such chat. */ public AbstractChat getChat(String account, String user) { return chats.get(account, user); } public Collection<AbstractChat> getChats() { return Collections.unmodifiableCollection(chats.values()); } /** * Creates and adds new regular chat to be managed. * * @param account * @param user * @return */ private RegularChat createChat(String account, String user) { RegularChat chat = new RegularChat(account, Jid.getBareAddress(user)); addChat(chat); return chat; } /** * Adds chat to be managed. * * @param chat */ public void addChat(AbstractChat chat) { if (getChat(chat.getAccount(), chat.getUser()) != null) throw new IllegalStateException(); chats.put(chat.getAccount(), chat.getUser(), chat); } /** * Removes chat from managed. * * @param chat */ public void removeChat(AbstractChat chat) { chats.remove(chat.getAccount(), chat.getUser()); } /** * Sends message. Creates and registers new chat if necessary. * * @param account * @param user * @param text */ public void sendMessage(String account, String user, String text) { AbstractChat chat = getChat(account, user); if (chat == null) chat = createChat(account, user); MessageItem messageItem = chat.newMessage(text); chat.sendQueue(messageItem); } /** * @param account * @param user * @return Where there is active chat. */ public boolean hasActiveChat(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return false; return chat.isActive(); } /** * @return Collection with active chats. */ public Collection<AbstractChat> getActiveChats() { Collection<AbstractChat> collection = new ArrayList<AbstractChat>(); for (AbstractChat chat : chats.values()) if (chat.isActive()) collection.add(chat); return Collections.unmodifiableCollection(collection); } /** * Returns existed chat or create new one. * * @param account * @param user * @return */ public AbstractChat getOrCreateChat(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) chat = createChat(account, user); return chat; } /** * Force open chat (make it active). * * @param account * @param user */ public void openChat(String account, String user) { getOrCreateChat(account, user).openChat(); } /** * Closes specified chat (make it inactive). * * @param account * @param user */ public void closeChat(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return; chat.closeChat(); } public void requestToLoadLocalHistory(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) chat = createChat(account, user); chat.requestToLoadLocalHistory(); } /** * @param account * @param user * @return Last incoming message's text. Empty string if last message is * outgoing. */ public String getLastText(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return ""; return chat.getLastText(); } /** * @param account * @param user * @return Time of last message in chat. Can be <code>null</code>. */ public Date getLastTime(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return null; return chat.getLastTime(); } /** * Sets currently visible chat. * * @param account * @param user */ public void setVisibleChat(String account, String user) { final boolean remove = !AccountManager.getInstance() .getArchiveMode(account).saveLocally(); AbstractChat chat = getChat(account, user); if (chat == null) chat = createChat(account, user); else { // Mark messages as read and them delete from db if necessary. final ArrayList<MessageItem> messageItems = new ArrayList<MessageItem>(); for (MessageItem messageItem : chat.getMessages()) { if (!messageItem.isRead()) { messageItem.markAsRead(); messageItems.add(messageItem); } } Application.getInstance().runInBackground(new Runnable() { @Override public void run() { Collection<Long> ids = getMessageIds(messageItems, remove); if (remove) MessageTable.getInstance().removeMessages(ids); else MessageTable.getInstance().markAsRead(ids); } }); } visibleChat = chat; } /** * All chats become invisible. */ public void removeVisibleChat() { visibleChat = null; } /** * @param chat * @return Whether specified chat is currently visible. */ boolean isVisibleChat(AbstractChat chat) { return visibleChat == chat; } /** * Removes all messages from chat. * * @param account * @param user */ public void clearHistory(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return; chat.removeAllMessages(); onChatChanged(chat.getAccount(), chat.getUser(), false); } /** * Removes message from history. * * @param messageItem */ public void removeMessage(MessageItem messageItem) { AbstractChat chat = messageItem.getChat(); chat.removeMessage(messageItem); onChatChanged(chat.getAccount(), chat.getUser(), false); } /** * @param account * @param user * @return List of messages or empty list. */ public Collection<MessageItem> getMessages(String account, String user) { AbstractChat chat = getChat(account, user); if (chat == null) return Collections.emptyList(); return chat.getMessages(); } /** * Called on action settings change. */ public void onActionSettings() { ChatsShowStatusChange showStatusChange = SettingsManager .chatsShowStatusChange(); Collection<BaseEntity> changedEntities = new ArrayList<BaseEntity>(); for (AbstractChat chat : chats.values()) if ((chat instanceof RegularChat && showStatusChange != ChatsShowStatusChange.always) || (chat instanceof RoomChat && showStatusChange == ChatsShowStatusChange.never)) { // Remove actions with status change. ArrayList<MessageItem> remove = new ArrayList<MessageItem>(); for (MessageItem messageItem : chat.getMessages()) if (messageItem.getAction() != null && messageItem.getAction().isStatusChage()) remove.add(messageItem); if (remove.isEmpty()) continue; for (MessageItem messageItem : remove) chat.removeMessage(messageItem); changedEntities.add(chat); } RosterManager.getInstance().onContactsChanged(changedEntities); } @Override public void onAccountArchiveModeChanged(AccountItem accountItem) { final ArchiveMode archiveMode = AccountManager.getInstance() .getArchiveMode(accountItem.getAccount()); if (archiveMode.saveLocally()) return; final String account = accountItem.getAccount(); final ArrayList<MessageItem> removeMessageItems = new ArrayList<MessageItem>(); for (AbstractChat chat : chats.getNested(account).values()) for (MessageItem messageItem : chat.getMessages()) if (archiveMode == ArchiveMode.dontStore || ((messageItem.isRead() || archiveMode != ArchiveMode.unreadOnly) && messageItem .isSent())) removeMessageItems.add(messageItem); Application.getInstance().runInBackground(new Runnable() { @Override public void run() { // If message was read or received after removeMessageItems // was created then it's ID will be not null. DB actions with // such message will have no effect as if it was removed. // History ids becomes invalid and will be cleared on next // history load. MessageTable.getInstance().removeMessages( getMessageIds(removeMessageItems, true)); if (archiveMode == ArchiveMode.dontStore) MessageTable.getInstance().removeAccount(account); else if (archiveMode == ArchiveMode.unreadOnly) MessageTable.getInstance().removeReadAndSent(account); else MessageTable.getInstance().removeSent(account); } }); AccountManager.getInstance().onAccountChanged(accountItem.getAccount()); } @Override public void onPacket(ConnectionItem connection, String bareAddress, Packet packet) { if (!(connection instanceof AccountItem)) return; String account = ((AccountItem) connection).getAccount(); if (bareAddress == null) return; if (packet instanceof Message && MessageArchiveManager.getInstance().isModificationsSucceed( account) && Delay.isOfflineMessage(Jid.getServer(account), packet)) // Ignore offline message if modification from server side message // archive have been received. return; final String user = packet.getFrom(); boolean processed = false; for (AbstractChat chat : chats.getNested(account).values()) if (chat.onPacket(bareAddress, packet)) { processed = true; break; } if (getChat(account, user) != null) return; if (!processed && packet instanceof Message) { final Message message = (Message) packet; final String body = message.getBody(); if (body == null) return; for (PacketExtension packetExtension : message.getExtensions()) if (packetExtension instanceof MUCUser) return; createChat(account, user).onPacket(bareAddress, packet); } } @Override public void onRosterReceived(AccountItem accountItem) { String account = accountItem.getAccount(); for (AbstractChat chat : chats.getNested(account).values()) chat.onComplete(); } @Override public void onDisconnect(ConnectionItem connection) { if (!(connection instanceof AccountItem)) return; String account = ((AccountItem) connection).getAccount(); for (AbstractChat chat : chats.getNested(account).values()) chat.onDisconnect(); } @Override public void onAccountRemoved(AccountItem accountItem) { chats.clear(accountItem.getAccount()); } /** * Export chat to file with specified name. * * @param account * @param user * @param fileName * @throws NetworkException */ public File exportChat(String account, String user, String fileName) throws NetworkException { final File file = new File(Environment.getExternalStorageDirectory(), fileName); try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); final String titleName = RosterManager.getInstance().getName( account, user) + " (" + user + ")"; out.write("<html><head><title>"); out.write(StringUtils.escapeHtml(titleName)); out.write("</title></head><body>"); final AbstractChat abstractChat = getChat(account, user); if (abstractChat != null) { final boolean isMUC = abstractChat instanceof RoomChat; final String accountName = AccountManager.getInstance() .getNickName(account); final String userName = RosterManager.getInstance().getName( account, user); for (MessageItem messageItem : abstractChat.getMessages()) { + if (messageItem.getAction() != null) + continue; final String name; if (isMUC) { name = messageItem.getResource(); } else { if (messageItem.isIncoming()) name = userName; else name = accountName; } out.write("<b>"); out.write(StringUtils.escapeHtml(name)); out.write("</b>&nbsp;("); out.write(StringUtils.getDateTimeText(messageItem .getTimestamp())); out.write(")<br />\n<p>"); out.write(StringUtils.escapeHtml(messageItem.getText())); out.write("</p><hr />\n"); } } out.write("</body></html>"); out.close(); } catch (IOException e) { throw new NetworkException(R.string.FILE_NOT_FOUND); } return file; } /** * Notifies registered {@link OnChatChangedListener}. * * @param account * @param user * @param incoming */ public void onChatChanged(final String account, final String user, final boolean incoming) { Application.getInstance().runOnUiThread(new Runnable() { @Override public void run() { for (OnChatChangedListener onChatChangedListener : Application .getInstance().getUIListeners( OnChatChangedListener.class)) onChatChangedListener .onChatChanged(account, user, incoming); } }); } /** * @param messageItems * @param clearId * Whether message id must be set to the <code>null</code>. * @return Collection with ids for specified messages. */ static Collection<Long> getMessageIds(Collection<MessageItem> messageItems, boolean clearId) { ArrayList<Long> ids = new ArrayList<Long>(); for (MessageItem messageItem : messageItems) { Long id = messageItem.getId(); if (id == null) continue; ids.add(id); if (clearId) messageItem.setId(null); } return ids; } }
true
true
public File exportChat(String account, String user, String fileName) throws NetworkException { final File file = new File(Environment.getExternalStorageDirectory(), fileName); try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); final String titleName = RosterManager.getInstance().getName( account, user) + " (" + user + ")"; out.write("<html><head><title>"); out.write(StringUtils.escapeHtml(titleName)); out.write("</title></head><body>"); final AbstractChat abstractChat = getChat(account, user); if (abstractChat != null) { final boolean isMUC = abstractChat instanceof RoomChat; final String accountName = AccountManager.getInstance() .getNickName(account); final String userName = RosterManager.getInstance().getName( account, user); for (MessageItem messageItem : abstractChat.getMessages()) { final String name; if (isMUC) { name = messageItem.getResource(); } else { if (messageItem.isIncoming()) name = userName; else name = accountName; } out.write("<b>"); out.write(StringUtils.escapeHtml(name)); out.write("</b>&nbsp;("); out.write(StringUtils.getDateTimeText(messageItem .getTimestamp())); out.write(")<br />\n<p>"); out.write(StringUtils.escapeHtml(messageItem.getText())); out.write("</p><hr />\n"); } } out.write("</body></html>"); out.close(); } catch (IOException e) { throw new NetworkException(R.string.FILE_NOT_FOUND); } return file; }
public File exportChat(String account, String user, String fileName) throws NetworkException { final File file = new File(Environment.getExternalStorageDirectory(), fileName); try { BufferedWriter out = new BufferedWriter(new FileWriter(file)); final String titleName = RosterManager.getInstance().getName( account, user) + " (" + user + ")"; out.write("<html><head><title>"); out.write(StringUtils.escapeHtml(titleName)); out.write("</title></head><body>"); final AbstractChat abstractChat = getChat(account, user); if (abstractChat != null) { final boolean isMUC = abstractChat instanceof RoomChat; final String accountName = AccountManager.getInstance() .getNickName(account); final String userName = RosterManager.getInstance().getName( account, user); for (MessageItem messageItem : abstractChat.getMessages()) { if (messageItem.getAction() != null) continue; final String name; if (isMUC) { name = messageItem.getResource(); } else { if (messageItem.isIncoming()) name = userName; else name = accountName; } out.write("<b>"); out.write(StringUtils.escapeHtml(name)); out.write("</b>&nbsp;("); out.write(StringUtils.getDateTimeText(messageItem .getTimestamp())); out.write(")<br />\n<p>"); out.write(StringUtils.escapeHtml(messageItem.getText())); out.write("</p><hr />\n"); } } out.write("</body></html>"); out.close(); } catch (IOException e) { throw new NetworkException(R.string.FILE_NOT_FOUND); } return file; }
diff --git a/src/com/android/camera/ImageViewTouchBase.java b/src/com/android/camera/ImageViewTouchBase.java index da2f2c32..bc33827a 100644 --- a/src/com/android/camera/ImageViewTouchBase.java +++ b/src/com/android/camera/ImageViewTouchBase.java @@ -1,377 +1,377 @@ /* * 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.camera; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.ImageView; abstract class ImageViewTouchBase extends ImageView { @SuppressWarnings("unused") private static final String TAG = "ImageViewTouchBase"; // This is the base transformation which is used to show the image // initially. The current computation for this shows the image in // it's entirety, letterboxing as needed. One could choose to // show the image as cropped instead. // // This matrix is recomputed when we go from the thumbnail image to // the full size image. protected Matrix mBaseMatrix = new Matrix(); // This is the supplementary transformation which reflects what // the user has done in terms of zooming and panning. // // This matrix remains the same when we go from the thumbnail image // to the full size image. protected Matrix mSuppMatrix = new Matrix(); // This is the final matrix which is computed as the concatentation // of the base matrix and the supplementary matrix. private final Matrix mDisplayMatrix = new Matrix(); // Temporary buffer used for getting the values out of a matrix. private final float[] mMatrixValues = new float[9]; // The current bitmap being displayed. protected Bitmap mBitmapDisplayed; int mThisWidth = -1, mThisHeight = -1; float mMaxZoom; // ImageViewTouchBase will pass a Bitmap to the Recycler if it has finished // its use of that Bitmap. public interface Recycler { public void recycle(Bitmap b); } public void setRecycler(Recycler r) { mRecycler = r; } private Recycler mRecycler; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mThisWidth = right - left; mThisHeight = bottom - top; Runnable r = mOnLayoutRunnable; if (r != null) { mOnLayoutRunnable = null; r.run(); } if (mBitmapDisplayed != null) { getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix); setImageMatrix(getImageViewMatrix()); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) { // If we're zoomed in, pressing Back jumps out to show the entire // image, otherwise Back returns the user to the gallery. zoomTo(1.0f); return true; } return super.onKeyDown(keyCode, event); } protected Handler mHandler = new Handler(); protected int mLastXTouchPos; protected int mLastYTouchPos; @Override public void setImageBitmap(Bitmap bitmap) { super.setImageBitmap(bitmap); Drawable d = getDrawable(); if (d != null) { d.setDither(true); } Bitmap old = mBitmapDisplayed; mBitmapDisplayed = bitmap; if (old != null && old != bitmap && mRecycler != null) { mRecycler.recycle(old); } } public void clear() { setImageBitmapResetBase(null, true); } private Runnable mOnLayoutRunnable = null; // This function changes bitmap, reset base matrix according to the size // of the bitmap, and optionally reset the supplementary matrix. public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp) { final int viewWidth = getWidth(); if (viewWidth <= 0) { mOnLayoutRunnable = new Runnable() { public void run() { setImageBitmapResetBase(bitmap, resetSupp); } }; return; } if (bitmap != null) { getProperBaseMatrix(bitmap, mBaseMatrix); setImageBitmap(bitmap); } else { mBaseMatrix.reset(); setImageBitmap(null); } if (resetSupp) { mSuppMatrix.reset(); } setImageMatrix(getImageViewMatrix()); mMaxZoom = maxZoom(); } // Center as much as possible in one or both axis. Centering is // defined as follows: if the image is scaled down below the // view's dimensions then center it (literally). If the image // is scaled larger than the view and is translated out of view // then translate it back into view (i.e. eliminate black bars). - protected void center(boolean vertical, boolean horizontal) { + protected void center(boolean horizontal, boolean vertical) { if (mBitmapDisplayed == null) { return; } Matrix m = getImageViewMatrix(); float [] topLeft = new float[] { 0, 0 }; float [] botRight = new float[] { mBitmapDisplayed.getWidth(), mBitmapDisplayed.getHeight() }; m.mapPoints(topLeft); m.mapPoints(botRight); float height = botRight[1] - topLeft[1]; float width = botRight[0] - topLeft[0]; float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - topLeft[1]; } else if (topLeft[1] > 0) { deltaY = -topLeft[1]; } else if (botRight[1] < viewHeight) { deltaY = getHeight() - botRight[1]; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - topLeft[0]; } else if (topLeft[0] > 0) { deltaX = -topLeft[0]; } else if (botRight[0] < viewWidth) { deltaX = viewWidth - botRight[0]; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); } public ImageViewTouchBase(Context context) { super(context); init(); } public ImageViewTouchBase(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setScaleType(ImageView.ScaleType.MATRIX); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } // Get the scale factor out of the matrix. protected float getScale(Matrix matrix) { return getValue(matrix, Matrix.MSCALE_X); } protected float getScale() { return getScale(mSuppMatrix); } // Setup the base matrix so that the image is centered and scaled properly. private void getProperBaseMatrix(Bitmap bitmap, Matrix matrix) { float viewWidth = getWidth(); float viewHeight = getHeight(); matrix.reset(); float widthScale = Math.min(viewWidth / bitmap.getWidth(), 1.0f); float heightScale = Math.min(viewHeight / bitmap.getHeight(), 1.0f); float scale; if (widthScale > heightScale) { scale = heightScale; } else { scale = widthScale; } matrix.setScale(scale, scale); matrix.postTranslate( (viewWidth - (bitmap.getWidth() * scale)) / 2F, (viewHeight - (bitmap.getHeight() * scale)) / 2F); } // Combine the base matrix and the supp matrix to make the final matrix. protected Matrix getImageViewMatrix() { // The final matrix is computed as the concatentation of the base matrix // and the supplementary matrix. mDisplayMatrix.set(mBaseMatrix); mDisplayMatrix.postConcat(mSuppMatrix); return mDisplayMatrix; } static final float SCALE_RATE = 1.25F; // Sets the maximum zoom, which is a scale relative to the base matrix. It // is calculated to show the image at 400% zoom regardless of screen or // image orientation. If in the future we decode the full 3 megapixel image, // rather than the current 1024x768, this should be changed down to 200%. protected float maxZoom() { if (mBitmapDisplayed == null) { return 1F; } float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth; float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight; float max = Math.max(fw, fh) * 4; return max; } protected void zoomTo(float scale, float centerX, float centerY) { if (scale > mMaxZoom) { scale = mMaxZoom; } float oldScale = getScale(); float deltaScale = scale / oldScale; mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); setImageMatrix(getImageViewMatrix()); center(true, true); } protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) { final float incrementPerMs = (scale - getScale()) / durationMs; final float oldScale = getScale(); final long startTime = System.currentTimeMillis(); mHandler.post(new Runnable() { public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min(durationMs, now - startTime); float target = oldScale + (incrementPerMs * currentMs); zoomTo(target, centerX, centerY); if (currentMs < durationMs) { mHandler.post(this); } } }); } protected void zoomTo(float scale) { float cx = getWidth() / 2F; float cy = getHeight() / 2F; zoomTo(scale, cx, cy); } protected void zoomIn() { zoomIn(SCALE_RATE); } protected void zoomOut() { zoomOut(SCALE_RATE); } protected void zoomIn(float rate) { if (getScale() >= mMaxZoom) { return; // Don't let the user zoom into the molecular level. } if (mBitmapDisplayed == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; mSuppMatrix.postScale(rate, rate, cx, cy); setImageMatrix(getImageViewMatrix()); } protected void zoomOut(float rate) { if (mBitmapDisplayed == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; // Zoom out to at most 1x. Matrix tmp = new Matrix(mSuppMatrix); tmp.postScale(1F / rate, 1F / rate, cx, cy); if (getScale(tmp) < 1F) { mSuppMatrix.setScale(1F, 1F, cx, cy); } else { mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy); } setImageMatrix(getImageViewMatrix()); center(true, true); } protected void postTranslate(float dx, float dy) { mSuppMatrix.postTranslate(dx, dy); } protected void panBy(float dx, float dy) { postTranslate(dx, dy); setImageMatrix(getImageViewMatrix()); } }
true
true
protected void center(boolean vertical, boolean horizontal) { if (mBitmapDisplayed == null) { return; } Matrix m = getImageViewMatrix(); float [] topLeft = new float[] { 0, 0 }; float [] botRight = new float[] { mBitmapDisplayed.getWidth(), mBitmapDisplayed.getHeight() }; m.mapPoints(topLeft); m.mapPoints(botRight); float height = botRight[1] - topLeft[1]; float width = botRight[0] - topLeft[0]; float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - topLeft[1]; } else if (topLeft[1] > 0) { deltaY = -topLeft[1]; } else if (botRight[1] < viewHeight) { deltaY = getHeight() - botRight[1]; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - topLeft[0]; } else if (topLeft[0] > 0) { deltaX = -topLeft[0]; } else if (botRight[0] < viewWidth) { deltaX = viewWidth - botRight[0]; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); }
protected void center(boolean horizontal, boolean vertical) { if (mBitmapDisplayed == null) { return; } Matrix m = getImageViewMatrix(); float [] topLeft = new float[] { 0, 0 }; float [] botRight = new float[] { mBitmapDisplayed.getWidth(), mBitmapDisplayed.getHeight() }; m.mapPoints(topLeft); m.mapPoints(botRight); float height = botRight[1] - topLeft[1]; float width = botRight[0] - topLeft[0]; float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - topLeft[1]; } else if (topLeft[1] > 0) { deltaY = -topLeft[1]; } else if (botRight[1] < viewHeight) { deltaY = getHeight() - botRight[1]; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - topLeft[0]; } else if (topLeft[0] > 0) { deltaX = -topLeft[0]; } else if (botRight[0] < viewWidth) { deltaX = viewWidth - botRight[0]; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); }